text
stringlengths 1
1.05M
|
|---|
######################################################################
# This file was autogenerated by `make`. Do not edit it directly!
######################################################################
# Antigen: A simple plugin manager for zsh
# Authors: Shrikant Sharat Kandula
# and Contributors <https://github.com/zsh-users/antigen/contributors>
# Homepage: http://antigen.sharats.me
# License: MIT License <mitl.sharats.me>
zmodload zsh/parameter
autoload -U is-at-least
# While boot.zsh is part of the ext/cache functionallity it may be disabled
# with ANTIGEN_CACHE flag, and it's always compiled with antigen.zsh
if [[ $ANTIGEN_CACHE != false ]]; then
ANTIGEN_CACHE="${ANTIGEN_CACHE:-${ADOTDIR:-$HOME/.antigen}/init.zsh}"
ANTIGEN_RSRC="${ANTIGEN_RSRC:-${ADOTDIR:-$HOME/.antigen}/.resources}"
# It may not be necessary to check ANTIGEN_AUTO_CONFIG.
if [[ $ANTIGEN_AUTO_CONFIG != false && -f $ANTIGEN_RSRC ]]; then
# Check the list of files for configuration changes (uses -nt comp)
ANTIGEN_CHECK_FILES=$(cat $ANTIGEN_RSRC 2> /dev/null)
ANTIGEN_CHECK_FILES=(${(@f)ANTIGEN_CHECK_FILES})
for config in $ANTIGEN_CHECK_FILES; do
if [[ "$config" -nt "$config.zwc" ]]; then
# Flag configuration file as newer
{ zcompile "$config" } &!
# Kill cache file in order to force full loading (see a few lines below)
[[ -f "$ANTIGEN_CACHE" ]] && rm -f "$ANTIGEN_CACHE"
fi
done
fi
# If there is a cache file do load from it
if [[ -f $ANTIGEN_CACHE && ! $_ANTIGEN_CACHE_LOADED == true ]]; then
# Wrap antigen in order to defer cache source until `antigen-apply`
antigen() {
if [[ $1 == "apply" ]]; then
source "$ANTIGEN_CACHE"
# Handle `antigen-init` command properly
elif [[ $1 == "init" ]]; then
source "$2"
fi
}
# Do not continue loading antigen as cache bundle takes care of it.
return 0
fi
fi
[[ -z "$_ANTIGEN_INSTALL_DIR" ]] && _ANTIGEN_INSTALL_DIR=${0:A:h}
# Each line in this string has the following entries separated by a space
# character.
# <repo-url>, <plugin-location>, <bundle-type>, <has-local-clone>
[[ $_ANTIGEN_CACHE_LOADED != true ]] && typeset -aU _ANTIGEN_BUNDLE_RECORD
# Do not load anything if git is not available.
if (( ! $+commands[git] )); then
echo 'Antigen: Please install git to use Antigen.' >&2
return 1
fi
# Used to defer compinit/compdef
typeset -a __deferred_compdefs
compdef () { __deferred_compdefs=($__deferred_compdefs "$*") }
# A syntax sugar to avoid the `-` when calling antigen commands. With this
# function, you can write `antigen-bundle` as `antigen bundle` and so on.
antigen () {
local cmd="$1"
if [[ -z "$cmd" ]]; then
echo 'Antigen: Please give a command to run.' >&2
return 1
fi
shift
if (( $+functions[antigen-$cmd] )); then
"antigen-$cmd" "$@"
return $?
else
echo "Antigen: Unknown command: $cmd" >&2
return 1
fi
}
# Returns the bundle's git revision
#
# Usage
# -antigen-bundle-rev bundle-name [is_local_clone]
#
# Returns
# Bundle rev-parse output (branch name or short ref name)
-antigen-bundle-rev () {
local bundle=$1
local is_local_clone=$2
local bundle_path=$bundle
# Get bunde path inside $ADOTDIR if bundle was effectively cloned
if [[ "$is_local_clone" == "true" ]]; then
bundle_path=$(-antigen-get-clone-dir $bundle)
fi
local ref
ref=$(git --git-dir="$bundle_path/.git" rev-parse --abbrev-ref '@' 2>/dev/null)
# Avoid 'HEAD' when in detached mode
if [[ $ref == "HEAD" ]]; then
ref=$(git --git-dir="$bundle_path/.git" describe --tags --exact-match 2>/dev/null \
|| git --git-dir="$bundle_path/.git" rev-parse --short '@' 2>/dev/null || "-")
fi
echo $ref
}
# Usage:
# -antigen-bundle-short-name "https://github.com/user/repo.git[|*]" "[branch/name]"
# Returns:
# user/repo@branch/name
-antigen-bundle-short-name () {
local bundle_name="${1%|*}"
local bundle_branch="$2"
local match mbegin mend MATCH MBEGIN MEND
[[ "$bundle_name" =~ '.*/(.*/.*).*$' ]] && bundle_name=$match[1]
bundle_name="${bundle_name%.git*}"
if [[ -n $bundle_branch ]]; then
bundle_name="$bundle_name@$bundle_branch"
fi
echo $bundle_name
}
# Echo the bundle specs as in the record. The first line is not echoed since it
# is a blank line.
-antigen-echo-record () {
echo ${(j:\n:)_ANTIGEN_BUNDLE_RECORD}
}
# Filters _ANTIGEN_BUNDLE_RECORD for $1
#
# Usage
# -antigen-find-bundle example/bundle
#
# Returns
# String if bundle is found
-antigen-find-bundle () {
echo $(-antigen-find-record $1 | cut -d' ' -f1)
}
# Filters _ANTIGEN_BUNDLE_RECORD for $1
#
# Usage
# -antigen-find-record example/bundle
#
# Returns
# String if record is found
-antigen-find-record () {
local bundle=$1
if [[ $# -eq 0 ]]; then
return 1
fi
local record=${bundle/\|/\\\|}
echo "${_ANTIGEN_BUNDLE_RECORD[(r)*$record*]}"
}
# Returns bundle names from _ANTIGEN_BUNDLE_RECORD
#
# Usage
# -antigen-get-bundles [--short|--simple|--long]
#
# Returns
# List of bundles installed
-antigen-get-bundles () {
local mode revision url bundle_name bundle_entry loc no_local_clone
local record bundle make_local_clone
mode=${1:-"--short"}
for record in $_ANTIGEN_BUNDLE_RECORD; do
bundle=(${(@s/ /)record})
url=$bundle[1]
loc=$bundle[2]
make_local_clone=$bundle[4]
bundle_name=$(-antigen-bundle-short-name $url)
case "$mode" in
--short)
# Only check revision for bundle with a requested branch
if [[ $url == *\|* ]]; then
revision=$(-antigen-bundle-rev $url $make_local_clone)
else
revision="master"
fi
if [[ $loc != '/' ]]; then
bundle_name="$bundle_name ~ $loc"
fi
echo "$bundle_name @ $revision"
;;
--simple)
echo "$bundle_name"
;;
--long)
echo "$record"
;;
esac
done
}
# Usage:
# -antigen-get-clone-dir "https://github.com/zsh-users/zsh-syntax-highlighting.git[|feature/branch]"
# Returns:
# $ANTIGEN_BUNDLES/zsh-users/zsh-syntax-highlighting[-feature-branch]
-antigen-get-clone-dir () {
local bundle="$1"
local url="${bundle%|*}"
local branch match mbegin mend MATCH MBEGIN MEND
[[ "$bundle" =~ "\|" ]] && branch="${bundle#*|}"
# Takes a repo url and mangles it, giving the path that this url will be
# cloned to. Doesn't actually clone anything.
local clone_dir="$ANTIGEN_BUNDLES"
url=$(-antigen-bundle-short-name $url)
# Suffix with branch/tag name
[[ -n "$branch" ]] && url="$url-${branch//\//-}"
url=${url//\*/x}
echo "$clone_dir/$url"
}
# Returns bundles flagged as make_local_clone
#
# Usage
# -antigen-cloned-bundles
#
# Returns
# Bundle metadata
-antigen-get-cloned-bundles() {
-antigen-echo-record |
awk '$4 == "true" {print $1}' |
sort -u
}
# Returns a list of themes from a default library (omz)
#
# Usage
# -antigen-get-themes
#
# Returns
# List of themes by name
-antigen-get-themes () {
local library='robbyrussell/oh-my-zsh'
local bundle=$(-antigen-find-bundle $library)
if [[ -n "$bundle" ]]; then
local dir=$(-antigen-get-clone-dir $ANTIGEN_DEFAULT_REPO_URL)
echo $(ls $dir/themes/ | grep '.zsh-theme$' | sed 's/.zsh-theme//')
fi
return 0
}
# This function check ZSH_EVAL_CONTEXT to determine if running in interactive shell.
#
# Usage
# -antigen-interactive-mode
#
# Returns
# Either true or false depending if we are running in interactive mode
-antigen-interactive-mode () {
WARN "-antigen-interactive-mode: $ZSH_EVAL_CONTEXT \$_ANTIGEN_INTERACTIVE = $_ANTIGEN_INTERACTIVE"
if [[ $_ANTIGEN_INTERACTIVE != "" ]]; then
[[ $_ANTIGEN_INTERACTIVE == true ]];
return
fi
[[ "$ZSH_EVAL_CONTEXT" == toplevel* || "$ZSH_EVAL_CONTEXT" == cmdarg* ]];
}
# Parses and retrieves a remote branch given a branch name.
#
# If the branch name contains '*' it will retrieve remote branches
# and try to match against tags and heads, returning the latest matching.
#
# Usage
# -antigen-parse-branch https://github.com/user/repo.git x.y.z
#
# Returns
# Branch name
-antigen-parse-branch () {
local url="$1" branch="$2" branches
local match mbegin mend MATCH MBEGIN MEND
if [[ "$branch" =~ '\*' ]]; then
branches=$(git ls-remote --tags -q "$url" "$branch"|cut -d'/' -f3|sort -n|tail -1)
# There is no --refs flag in git 1.8 and below, this way we
# emulate this flag -- also git 1.8 ref order is undefined.
branch=${${branches#*/*/}%^*} # Why you are like this?
fi
echo $branch
}
-antigen-update-repos () {
local repo bundle url target
local log=/tmp/antigen-v2-migrate.log
echo "It seems you have bundles cloned with Antigen v1.x."
echo "We'll try to convert directory structure to v2."
echo
echo -n "Moving bundles to '\$ADOTDIR/bundles'... "
# Migrate old repos -> bundles
local errors=0
for repo in $ADOTDIR/repos/*; do
bundle=${repo/$ADOTDIR\/repos\//}
bundle=${bundle//-SLASH-/\/}
bundle=${bundle//-COLON-/\:}
bundle=${bundle//-STAR-/\*}
url=${bundle//-PIPE-/\|}
target=$(-antigen-get-clone-dir $url)
mkdir -p "${target:A:h}"
echo " ---> ${repo/$ADOTDIR\/} -> ${target/$ADOTDIR\/}" | tee > $log
mv "$repo" "$target" &> $log
if [[ $? != 0 ]]; then
echo "Failed to migrate '$repo'!."
errors+=1
fi
done
if [[ $errors == 0 ]]; then
echo "Done."
else
echo "An error ocurred!"
fi
echo
if [[ "$(ls -A $ADOTDIR/repos | wc -l | xargs)" == 0 ]]; then
echo "You can safely remove \$ADOTDIR/repos."
else
echo "Some bundles couldn't be migrated. See \$ADOTDIR/repos."
fi
echo
if [[ $errors == 0 ]]; then
echo "Bundles migrated successfuly."
rm $log
else
echo "Some errors occured. Review migration log in '$log'."
fi
antigen-reset
}
# Ensure that a clone exists for the given repo url and branch. If the first
# argument is `update` and if a clone already exists for the given repo
# and branch, it is pull-ed, i.e., updated.
#
# This function expects three arguments in order:
# - 'url=<url>'
# - 'update=true|false'
# - 'verbose=true|false'
#
# Returns true|false Whether cloning/pulling was succesful
-antigen-ensure-repo () {
# Argument defaults. Previously using ${1:?"missing url argument"} format
# but it seems to mess up with cram
if (( $# < 1 )); then
echo "Antigen: Missing url argument."
return 1
fi
# The url. No sane default for this, so just empty.
local url=$1
# Check if we have to update.
local update=${2:-false}
# Verbose output.
local verbose=${3:-false}
shift $#
# Get the clone's directory as per the given repo url and branch.
local clone_dir=$(-antigen-get-clone-dir $url)
if [[ -d "$clone_dir" && $update == false ]]; then
return true
fi
# A temporary function wrapping the `git` command with repeated arguments.
--plugin-git () {
(\cd -q "$clone_dir" && eval ${ANTIGEN_CLONE_ENV} git --git-dir="$clone_dir/.git" --no-pager "$@" &>>! $ANTIGEN_LOG)
}
local success=false
# If its a specific branch that we want, checkout that branch.
local branch="master" # TODO FIX THIS
if [[ $url == *\|* ]]; then
branch="$(-antigen-parse-branch ${url%|*} ${url#*|})"
fi
if [[ ! -d $clone_dir ]]; then
eval ${ANTIGEN_CLONE_ENV} git clone ${=ANTIGEN_CLONE_OPTS} --branch "$branch" -- "${url%|*}" "$clone_dir" &>> $ANTIGEN_LOG
success=$?
elif $update; then
# Save current revision.
local old_rev="$(--plugin-git rev-parse HEAD)"
# Pull changes if update requested.
--plugin-git checkout "$branch"
--plugin-git pull origin "$branch"
success=$?
# Update submodules.
--plugin-git submodule update ${=ANTIGEN_SUBMODULE_OPTS}
# Get the new revision.
local new_rev="$(--plugin-git rev-parse HEAD)"
fi
if [[ -n $old_rev && $old_rev != $new_rev ]]; then
echo Updated from $old_rev[0,7] to $new_rev[0,7].
if $verbose; then
--plugin-git log --oneline --reverse --no-merges --stat '@{1}..'
fi
fi
# Remove the temporary git wrapper function.
unfunction -- --plugin-git
return $success
}
# Helper function: Same as `$1=$2`, but will only happen if the name
# specified by `$1` is not already set.
-antigen-set-default () {
local arg_name="$1"
local arg_value="$2"
eval "test -z \"\$$arg_name\" && typeset -g $arg_name='$arg_value'"
}
-antigen-env-setup () {
typeset -gU fpath path
# Pre-startup initializations.
-antigen-set-default ANTIGEN_OMZ_REPO_URL \
https://github.com/robbyrussell/oh-my-zsh.git
-antigen-set-default ANTIGEN_PREZTO_REPO_URL \
https://github.com/sorin-ionescu/prezto.git
-antigen-set-default ANTIGEN_DEFAULT_REPO_URL $ANTIGEN_OMZ_REPO_URL
# Default Antigen directory.
-antigen-set-default ADOTDIR $HOME/.antigen
[[ ! -d $ADOTDIR ]] && mkdir -p $ADOTDIR
# Defaults bundles directory.
-antigen-set-default ANTIGEN_BUNDLES $ADOTDIR/bundles
# If there is no bundles directory, create it.
if [[ ! -d $ANTIGEN_BUNDLES ]]; then
mkdir -p $ANTIGEN_BUNDLES
# Check for v1 repos directory, transform it to v2 format.
[[ -d $ADOTDIR/repos ]] && -antigen-update-repos
fi
-antigen-set-default ANTIGEN_COMPDUMP "${ADOTDIR:-$HOME}/.zcompdump"
-antigen-set-default ANTIGEN_LOG /dev/null
# CLONE_OPTS uses ${=CLONE_OPTS} expansion so don't use spaces
# for arguments that can be passed as `--key=value`.
-antigen-set-default ANTIGEN_CLONE_ENV "GIT_TERMINAL_PROMPT=0"
-antigen-set-default ANTIGEN_CLONE_OPTS "--single-branch --recursive --depth=1"
-antigen-set-default ANTIGEN_SUBMODULE_OPTS "--recursive --depth=1"
# Complain when a bundle is already installed.
-antigen-set-default _ANTIGEN_WARN_DUPLICATES true
# Compatibility with oh-my-zsh themes.
-antigen-set-default _ANTIGEN_THEME_COMPAT true
# Add default built-in extensions to load at start up
-antigen-set-default _ANTIGEN_BUILTIN_EXTENSIONS 'lock parallel defer cache'
# Setup antigen's own completion.
if -antigen-interactive-mode; then
TRACE "Gonna create compdump file @ env-setup" COMPDUMP
autoload -Uz compinit
compinit -d "$ANTIGEN_COMPDUMP"
compdef _antigen antigen
else
(( $+functions[antigen-ext-init] )) && antigen-ext-init
fi
}
# Load a given bundle by sourcing it.
#
# The function also modifies fpath to add the bundle path.
#
# Usage
# -antigen-load "bundle-url" ["location"] ["make_local_clone"] ["btype"]
#
# Returns
# Integer. 0 if success 1 if an error ocurred.
-antigen-load () {
local bundle list
typeset -A bundle; bundle=($@)
typeset -Ua list; list=()
local location="${bundle[dir]}/${bundle[loc]}"
# Prioritize location when given.
if [[ -f "${location}" ]]; then
list=(${location})
else
# Directory locations must be suffixed with slash
location="$location/"
# Prioritize theme with antigen-theme
if [[ ${bundle[btype]} == "theme" ]]; then
list=(${location}*.zsh-theme(N[1]))
fi
# Common frameworks
if [[ $#list == 0 ]]; then
# dot-plugin, init and functions support (omz, prezto)
# Support prezto function loading. See https://github.com/zsh-users/antigen/pull/428
list=(${location}*.plugin.zsh(N[1]) ${location}init.zsh(N[1]) ${location}/functions(N[1]))
fi
# Default to zsh and sh
if [[ $#list == 0 ]]; then
list=(${location}*.zsh(N) ${location}*.sh(N))
fi
fi
-antigen-load-env ${(kv)bundle}
# If there is any sourceable try to load it
if ! -antigen-load-source "${list[@]}" && [[ ! -d ${location} ]]; then
return 1
fi
return 0
}
-antigen-load-env () {
typeset -A bundle; bundle=($@)
local location=${bundle[dir]}/${bundle[loc]}
# Load to path if there is no sourceable
if [[ -d ${location} ]]; then
PATH="$PATH:${location:A}"
fpath+=("${location:A}")
return
fi
PATH="$PATH:${location:A:h}"
fpath+=("${location:A:h}")
}
-antigen-load-source () {
typeset -a list
list=($@)
local src match mbegin mend MATCH MBEGIN MEND
# Return error when we're given an empty list
if [[ $#list == 0 ]]; then
return 1
fi
# Using a for rather than `source $list` as we need to check for zsh-themes
# In order to create antigen-compat file. This is only needed for interactive-mode
# theme switching, for static loading (cache) there is no need.
for src in $list; do
if [[ $_ANTIGEN_THEME_COMPAT == true && -f "$src" && "$src" == *.zsh-theme* ]]; then
local compat="${src:A}.antigen-compat"
echo "# Generated by Antigen. Do not edit!" >! "$compat"
cat $src | sed -Ee '/\{$/,/^\}/!{
s/^local //
}' >>! "$compat"
src="$compat"
fi
if ! source "$src" 2>/dev/null; then
return 1
fi
done
}
# Usage:
# -antigen-parse-args output_assoc_arr <args...>
-antigen-parse-args () {
local argkey key value index=0 args
local match mbegin mend MATCH MBEGIN MEND
local var=$1
shift
# Bundle spec arguments' default values.
#setopt XTRACE VERBOSE
builtin typeset -A args
args[url]="$ANTIGEN_DEFAULT_REPO_URL"
#unsetopt XTRACE VERBOSE
args[loc]=/
args[make_local_clone]=true
args[btype]=plugin
#args[branch]= # commented out as it may cause assoc array kv mismatch
while [[ $# -gt 0 ]]; do
argkey="${1%\=*}"
key="${argkey//--/}"
value="${1#*=}"
case "$argkey" in
--url|--loc|--branch|--btype)
if [[ "$value" == "$argkey" ]]; then
printf "Required argument for '%s' not provided.\n" $key >&2
else
args[$key]="$value"
fi
;;
--no-local-clone)
args[make_local_clone]=false
;;
--*)
printf "Unknown argument '%s'.\n" $key >&2
;;
*)
value=$key
case $index in
0)
key=url
local domain=""
local url_path=$value
# Full url with protocol or ssh github url (github.com:org/repo)
if [[ "$value" =~ "://" || "$value" =~ ":" ]]; then
if [[ "$value" =~ [@.][^/:]+[:]?[0-9]*[:/]?(.*)@?$ ]]; then
url_path=$match[1]
domain=${value/$url_path/}
fi
fi
if [[ "$url_path" =~ '@' ]]; then
args[branch]="${url_path#*@}"
value="$domain${url_path%@*}"
else
value="$domain$url_path"
fi
;;
1) key=loc ;;
esac
let index+=1
args[$key]="$value"
;;
esac
shift
done
# Check if url is just the plugin name. Super short syntax.
if [[ "${args[url]}" != */* ]]; then
case "$ANTIGEN_DEFAULT_REPO_URL" in
"$ANTIGEN_OMZ_REPO_URL")
args[loc]="plugins/${args[url]}"
;;
"$ANTIGEN_PREZTO_REPO_URL")
args[loc]="modules/${args[url]}"
;;
*)
args[loc]="${args[url]}"
;;
esac
args[url]="$ANTIGEN_DEFAULT_REPO_URL"
fi
# Resolve the url.
# Expand short github url syntax: `username/reponame`.
local url="${args[url]}"
if [[ $url != git://* &&
$url != https://* &&
$url != http://* &&
$url != ssh://* &&
$url != /* &&
$url != *github.com:*/*
]]; then
url="https://github.com/${url%.git}.git"
fi
args[url]="$url"
# Ignore local clone if url given is not a git directory
if [[ ${args[url]} == /* && ! -d ${args[url]}/.git ]]; then
args[make_local_clone]=false
fi
# Add the branch information to the url if we need to create a local clone.
# Format url in bundle-metadata format: url[|branch]
if [[ ! -z "${args[branch]}" && ${args[make_local_clone]} == true ]]; then
args[url]="${args[url]}|${args[branch]}"
fi
# Add the theme extension to `loc`, if this is a theme, but only
# if it's especified, ie, --loc=theme-name, in case when it's not
# specified antige-load-list will look for *.zsh-theme files
if [[ ${args[btype]} == "theme" &&
${args[loc]} != "/" && ${args[loc]} != *.zsh-theme ]]; then
args[loc]="${args[loc]}.zsh-theme"
fi
local name="${args[url]%|*}"
local branch="${args[branch]}"
# Extract bundle name.
if [[ "$name" =~ '.*/(.*/.*).*$' ]]; then
name="${match[1]}"
fi
name="${name%.git*}"
# Format bundle name with optional branch.
if [[ -n "${branch}" ]]; then
args[name]="${name}@${branch}"
else
args[name]="${name}"
fi
# Format bundle path.
if [[ ${args[make_local_clone]} == true ]]; then
local bpath="$name"
# Suffix with branch/tag name
if [[ -n "$branch" ]]; then
# bpath is in the form of repo/name@version => repo/name-version
# Replace / with - in bundle branch.
local bbranch=${branch//\//-}
# If branch/tag is semver-like do replace * by x.
bbranch=${bbranch//\*/x}
bpath="${name}-${bbranch}"
fi
bpath="$ANTIGEN_BUNDLES/$bpath"
args[dir]="${(qq)bpath}"
else
# if it's local then path is just the "url" argument, loc remains the same
args[dir]=${args[url]}
fi
# Escape url and branch (may contain semver-like and pipe characters)
args[url]="${(qq)args[url]}"
if [[ -n "${args[branch]}" ]]; then
args[branch]="${(qq)args[branch]}"
fi
# Escape bundle name (may contain semver-like characters)
args[name]="${(qq)args[name]}"
eval "${var}=(${(kv)args})"
return 0
}
# Updates revert-info data with git hash.
#
# This does process only cloned bundles.
#
# Usage
# -antigen-revert-info
#
# Returns
# Nothing. Generates/updates $ADOTDIR/revert-info.
-antigen-revert-info() {
local url
# Update your bundles, i.e., `git pull` in all the plugin repos.
date >! $ADOTDIR/revert-info
-antigen-get-cloned-bundles | while read url; do
local clone_dir="$(-antigen-get-clone-dir "$url")"
if [[ -d "$clone_dir" ]]; then
(echo -n "$clone_dir:"
\cd -q "$clone_dir"
git rev-parse HEAD) >> $ADOTDIR/revert-info
fi
done
}
-antigen-use-oh-my-zsh () {
typeset -g ZSH ZSH_CACHE_DIR
ANTIGEN_DEFAULT_REPO_URL=$ANTIGEN_OMZ_REPO_URL
if [[ -z "$ZSH" ]]; then
ZSH="$(-antigen-get-clone-dir "$ANTIGEN_DEFAULT_REPO_URL")"
fi
if [[ -z "$ZSH_CACHE_DIR" ]]; then
ZSH_CACHE_DIR="$ZSH/cache/"
fi
antigen-bundle --loc=lib
}
-antigen-use-prezto () {
ANTIGEN_DEFAULT_REPO_URL=$ANTIGEN_PREZTO_REPO_URL
antigen-bundle "$ANTIGEN_PREZTO_REPO_URL"
}
# Initialize completion
antigen-apply () {
LOG "Called antigen-apply"
# Load the compinit module. This will readefine the `compdef` function to
# the one that actually initializes completions.
TRACE "Gonna create compdump file @ apply" COMPDUMP
autoload -Uz compinit
compinit -d "$ANTIGEN_COMPDUMP"
# Apply all `compinit`s that have been deferred.
local cdef
for cdef in "${__deferred_compdefs[@]}"; do
compdef "$cdef"
done
{ zcompile "$ANTIGEN_COMPDUMP" } &!
unset __deferred_compdefs
}
# Syntaxes
# antigen-bundle <url> [<loc>=/]
# Keyword only arguments:
# branch - The branch of the repo to use for this bundle.
antigen-bundle () {
TRACE "Called antigen-bundle with $@" BUNDLE
if [[ -z "$1" ]]; then
printf "Antigen: Must provide a bundle url or name.\n" >&2
return 1
fi
builtin typeset -A bundle; -antigen-parse-args 'bundle' ${=@}
if [[ -z ${bundle[btype]} ]]; then
bundle[btype]=bundle
fi
local record="${bundle[url]} ${bundle[loc]} ${bundle[btype]} ${bundle[make_local_clone]}"
if [[ $_ANTIGEN_WARN_DUPLICATES == true && ! ${_ANTIGEN_BUNDLE_RECORD[(I)$record]} == 0 ]]; then
printf "Seems %s is already installed!\n" ${bundle[name]}
return 1
fi
# Clone bundle if we haven't done do already.
if [[ ! -d "${bundle[dir]}" ]]; then
if ! -antigen-bundle-install ${(kv)bundle}; then
return 1
fi
fi
# Load the plugin.
if ! -antigen-load ${(kv)bundle}; then
TRACE "-antigen-load failed to load ${bundle[name]}" BUNDLE
printf "Antigen: Failed to load %s.\n" ${bundle[btype]} >&2
return 1
fi
# Only add it to the record if it could be installed and loaded.
_ANTIGEN_BUNDLE_RECORD+=("$record")
}
#
# Usage:
# -antigen-bundle-install <record>
# Returns:
# 1 if it fails to install bundle
-antigen-bundle-install () {
typeset -A bundle; bundle=($@)
# Ensure a clone exists for this repo, if needed.
# Get the clone's directory as per the given repo url and branch.
local bpath="${bundle[dir]}"
# Clone if it doesn't already exist.
local start=$(date +'%s')
printf "Installing %s... " "${bundle[name]}"
if ! -antigen-ensure-repo "${bundle[url]}"; then
# Return immediately if there is an error cloning
TRACE "-antigen-bundle-instal failed to clone ${bundle[url]}" BUNDLE
printf "Error! Activate logging and try again.\n" >&2
return 1
fi
local took=$(( $(date +'%s') - $start ))
printf "Done. Took %ds.\n" $took
}
antigen-bundles () {
# Bulk add many bundles at one go. Empty lines and lines starting with a `#`
# are ignored. Everything else is given to `antigen-bundle` as is, no
# quoting rules applied.
local line
setopt localoptions no_extended_glob # See https://github.com/zsh-users/antigen/issues/456
grep '^[[:space:]]*[^[:space:]#]' | while read line; do
antigen-bundle ${=line%#*}
done
}
# Cleanup unused repositories.
antigen-cleanup () {
local force=false
if [[ $1 == --force ]]; then
force=true
fi
if [[ ! -d "$ANTIGEN_BUNDLES" || -z "$(\ls -A "$ANTIGEN_BUNDLES")" ]]; then
echo "You don't have any bundles."
return 0
fi
# Find directores in ANTIGEN_BUNDLES, that are not in the bundles record.
typeset -a unused_clones clones
local url record clone
for record in $(-antigen-get-cloned-bundles); do
url=${record% /*}
clones+=("$(-antigen-get-clone-dir $url)")
done
for clone in $ANTIGEN_BUNDLES/*/*(/); do
if [[ $clones[(I)$clone] == 0 ]]; then
unused_clones+=($clone)
fi
done
if [[ -z $unused_clones ]]; then
echo "You don't have any unidentified bundles."
return 0
fi
echo 'You have clones for the following repos, but are not used.'
echo "\n${(j:\n:)unused_clones}"
if $force || (echo -n '\nDelete them all? [y/N] '; read -q); then
echo
echo
for clone in $unused_clones; do
echo -n "Deleting clone \"$clone\"..."
\rm -rf "$clone"
echo ' done.'
done
else
echo
echo "Nothing deleted."
fi
}
antigen-help () {
antigen-version
cat <<EOF
Antigen is a plugin management system for zsh. It makes it easy to grab awesome
shell scripts and utilities, put up on Github.
Usage: antigen <command> [args]
Commands:
apply Must be called in the zshrc after all calls to 'antigen bundle'.
bundle Install and load a plugin.
cache-gen Generate Antigen's cache with currently loaded bundles.
cleanup Remove clones of repos not used by any loaded plugins.
init Use caching to quickly load bundles.
list List currently loaded plugins.
purge Remove a bundle from the filesystem.
reset Clean the generated cache.
restore Restore plugin state from a snapshot file.
revert Revert plugins to their state prior to the last time 'antigen
update' was run.
selfupdate Update antigen.
snapshot Create a snapshot of all active plugin repos and save it to a
snapshot file.
update Update plugins.
use Load a supported zsh pre-packaged framework.
For further details and complete documentation, visit the project's page at
'http://antigen.sharats.me'.
EOF
}
# Antigen command to load antigen configuration
#
# This method is slighlty more performing than using various antigen-* methods.
#
# Usage
# Referencing an antigen configuration file:
#
# antigen-init "/path/to/antigenrc"
#
# or using HEREDOCS:
#
# antigen-init <<EOBUNDLES
# antigen use oh-my-zsh
#
# antigen bundle zsh/bundle
# antigen bundle zsh/example
#
# antigen theme zsh/theme
#
# antigen apply
# EOBUNDLES
#
# Returns
# Nothing
antigen-init () {
local src="$1" line
# If we're given an argument it should be a path to a file
if [[ -n "$src" ]]; then
if [[ -f "$src" ]]; then
source "$src"
return
else
printf "Antigen: invalid argument provided.\n" >&2
return 1
fi
fi
# Otherwise we expect it to be a heredoc
grep '^[[:space:]]*[^[:space:]#]' | while read -r line; do
eval $line
done
}
# List instaled bundles either in long (record), short or simple format.
#
# Usage
# antigen-list [--short|--long|--simple]
#
# Returns
# List of bundles
antigen-list () {
local format=$1
# List all currently installed bundles.
if [[ -z $_ANTIGEN_BUNDLE_RECORD ]]; then
echo "You don't have any bundles." >&2
return 1
fi
-antigen-get-bundles $format
}
# Remove a bundle from filesystem
#
# Usage
# antigen-purge example/bundle [--force]
#
# Returns
# Nothing. Removes bundle from filesystem.
antigen-purge () {
local bundle=$1
local force=$2
if [[ $# -eq 0 ]]; then
echo "Antigen: Missing argument." >&2
return 1
fi
if -antigen-purge-bundle $bundle $force; then
antigen-reset
else
return $?
fi
return 0
}
# Remove a bundle from filesystem
#
# Usage
# antigen-purge example/bundle [--force]
#
# Returns
# Nothing. Removes bundle from filesystem.
-antigen-purge-bundle () {
local bundle=$1
local force=$2
local clone_dir=""
local record=""
local url=""
local make_local_clone=""
if [[ $# -eq 0 ]]; then
echo "Antigen: Missing argument." >&2
return 1
fi
# local keyword doesn't work on zsh <= 5.0.0
record=$(-antigen-find-record $bundle)
if [[ ! -n "$record" ]]; then
echo "Bundle not found in record. Try 'antigen bundle $bundle' first." >&2
return 1
fi
url="$(echo "$record" | cut -d' ' -f1)"
make_local_clone=$(echo "$record" | cut -d' ' -f4)
if [[ $make_local_clone == "false" ]]; then
echo "Bundle has no local clone. Will not be removed." >&2
return 1
fi
clone_dir=$(-antigen-get-clone-dir "$url")
if [[ $force == "--force" ]] || read -q "?Remove '$clone_dir'? (y/n) "; then
# Need empty line after read -q
[[ ! -n $force ]] && echo "" || echo "Removing '$clone_dir'.";
rm -rf "$clone_dir"
return $?
fi
return 1
}
# Removes cache payload and metadata if available
#
# Usage
# antigen-reset
#
# Returns
# Nothing
antigen-reset () {
[[ -f "$ANTIGEN_CACHE" ]] && rm -f "$ANTIGEN_CACHE" "$ANTIGEN_CACHE.zwc" 1> /dev/null
[[ -f "$ANTIGEN_RSRC" ]] && rm -f "$ANTIGEN_RSRC" 1> /dev/null
[[ -f "$ANTIGEN_COMPDUMP" ]] && rm -f "$ANTIGEN_COMPDUMP" "$ANTIGEN_COMPDUMP.zwc" 1> /dev/null
[[ -f "$ANTIGEN_LOCK" ]] && rm -f "$ANTIGEN_LOCK" 1> /dev/null
echo 'Done. Please open a new shell to see the changes.'
}
antigen-restore () {
local line
if [[ $# == 0 ]]; then
echo 'Please provide a snapshot file to restore from.' >&2
return 1
fi
local snapshot_file="$1"
# TODO: Before doing anything with the snapshot file, verify its checksum.
# If it fails, notify this to the user and confirm if restore should
# proceed.
echo -n "Restoring from $snapshot_file..."
sed -n '1!p' "$snapshot_file" |
while read line; do
local version_hash="${line%% *}"
local url="${line##* }"
local clone_dir="$(-antigen-get-clone-dir "$url")"
if [[ ! -d $clone_dir ]]; then
git clone "$url" "$clone_dir" &> /dev/null
fi
(\cd -q "$clone_dir" && git checkout $version_hash) &> /dev/null
done
echo ' done.'
echo 'Please open a new shell to get the restored changes.'
}
# Reads $ADORDIR/revert-info and restores bundles' revision
antigen-revert () {
local line
if [[ -f $ADOTDIR/revert-info ]]; then
cat $ADOTDIR/revert-info | sed -n '1!p' | while read line; do
local dir="$(echo "$line" | cut -d: -f1)"
git --git-dir="$dir/.git" --work-tree="$dir" \
checkout "$(echo "$line" | cut -d: -f2)" 2> /dev/null
done
echo "Reverted to state before running -update on $(
cat $ADOTDIR/revert-info | sed -n '1p')."
else
echo 'No revert information available. Cannot revert.' >&2
return 1
fi
}
# Update (with `git pull`) antigen itself.
# TODO: Once update is finished, show a summary of the new commits, as a kind of
# "what's new" message.
antigen-selfupdate () {
(\cd -q $_ANTIGEN_INSTALL_DIR
if [[ ! ( -d .git || -f .git ) ]]; then
echo "Your copy of antigen doesn't appear to be a git clone. " \
"The 'selfupdate' command cannot work in this case."
return 1
fi
local head="$(git rev-parse --abbrev-ref HEAD)"
if [[ $head == "HEAD" ]]; then
# If current head is detached HEAD, checkout to master branch.
git checkout master
fi
git pull
# TODO Should be transparently hooked by zcache
antigen-reset &>> /dev/null
)
}
antigen-snapshot () {
local snapshot_file="${1:-antigen-shapshot}"
local urls url dir version_hash snapshot_content
local -a bundles
# The snapshot content lines are pairs of repo-url and git version hash, in
# the form:
# <version-hash> <repo-url>
urls=$(-antigen-echo-record | awk '$4 == "true" {print $1}' | sort -u)
for url in ${(f)urls}; do
dir="$(-antigen-get-clone-dir "$url")"
version_hash="$(\cd -q "$dir" && git rev-parse HEAD)"
bundles+=("$version_hash $url");
done
snapshot_content=${(j:\n:)bundles}
{
# The first line in the snapshot file is for metadata, in the form:
# key='value'; key='value'; key='value';
# Where `key`s are valid shell variable names.
# Snapshot version. Has no relation to antigen version. If the snapshot
# file format changes, this number can be incremented.
echo -n "version='1';"
# Snapshot creation date+time.
echo -n " created_on='$(date)';"
# Add a checksum with the md5 checksum of all the snapshot lines.
chksum() { (md5sum; test $? = 127 && md5) 2>/dev/null | cut -d' ' -f1 }
local checksum="$(echo "$snapshot_content" | chksum)"
unset -f chksum;
echo -n " checksum='${checksum%% *}';"
# A newline after the metadata and then the snapshot lines.
echo "\n$snapshot_content"
} > "$snapshot_file"
}
# Loads a given theme.
#
# Shares the same syntax as antigen-bundle command.
#
# Usage
# antigen-theme zsh/theme[.zsh-theme]
#
# Returns
# 0 if everything was succesfully
antigen-theme () {
local name=$1 result=0 record
local match mbegin mend MATCH MBEGIN MEND
if [[ -z "$1" ]]; then
printf "Antigen: Must provide a theme url or name.\n" >&2
return 1
fi
-antigen-theme-reset-hooks
record=$(-antigen-find-record "theme")
if [[ "$1" != */* && "$1" != --* ]]; then
# The first argument is just a name of the plugin, to be picked up from
# the default repo.
antigen-bundle --loc=themes/$name --btype=theme
else
antigen-bundle "$@" --btype=theme
fi
result=$?
# Remove a theme from the record if the following conditions apply:
# - there was no error in bundling the given theme
# - there is a theme registered
# - registered theme is not the same as the current one
if [[ $result == 0 && -n $record ]]; then
# http://zsh-workers.zsh.narkive.com/QwfCWpW8/what-s-wrong-with-this-expression
if [[ "$record" =~ "$@" ]]; then
return $result
else
_ANTIGEN_BUNDLE_RECORD[$_ANTIGEN_BUNDLE_RECORD[(I)$record]]=()
fi
fi
return $result
}
-antigen-theme-reset-hooks () {
# This is only needed on interactive mode
autoload -U add-zsh-hook is-at-least
local hook
# Clear out prompts
PROMPT=""
if [[ -n $RPROMPT ]]; then
RPROMPT=""
fi
for hook in chpwd precmd preexec periodic; do
add-zsh-hook -D "${hook}" "prompt_*"
# common in omz themes
add-zsh-hook -D "${hook}" "*_${hook}"
add-zsh-hook -d "${hook}" "vcs_info"
done
}
# Updates the bundles or a single bundle.
#
# Usage
# antigen-update [example/bundle]
#
# Returns
# Nothing. Performs a `git pull`.
antigen-update () {
local bundle=$1 url
# Clear log
:> $ANTIGEN_LOG
# Update revert-info data
-antigen-revert-info
# If no argument is given we update all bundles
if [[ $# -eq 0 ]]; then
# Here we're ignoring all non cloned bundles (ie, --no-local-clone)
-antigen-get-cloned-bundles | while read url; do
-antigen-update-bundle $url
done
# TODO next minor version
# antigen-reset
else
if -antigen-update-bundle $bundle; then
# TODO next minor version
# antigen-reset
else
return $?
fi
fi
}
# Updates a bundle performing a `git pull`.
#
# Usage
# -antigen-update-bundle example/bundle
#
# Returns
# Nothing. Performs a `git pull`.
-antigen-update-bundle () {
local bundle="$1"
local record=""
local url=""
local make_local_clone=""
local start=$(date +'%s')
if [[ $# -eq 0 ]]; then
printf "Antigen: Missing argument.\n" >&2
return 1
fi
record=$(-antigen-find-record $bundle)
if [[ ! -n "$record" ]]; then
printf "Bundle not found in record. Try 'antigen bundle %s' first.\n" $bundle >&2
return 1
fi
url="$(echo "$record" | cut -d' ' -f1)"
make_local_clone=$(echo "$record" | cut -d' ' -f4)
local branch="master"
if [[ $url == *\|* ]]; then
branch="$(-antigen-parse-branch ${url%|*} ${url#*|})"
fi
printf "Updating %s... " $(-antigen-bundle-short-name "$url" "$branch")
if [[ $make_local_clone == "false" ]]; then
printf "Bundle has no local clone. Will not be updated.\n" >&2
return 1
fi
# update=true verbose=false
if ! -antigen-ensure-repo "$url" true false; then
printf "Error! Activate logging and try again.\n" >&2
return 1
fi
local took=$(( $(date +'%s') - $start ))
printf "Done. Took %ds.\n" $took
}
antigen-use () {
if [[ $1 == oh-my-zsh ]]; then
-antigen-use-oh-my-zsh
elif [[ $1 == prezto ]]; then
-antigen-use-prezto
elif [[ $1 != "" ]]; then
ANTIGEN_DEFAULT_REPO_URL=$1
antigen-bundle $@
else
echo 'Usage: antigen-use <library-name|url>' >&2
echo 'Where <library-name> is any one of the following:' >&2
echo ' * oh-my-zsh' >&2
echo ' * prezto' >&2
echo '<url> is the full url.' >&2
return 1
fi
}
antigen-version () {
local version="v2.2.2"
local extensions revision=""
if [[ -d $_ANTIGEN_INSTALL_DIR/.git ]]; then
revision=" ($(git --git-dir=$_ANTIGEN_INSTALL_DIR/.git rev-parse --short '@'))"
fi
printf "Antigen %s%s\n" $version $revision
if (( $+functions[antigen-ext] )); then
typeset -a extensions; extensions=($(antigen-ext-list))
if [[ $#extensions -gt 0 ]]; then
printf "Extensions loaded: %s\n" ${(j:, :)extensions}
fi
fi
}
typeset -Ag _ANTIGEN_HOOKS; _ANTIGEN_HOOKS=()
typeset -Ag _ANTIGEN_HOOKS_META; _ANTIGEN_HOOKS_META=()
typeset -g _ANTIGEN_HOOK_PREFIX="-antigen-hook-"
typeset -g _ANTIGEN_EXTENSIONS; _ANTIGEN_EXTENSIONS=()
# -antigen-add-hook antigen-apply antigen-apply-hook replace
# - Replaces hooked function with hook, do not call hooked function
# - Return -1 to stop calling further hooks
# -antigen-add-hook antigen-apply antigen-apply-hook pre (pre-call)
# - By default it will call hooked function
# -antigen-add-hook antigen-pply antigen-apply-hook post (post-call)
# - Calls antigen-apply and then calls hook function
# Usage:
# -antigen-add-hook antigen-apply antigen-apply-hook ["replace"|"pre"|"post"] ["once"|"repeat"]
antigen-add-hook () {
local target="$1" hook="$2" type="$3" mode="${4:-repeat}"
if (( ! $+functions[$target] )); then
printf "Antigen: Function %s doesn't exist.\n" $target
return 1
fi
if (( ! $+functions[$hook] )); then
printf "Antigen: Function %s doesn't exist.\n" $hook
return 1
fi
if [[ "${_ANTIGEN_HOOKS[$target]}" == "" ]]; then
_ANTIGEN_HOOKS[$target]="${hook}"
else
_ANTIGEN_HOOKS[$target]="${_ANTIGEN_HOOKS[$target]}:${hook}"
fi
_ANTIGEN_HOOKS_META[$hook]="target $target type $type mode $mode called 0"
# Do shadow for this function if there is none already
local hook_function="${_ANTIGEN_HOOK_PREFIX}$target"
if (( ! $+functions[$hook_function] )); then
# Preserve hooked function
eval "function ${_ANTIGEN_HOOK_PREFIX}$(functions -- $target)"
# Create hook, call hook-handler to further process hook functions
eval "function $target () {
noglob -antigen-hook-handler $target \$@
return \$?
}"
fi
return 0
}
# Private function to handle multiple hooks in a central point.
-antigen-hook-handler () {
local target="$1" args hook called
local hooks meta
shift
typeset -a args; args=(${@})
typeset -a pre_hooks replace_hooks post_hooks;
typeset -a hooks; hooks=(${(s|:|)_ANTIGEN_HOOKS[$target]})
typeset -A meta;
for hook in $hooks; do
meta=(${(s: :)_ANTIGEN_HOOKS_META[$hook]})
if [[ ${meta[mode]} == "once" && ${meta[called]} == 1 ]]; then
WARN "Ignoring hook due to mode ${meta[mode]}: $hook"
continue
fi
let called=${meta[called]}+1
meta[called]=$called
_ANTIGEN_HOOKS_META[$hook]="${(kv)meta}"
WARN "Updated meta: "${(kv)meta}
case "${meta[type]}" in
"pre")
pre_hooks+=($hook)
;;
"replace")
replace_hooks+=($hook)
;;
"post")
post_hooks+=($hook)
;;
esac
done
WARN "Processing hooks: ${hooks}"
for hook in $pre_hooks; do
WARN "Pre hook:" $hook $args
noglob $hook $args
[[ $? == -1 ]] && WARN "$hook shortcircuited" && return $ret
done
# A replace hook will return inmediately
local replace_hook=0 ret=0
for hook in $replace_hooks; do
replace_hook=1
# Should not be needed if `antigen-remove-hook` removed unneeded hooks.
if (( $+functions[$hook] )); then
WARN "Replace hook:" $hook $args
noglob $hook $args
[[ $? == -1 ]] && WARN "$hook shortcircuited" && return $ret
fi
done
if [[ $replace_hook == 0 ]]; then
WARN "${_ANTIGEN_HOOK_PREFIX}$target $args"
noglob ${_ANTIGEN_HOOK_PREFIX}$target $args
ret=$?
else
WARN "Replaced hooked function."
fi
for hook in $post_hooks; do
WARN "Post hook:" $hook $args
noglob $hook $args
[[ $? == -1 ]] && WARN "$hook shortcircuited" && return $ret
done
LOG "Return from hook ${target} with ${ret}"
return $ret
}
# Usage:
# -antigen-remove-hook antigen-apply-hook
antigen-remove-hook () {
local hook="$1"
typeset -A meta; meta=(${(s: :)_ANTIGEN_HOOKS_META[$hook]})
local target="${meta[target]}"
local -a hooks; hooks=(${(s|:|)_ANTIGEN_HOOKS[$target]})
# Remove registered hook
if [[ $#hooks > 0 ]]; then
hooks[$hooks[(I)$hook]]=()
fi
_ANTIGEN_HOOKS[${target}]="${(j|:|)hooks}"
if [[ $#hooks == 0 ]]; then
# Destroy base hook
eval "function $(functions -- ${_ANTIGEN_HOOK_PREFIX}$target | sed s/${_ANTIGEN_HOOK_PREFIX}//)"
if (( $+functions[${_ANTIGEN_HOOK_PREFIX}$target] )); then
unfunction -- "${_ANTIGEN_HOOK_PREFIX}$target"
fi
fi
unfunction -- $hook 2> /dev/null
}
# Remove all defined hooks.
-antigen-reset-hooks () {
local target
for target in ${(k)_ANTIGEN_HOOKS}; do
# Release all hooked functions
eval "function $(functions -- ${_ANTIGEN_HOOK_PREFIX}$target | sed s/${_ANTIGEN_HOOK_PREFIX}//)"
unfunction -- "${_ANTIGEN_HOOK_PREFIX}$target" 2> /dev/null
done
_ANTIGEN_HOOKS=()
_ANTIGEN_HOOKS_META=()
_ANTIGEN_EXTENSIONS=()
}
# Initializes an extension
# Usage:
# antigen-ext ext-name
antigen-ext () {
local ext=$1
local func="-antigen-$ext-init"
if (( $+functions[$func] && $_ANTIGEN_EXTENSIONS[(I)$ext] == 0 )); then
eval $func
local ret=$?
WARN "$func return code was $ret"
if (( $ret == 0 )); then
LOG "LOADED EXTENSION $ext" EXT
-antigen-$ext-execute && _ANTIGEN_EXTENSIONS+=($ext)
else
WARN "IGNORING EXTENSION $func" EXT
return 1
fi
else
printf "Antigen: No extension defined or already loaded: %s\n" $func >&2
return 1
fi
}
# List installed extensions
# Usage:
# antigen ext-list
antigen-ext-list () {
echo $_ANTIGEN_EXTENSIONS
}
# Initializes built-in extensions
# Usage:
# antigen-ext-init
antigen-ext-init () {
# Initialize extensions. unless in interactive mode.
local ext
for ext in ${(s/ /)_ANTIGEN_BUILTIN_EXTENSIONS}; do
# Check if extension is loaded before intializing it
(( $+functions[-antigen-$ext-init] )) && antigen-ext $ext
done
}
# Initialize defer lib
-antigen-defer-init () {
typeset -ga _DEFERRED_BUNDLE; _DEFERRED_BUNDLE=()
if -antigen-interactive-mode; then
return 1
fi
}
-antigen-defer-execute () {
# Hooks antigen-bundle in order to defer its execution.
antigen-bundle-defer () {
_DEFERRED_BUNDLE+=("${(j: :)${@}}")
return -1 # Stop right there
}
antigen-add-hook antigen-bundle antigen-bundle-defer replace
# Hooks antigen-apply in order to release hooked functions
antigen-apply-defer () {
WARN "Defer pre-apply" DEFER PRE-APPLY
antigen-remove-hook antigen-bundle-defer
# Process all deferred bundles.
local bundle
for bundle in ${_DEFERRED_BUNDLE[@]}; do
LOG "Processing deferred bundle: ${bundle}" DEFER
antigen-bundle $bundle
done
unset _DEFERRED_BUNDLE
}
antigen-add-hook antigen-apply antigen-apply-defer pre once
}
# Initialize lock lib
-antigen-lock-init () {
# Default lock path.
-antigen-set-default ANTIGEN_LOCK $ADOTDIR/.lock
typeset -g _ANTIGEN_LOCK_PROCESS=false
# Use env variable to determine if we should load this extension
-antigen-set-default ANTIGEN_MUTEX true
# Set ANTIGEN_MUTEX to false to avoid loading this extension
if [[ $ANTIGEN_MUTEX == true ]]; then
return 0;
fi
# Do not use mutex
return 1;
}
-antigen-lock-execute () {
# Hook antigen command in order to check/create a lock file.
# This hook is only run once then releases itself.
antigen-lock () {
LOG "antigen-lock called"
# If there is a lock set up then we won't process anything.
if [[ -f $ANTIGEN_LOCK ]]; then
# Set up flag do the message is not repeated for each antigen-* command
[[ $_ANTIGEN_LOCK_PROCESS == false ]] && printf "Antigen: Another process in running.\n"
_ANTIGEN_LOCK_PROCESS=true
# Do not further process hooks. For this hook to properly work it
# should be registered first.
return -1
fi
WARN "Creating antigen-lock file at $ANTIGEN_LOCK"
touch $ANTIGEN_LOCK
}
antigen-add-hook antigen antigen-lock pre once
# Hook antigen-apply in order to release .lock file.
antigen-apply-lock () {
WARN "Freeing antigen-lock file at $ANTIGEN_LOCK"
unset _ANTIGEN_LOCK_PROCESS
rm -f $ANTIGEN_LOCK &> /dev/null
}
antigen-add-hook antigen-apply antigen-apply-lock post once
}
# Initialize parallel lib
-antigen-parallel-init () {
WARN "Init parallel extension" PARALLEL
typeset -ga _PARALLEL_BUNDLE; _PARALLEL_BUNDLE=()
if -antigen-interactive-mode; then
return 1
fi
}
-antigen-parallel-execute() {
WARN "Exec parallel extension" PARALLEL
# Install bundles in parallel
antigen-bundle-parallel-execute () {
WARN "Parallel antigen-bundle-parallel-execute" PARALLEL
typeset -a pids; pids=()
local args pid
WARN "Gonna install in parallel ${#_PARALLEL_BUNDLE} bundles." PARALLEL
# Do ensure-repo in parallel
WARN "${_PARALLEL_BUNDLE}" PARALLEL
typeset -Ua repositories # Used to keep track of cloned repositories to avoid
# trying to clone it multiple times.
for args in ${_PARALLEL_BUNDLE}; do
typeset -A bundle; -antigen-parse-args 'bundle' ${=args}
if [[ ! -d ${bundle[dir]} && $repositories[(I)${bundle[url]}] == 0 ]]; then
WARN "Install in parallel ${bundle[name]}." PARALLEL
echo "Installing ${bundle[name]}!..."
# $bundle[url]'s format is "url|branch" as to create "$ANTIGEN_BUNDLES/bundle/name-branch",
# this way you may require multiple branches from the same repository.
-antigen-ensure-repo "${bundle[url]}" > /dev/null &!
pids+=($!)
else
WARN "Bundle ${bundle[name]} already cloned locally." PARALLEL
fi
repositories+=(${bundle[url]})
done
# Wait for all background processes to end
while [[ $#pids > 0 ]]; do
for pid in $pids; do
# `ps` may diplay an error message such "Signal 18 (CONT) caught by ps
# (procps-ng version 3.3.9).", see https://bugs.debian.org/cgi-bin/bugreport.cgi?bug=732410
if [[ $(ps -o pid= -p $pid 2>/dev/null) == "" ]]; then
pids[$pids[(I)$pid]]=()
fi
done
sleep .5
done
builtin local bundle &> /dev/null
for bundle in ${_PARALLEL_BUNDLE[@]}; do
antigen-bundle $bundle
done
WARN "Parallel install done" PARALLEL
}
# Hooks antigen-apply in order to release hooked functions
antigen-apply-parallel () {
WARN "Parallel pre-apply" PARALLEL PRE-APPLY
#antigen-remove-hook antigen-pre-apply-parallel
# Hooks antigen-bundle in order to parallel its execution.
antigen-bundle-parallel () {
TRACE "antigen-bundle-parallel: $@" PARALLEL
_PARALLEL_BUNDLE+=("${(j: :)${@}}")
}
antigen-add-hook antigen-bundle antigen-bundle-parallel replace
}
antigen-add-hook antigen-apply antigen-apply-parallel pre once
antigen-apply-parallel-execute () {
WARN "Parallel replace-apply" PARALLEL REPLACE-APPLY
antigen-remove-hook antigen-bundle-parallel
# Process all parallel bundles.
antigen-bundle-parallel-execute
unset _PARALLEL_BUNDLE
antigen-remove-hook antigen-apply-parallel-execute
antigen-apply
}
antigen-add-hook antigen-apply antigen-apply-parallel-execute replace once
}
typeset -ga _ZCACHE_BUNDLE_SOURCE _ZCACHE_CAPTURE_BUNDLE
typeset -g _ZCACHE_CAPTURE_PREFIX
# Generates cache from listed bundles.
#
# Iterates over _ANTIGEN_BUNDLE_RECORD and join all needed sources into one,
# if this is done through -antigen-load-list.
# Result is stored in ANTIGEN_CACHE.
#
# _ANTIGEN_BUNDLE_RECORD and fpath is stored in cache.
#
# Usage
# -zcache-generate-cache
#
# Returns
# Nothing. Generates ANTIGEN_CACHE
-antigen-cache-generate () {
local -aU _fpath _PATH _sources
local record
LOG "Gonna generate cache for $_ZCACHE_BUNDLE_SOURCE"
for record in $_ZCACHE_BUNDLE_SOURCE; do
record=${record:A}
# LOG "Caching $record"
if [[ -f $record ]]; then
# Adding $'\n' as a suffix as j:\n: doesn't work inside a heredoc.
if [[ $_ANTIGEN_THEME_COMPAT == true && "$record" == *.zsh-theme* ]]; then
local compat="${record:A}.antigen-compat"
echo "# Generated by Antigen. Do not edit!" >! "$compat"
cat $record | sed -Ee '/\{$/,/^\}/!{
s/^local //
}' >>! "$compat"
record="$compat"
fi
_sources+=("source '${record}';"$'\n')
elif [[ -d $record ]]; then
_PATH+=("${record}")
_fpath+=("${record}")
fi
done
cat > $ANTIGEN_CACHE <<EOC
#-- START ZCACHE GENERATED FILE
#-- GENERATED: $(date)
#-- ANTIGEN v2.2.2
$(functions -- _antigen)
antigen () {
local MATCH MBEGIN MEND
[[ "\$ZSH_EVAL_CONTEXT" =~ "toplevel:*" || "\$ZSH_EVAL_CONTEXT" =~ "cmdarg:*" ]] && source "$_ANTIGEN_INSTALL_DIR/antigen.zsh" && eval antigen \$@;
return 0;
}
typeset -gaU fpath path
fpath+=(${_fpath[@]}) path+=(${_PATH[@]})
_antigen_compinit () {
autoload -Uz compinit; compinit -d "$ANTIGEN_COMPDUMP"; compdef _antigen antigen
add-zsh-hook -D precmd _antigen_compinit
}
autoload -Uz add-zsh-hook; add-zsh-hook precmd _antigen_compinit
compdef () {}
if [[ -n "$ZSH" ]]; then
ZSH="$ZSH"; ZSH_CACHE_DIR="$ZSH_CACHE_DIR"
fi
#--- BUNDLES BEGIN
${(j::)_sources}
#--- BUNDLES END
typeset -gaU _ANTIGEN_BUNDLE_RECORD; _ANTIGEN_BUNDLE_RECORD=($(print ${(qq)_ANTIGEN_BUNDLE_RECORD}))
typeset -g _ANTIGEN_CACHE_LOADED; _ANTIGEN_CACHE_LOADED=true
typeset -ga _ZCACHE_BUNDLE_SOURCE; _ZCACHE_BUNDLE_SOURCE=($(print ${(qq)_ZCACHE_BUNDLE_SOURCE}))
typeset -g _ANTIGEN_CACHE_VERSION; _ANTIGEN_CACHE_VERSION='v2.2.2'
#-- END ZCACHE GENERATED FILE
EOC
{ zcompile "$ANTIGEN_CACHE" } &!
# Compile config files, if any
LOG "CHECK_FILES $ANTIGEN_CHECK_FILES"
[[ $ANTIGEN_AUTO_CONFIG == true && -n $ANTIGEN_CHECK_FILES ]] && {
echo ${(j:\n:)ANTIGEN_CHECK_FILES} >! "$ANTIGEN_RSRC"
for rsrc in $ANTIGEN_CHECK_FILES; do
zcompile $rsrc
done
} &!
return true
}
# Initializes caching mechanism.
#
# Hooks `antigen-bundle` and `antigen-apply` in order to defer bundle install
# and load. All bundles are loaded from generated cache rather than dynamically
# as these are bundled.
#
# Usage
# -antigen-cache-init
# Returns
# Nothing
-antigen-cache-init () {
if -antigen-interactive-mode; then
return 1
fi
_ZCACHE_CAPTURE_PREFIX=${_ZCACHE_CAPTURE_PREFIX:-"--zcache-"}
_ZCACHE_BUNDLE_SOURCE=(); _ZCACHE_CAPTURE_BUNDLE=()
# Cache auto config files to check for changes (.zshrc, .antigenrc etc)
-antigen-set-default ANTIGEN_AUTO_CONFIG true
# Default cache path.
-antigen-set-default ANTIGEN_CACHE $ADOTDIR/init.zsh
-antigen-set-default ANTIGEN_RSRC $ADOTDIR/.resources
if [[ $ANTIGEN_CACHE == false ]]; then
return 1
fi
return 0
}
-antigen-cache-execute () {
# Main function. Deferred antigen-apply.
antigen-apply-cached () {
# TRACE "APPLYING CACHE" EXT
# Auto determine check_files
# There always should be 5 steps from original source as the correct way is to use
# `antigen` wrapper not `antigen-apply` directly and it's called by an extension.
LOG "TRACE: ${funcfiletrace}"
if [[ $ANTIGEN_AUTO_CONFIG == true && $#ANTIGEN_CHECK_FILES -eq 0 ]]; then
ANTIGEN_CHECK_FILES+=(~/.zshrc)
if [[ $#funcfiletrace -ge 6 ]]; then
ANTIGEN_CHECK_FILES+=("${${funcfiletrace[6]%:*}##* }")
fi
fi
# Generate and compile cache
-antigen-cache-generate
[[ -f "$ANTIGEN_CACHE" ]] && source "$ANTIGEN_CACHE";
# Commented out in order to have a working `cache-gen` command
#unset _ZCACHE_BUNDLE_SOURCE
unset _ZCACHE_CAPTURE_BUNDLE _ZCACHE_CAPTURE_FUNCTIONS
# Release all hooked functions
antigen-remove-hook -antigen-load-env-cached
antigen-remove-hook -antigen-load-source-cached
antigen-remove-hook antigen-bundle-cached
}
antigen-add-hook antigen-apply antigen-apply-cached post once
# Defer antigen-bundle.
antigen-bundle-cached () {
_ZCACHE_CAPTURE_BUNDLE+=("${(j: :)${@}}")
}
antigen-add-hook antigen-bundle antigen-bundle-cached pre
# Defer loading.
-antigen-load-env-cached () {
local bundle
typeset -A bundle; bundle=($@)
local location=${bundle[dir]}/${bundle[loc]}
# Load to path if there is no sourceable
if [[ ${bundle[loc]} == "/" ]]; then
_ZCACHE_BUNDLE_SOURCE+=("${location}")
return
fi
_ZCACHE_BUNDLE_SOURCE+=("${location}")
}
antigen-add-hook -antigen-load-env -antigen-load-env-cached replace
# Defer sourcing.
-antigen-load-source-cached () {
_ZCACHE_BUNDLE_SOURCE+=($@)
}
antigen-add-hook -antigen-load-source -antigen-load-source-cached replace
return 0
}
# Generate static-cache file at $ANTIGEN_CACHE using currently loaded
# bundles from $_ANTIGEN_BUNDLE_RECORD
#
# Usage
# antigen-cache-gen
#
# Returns
# Nothing
antigen-cache-gen () {
-antigen-cache-generate
}
#compdef _antigen
# Setup antigen's autocompletion
_antigen () {
local -a _1st_arguments
_1st_arguments=(
'apply:Load all bundle completions'
'bundle:Install and load the given plugin'
'bundles:Bulk define bundles'
'cleanup:Clean up the clones of repos which are not used by any bundles currently loaded'
'cache-gen:Generate cache'
'init:Load Antigen configuration from file'
'list:List out the currently loaded bundles'
'purge:Remove a cloned bundle from filesystem'
'reset:Clears cache'
'restore:Restore the bundles state as specified in the snapshot'
'revert:Revert the state of all bundles to how they were before the last antigen update'
'selfupdate:Update antigen itself'
'snapshot:Create a snapshot of all the active clones'
'theme:Switch the prompt theme'
'update:Update all bundles'
'use:Load any (supported) zsh pre-packaged framework'
);
_1st_arguments+=(
'help:Show this message'
'version:Display Antigen version'
)
__bundle() {
_arguments \
'--loc[Path to the location <path-to/location>]' \
'--url[Path to the repository <github-account/repository>]' \
'--branch[Git branch name]' \
'--no-local-clone[Do not create a clone]'
}
__list() {
_arguments \
'--simple[Show only bundle name]' \
'--short[Show only bundle name and branch]' \
'--long[Show bundle records]'
}
__cleanup() {
_arguments \
'--force[Do not ask for confirmation]'
}
_arguments '*:: :->command'
if (( CURRENT == 1 )); then
_describe -t commands "antigen command" _1st_arguments
return
fi
local -a _command_args
case "$words[1]" in
bundle)
__bundle
;;
use)
compadd "$@" "oh-my-zsh" "prezto"
;;
cleanup)
__cleanup
;;
(update|purge)
compadd $(type -f \-antigen-get-bundles &> /dev/null || antigen &> /dev/null; -antigen-get-bundles --simple 2> /dev/null)
;;
theme)
compadd $(type -f \-antigen-get-themes &> /dev/null || antigen &> /dev/null; -antigen-get-themes 2> /dev/null)
;;
list)
__list
;;
esac
}
zmodload zsh/datetime
ANTIGEN_DEBUG_LOG=${ANTIGEN_DEBUG_LOG:-${ADOTDIR:-$HOME/.antigen}/debug.log}
LOG () {
local PREFIX="[LOG][${EPOCHREALTIME}]"
echo "${PREFIX} ${funcfiletrace[1]}\n${PREFIX} $@" >> $ANTIGEN_DEBUG_LOG
}
ERR () {
local PREFIX="[ERR][${EPOCHREALTIME}]"
echo "${PREFIX} ${funcfiletrace[1]}\n${PREFIX} $@" >> $ANTIGEN_DEBUG_LOG
}
WARN () {
local PREFIX="[WRN][${EPOCHREALTIME}]"
echo "${PREFIX} ${funcfiletrace[1]}\n${PREFIX} $@" >> $ANTIGEN_DEBUG_LOG
}
TRACE () {
local PREFIX="[TRA][${EPOCHREALTIME}]"
echo "${PREFIX} ${funcfiletrace[1]}\n${PREFIX} $@\n${PREFIX} ${(j:\n:)funcstack}" >> $ANTIGEN_DEBUG_LOG
}
-antigen-env-setup
|
class LinkedList {
Node head;
class Node {
int data;
Node next;
Node(int d) {
data = d;
next = null;
}
}
Node sortedMerge(Node a, Node b) {
Node result = null;
if (a == null)
return b;
else if (b == null)
return a;
if (a.data <= b.data) {
result = a;
result.next = sortedMerge(a.next, b);
} else {
result = b;
result.next = sortedMerge(a, b.next);
}
return result;
}
}
|
// THIS CODE AND INFORMATION IS PROVIDED "AS IS" WITHOUT WARRANTY OF
// ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO
// THE IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A
// PARTICULAR PURPOSE.
//
// Copyright (c) Microsoft Corporation. All rights reserved
//
#pragma once
// Modify the following defines if you have to target a platform prior to the ones specified below.
// Refer to MSDN for the latest info on corresponding values for different platforms.
#ifndef WINVER // Allow use of features specific to Windows 7 or later.
#define WINVER 0x0700 // Change this to the appropriate value to target other versions of Windows.
#endif
#ifndef _WIN32_WINNT // Allow use of features specific to Windows 7 or later.
#define _WIN32_WINNT 0x0700 // Change this to the appropriate value to target other versions of Windows.
#endif
#ifndef UNICODE
#define UNICODE
#endif
// Exclude rarely-used items from Windows headers.
#define WIN32_LEAN_AND_MEAN
// Windows Header Files:
#include <windows.h>
// C RunTime Header Files:
#include <stdlib.h>
#include <malloc.h>
#include <memory.h>
#include <wchar.h>
#include <math.h>
#include <d2d1.h>
#include <d2d1helper.h>
#include <dwrite.h>
#include <wincodec.h>
#include <CoreFoundation/CoreFoundation.h>
#include <CoreGraphics/CoreGraphics.h>
#include <CoreGraphics/CoreGraphicsPrivate.h>
/******************************************************************
* *
* Macros *
* *
******************************************************************/
template<class Interface>
inline void SafeRelease(
Interface **ppInterfaceToRelease
)
{
if (*ppInterfaceToRelease != NULL)
{
(*ppInterfaceToRelease)->Release();
(*ppInterfaceToRelease) = NULL;
}
}
#ifndef Assert
#if defined( DEBUG ) || defined( _DEBUG )
#define Assert(b) do {if (!(b)) {OutputDebugStringA("Assert: " #b "\n");}} while(0)
#else
#define Assert(b)
#endif //DEBUG || _DEBUG
#endif
#ifndef HINST_THISCOMPONENT
EXTERN_C IMAGE_DOS_HEADER __ImageBase;
#define HINST_THISCOMPONENT ((HINSTANCE)&__ImageBase)
#endif
//
// DemoApp class declaration
//
class DemoApp
{
public:
DemoApp();
~DemoApp();
// Register the window class and call methods for instantiating drawing resources
HRESULT Initialize();
// Process and dispatch messages
void RunMessageLoop();
private:
// Initialize device-independent resources.
HRESULT CreateDeviceIndependentResources();
// Initialize device-dependent resources.
HRESULT CreateDeviceResources();
// Release device-dependent resource.
void DiscardDeviceResources();
// Draw content.
HRESULT OnRender();
// Resize the render target.
void OnResize(
UINT width,
UINT height
);
// The windows procedure.
static LRESULT CALLBACK WndProc(
HWND hWnd,
UINT message,
WPARAM wParam,
LPARAM lParam
);
private:
HWND m_hwnd;
CGContextRef m_context;
ID2D1Factory* m_pDirect2dFactory;
ID2D1HwndRenderTarget* m_pRenderTarget;
ID2D1SolidColorBrush* m_pLightSlateGrayBrush;
ID2D1SolidColorBrush* m_pCornflowerBlueBrush;
};
|
longest_word_length = len(max(Text.split(), key=len))
print(longest_word_length) # prints 10
|
#!/bin/bash
git archive --format=zip --output=trzmc.zip main
|
#!/bin/bash -e
set -o pipefail
# Copyright 2014 Google Inc. All rights reserved.
#
# 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.
# This script verifies and formats a single Kythe example, which is expected
# to be piped in on standard input from example.sh.
#
# The script assumes it's working directory is the schema output directory and
# requires the following environment variables:
# TMP
# LANGUAGE
# LABEL
# CXX_INDEXER_BIN
# VERIFIER_BIN
SRCS="$TMP/example"
mkdir "$SRCS"
ARGS_FILE="$TMP/args"
touch "$ARGS_FILE"
# This filter assumes that it's stdin is a full C++ source file which will be
# placed into $TEST_MAIN for compilation/verification. Optionally, after the
# main source text, more files can be specified with header lines formatted like
# "#example filename". The lines proceeding these header lines will be placed
# next to test.cc in "$SRCS/filename".
TEST_MAIN="$SRCS/test.cc"
# The raw filter input will be placed into this file for later syntax highlighting
RAW_EXAMPLE="$TMP/raw.hcc"
# Example filter input:
# #include "test.h"
# //- @C completes Decl1
# //- @C completes Decl2
# //- @C defines Defn
# class C { };
#
# #example test.h
# //- @C defines Decl1
# class C;
# //- @C defines Decl2
# class C;
#
# The above input will generate/verify two files: test.cc and test.h
# Split collected_files.hcc into files via "#example file.name" delimiter lines.
{ echo "#example test.cc";
tee "$RAW_EXAMPLE";
} | awk -v argsfile="$ARGS_FILE" -v root="$SRCS/" '
/#example .*/ {
x=root $2;
next;
}
/#arguments / {
$1 = "";
print > argsfile;
next;
}
{print > x;}'
CXX_ARGS="-std=c++1y $(cat "$ARGS_FILE")"
set +e # Handle these error separately below
"$CXX_INDEXER_BIN" -i "$TEST_MAIN" -- $CXX_ARGS | "$VERIFIER_BIN" "$SRCS"/*
RESULTS=( ${PIPESTATUS[0]} ${PIPESTATUS[1]} )
set -e
if [[ ${RESULTS[0]} -ne 0 ]]; then
error INDEX
elif [[ ${RESULTS[1]} -ne 0 ]]; then
error VERIFY
fi
trap 'error FORMAT' ERR
EXAMPLE_ID=$(sha1sum "$RAW_EXAMPLE" | cut -c 1-40)
"$CXX_INDEXER_BIN" -i "$TEST_MAIN" -- $CXX_ARGS \
| "$VERIFIER_BIN" --graphviz > "$TMP/EXAMPLE_ID.dot"
dot -Tsvg -o "$EXAMPLE_ID.svg" "$TMP/EXAMPLE_ID.dot"
echo "<div><h5 id=\"_${LABEL}\">${LABEL}"
echo "(<a href=\"${EXAMPLE_ID}.svg\" target=\"_blank\">${LANGUAGE}</a>)</h5>"
source-highlight --failsafe --output=STDOUT --src-lang cpp -i "$RAW_EXAMPLE"
echo "</div>"
|
<filename>tiger/src/test/java/tiger/test/methodloop/BeanTest.java
/**
*
* @creatTime ไธๅ3:21:45
* @author Eddy
*/
package tiger.test.methodloop;
import org.eddy.tiger.TigerBean;
import org.eddy.tiger.TigerBeanManage;
import org.eddy.tiger.impl.TigerBeanManageImpl;
import org.junit.Test;
/**
* @author Eddy
*
*/
@SuppressWarnings("all")
public class BeanTest {
@Test
public void test() {
TigerBeanManage manage = new TigerBeanManageImpl();
TigerBean<A> aBean = manage.createBean(A.class);
manage.createBean(B.class);
manage.createBean(C.class);
A a = manage.getReference(aBean);
}
}
|
#!/bin/bash
./configure --prefix=/usr \
--disable-static \
--without-nettle && \
make -j $SHED_NUMJOBS && \
make DESTDIR="$SHED_FAKEROOT" install
|
import ConcreteEmitter from '../../src/implementations/ConcreteEmitter'
import randomString from '../../src/utils/randomString'
describe('Emitter suite', (): void => {
let instance: ConcreteEmitter
beforeEach(() => {
instance = new ConcreteEmitter({})
})
it('should create new instance of event emitter', (): void => {
expect.assertions(1)
expect(instance).toBeInstanceOf(ConcreteEmitter)
})
it('should subscribe to a random event and fire that event with a random array', (): void => {
expect.assertions(1)
let randomData = new Array(Math.floor(Math.random() * 10000)).map(
(i: any): number => Math.floor(Math.random() * 100)
)
let str = randomString()
instance.on(str, (dataArray) => {
expect(dataArray).toEqual(randomData)
})
instance.emit(str, randomData)
})
})
|
/*
============================================================================
This source file is part of the Ogre-Maya Tools.
Distributed as part of Ogre (Object-oriented Graphics Rendering Engine).
Copyright (C) 2003 Fifty1 Software Inc., Bytelords
This program is free software; you can redistribute it and/or
modify it under the terms of the GNU General Public License
as published by the Free Software Foundation; either version 2
of the License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
or go to http://www.gnu.org/licenses/gpl.txt
============================================================================
*/
#ifndef _OGREMAYA_OPTIONS_H_
#define _OGREMAYA_OPTIONS_H_
#include "OgreMayaCommon.h"
#include <maya/MString.h>
#include <maya/MStringArray.h>
#include <map>
#include <string>
namespace OgreMaya {
// using namespace std;
using std::map;
using std::string;
class Options {
public:
static Options& Options::instance();
void reset();
void debugOutput();
public:
struct KeyframeRange {
KeyframeRange(int from=0, int to=0, int step=1): from(from), to(to), step(1) {}
bool isValid() {return from>0 && to>0;}
int from;
int to;
int step;
};
typedef map<string, KeyframeRange> KeyframeRangeMap;
string
inFile,
inAnimFile,
outMeshFile,
outSkelFile,
outAnimFile,
outMatFile,
matPrefix;
bool
verboseMode,
exportSelected,
exportMesh,
exportSkeleton,
exportVBA,
exportNormals,
exportColours,
exportUVs,
exportMaterial,
exportBounds;
KeyframeRangeMap
animations;
bool
valid;
int
precision;
float
scale;
private:
Options();
};
} // namespace OgreMaya
#define OPTIONS Options::instance()
#endif
|
from django.utils.translation import gettext_lazy as _
def get_item_value(item, accessor, *, container=None, exclude=None):
container_class = type(container)
if isinstance(accessor, StaticText):
return accessor
if container is not None and hasattr(container, accessor):
attr = getattr(container_class, accessor)
if callable(attr):
if item is None:
return getattr(container, accessor)()
else:
return getattr(container, accessor)(item)
elif isinstance(attr, property):
return getattr(container, accessor)
elif exclude is None or not isinstance(attr, exclude):
return attr
paths = accessor.split(".")
item_value = item
for path in paths:
if hasattr(item_value, path):
item_value = getattr(item_value, path)
else:
item_value = None
break
if callable(item_value):
item_value = item_value()
if item_value is not None:
return item_value
return None
class StaticText:
"""Wrapper around gettext_lazy that allows us to mark text as static in data sources - data grids.
(The datacard / datagrid won't consider it as an accessor and will use it as is).
"""
def __init__(self, text):
self.text = _(text)
def __str__(self):
return str(self.text)
def replace(self, a, b):
return self.text.replace(a, b)
|
const findMissingPositiveInteger = (arr) => {
let arrSorted = arr.sort((a, b) => a - b);
let i = 0;
let j = 1;
while (arrSorted[i] < 0) {
i++;
}
while (arrSorted.indexOf(j) !== -1) {
j++;
}
return j;
}
|
#!/bin/bash
run_memory_benchmark () {
path="benchmarks/data/memory/run"
i=0
while [[ -e $path-$i.txt || -L $path-$i.txt || -d $path-$i ]] ; do
let i++
done
path=$path-$i
benchmarks=$(stack run memo-cata-regular-memory -- --list)
readarray -t y <<< $benchmarks
for benchmark in "${y[@]}"
do
dir="$(dirname "$path/$benchmark")"
mkdir -p "$dir"
stack run memo-cata-regular-memory -- --match glob "$benchmark" +RTS -t --machine-readable 2> "$path/$benchmark.txt"
done
}
run_time_benchmark () {
name="benchmarks/data/time/run"
i=0
while [[ -e $name-$i.csv || -L $name-$i.csv ]] ; do
let i++
done
name=$name-$i
stack run memo-cata-regular-time -- --csv="${name}.csv"
}
run_time_benchmark
run_memory_benchmark
|
<filename>src/shared/modules/Var/vos/VarDataValueResVO.ts
import VarDataBaseVO from './VarDataBaseVO';
export default class VarDataValueResVO {
public static API_TYPE_ID: string = "vdvr";
public id: number;
public _type: string = VarDataValueResVO.API_TYPE_ID;
public index: string;
public is_computing: boolean;
public value: number;
public value_type: number;
public value_ts: number;
public constructor() { }
public set_from_vardata(vardata: VarDataBaseVO): VarDataValueResVO {
this.id = vardata.id;
this.value = vardata.value;
this.index = vardata.index;
this.value_ts = vardata.value_ts;
this.value_type = vardata.value_type;
this.is_computing = false;
return this;
}
public set_value(value: number): VarDataValueResVO {
this.value = value;
return this;
}
public set_value_type(value_type: number): VarDataValueResVO {
this.value_type = value_type;
return this;
}
public set_value_ts(value_ts: number): VarDataValueResVO {
this.value_ts = value_ts;
return this;
}
public set_index(index: string): VarDataValueResVO {
this.index = index;
return this;
}
public set_is_computing(is_computing: boolean): VarDataValueResVO {
this.is_computing = is_computing;
return this;
}
}
|
#!/bin/bash
# Copyright 2016 gRPC authors.
#
# 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.
set -ex
cd "$(dirname "$0")/../../.."
mkdir -p artifacts/
# All the python packages have been built in the artifact phase already
# and we only collect them here to deliver them to the distribtest phase.
cp -r "$EXTERNAL_GIT_ROOT"/platform={windows,linux,macos}/artifacts/python_*/* artifacts/ || true
# TODO: all the artifact builder configurations generate a grpcio-VERSION.tar.gz
# source distribution package, and only one of them will end up
# in the artifacts/ directory. They should be all equivalent though.
|
const emailStatus = {
request: "Envoyรฉ",
click: "Clickรฉ",
deferred: "Diffรฉrรฉ",
delivered: "Dรฉlivrรฉ",
soft_bounce: "Rejectรฉ (soft)",
spam: "Spam",
unique_opened: "Ouverture unique",
hard_bounce: "Rejetรฉ (hard)",
unsubscribed: "Dรฉsinscrit",
opened: "Ouvert",
invalid_email: "Email invalide",
blocked: "Bloquรฉ",
error: "Erreur",
};
/**
* @description Returns email status.
* @param {string} status - Status stored in database
* @return {string}
*/
const getEmailStatus = (status) => emailStatus[status] || "N/C";
module.exports = {
getEmailStatus,
};
|
<filename>scripts/libs.ts
import chalk from "chalk";
import execa from "execa";
import readline from "readline";
export class OperationError extends Error {
private readonly _isOperationError = true;
static isOperationError(e: Error | OperationError): e is OperationError {
if ("_isOperationError" in e) {
return e._isOperationError === true;
}
return false;
}
constructor(name: string, data: string) {
super("Operation Error");
console.error(`[${chalk.red("โ")}] ${name}\n`);
console.error(data);
console.info("\n", chalk.redBright("Exiting"));
}
}
export async function run<T>(promise: Promise<T>) {
try {
return {
error: null,
data: await promise,
};
} catch (e) {
return { error: e as execa.ExecaError, data: null };
}
}
export function onError(name: string, v: execa.ExecaError<string>) {
throw new OperationError(name, v.stdout + "\n" + chalk.red(v.stderr));
}
export function onSuccess(name: string) {
console.info(`[${chalk.green("โ")}] ${name}`);
}
export const stdin = (() => {
return (message: string) => {
const rl = readline.createInterface({
input: process.stdin,
output: process.stdout,
});
return new Promise<string>((resolve) => {
rl.question(message, (answer) => {
rl.close();
resolve(answer);
});
});
};
})();
|
package main
import (
"archive/zip"
"fmt"
"io"
"io/ioutil"
"os"
"path/filepath"
"strings"
)
func build(project string) {
gradlew(os.Stdout, config.Aliucord, ":"+project+":compileDebugJavaWithJavac")
javacBuild, err := filepath.Abs(fmt.Sprintf("%s/%s/build/intermediates/javac/debug", config.Aliucord, project))
handleErr(err)
f, _ := os.Create(javacBuild + "/classes.zip")
zipw := zip.NewWriter(f)
zipAndD8(f, zipw, javacBuild, "/classes.zip", config.Outputs)
out := project + ".dex"
if *outName != "" {
out = *outName
if !strings.HasSuffix(out, ".dex") {
out += ".dex"
}
}
os.Rename(config.Outputs+"/classes.dex", config.Outputs+"/"+out)
colorPrint(success, "Successfully built "+project)
}
func buildPlugin(pluginName string) {
plugin, err := filepath.Abs(config.Plugins + "/" + pluginName)
handleErr(err)
_, err = os.Stat(plugin)
handleErr(err)
gradlew(os.Stdout, config.Plugins, pluginName+":compileDebugJavaWithJavac")
javacBuild := plugin + "/build/intermediates/javac/debug"
f, _ := os.Create(javacBuild + "/classes.zip")
zipw := zip.NewWriter(f)
zipAndD8(f, zipw, javacBuild, "/classes.zip", config.OutputsPlugins)
outputsPlugins, err := filepath.Abs(config.OutputsPlugins)
handleErr(err)
out := pluginName + ".zip"
if *outName != "" {
out = *outName
if !strings.HasSuffix(out, ".zip") {
out += ".zip"
}
}
src, err := filepath.Abs(config.Plugins + "/" + pluginName + "/src/main")
if err == nil {
files, err := ioutil.ReadDir(src + "/res")
if err == nil && len(files) > 0 {
tmpApk := outputsPlugins + "/" + pluginName + "-tmp.apk"
execCmd(os.Stdout, outputsPlugins, "aapt2", "compile", "--dir", src+"/res", "-o", "tmpres.zip")
execCmd(os.Stdout, outputsPlugins, "aapt2", "link", "-I", config.AndroidSDK+"/platforms/android-"+config.AndroidSDKVersion+"/android.jar",
"-R", "tmpres.zip", "--manifest", src+"/AndroidManifest.xml", "-o", tmpApk)
os.Remove(outputsPlugins + "/tmpres.zip")
zipr, _ := zip.OpenReader(tmpApk)
f, _ = os.Create(outputsPlugins + "/" + out)
defer f.Close()
zipw = zip.NewWriter(f)
defer zipw.Close()
for _, zipFile := range zipr.File {
if zipFile.Name == "AndroidManifest.xml" {
continue
}
zipFiler, _ := zipFile.Open()
zipFilew, _ := zipw.Create(zipFile.Name)
io.Copy(zipFilew, zipFiler)
zipFiler.Close()
}
zipr.Close()
f, _ = os.Open(outputsPlugins + "/classes.dex")
zipFilew, _ := zipw.Create("classes.dex")
io.Copy(zipFilew, f)
f.Close()
writePluginEntry(zipw, pluginName)
os.Remove(tmpApk)
} else {
makeZipWithClasses(out, pluginName)
}
} else {
makeZipWithClasses(out, pluginName)
}
os.Remove(outputsPlugins + "/classes.dex")
colorPrint(success, "Successfully built plugin "+pluginName)
}
func zipAndD8(f *os.File, zipw *zip.Writer, javacBuild, zipName, outputPath string) {
filepath.Walk(javacBuild+"/classes", func(path string, f os.FileInfo, err error) error {
if err != nil {
colorPrint(red, err)
return nil
}
if f.IsDir() {
return nil
}
file, _ := os.Open(path)
defer file.Close()
zipf, _ := zipw.Create(strings.Split(strings.ReplaceAll(path, "\\", "/"), "javac/debug/classes/")[1])
io.Copy(zipf, file)
return nil
})
zipw.Close()
f.Close()
output, err := filepath.Abs(outputPath)
handleErr(err)
execCmd(os.Stdout, output, "d8", javacBuild+zipName)
}
func makeZipWithClasses(out, pluginName string) {
f, _ := os.Create(config.OutputsPlugins + "/" + out)
defer f.Close()
zipw := zip.NewWriter(f)
defer zipw.Close()
f, _ = os.Open(config.OutputsPlugins + "/classes.dex")
zipFilew, _ := zipw.Create("classes.dex")
io.Copy(zipFilew, f)
f.Close()
writePluginEntry(zipw, pluginName)
}
|
#!/bin/bash
echo "========npm install no ta-gui========"
cd gui/ta-gui/
rm -rf node_modules/
npm install
cd ../../
echo "========tsc no ta-server==========="
cd server/ta-server/
npm install @types/express
tsc
npm install
cd ../../
echo "=========tsc no app========="
cd gui/ta-gui/src/app/
tsc
cd ../../../../
echo "==========npm install no tests-acceptance=========="
cd tests-acceptance/
rm -rf node_modules/
npm install
cd ../
echo "======tsc no config.ts========"
cd tests-acceptance/config/
tsc
cd ../../
echo "===========webdriver update no tests-acceptance============"
cd tests-acceptance/
webdriver-manager update
echo "============tsc no tests-acceptance============"
tsc
cd ../
|
<reponame>infinitiessoft/skyport-api
/*******************************************************************************
* Copyright 2015 InfinitiesSoft Solutions Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may
* not use this file except in compliance with the License. You may obtain
* a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations
* under the License.
*******************************************************************************/
package com.infinities.skyport.async.service;
import javax.annotation.Nullable;
import com.infinities.skyport.async.service.identity.AsyncIdentityAndAccessSupport;
import com.infinities.skyport.async.service.identity.AsyncShellKeySupport;
public interface AsyncIdentityServices {
public @Nullable AsyncIdentityAndAccessSupport getIdentityAndAccessSupport();
public @Nullable AsyncShellKeySupport getShellKeySupport();
public boolean hasIdentityAndAccessSupport();
public boolean hasShellKeySupport();
void initialize() throws Exception;
void close();
}
|
<gh_stars>1-10
import React from "react"
import styled from "styled-components"
import { Sections } from "../sections"
const StoryWrapper = styled(Sections)`
display: flex;
flex-direction: column;
justify-content: space-evenly;
h2 {
text-align: center;
color: var(--orange);
}
p {
color: var(--red);
margin-top: 2rem;
}
@media (max-width: 768px) {
}
@media (max-width: 512px) {
p {
width: 100%;
}
}
`
export const Story = () => (
<StoryWrapper>
<h2>WOULD YOU LIKE TO START YOUR BUSINESS?</h2>
<p>
We know starting a business can sound overwhelming, but Atole Techย is
here to help and guide you in figuringย out what services you can sell in
your website and define your brand.ย We want to help you diversify your
income streams with online products, subscriptions and more!ย {" "}
</p>
<p>
Our team loves exploring new ideas, and we want the chance to conduct that
exploration alongside other creative people such as yourself. We believe
every business and every website is unique, weย are committed to knowingย
your product and enhancingย it by giving it the image and personality you
desire.
</p>
</StoryWrapper>
)
|
import { Injectable, Inject } from '@angular/core';
import { DOCUMENT } from '@angular/common';
/** Class representing a SpinnerService */
@Injectable()
export class SpinnerService {
private selector: string = 'global-spinner';
private el: HTMLElement;
/**
* Create a SpinnerService.
* @param document
*/
constructor(
@Inject(DOCUMENT) private document) {
this.el = this.document.getElementById(this.selector);
}
/**
* Show the spinner.
*/
show() {
this.el.style['display'] = 'block';
}
/**
* Hide the spinner.
*/
hide() {
this.el.style['display'] = 'none';
}
}
|
const blue_size = 120;
const white_size = 250;
const yellow_circle_size = 50;
const red_circle_size = 75;
const red_circle_size_list = [200, 350, 100, 50, 600];
const opacity_max = 127;
let red_circle_pos_list = [];
let startTIme;
let elapsedTime;
let sketch = function(p) {
function setContext(){
let xv = Math.abs(Math.sin(elapsedTime/100))*50
p.drawingContext.shadowBlur = 100;
p.drawingContext.shadowColor = p.color(255,255,0);
}
async function blur() {
p.filter(p.BLUR, 1);
}
p.setup = function(){
// createCanvas(600,425);
startTIme = p.millis();
p.createCanvas(1000, 1000);
p.background(255,255,255);
p.drawingContext.shadowBlur = 100;
p.drawingContext.shadowColor = p.color(255,255,255);
red_circle_size_list.forEach((item, i) => {
red_circle_pos_list.push([p.random(p.width), p.random(p.height)])
});
}
// ใใฌใผใ ใใจใฎๅฆ็
p.draw = function(){
const now = p.millis();
elapsedTime = now - startTIme;
p.strokeWeight(0);
p.fill(255,255,255);
// p.square(p.random(p.width),p.random(p.height),p.random(white_size));
// p.ellipse(p.random(p.width),p.random(p.height),p.random(white_size), p.random(white_size));
const eye_pos = [p.random(p.width), p.random(p.height)]
p.strokeWeight(1);
p.circle(eye_pos[0],eye_pos[1],p.random(white_size));
p.fill(0,0,0);
p.circle(eye_pos[0] + p.random(5) + p.random(5), eye_pos[1],5);
p.strokeWeight(0);
p.fill(240,240,0,p.random(opacity_max));
p.drawingContext.shadowColor = p.color(240,240,0);
p.circle(p.random(p.width),p.random(p.height),p.random(yellow_circle_size));
p.fill(240,25,50);
p.circle(p.random(p.width),p.random(p.height),p.random(red_circle_size));
p.fill(0,188,214,p.random(opacity_max));
p.drawingContext.shadowColor = p.color(0,188,214);
// p.square(p.random(p.width),p.random(p.height),p.random(blue_size));
red_circle_size_list.forEach((item, i) => {
p.circle(
item * Math.sin(elapsedTime % Math.PI*2) + red_circle_pos_list[i][0],
item * Math.cos(elapsedTime % Math.PI*2) + red_circle_pos_list[i][1],
p.random(red_circle_size) + 20
);
});
p.ellipse(p.random(p.width),p.random(p.height),p.random(blue_size), p.random(blue_size));
p.circle(p.mouseX, p.mouseY, 100);
p.circle(p.random(p.width),p.random(p.height),p.random(blue_size));
p.drawingContext.shadowColor = p.color(255,255,255);
// 1็งใใจใซblur
if (elapsedTime >= 3000) {
// (async () => console.log(await blur()))()
// p.clear();
// startTIme = p.millis();
}
}
}
new p5(sketch, 'container');
|
def recur_factorial(num):
"""Computes factorial of a number using recursion"""
# Base case
if num == 1:
return 1
else:
return num * recur_factorial(num - 1)
|
<reponame>hhxlearning/fine-ui<filename>fine-ui/src/main.js
import Vue from 'vue'
import App from './App.vue'
import router from './router'
import './assets/iconfont/iconfont.css'
import Button from './components/Button.vue'
import Dialog from './components/Dialog.vue'
import Card from './components/Card.vue'
Vue.component(Button.name, Button)
Vue.component(Dialog.name, Dialog)
Vue.component(Card.name, Card)
Vue.config.productionTip = false
new Vue({
router,
render: h => h(App)
}).$mount('#app')
|
# Import necessary libraries
from PyQt5.QtWidgets import QTableView, QHeaderView
from PyQt5.QtCore import Qt
# Create a custom table view widget
class CustomMusicPlayerTableView(QTableView):
def __init__(self):
super().__init__()
# Set default alignment for the horizontal header
self.horizontalHeader().setDefaultAlignment(Qt.AlignLeft)
# Set section resize mode and default section size for the vertical header
self.verticalHeader().setSectionResizeMode(QHeaderView.Fixed)
self.verticalHeader().setDefaultSectionSize(47)
# Set minimum height for the horizontal header
self.horizontalHeader().setMinimumHeight(30)
# Set the column representing song names to automatically stretch
self.horizontalHeader().setSectionResizeMode(0, QHeaderView.Stretch)
# Set a fixed width for the second column
self.horizontalHeader().setSectionResizeMode(1, QHeaderView.Fixed)
|
#!/bin/bash
# Copyright (c) 2012 The Chromium OS Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
LIBDOT_DIR="$(dirname -- "$0")/../../libdot"
source "${LIBDOT_DIR}/bin/common.sh"
cd "${BIN_DIR}/.."
concat "$@" -i ./concat/wash_deps.concat \
-o ./js/wash_deps.concat.js
|
<reponame>vany152/FilesHash
// Copyright 2020 <NAME>
// Distributed under the Boost Software License, Version 1.0.
// https://www.boost.org/LICENSE_1_0.txt
#include <boost/describe/members.hpp>
#include <boost/describe/class.hpp>
#include <boost/core/lightweight_test.hpp>
#include <boost/config.hpp>
struct X
{
};
BOOST_DESCRIBE_STRUCT(X, (), ())
class Y
{
public:
int m1;
int m2;
private:
int m3;
int m4;
BOOST_DESCRIBE_CLASS(Y, (), (m1, m2), (), (m3, m4))
public:
Y( int m1, int m2, int m3, int m4 ): m1( m1 ), m2( m2 ), m3( m3 ), m4( m4 )
{
}
// using Pm = int Y::*;
typedef int Y::* Pm;
static Pm m3_pointer() BOOST_NOEXCEPT
{
return &Y::m3;
}
static Pm m4_pointer() BOOST_NOEXCEPT
{
return &Y::m4;
}
};
#if !defined(BOOST_DESCRIBE_CXX14)
#include <boost/config/pragma_message.hpp>
BOOST_PRAGMA_MESSAGE("Skipping test because C++14 is not available")
int main() {}
#else
#include <boost/mp11.hpp>
int main()
{
using namespace boost::describe;
using namespace boost::mp11;
{
using L = describe_members<X, mod_any_access>;
BOOST_TEST_EQ( mp_size<L>::value, 0 );
}
{
using L = describe_members<Y, mod_any_access>;
BOOST_TEST_EQ( mp_size<L>::value, 4 );
BOOST_TEST( (mp_at_c<L, 0>::pointer) == &Y::m1 );
BOOST_TEST_CSTR_EQ( (mp_at_c<L, 0>::name), "m1" );
BOOST_TEST_EQ( (mp_at_c<L, 0>::modifiers), mod_public );
BOOST_TEST( (mp_at_c<L, 1>::pointer) == &Y::m2 );
BOOST_TEST_CSTR_EQ( (mp_at_c<L, 1>::name), "m2" );
BOOST_TEST_EQ( (mp_at_c<L, 1>::modifiers), mod_public );
BOOST_TEST( (mp_at_c<L, 2>::pointer) == Y::m3_pointer() );
BOOST_TEST_CSTR_EQ( (mp_at_c<L, 2>::name), "m3" );
BOOST_TEST_EQ( (mp_at_c<L, 2>::modifiers), mod_private );
BOOST_TEST( (mp_at_c<L, 3>::pointer) == Y::m4_pointer() );
BOOST_TEST_CSTR_EQ( (mp_at_c<L, 3>::name), "m4" );
BOOST_TEST_EQ( (mp_at_c<L, 3>::modifiers), mod_private );
}
{
using L = describe_members<Y, mod_public>;
BOOST_TEST_EQ( mp_size<L>::value, 2 );
BOOST_TEST( (mp_at_c<L, 0>::pointer) == &Y::m1 );
BOOST_TEST_CSTR_EQ( (mp_at_c<L, 0>::name), "m1" );
BOOST_TEST_EQ( (mp_at_c<L, 0>::modifiers), mod_public );
BOOST_TEST( (mp_at_c<L, 1>::pointer) == &Y::m2 );
BOOST_TEST_CSTR_EQ( (mp_at_c<L, 1>::name), "m2" );
BOOST_TEST_EQ( (mp_at_c<L, 1>::modifiers), mod_public );
}
{
using L = describe_members<Y, mod_private>;
BOOST_TEST_EQ( mp_size<L>::value, 2 );
BOOST_TEST( (mp_at_c<L, 0>::pointer) == Y::m3_pointer() );
BOOST_TEST_CSTR_EQ( (mp_at_c<L, 0>::name), "m3" );
BOOST_TEST_EQ( (mp_at_c<L, 0>::modifiers), mod_private );
BOOST_TEST( (mp_at_c<L, 1>::pointer) == Y::m4_pointer() );
BOOST_TEST_CSTR_EQ( (mp_at_c<L, 1>::name), "m4" );
BOOST_TEST_EQ( (mp_at_c<L, 1>::modifiers), mod_private );
}
{
using L = describe_members<Y, mod_protected>;
BOOST_TEST_EQ( mp_size<L>::value, 0 );
}
return boost::report_errors();
}
#endif // !defined(BOOST_DESCRIBE_CXX14)
|
import React from 'react';
import './styles.scss';
const Panel = props =>
(<div className="panel">
{props.children}
</div>);
Panel.propTypes = {
children: React.PropTypes.objectOf(React.PropTypes.object).isRequired,
};
Panel.Head = props =>
(<div className="panel-head">
{props.children}
</div>);
Panel.Head.propTypes = {
children: React.PropTypes.objectOf(React.PropTypes.object).isRequired,
};
Panel.Body = props =>
(<div className="panel-body">
{props.children}
</div>);
Panel.Body.propTypes = {
children: React.PropTypes.objectOf(React.PropTypes.object).isRequired,
};
Panel.Footer = props =>
(<div className="panel-foot">
{props.children}
</div>);
Panel.Footer.propTypes = {
children: React.PropTypes.objectOf(React.PropTypes.object).isRequired,
};
export default Panel;
|
#!/bin/bash
#
# Script to launch the CarND Unity simulator
THIS_DIR="$(cd "$(dirname "$0")" && pwd -P && cd - > /dev/null)"
USER_PROFILE="$THIS_DIR/profile.tmp"
if [ ! -f "$USER_PROFILE" ];
then
echo "What is the full path to your Unity simulator?"
read unity_path
# write to the file
echo "$unity_path" > $USER_PROFILE
else
unity_path=$(cat "$USER_PROFILE")
fi
# $unity_path
|
<gh_stars>0
package nl.probotix.autonomous;
import android.util.Log;
import com.disnodeteam.dogecv.CameraViewDisplay;
import com.disnodeteam.dogecv.DogeCV;
import com.disnodeteam.dogecv.detectors.roverrukus.GoldDetector;
import com.qualcomm.robotcore.eventloop.opmode.Autonomous;
import com.qualcomm.robotcore.eventloop.opmode.LinearOpMode;
import com.qualcomm.robotcore.hardware.DcMotor;
import com.qualcomm.robotcore.util.ElapsedTime;
import nl.probotix.RuckusHardware;
import nl.probotix.helpers.AutoHelper;
import nl.probotix.helpers.HeavyLiftStages;
/**
* Copyright 2018 (c) ProBotiX
*/
@Autonomous(name = "Auto: Crater", group = "RuckusAuto")
public class CraterAuto extends LinearOpMode {
private RuckusHardware ruckusHardware;
private AutoHelper autoHelper;
private String opModeName = "AutoCrater";
private GoldDetector detector;
private int stage = 4;
@Override
public void runOpMode() throws InterruptedException {
//start of initialization
telemetry.addData("Status", "Initializing....");
telemetry.update();
Log.d("Ruckus", opModeName + " > Status > Initializing...");
//setting up hardware class and helpers
ruckusHardware = new RuckusHardware(hardwareMap);
autoHelper = new AutoHelper(ruckusHardware, this);
ruckusHardware.telemetryData(telemetry, opModeName, "Status", "Now setting up DogeCV");
//initializing DogeCV
detector = new GoldDetector();
detector.init(hardwareMap.appContext, CameraViewDisplay.getInstance());
detector.useDefaults();
//optional tuning
detector.downscale = 0;
detector.areaScoringMethod = DogeCV.AreaScoringMethod.MAX_AREA;
detector.maxAreaScorer.weight = 0.005;
detector.ratioScorer.weight = 5;
detector.ratioScorer.perfectRatio = 1.0;
//initialization done
ruckusHardware.telemetryData(telemetry, opModeName, "Status", "Initialized. Press start...");
//wait for user to press start
waitForStart();
//player presses start
ruckusHardware.telemetryData(telemetry, opModeName, "Status", "Autonomous started");
ruckusHardware.telemetryData(telemetry, opModeName, "Autonomous", "Autonomous started; Landing...");
//7s //landing the robot
ruckusHardware.heavyLiftMotor.setMode(DcMotor.RunMode.STOP_AND_RESET_ENCODER);
ruckusHardware.heavyLiftMotor.setMode(DcMotor.RunMode.RUN_TO_POSITION);
ruckusHardware.heavyLiftMotor.setPower(0.8);
ruckusHardware.heavyLiftMotor.setTargetPosition(HeavyLiftStages.OUT.getTicks());
ElapsedTime timeout = new ElapsedTime();
timeout.reset();
while (opModeIsActive() && timeout.milliseconds() < 12000 && ruckusHardware.heavyLiftMotor.isBusy()) {
}
DcMotor.RunMode runMode = ruckusHardware.lfWheel.getMode();
ruckusHardware.setDcMotorMode(DcMotor.RunMode.STOP_AND_RESET_ENCODER);
ElapsedTime elapsedTime = new ElapsedTime();
elapsedTime.reset();
while(elapsedTime.milliseconds() < 100 && opModeIsActive()) {
}
ruckusHardware.setDcMotorMode(runMode);
while(elapsedTime.milliseconds() < 200 && opModeIsActive()) {
}
ruckusHardware.telemetryData(telemetry, "DriveAndWait", "CurrentEncoders", "LF: " + ruckusHardware.lfWheel.getCurrentPosition() + " " + ruckusHardware.lfWheel.getTargetPosition() + "\n" +
"RF: " + ruckusHardware.rfWheel.getCurrentPosition() + " " + ruckusHardware.rfWheel.getTargetPosition() + "\n" +
"LR: " + ruckusHardware.lrWheel.getCurrentPosition() + " " + ruckusHardware.lrWheel.getTargetPosition() + "\n" +
"RR: " + ruckusHardware.rrWheel.getCurrentPosition() + " " + ruckusHardware.rrWheel.getTargetPosition());
//0.5s //unhook
autoHelper.driveAndWait(0, 80, 0, 0.1, 0.25);
ElapsedTime liftTimeout = new ElapsedTime();
liftTimeout.reset();
//retract landing system (will finish while driving autonomous)
ruckusHardware.heavyLiftMotor.setPower(1.0);
ruckusHardware.heavyLiftMotor.setTargetPosition(HeavyLiftStages.IN.getTicks());
//1s //drive 10 cm forward
ruckusHardware.telemetryData(telemetry, opModeName, "Autonomous", "Landing done; Driving...");
detector.enable();
autoHelper.driveAndWait(100, 0, 0, 0.25, 0.5);
//0.5s //back to middle
autoHelper.driveAndWait(0, -80, 0, 0.1, 0.25);
boolean found = false;
//2s //turn 45 degree left
autoHelper.driveAndWait(0, 0, 70, 1, 2);
//5s //turn 90 degree right until seeing gold mineral
ruckusHardware.telemetryData(telemetry, opModeName, "Autonomous", "Drive done; Scanning...");
autoHelper.driveEncoded(0, 0, -140, 4);
ElapsedTime runtime = new ElapsedTime();
runtime.reset();
while (opModeIsActive() && ruckusHardware.lfWheel.isBusy() && runtime.milliseconds() < 5000) {
//scan for gold mineral
double x = detector.getScreenPosition().x;
double y = detector.getScreenPosition().y;
if (x > 420 && x < 500 && y > 200) {
//set motors to current position
found = true;
ruckusHardware.stopEncodedDrive();
}
}
if(!found) {
autoHelper.driveAndWait(0, 0, 70, 2, 3);
}
ruckusHardware.telemetryData(telemetry, opModeName, "Autonomous", "Gold mineral found: " + found + "; Hitting mineral...");
detector.disable();
ruckusHardware.telemetryData(telemetry, "DriveAndWait", "CurrentEncoders", "LF: " + ruckusHardware.lfWheel.getCurrentPosition() + " " + ruckusHardware.lfWheel.getTargetPosition() + "\n" +
"RF: " + ruckusHardware.rfWheel.getCurrentPosition() + " " + ruckusHardware.rfWheel.getTargetPosition() + "\n" +
"LR: " + ruckusHardware.lrWheel.getCurrentPosition() + " " + ruckusHardware.lrWheel.getTargetPosition() + "\n" +
"RR: " + ruckusHardware.rrWheel.getCurrentPosition() + " " + ruckusHardware.rrWheel.getTargetPosition());
int lfTicks = ruckusHardware.lfWheel.getCurrentPosition();
int lrTicks = ruckusHardware.lrWheel.getCurrentPosition();
if(lfTicks < 0 && lrTicks < 0) {
//left mineral
autoHelper.driveAndWait(650, 0, 0, 1.5, 2);
autoHelper.driveAndWait(0, 0, -45, 1, 2);
autoHelper.driveAndWait(50, 0, 0, 0.25, 0.5);
} else if(lfTicks > 600 && lrTicks > 600) {
//right mineral
autoHelper.driveAndWait(650, 0, 0, 1.5, 2);
autoHelper.driveAndWait(0, 0, 45, 1, 2);
autoHelper.driveAndWait(50, 0, 0, 0.25, 0.5);
} else {
//middle mineral
autoHelper.driveAndWait(560, 0, 0, 2, 3);
}
ruckusHardware.craterServo.setPosition(0.15);
elapsedTime = new ElapsedTime();
elapsedTime.reset();
while(opModeIsActive() && elapsedTime.milliseconds() < 1000) {
}
while(ruckusHardware.heavyLiftMotor.isBusy() && opModeIsActive()) {
}
//28s //AUTONOMOUS DONE
ruckusHardware.telemetryData(telemetry, opModeName, "Status", "Autonomous done");
}
}
|
var NAVTREEINDEX27 =
{
"_subtraction_test_impl_8cpp.xhtml#a7a25b712f181d499480edcf8ec5474cc":[8,0,1,10,1,0,0,89,10],
"_subtraction_test_impl_8cpp.xhtml#abaaed9ad1a85f80958dcec993bba6f3a":[8,0,1,10,1,0,0,89,9],
"_subtraction_test_impl_8cpp.xhtml#aedabb354e4e5af0759202e4dbbeb8441":[8,0,1,10,1,0,0,89,12],
"_subtraction_test_impl_8cpp.xhtml#aef09cbd7cc6981573d1436888cf1a82a":[8,0,1,10,1,0,0,89,1],
"_subtraction_test_impl_8cpp.xhtml#af58d639c9d64bb08acb8b8e3ffaccbbb":[8,0,1,10,1,0,0,89,11],
"_subtraction_test_impl_8cpp.xhtml#af9a0ddee6e06cef7c196cf9b4b363f77":[8,0,1,10,1,0,0,89,3],
"_subtraction_test_impl_8cpp_source.xhtml":[8,0,1,10,1,0,0,89],
"_subtraction_test_impl_8hpp.xhtml":[8,0,1,10,1,0,0,90],
"_subtraction_test_impl_8hpp.xhtml#a098b3aa8ae40141e9c43fc11233bc9ca":[8,0,1,10,1,0,0,90,3],
"_subtraction_test_impl_8hpp.xhtml#a0a1eb21d1ee13e500e36635ebd4c2d2b":[8,0,1,10,1,0,0,90,1],
"_subtraction_test_impl_8hpp.xhtml#a230ab661651ba87930a5bc6a7604e6c8":[8,0,1,10,1,0,0,90,6],
"_subtraction_test_impl_8hpp.xhtml#a28d606742965f098a62e8268dd03d1d6":[8,0,1,10,1,0,0,90,4],
"_subtraction_test_impl_8hpp.xhtml#a3a6e0120f7dce89c2ef03a579c6c581e":[8,0,1,10,1,0,0,90,7],
"_subtraction_test_impl_8hpp.xhtml#a47fe3e5a47fb2e37c3371ab264a07ffd":[8,0,1,10,1,0,0,90,5],
"_subtraction_test_impl_8hpp.xhtml#a7a25b712f181d499480edcf8ec5474cc":[8,0,1,10,1,0,0,90,9],
"_subtraction_test_impl_8hpp.xhtml#abaaed9ad1a85f80958dcec993bba6f3a":[8,0,1,10,1,0,0,90,8],
"_subtraction_test_impl_8hpp.xhtml#aedabb354e4e5af0759202e4dbbeb8441":[8,0,1,10,1,0,0,90,11],
"_subtraction_test_impl_8hpp.xhtml#aef09cbd7cc6981573d1436888cf1a82a":[8,0,1,10,1,0,0,90,0],
"_subtraction_test_impl_8hpp.xhtml#af58d639c9d64bb08acb8b8e3ffaccbbb":[8,0,1,10,1,0,0,90,10],
"_subtraction_test_impl_8hpp.xhtml#af9a0ddee6e06cef7c196cf9b4b363f77":[8,0,1,10,1,0,0,90,2],
"_subtraction_test_impl_8hpp_source.xhtml":[8,0,1,10,1,0,0,90],
"_switch_layer_8cpp.xhtml":[8,0,1,0,0,117],
"_switch_layer_8cpp_source.xhtml":[8,0,1,0,0,117],
"_switch_layer_8hpp.xhtml":[8,0,1,0,0,118],
"_switch_layer_8hpp_source.xhtml":[8,0,1,0,0,118],
"_tensor_8cpp.xhtml":[8,0,1,0,69],
"_tensor_8cpp_source.xhtml":[8,0,1,0,69],
"_tensor_8hpp.xhtml":[8,0,0,0,26],
"_tensor_8hpp.xhtml#a280670a263dc4fd40491f6d0a2737f44":[8,0,0,0,26,5],
"_tensor_8hpp.xhtml#a8f091a512915d1cb29a4ebf13dfc53ea":[8,0,0,0,26,7],
"_tensor_8hpp.xhtml#aa01bce88f89975a5a031db4cc8861527":[8,0,0,0,26,6],
"_tensor_8hpp_source.xhtml":[8,0,0,0,26],
"_tensor_buffer_array_view_8hpp.xhtml":[8,0,1,10,5,1,159],
"_tensor_buffer_array_view_8hpp_source.xhtml":[8,0,1,10,5,1,159],
"_tensor_copy_utils_8cpp.xhtml":[8,0,1,10,1,0,45],
"_tensor_copy_utils_8cpp.xhtml#a99b626c58a926dc7d6df78d22ec186c8":[8,0,1,10,1,0,45,1],
"_tensor_copy_utils_8cpp.xhtml#ae15f1a3c55d2db87683577de9fa4437c":[8,0,1,10,1,0,45,2],
"_tensor_copy_utils_8cpp.xhtml#afaaca8c3f3a467d124bba44067d2afa8":[8,0,1,10,1,0,45,0],
"_tensor_copy_utils_8cpp_source.xhtml":[8,0,1,10,1,0,45],
"_tensor_copy_utils_8hpp.xhtml":[8,0,1,10,1,0,46],
"_tensor_copy_utils_8hpp.xhtml#ab5dfed8358e500ed523d78090ec78e88":[8,0,1,10,1,0,46,1],
"_tensor_copy_utils_8hpp.xhtml#ae15f1a3c55d2db87683577de9fa4437c":[8,0,1,10,1,0,46,2],
"_tensor_copy_utils_8hpp.xhtml#afaaca8c3f3a467d124bba44067d2afa8":[8,0,1,10,1,0,46,0],
"_tensor_copy_utils_8hpp_source.xhtml":[8,0,1,10,1,0,46],
"_tensor_fwd_8hpp.xhtml":[8,0,0,0,27],
"_tensor_fwd_8hpp_source.xhtml":[8,0,0,0,27],
"_tensor_handle_factory_registry_8cpp.xhtml":[8,0,1,10,1,27],
"_tensor_handle_factory_registry_8cpp_source.xhtml":[8,0,1,10,1,27],
"_tensor_handle_factory_registry_8hpp.xhtml":[8,0,1,10,1,28],
"_tensor_handle_factory_registry_8hpp_source.xhtml":[8,0,1,10,1,28],
"_tensor_handle_strategy_test_8cpp.xhtml":[8,0,1,0,2,27],
"_tensor_handle_strategy_test_8cpp.xhtml#a3b686f41b00e6932d0295bc0ba350580":[8,0,1,0,2,27,1],
"_tensor_handle_strategy_test_8cpp.xhtml#ac85858fa4c4f1c9574f249dcc3ac0cf5":[8,0,1,0,2,27,0],
"_tensor_handle_strategy_test_8cpp_source.xhtml":[8,0,1,0,2,27],
"_tensor_helpers_8hpp.xhtml":[8,0,1,0,2,28],
"_tensor_helpers_8hpp.xhtml#a0b8fbb443d2cf34a41f6aaae934e3dcb":[8,0,1,0,2,28,2],
"_tensor_helpers_8hpp.xhtml#a1268c19758dd636d0da80d16d2a4f2f4":[8,0,1,0,2,28,3],
"_tensor_helpers_8hpp.xhtml#a1ed60e4e5a0ec57f6483904e11fbd781":[8,0,1,0,2,28,8],
"_tensor_helpers_8hpp.xhtml#a617427516e17888a138c16d3af503cfd":[8,0,1,0,2,28,7],
"_tensor_helpers_8hpp.xhtml#a833e7db5d5f7e93102e80de57a602cf7":[8,0,1,0,2,28,6],
"_tensor_helpers_8hpp.xhtml#a9c063a8b0e52737d20184cd36dcf483e":[8,0,1,0,2,28,4],
"_tensor_helpers_8hpp.xhtml#aca9db6ac279d665c182b8bc1be743d4b":[8,0,1,0,2,28,5],
"_tensor_helpers_8hpp_source.xhtml":[8,0,1,0,2,28],
"_tensor_i_o_utils_8hpp.xhtml":[8,0,1,9,29],
"_tensor_i_o_utils_8hpp.xhtml#ad4efd5a7fa660df5246466d83517220d":[8,0,1,9,29,1],
"_tensor_i_o_utils_8hpp.xhtml#ad5310a199d4969927169ed084b1f6c28":[8,0,1,9,29,0],
"_tensor_i_o_utils_8hpp_source.xhtml":[8,0,1,9,29],
"_tensor_test_8cpp.xhtml":[8,0,1,0,2,29],
"_tensor_test_8cpp.xhtml#a0c4119e76379387b984dbbbf998f2925":[8,0,1,0,2,29,9],
"_tensor_test_8cpp.xhtml#a3370241e4a543440e79a3d1842fe6f9f":[8,0,1,0,2,29,6],
"_tensor_test_8cpp.xhtml#a37f7ffb280c544fe70e212e24fc5c2a7":[8,0,1,0,2,29,5],
"_tensor_test_8cpp.xhtml#a60cf24873ff60e391417efc873e9c55e":[8,0,1,0,2,29,2],
"_tensor_test_8cpp.xhtml#a67f451b173e1cea17e907085cb967184":[8,0,1,0,2,29,1],
"_tensor_test_8cpp.xhtml#a8ff9749fd66d314c3c2bbef1eca00f09":[8,0,1,0,2,29,7],
"_tensor_test_8cpp.xhtml#aa08fb9adf6eaf05fd4a3698880c1c292":[8,0,1,0,2,29,0],
"_tensor_test_8cpp.xhtml#aa2d0d8c3d827fec2b96ff3ae2389550e":[8,0,1,0,2,29,8],
"_tensor_test_8cpp.xhtml#ab7e46ed88187c63506b21f45abbabb13":[8,0,1,0,2,29,4],
"_tensor_test_8cpp.xhtml#abe311824d11bad4e6f93c8f94a721052":[8,0,1,0,2,29,10],
"_tensor_test_8cpp.xhtml#ad80e179ec400af9d2547f172f3ca05f3":[8,0,1,0,2,29,12],
"_tensor_test_8cpp.xhtml#ad842127d839c39ea39e3c0f3ac219728":[8,0,1,0,2,29,3],
"_tensor_test_8cpp.xhtml#af676ec7e9534bd6e6ac3072a2c0403f4":[8,0,1,0,2,29,11],
"_tensor_test_8cpp_source.xhtml":[8,0,1,0,2,29],
"_tensor_utils_8cpp.xhtml":[8,0,1,9,30],
"_tensor_utils_8cpp.xhtml#a0d3b1be320610515e0cac8d745d9f8c2":[8,0,1,9,30,0],
"_tensor_utils_8cpp.xhtml#a1826e433f7e6817976a8175b4ef8296c":[8,0,1,9,30,4],
"_tensor_utils_8cpp.xhtml#a1c9097ab13afc54b48c503c6487aaee1":[8,0,1,9,30,1],
"_tensor_utils_8cpp.xhtml#a276aac5f7a8bdc3db4f62203870ca13b":[8,0,1,9,30,2],
"_tensor_utils_8cpp.xhtml#ab53d94ea22b51c6bcdf9584644bd67bb":[8,0,1,9,30,6],
"_tensor_utils_8cpp.xhtml#ac93cb1365b4bcb67df2a3164606096c5":[8,0,1,9,30,7],
"_tensor_utils_8cpp.xhtml#acee63cd08da47910fc166a1990988fa8":[8,0,1,9,30,5],
"_tensor_utils_8cpp.xhtml#af57864f5e03358d14c2988edae912b8b":[8,0,1,9,30,3],
"_tensor_utils_8cpp_source.xhtml":[8,0,1,9,30],
"_tensor_utils_8hpp.xhtml":[8,0,0,8,3],
"_tensor_utils_8hpp.xhtml#a0d3b1be320610515e0cac8d745d9f8c2":[8,0,0,8,3,0],
"_tensor_utils_8hpp.xhtml#a1826e433f7e6817976a8175b4ef8296c":[8,0,0,8,3,4],
"_tensor_utils_8hpp.xhtml#a1c9097ab13afc54b48c503c6487aaee1":[8,0,0,8,3,1],
"_tensor_utils_8hpp.xhtml#a276aac5f7a8bdc3db4f62203870ca13b":[8,0,0,8,3,2],
"_tensor_utils_8hpp.xhtml#ab53d94ea22b51c6bcdf9584644bd67bb":[8,0,0,8,3,6],
"_tensor_utils_8hpp.xhtml#ac93cb1365b4bcb67df2a3164606096c5":[8,0,0,8,3,7],
"_tensor_utils_8hpp.xhtml#acee63cd08da47910fc166a1990988fa8":[8,0,0,8,3,5],
"_tensor_utils_8hpp.xhtml#af57864f5e03358d14c2988edae912b8b":[8,0,0,8,3,3],
"_tensor_utils_8hpp_source.xhtml":[8,0,0,8,3],
"_tensor_utils_test_8cpp.xhtml":[8,0,1,9,0,3],
"_tensor_utils_test_8cpp.xhtml#a0d048754792d48814de6439d92a29d9c":[8,0,1,9,0,3,3],
"_tensor_utils_test_8cpp.xhtml#a1e0b87cda1d2bfe80088d3471e7fd686":[8,0,1,9,0,3,5],
"_tensor_utils_test_8cpp.xhtml#a24cf6420255d3bd5216d6647b4a9bbe4":[8,0,1,9,0,3,4],
"_tensor_utils_test_8cpp.xhtml#a37e741751fee525555c3ea6532cd17da":[8,0,1,9,0,3,7],
"_tensor_utils_test_8cpp.xhtml#a5a5368956088b8ef14d465055b89d447":[8,0,1,9,0,3,9],
"_tensor_utils_test_8cpp.xhtml#a6e672cf04351ee8892329b68c27e9c14":[8,0,1,9,0,3,0],
"_tensor_utils_test_8cpp.xhtml#a86bc813164349ab85f235da3c80358a7":[8,0,1,9,0,3,1],
"_tensor_utils_test_8cpp.xhtml#abceec4b5019af3a180d3984b9dea53b8":[8,0,1,9,0,3,6],
"_tensor_utils_test_8cpp.xhtml#adcbc12d75dfa067e4664f40ec118ea13":[8,0,1,9,0,3,8],
"_tensor_utils_test_8cpp.xhtml#ae770db0f1e6414418b5c218cd911240f":[8,0,1,9,0,3,2],
"_tensor_utils_test_8cpp_source.xhtml":[8,0,1,9,0,3],
"_test_add_8cpp.xhtml":[8,0,1,1,0,0],
"_test_add_8cpp.xhtml#aa070655d65367bb3a6bc1fb8c766de5a":[8,0,1,1,0,0,0],
"_test_add_8cpp_source.xhtml":[8,0,1,1,0,0],
"_test_concat_8cpp.xhtml":[8,0,1,1,0,1],
"_test_concat_8cpp.xhtml#ac0bbd42b4559d14d119a2c8710d030ec":[8,0,1,1,0,1,0],
"_test_concat_8cpp_source.xhtml":[8,0,1,1,0,1],
"_test_convolution_8cpp.xhtml":[8,0,1,1,0,2],
"_test_convolution_8cpp.xhtml#a4357dcb7cef65e5008a7a3b740abab71":[8,0,1,1,0,2,0],
"_test_convolution_8cpp.xhtml#a7c046499aa69c269044b80c668ce7694":[8,0,1,1,0,2,1],
"_test_convolution_8cpp_source.xhtml":[8,0,1,1,0,2],
"_test_dependencies_8cpp.xhtml":[8,0,1,8,0,39],
"_test_dependencies_8cpp.xhtml#a22ab2542baa07554aea2836269a428b5":[8,0,1,8,0,39,3],
"_test_dependencies_8cpp.xhtml#a549bbef9e3ef8485b3936026f9b1c586":[8,0,1,8,0,39,1],
"_test_dependencies_8cpp.xhtml#a64c9c9e6a66e55bcb1deecfff7793fd1":[8,0,1,8,0,39,4],
"_test_dependencies_8cpp.xhtml#a8c5f97c76a7b00b63d915315583a9634":[8,0,1,8,0,39,2],
"_test_dependencies_8cpp.xhtml#afdf3505a3289794a0c15d764343bfa2f":[8,0,1,8,0,39,0],
"_test_dependencies_8cpp_source.xhtml":[8,0,1,8,0,39],
"_test_dropout_8cpp.xhtml":[8,0,1,1,0,3],
"_test_dropout_8cpp.xhtml#a7b2c545295539f1be317977a258dd22d":[8,0,1,1,0,3,0],
"_test_dropout_8cpp_source.xhtml":[8,0,1,1,0,3],
"_test_dynamic_backend_8cpp.xhtml":[8,0,1,10,1,0,47],
"_test_dynamic_backend_8cpp.xhtml#a6a075b7c32d5511f95903749eef44b22":[8,0,1,10,1,0,47,0],
"_test_dynamic_backend_8cpp.xhtml#aa8f09f94b0356f870c9bdb9c594cddfc":[8,0,1,10,1,0,47,2],
"_test_dynamic_backend_8cpp.xhtml#adaff295134ed2825ae43a8e9281b6f2a":[8,0,1,10,1,0,47,1],
"_test_dynamic_backend_8cpp.xhtml#aec75c1d78333f881f2516f55a0ed00df":[8,0,1,10,1,0,47,3],
"_test_dynamic_backend_8cpp_source.xhtml":[8,0,1,10,1,0,47],
"_test_dynamic_backend_8hpp.xhtml":[8,0,1,10,1,0,48],
"_test_dynamic_backend_8hpp_source.xhtml":[8,0,1,10,1,0,48],
"_test_in_place_8cpp.xhtml":[8,0,1,1,0,4],
"_test_in_place_8cpp.xhtml#a0df8f0933c0d59c08a94862170c6d3f9":[8,0,1,1,0,4,1],
"_test_in_place_8cpp.xhtml#aa4fe1c594e7b6adfd6c2d8a8ec828128":[8,0,1,1,0,4,0],
"_test_in_place_8cpp_source.xhtml":[8,0,1,1,0,4],
"_test_input_output_layer_visitor_8cpp.xhtml":[8,0,1,0,2,30],
"_test_input_output_layer_visitor_8cpp.xhtml#a9a7475b081b431ffa9915aac51c2d338":[8,0,1,0,2,30,3],
"_test_input_output_layer_visitor_8cpp.xhtml#ac28b0a4861e6eab3e7621a7ed4eb5f62":[8,0,1,0,2,30,2],
"_test_input_output_layer_visitor_8cpp.xhtml#ac7ce83f024515592cffac13ae5220f1e":[8,0,1,0,2,30,1],
"_test_input_output_layer_visitor_8cpp.xhtml#ad3d9cbf26cb5894fd6d9169dbe743417":[8,0,1,0,2,30,0],
"_test_input_output_layer_visitor_8cpp_source.xhtml":[8,0,1,0,2,30],
"_test_input_output_layer_visitor_8hpp.xhtml":[8,0,1,0,2,31],
"_test_input_output_layer_visitor_8hpp.xhtml#a5a38bd982292180692711b0ae296bb34":[8,0,1,0,2,31,2],
"_test_input_output_layer_visitor_8hpp_source.xhtml":[8,0,1,0,2,31],
"_test_inputs_8cpp.xhtml":[8,0,1,1,0,5],
"_test_inputs_8cpp.xhtml#adcdb40b9138ac9b00e08ee5ba4721c0f":[8,0,1,1,0,5,0],
"_test_inputs_8cpp_source.xhtml":[8,0,1,1,0,5],
"_test_layer_visitor_8cpp.xhtml":[8,0,1,0,2,32],
"_test_layer_visitor_8cpp_source.xhtml":[8,0,1,0,2,32],
"_test_layer_visitor_8hpp.xhtml":[8,0,1,0,2,33],
"_test_layer_visitor_8hpp_source.xhtml":[8,0,1,0,2,33],
"_test_mul_8cpp.xhtml":[8,0,1,1,0,6],
"_test_mul_8cpp.xhtml#a0f1190f1e2f88395a87909d491023f6d":[8,0,1,1,0,6,0],
"_test_mul_8cpp_source.xhtml":[8,0,1,1,0,6],
"_test_name_and_descriptor_layer_visitor_8cpp.xhtml":[8,0,1,0,2,34],
"_test_name_and_descriptor_layer_visitor_8cpp.xhtml#a02dbd979639aab5075de848f20ae3334":[8,0,1,0,2,34,21],
"_test_name_and_descriptor_layer_visitor_8cpp.xhtml#a04a75c2b471c8c2914fb9ed45773dec8":[8,0,1,0,2,34,15],
"_test_name_and_descriptor_layer_visitor_8cpp.xhtml#a05c1b0442f2da63f19cd12e830b95c88":[8,0,1,0,2,34,48],
"_test_name_and_descriptor_layer_visitor_8cpp.xhtml#a0f352902d18c1f1f62f6c7051a26ca2c":[8,0,1,0,2,34,4],
"_test_name_and_descriptor_layer_visitor_8cpp.xhtml#a1b7b470267c546298d1af9d4df62cd87":[8,0,1,0,2,34,28],
"_test_name_and_descriptor_layer_visitor_8cpp.xhtml#a1c96b11c93b181f61ef2f78a6b2aef70":[8,0,1,0,2,34,25],
"_test_name_and_descriptor_layer_visitor_8cpp.xhtml#a1cf9c6892d6fe97f44a8f445a1a50cac":[8,0,1,0,2,34,43],
"_test_name_and_descriptor_layer_visitor_8cpp.xhtml#a2647d29147747ec8b924a3c9fb22fd6d":[8,0,1,0,2,34,2],
"_test_name_and_descriptor_layer_visitor_8cpp.xhtml#a2fb68738871234e75f17c26e5ff8a755":[8,0,1,0,2,34,24],
"_test_name_and_descriptor_layer_visitor_8cpp.xhtml#a32e1d00f5582145b5f1e35696c84094f":[8,0,1,0,2,34,32],
"_test_name_and_descriptor_layer_visitor_8cpp.xhtml#a345bd1611aee381dd2d80220420e7e6e":[8,0,1,0,2,34,16],
"_test_name_and_descriptor_layer_visitor_8cpp.xhtml#a3aa5e503846c044f79c3e8d3bf08785b":[8,0,1,0,2,34,7],
"_test_name_and_descriptor_layer_visitor_8cpp.xhtml#a3d6fcc84aaef5ce77eed2e6701ac8a86":[8,0,1,0,2,34,18],
"_test_name_and_descriptor_layer_visitor_8cpp.xhtml#a3e8fdeb655e6fe9faf8df1910426cfe0":[8,0,1,0,2,34,27],
"_test_name_and_descriptor_layer_visitor_8cpp.xhtml#a4bb5aced71588ef3f382378b0c14b179":[8,0,1,0,2,34,3],
"_test_name_and_descriptor_layer_visitor_8cpp.xhtml#a4d5eb1336da365183afeb01f03495793":[8,0,1,0,2,34,40],
"_test_name_and_descriptor_layer_visitor_8cpp.xhtml#a4ee103b7f00dc65fe891df4af4e9061d":[8,0,1,0,2,34,22],
"_test_name_and_descriptor_layer_visitor_8cpp.xhtml#a570d9ca70ab7406de40868f438720e7d":[8,0,1,0,2,34,50],
"_test_name_and_descriptor_layer_visitor_8cpp.xhtml#a577b9a70537368382f9002f0df723512":[8,0,1,0,2,34,0],
"_test_name_and_descriptor_layer_visitor_8cpp.xhtml#a59dd186be463bbf8ee84c32de0dff360":[8,0,1,0,2,34,36],
"_test_name_and_descriptor_layer_visitor_8cpp.xhtml#a6b736b00085e9a711587bc9fb4d750fe":[8,0,1,0,2,34,13],
"_test_name_and_descriptor_layer_visitor_8cpp.xhtml#a74b47f1baf38bdc6e8f44351271c472e":[8,0,1,0,2,34,45],
"_test_name_and_descriptor_layer_visitor_8cpp.xhtml#a7a7ad4ab5d2fb859884a1ce251b75b78":[8,0,1,0,2,34,34],
"_test_name_and_descriptor_layer_visitor_8cpp.xhtml#a7c204d840b975323b936ad1780d61ae3":[8,0,1,0,2,34,42],
"_test_name_and_descriptor_layer_visitor_8cpp.xhtml#a83b6d6bd54b548c5be56767ce8420805":[8,0,1,0,2,34,11],
"_test_name_and_descriptor_layer_visitor_8cpp.xhtml#a84b4e27f8f132d14e0b133f58cf281a1":[8,0,1,0,2,34,38],
"_test_name_and_descriptor_layer_visitor_8cpp.xhtml#a899e2a3eeec95bb534a78676eb868dda":[8,0,1,0,2,34,9],
"_test_name_and_descriptor_layer_visitor_8cpp.xhtml#a8dd034c2704df7600b2b0f77b6111094":[8,0,1,0,2,34,52],
"_test_name_and_descriptor_layer_visitor_8cpp.xhtml#a8f39ccf6290d0bc7d04c34790ed0fb8b":[8,0,1,0,2,34,6],
"_test_name_and_descriptor_layer_visitor_8cpp.xhtml#a903fcf9df34ffa45b58eb62cae927332":[8,0,1,0,2,34,5],
"_test_name_and_descriptor_layer_visitor_8cpp.xhtml#a91fed2f3208a10aa539672d51074ed30":[8,0,1,0,2,34,19],
"_test_name_and_descriptor_layer_visitor_8cpp.xhtml#a966256ee58f3a64e06b98e4db415dd38":[8,0,1,0,2,34,51],
"_test_name_and_descriptor_layer_visitor_8cpp.xhtml#a99da153508dc554746600cee44f89c5c":[8,0,1,0,2,34,49],
"_test_name_and_descriptor_layer_visitor_8cpp.xhtml#a9b3fe4cff6c810098cfdcb4c30d36a8d":[8,0,1,0,2,34,29],
"_test_name_and_descriptor_layer_visitor_8cpp.xhtml#a9da8a16fa1b8af055dc8950c3f6d6e5d":[8,0,1,0,2,34,17],
"_test_name_and_descriptor_layer_visitor_8cpp.xhtml#a9e71542e80315e0b460443c61b4221b6":[8,0,1,0,2,34,44],
"_test_name_and_descriptor_layer_visitor_8cpp.xhtml#aad3338b700397b8f0d3c2f131a0f6e02":[8,0,1,0,2,34,31],
"_test_name_and_descriptor_layer_visitor_8cpp.xhtml#aadddaf7f38216b8df27814af8dd34e39":[8,0,1,0,2,34,12],
"_test_name_and_descriptor_layer_visitor_8cpp.xhtml#abdf82785b118309efb02e78aebdc1f51":[8,0,1,0,2,34,20],
"_test_name_and_descriptor_layer_visitor_8cpp.xhtml#ac609f4a59586c7e4c21a058e42bef363":[8,0,1,0,2,34,46],
"_test_name_and_descriptor_layer_visitor_8cpp.xhtml#acbbcbec522726368c08c7cf2e7ef7166":[8,0,1,0,2,34,39],
"_test_name_and_descriptor_layer_visitor_8cpp.xhtml#acf3de9ce3705fd18bf4b94b2343ff01e":[8,0,1,0,2,34,26],
"_test_name_and_descriptor_layer_visitor_8cpp.xhtml#ad359323fe69e8bcd98400c6100b28e52":[8,0,1,0,2,34,47],
"_test_name_and_descriptor_layer_visitor_8cpp.xhtml#ad4490cd60e4cd92806612f9c71a89260":[8,0,1,0,2,34,10],
"_test_name_and_descriptor_layer_visitor_8cpp.xhtml#ae074337406c649c72587e5010640d1fd":[8,0,1,0,2,34,35],
"_test_name_and_descriptor_layer_visitor_8cpp.xhtml#aef96298e8ecd561861a355e3fdf6e55b":[8,0,1,0,2,34,33],
"_test_name_and_descriptor_layer_visitor_8cpp.xhtml#af0adc9f8427d070f18b6c6098fcd4fee":[8,0,1,0,2,34,37],
"_test_name_and_descriptor_layer_visitor_8cpp.xhtml#af14f427675d2a23d8f21106911ab0ceb":[8,0,1,0,2,34,1],
"_test_name_and_descriptor_layer_visitor_8cpp.xhtml#af2031a80bd42b21d5cb51f9af0b7721e":[8,0,1,0,2,34,14],
"_test_name_and_descriptor_layer_visitor_8cpp.xhtml#af28112fcb200bf77c83910f80bfff9c3":[8,0,1,0,2,34,23],
"_test_name_and_descriptor_layer_visitor_8cpp.xhtml#af4b8978e4b4ef6588ef2df79395c5091":[8,0,1,0,2,34,41],
"_test_name_and_descriptor_layer_visitor_8cpp.xhtml#afa3fd30f4967d694c7676137941824f1":[8,0,1,0,2,34,8],
"_test_name_and_descriptor_layer_visitor_8cpp.xhtml#afbb5ed8d3b7d26fe583b23141e69cf2d":[8,0,1,0,2,34,30],
"_test_name_and_descriptor_layer_visitor_8cpp_source.xhtml":[8,0,1,0,2,34],
"_test_name_and_descriptor_layer_visitor_8hpp.xhtml":[8,0,1,0,2,35],
"_test_name_and_descriptor_layer_visitor_8hpp.xhtml#abb64418b249a328aae53463610990dc4":[8,0,1,0,2,35,26],
"_test_name_and_descriptor_layer_visitor_8hpp_source.xhtml":[8,0,1,0,2,35],
"_test_name_only_layer_visitor_8cpp.xhtml":[8,0,1,0,2,36],
"_test_name_only_layer_visitor_8cpp.xhtml#a0875cd811c56ce312446691182748d9a":[8,0,1,0,2,36,19],
"_test_name_only_layer_visitor_8cpp.xhtml#a130f01c9c45fcf7cfed16119d3b205bf":[8,0,1,0,2,36,8],
"_test_name_only_layer_visitor_8cpp.xhtml#a19538928d62dead0627f24bcdfec7ccc":[8,0,1,0,2,36,28],
"_test_name_only_layer_visitor_8cpp.xhtml#a1b40448b6fb040f20a618dda9456b9d4":[8,0,1,0,2,36,3],
"_test_name_only_layer_visitor_8cpp.xhtml#a23eb3410282e4b211da025fdcf40c766":[8,0,1,0,2,36,15],
"_test_name_only_layer_visitor_8cpp.xhtml#a24d4ba09b4dc38870a9cd54015390a6f":[8,0,1,0,2,36,24],
"_test_name_only_layer_visitor_8cpp.xhtml#a3d5f1bbce77e67bb4730842854c9dbf5":[8,0,1,0,2,36,17],
"_test_name_only_layer_visitor_8cpp.xhtml#a60c2decf7c454434142f5d97a080600f":[8,0,1,0,2,36,7],
"_test_name_only_layer_visitor_8cpp.xhtml#a6cb0eb9dc9d4ca024e598e20a98ccbea":[8,0,1,0,2,36,27],
"_test_name_only_layer_visitor_8cpp.xhtml#a701ce0a217a8d5a2ed0e9037cf765427":[8,0,1,0,2,36,6],
"_test_name_only_layer_visitor_8cpp.xhtml#a7acba4ff7297af8c3b6977e20430d5da":[8,0,1,0,2,36,21],
"_test_name_only_layer_visitor_8cpp.xhtml#a7f3835dd0849992901ad3d743a9afc8e":[8,0,1,0,2,36,23],
"_test_name_only_layer_visitor_8cpp.xhtml#a854b9394f3190ff6eb7bbdc39f961a98":[8,0,1,0,2,36,12],
"_test_name_only_layer_visitor_8cpp.xhtml#a868d7e7a9216e27635714eb2b3c17bc9":[8,0,1,0,2,36,20],
"_test_name_only_layer_visitor_8cpp.xhtml#a8bf90c752dff6071dc1784f44def0e40":[8,0,1,0,2,36,16],
"_test_name_only_layer_visitor_8cpp.xhtml#a8d0d3748f0a8e0cfb1b59adbffda8ffb":[8,0,1,0,2,36,13],
"_test_name_only_layer_visitor_8cpp.xhtml#a960d5f61d365f02818892192b067cd3e":[8,0,1,0,2,36,11],
"_test_name_only_layer_visitor_8cpp.xhtml#a98ee232e2c09675a167a4f126d14b3cf":[8,0,1,0,2,36,9],
"_test_name_only_layer_visitor_8cpp.xhtml#aa10c0f132720466b600e0179fa44d9b6":[8,0,1,0,2,36,26],
"_test_name_only_layer_visitor_8cpp.xhtml#ab9e0246f4b11f2a3678f9fb69cf338b4":[8,0,1,0,2,36,18],
"_test_name_only_layer_visitor_8cpp.xhtml#abe5fb1aee487dfd4f7beeb6861ea5688":[8,0,1,0,2,36,22],
"_test_name_only_layer_visitor_8cpp.xhtml#abfa44889060be0a901c6a9527356d575":[8,0,1,0,2,36,0],
"_test_name_only_layer_visitor_8cpp.xhtml#ac9344e06190544c7697466ed6d0f8fc8":[8,0,1,0,2,36,5],
"_test_name_only_layer_visitor_8cpp.xhtml#ad5e44825beaadbf65463be63c6d80099":[8,0,1,0,2,36,4],
"_test_name_only_layer_visitor_8cpp.xhtml#ae531df2fd42d3c517302410fa5f0b119":[8,0,1,0,2,36,25],
"_test_name_only_layer_visitor_8cpp.xhtml#ae6d90b5ebd931bd8696fc6220f10933c":[8,0,1,0,2,36,1]
};
|
#!/bin/sh
# CYBERWATCH SAS - 2017
#
# Security fix for DSA-3490-1
#
# Security announcement date: 2016-02-24 00:00:00 UTC
# Script generation date: 2017-01-01 21:07:52 UTC
#
# Operating System: Debian 8 (Jessie)
# Architecture: i386
#
# Vulnerable packages fix on version:
# - websvn:2.3.3-1.2+deb8u1
#
# Last versions recommanded by security team:
# - websvn:2.3.3-1.2+deb8u2
#
# CVE List:
# - CVE-2016-2511
#
# More details:
# - https://www.cyberwatch.fr/vulnerabilites
#
# Licence: Released under The MIT License (MIT), See LICENSE FILE
sudo apt-get install --only-upgrade websvn=2.3.3-1.2+deb8u2 -y
|
import numpy as np
from sklearn import tree
# Load the data
data = np.genfromtxt("data.csv", delimiter=",")
X = data[:,:-1]
y = data[:,-1]
# Create and train the decision tree model
clf = tree.DecisionTreeClassifier()
clf = clf.fit(X, y)
# Use the model to predict values
predictions = clf.predict(X)
|
package yotacast.com.yotacast;
import android.app.Service;
import android.appwidget.AppWidgetManager;
import android.content.BroadcastReceiver;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.media.Ringtone;
import android.media.RingtoneManager;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.IBinder;
import android.preference.PreferenceManager;
import android.util.Base64;
import android.util.Log;
import android.view.View;
import android.widget.RemoteViews;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.BufferedInputStream;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.net.URLConnection;
import java.util.ArrayList;
public class YotaCastService extends Service {
AsyncTask t, jsonTask;
SharedPreferences prefs = null;
boolean ended = false;
int position = -1;
ArrayList<Bitmap> imageCache = new ArrayList<Bitmap>();
private BroadcastReceiver mReceiver;
IntentFilter intentFilter;
public YotaCastService() {
}
public int onStartCommand(Intent intent, int flags, int startId) {
Log.d("casting", "on");
t = new CastTask().execute();
prefs = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
showView();
// prev fwd back
intentFilter = new IntentFilter(
"yotacast.com.yotacast.cache");
mReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
String msg = intent.getStringExtra("type");
if (position == -1) {
showCache();
position = imageCache.size() - 1;
}
if (msg.equals("prev"))
YotaCastService.this.setCache(position-1);
else if (msg.equals("fwd"))
YotaCastService.this.setCache(position+1);
else if (msg.equals("back")) {
position = -1;
YotaCastService.this.showView();
}
}
};
//registering our receiver
this.registerReceiver(mReceiver, intentFilter);
return START_STICKY;
}
@Override
public IBinder onBind(Intent intent) {
// TODO: Return the communication channel to the service.
throw new UnsupportedOperationException("Not yet implemented");
}
// Ping
private class CastTask extends AsyncTask<Void, Void, Void> {
protected Void doInBackground(Void... v) {
if (ended)
return null;
int freq = prefs.getInt("freq", 1000);
try {
jsonTask = new AsyncTaskParseJson().executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
} catch (Exception e){
}
try {
Thread.sleep(freq);
} catch (Exception e) {
e.printStackTrace();
return null;
}
t = new CastTask().execute();
return null;
}
}
// you can make this class as another java file so it will be separated from your main activity.
public class AsyncTaskParseJson extends AsyncTask<Void, Void, Void> {
@Override
protected Void doInBackground(Void... arg0) {
refresh();
return null;
}
}
public void refresh(){
String img = null;
boolean alert = false;
String endpoint = prefs.getString("endpoint", "http://google.com")+"/latest_image";
try {
// instantiate our json parser
JSONParser jParser = new JSONParser();
// get json string from url
JSONObject json = jParser.getJSONFromUrl(endpoint);
if (json == null)
return;
// img and alert
img = json.getString("raw_string");
alert = json.getBoolean("play_alert");
double diffValue = 0;
try {
diffValue = json.getDouble("diff");
} catch (Exception e){
}
if (diffValue > 30)
alert = true;
byte[] decodedString = Base64.decode(img, Base64.NO_WRAP);
InputStream inputStream = new ByteArrayInputStream(decodedString);
Bitmap bitmap = BitmapFactory.decodeStream(inputStream);
updateView(bitmap);
if (alert)
showAlert();
else
hideAlert();
} catch (Exception e) {
e.printStackTrace();
}
}
public void updateView(Bitmap img){
RemoteViews view = new RemoteViews(getPackageName(), R.layout.yotacast);
view.setImageViewBitmap(R.id.imageView, img);
// Push update for this widget to the home screen
ComponentName thisWidget = new ComponentName(YotaCastService.this, YotaCastWidget.class);
AppWidgetManager manager = AppWidgetManager.getInstance(YotaCastService.this);
manager.updateAppWidget(thisWidget, view);
if (position == -1)
imageCache.add(img);
if (imageCache.size() > 10)
imageCache.remove(0);
}
public void hideView(){
Log.d("yota", "show place");
RemoteViews view = new RemoteViews(getPackageName(), R.layout.yotacast);
view.setViewVisibility(R.id.imageView, View.INVISIBLE);
view.setViewVisibility(R.id.imageCache, View.INVISIBLE);
view.setViewVisibility(R.id.imagePlaceholder, View.VISIBLE);
view.setTextColor(R.id.buttonPlay, Color.parseColor("#80000000"));
view.setViewVisibility(R.id.buttonBack, View.INVISIBLE);
view.setViewVisibility(R.id.buttonFwd, View.INVISIBLE);
// Push update for this widget to the home screen
ComponentName thisWidget = new ComponentName(YotaCastService.this, YotaCastWidget.class);
AppWidgetManager manager = AppWidgetManager.getInstance(YotaCastService.this);
manager.updateAppWidget(thisWidget, view);
}
public void showView(){
Log.d("yota", "show view");
RemoteViews view = new RemoteViews(getPackageName(), R.layout.yotacast);
view.setViewVisibility(R.id.imageView, View.VISIBLE);
view.setViewVisibility(R.id.imagePlaceholder, View.INVISIBLE);
view.setViewVisibility(R.id.imageCache, View.INVISIBLE);
view.setTextColor(R.id.buttonPlay, Color.TRANSPARENT);
view.setViewVisibility(R.id.buttonBack, View.INVISIBLE);
view.setViewVisibility(R.id.buttonFwd, View.INVISIBLE);
// Push update for this widget to the home screen
ComponentName thisWidget = new ComponentName(YotaCastService.this, YotaCastWidget.class);
AppWidgetManager manager = AppWidgetManager.getInstance(YotaCastService.this);
manager.updateAppWidget(thisWidget, view);
}
void showCache(){
Log.d("yota", "show cache");
RemoteViews view = new RemoteViews(getPackageName(), R.layout.yotacast);
view.setViewVisibility(R.id.imageCache, View.VISIBLE);
view.setViewVisibility(R.id.imageView, View.INVISIBLE);
view.setViewVisibility(R.id.imagePlaceholder, View.INVISIBLE);
view.setViewVisibility(R.id.buttonBack, View.VISIBLE);
view.setViewVisibility(R.id.buttonFwd, View.VISIBLE);
// Push update for this widget to the home screen
ComponentName thisWidget = new ComponentName(YotaCastService.this, YotaCastWidget.class);
AppWidgetManager manager = AppWidgetManager.getInstance(YotaCastService.this);
manager.updateAppWidget(thisWidget, view);
}
void setCache(int pos){
if (pos == -1)
pos = 0;
if (pos >= imageCache.size())
pos = imageCache.size() - 1;
position = pos;
Log.d("yota", "position "+position + " " +imageCache.size());
if (position < 0)
return;
RemoteViews view = new RemoteViews(getPackageName(), R.layout.yotacast);
view.setImageViewBitmap(R.id.imageCache, imageCache.get(position));
// Push update for this widget to the home screen
ComponentName thisWidget = new ComponentName(YotaCastService.this, YotaCastWidget.class);
AppWidgetManager manager = AppWidgetManager.getInstance(YotaCastService.this);
manager.updateAppWidget(thisWidget, view);
}
boolean isWhite = false;
public void showAlert(){
RemoteViews view = new RemoteViews(getPackageName(), R.layout.yotacast);
if (isWhite) {
view.setViewVisibility(R.id.alertText, View.INVISIBLE);
} else {
view.setViewVisibility(R.id.alertText, View.VISIBLE);
}
isWhite = !isWhite;
// Push update for this widget to the home screen
ComponentName thisWidget = new ComponentName(YotaCastService.this, YotaCastWidget.class);
AppWidgetManager manager = AppWidgetManager.getInstance(YotaCastService.this);
manager.updateAppWidget(thisWidget, view);
Log.d("yota", "ALERT");
Uri notification = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
Ringtone r = RingtoneManager.getRingtone(getApplicationContext(), notification);
r.play();
}
public void hideAlert(){
RemoteViews view = new RemoteViews(getPackageName(), R.layout.yotacast);
view.setViewVisibility(R.id.alertText, View.INVISIBLE);
// Push update for this widget to the home screen
ComponentName thisWidget = new ComponentName(YotaCastService.this, YotaCastWidget.class);
AppWidgetManager manager = AppWidgetManager.getInstance(YotaCastService.this);
manager.updateAppWidget(thisWidget, view);
}
public void onDestroy(){
ended = true;
Log.d("casting", "off");
if (jsonTask != null)
jsonTask.cancel(true);
if (t != null)
t.cancel(true);
hideView();
super.onDestroy();
this.unregisterReceiver(this.mReceiver);
}
private Bitmap getImageBitmap(String url) {
Bitmap bm = null;
try {
URL aURL = new URL(url);
URLConnection conn = aURL.openConnection();
conn.connect();
InputStream is = conn.getInputStream();
BufferedInputStream bis = new BufferedInputStream(is);
bm = BitmapFactory.decodeStream(bis);
bis.close();
is.close();
} catch (IOException e) {
Log.e("yo", "Error getting bitmap", e);
}
return bm;
}
}
|
require 'arbre/element/builder_methods'
require 'arbre/element_collection'
module Arbre
class Element
include BuilderMethods
attr_accessor :parent
attr_reader :children, :arbre_context
def initialize(arbre_context = Arbre::Context.new)
@arbre_context = arbre_context
@children = ElementCollection.new
end
def assigns
arbre_context.assigns
end
def helpers
arbre_context.helpers
end
def tag_name
@tag_name ||= self.class.name.demodulize.downcase
end
def build(*args, &block)
# Render the block passing ourselves in
append_return_block(block.call(self)) if block
end
def add_child(child)
return unless child
if child.is_a?(Array)
child.each{|item| add_child(item) }
return @children
end
# If its not an element, wrap it in a TextNode
unless child.is_a?(Element)
child = Arbre::HTML::TextNode.from_string(child)
end
if child.respond_to?(:parent)
# Remove the child
child.parent.remove_child(child) if child.parent
# Set ourselves as the parent
child.parent = self
end
@children << child
end
def remove_child(child)
child.parent = nil if child.respond_to?(:parent=)
@children.delete(child)
end
def <<(child)
add_child(child)
end
def children?
@children.any?
end
def parent=(parent)
@parent = parent
end
def parent?
!@parent.nil?
end
def ancestors
if parent?
[parent] + parent.ancestors
else
[]
end
end
# TODO: Shouldn't grab whole tree
def find_first_ancestor(type)
ancestors.find{|a| a.is_a?(type) }
end
def content=(contents)
clear_children!
add_child(contents)
end
def get_elements_by_tag_name(tag_name)
elements = ElementCollection.new
children.each do |child|
elements << child if child.tag_name == tag_name
elements.concat(child.get_elements_by_tag_name(tag_name))
end
elements
end
alias_method :find_by_tag, :get_elements_by_tag_name
def get_elements_by_class_name(class_name)
elements = ElementCollection.new
children.each do |child|
elements << child if child.class_list.include?(class_name)
elements.concat(child.get_elements_by_tag_name(tag_name))
end
elements
end
alias_method :find_by_class, :get_elements_by_class_name
def content
children.to_s
end
def html_safe
to_s
end
def indent_level
parent? ? parent.indent_level + 1 : 0
end
def each(&block)
[to_s].each(&block)
end
def to_str
to_s
end
def to_s
content
end
def +(element)
case element
when Element, ElementCollection
else
element = Arbre::HTML::TextNode.from_string(element)
end
ElementCollection.new([self]) + element
end
def to_ary
ElementCollection.new [self]
end
alias_method :to_a, :to_ary
private
# Resets the Elements children
def clear_children!
@children.clear
end
# Implements the method lookup chain. When you call a method that
# doesn't exist, we:
#
# 1. Try to call the method on the current DOM context
# 2. Return an assigned variable of the same name
# 3. Call the method on the helper object
# 4. Call super
#
def method_missing(name, *args, &block)
if current_arbre_element.respond_to?(name)
current_arbre_element.send name, *args, &block
elsif assigns && assigns.has_key?(name)
assigns[name]
elsif helpers.respond_to?(name)
helpers.send(name, *args, &block)
else
super
end
end
end
end
|
ALTER TABLE versions ADD COLUMN updated_at TIMESTAMP NOT NULL DEFAULT now();
|
#!/bin/bash
# Copyright 2019 Huawei Technologies Co., Ltd
#
# 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.
# ============================================================================
CURRPATH=$(cd $(dirname $0); pwd)
IGNORE_EXEC="--ignore=$CURRPATH/exec"
PROJECT_PATH=$(cd ${CURRPATH}/../../..; pwd)
if [ $BUILD_PATH ];then
echo "BUILD_PATH = $BUILD_PATH"
else
BUILD_PATH=${PROJECT_PATH}/build
echo "BUILD_PATH = $BUILD_PATH"
fi
export LD_LIBRARY_PATH=$LD_LIBRARY_PATH:${BUILD_PATH}/third_party/gtest/lib
export PYTHONPATH=$PYTHONPATH:${PROJECT_PATH}:${PROJECT_PATH}/tests/ut/cpp/python_input:${PROJECT_PATH}/tests/ut/python
echo "export PYTHONPATH=$PYTHONPATH"
export GC_COLLECT_IN_CELL=1
if [ $# -eq 1 ] && ([ "$1" == "stage1" ] || [ "$1" == "stage2" ] || [ "$1" == "stage3" ]); then
if [ $1 == "stage1" ]; then
echo "run python dataset ut"
pytest $CURRPATH/dataset
elif [ $1 == "stage2" ]; then
echo "run python parallel\train\ops ut"
pytest -n 4 --dist=loadfile -v $CURRPATH/parallel $CURRPATH/train
RET=$?
if [ ${RET} -ne 0 ]; then
exit ${RET}
fi
pytest -n 2 --dist=loadfile -v $CURRPATH/ops
elif [ $1 == "stage3" ]; then
echo "run other ut"
pytest --ignore=$CURRPATH/dataset --ignore=$CURRPATH/parallel --ignore=$CURRPATH/train --ignore=$CURRPATH/ops --ignore=$CURRPATH/pynative_mode $IGNORE_EXEC $CURRPATH
RET=$?
if [ ${RET} -ne 0 ]; then
exit ${RET}
fi
pytest $CURRPATH/pynative_mode
fi
else
echo "run all python ut"
pytest $CURRPATH/dataset
RET=$?
if [ ${RET} -ne 0 ]; then
exit ${RET}
fi
pytest -n 4 --dist=loadfile -v $CURRPATH/parallel $CURRPATH/train
RET=$?
if [ ${RET} -ne 0 ]; then
exit ${RET}
fi
pytest -n 2 --dist=loadfile -v $CURRPATH/ops
RET=$?
if [ ${RET} -ne 0 ]; then
exit ${RET}
fi
pytest --ignore=$CURRPATH/dataset --ignore=$CURRPATH/parallel --ignore=$CURRPATH/train --ignore=$CURRPATH/ops $IGNORE_EXEC --ignore=$CURRPATH/pynative_mode $CURRPATH
RET=$?
if [ ${RET} -ne 0 ]; then
exit ${RET}
fi
pytest $CURRPATH/pynative_mode
fi
RET=$?
exit ${RET}
|
#!/bin/bash
#SBATCH --time=90:55:00
#SBATCH --account=vhs
#SBATCH --job-name=sea_cp_5n_64t_6d_1000f_617m_5i
#SBATCH --nodes=5
#SBATCH --nodelist=comp02,comp03,comp04,comp06,comp07
#SBATCH --output=./results/exp_threads/run-1/sea_cp_5n_64t_6d_1000f_617m_5i/slurm-%x-%j.out
source /home/vhs/Sea/.venv/bin/activate
export SEA_HOME=/home/vhs/Sea
srun -N5 rm -rf /disk0/vhs/seatmp /disk1/vhs/seatmp /disk2/vhs/seatmp /disk3/vhs/seatmp /disk4/vhs/seatmp /disk5/vhs/seatmp /dev/shm/seatmp
srun -N5 echo "Clearing cache" && sync && echo 3 | sudo tee /proc/sys/vm/drop_caches
echo "Creating temp source mount directories"
srun -N5 mkdir /dev/shm/seatmp
srun -N5 mkdir /disk0/vhs/seatmp /disk1/vhs/seatmp /disk2/vhs/seatmp /disk3/vhs/seatmp /disk4/vhs/seatmp /disk5/vhs/seatmp
start=`date +%s.%N`
srun -N 1 bash ${SEA_HOME}/bin/sea_launch.sh ./results/exp_threads/run-1/sea_cp_5n_64t_6d_1000f_617m_5i/n0_sea_parallel.sh &
srun -N 1 bash ${SEA_HOME}/bin/sea_launch.sh ./results/exp_threads/run-1/sea_cp_5n_64t_6d_1000f_617m_5i/n1_sea_parallel.sh &
srun -N 1 bash ${SEA_HOME}/bin/sea_launch.sh ./results/exp_threads/run-1/sea_cp_5n_64t_6d_1000f_617m_5i/n2_sea_parallel.sh &
srun -N 1 bash ${SEA_HOME}/bin/sea_launch.sh ./results/exp_threads/run-1/sea_cp_5n_64t_6d_1000f_617m_5i/n3_sea_parallel.sh &
srun -N 1 bash ${SEA_HOME}/bin/sea_launch.sh ./results/exp_threads/run-1/sea_cp_5n_64t_6d_1000f_617m_5i/n4_sea_parallel.sh &
wait
end=`date +%s.%N`
runtime=$( echo "$end - $start" | bc -l )
echo "Runtime: $runtime"
echo "Removing directories"
srun -N5 rm -rf /disk0/vhs/seatmp /disk1/vhs/seatmp /disk2/vhs/seatmp /disk3/vhs/seatmp /disk4/vhs/seatmp /disk5/vhs/seatmp /dev/shm/seatmp
|
#/bin/bash
# run psql from within postgres container
docker exec -it $(docker ps -aqf "name=pgserver") psql 'postgres://masta:pregust0fth3w!nd@localhost:5432/masta' "$@"
|
#!/usr/bin/env bash
pip3 install tensorflow==1.4
pip3 install keras==2.1.3
pip3 install argparse
pip3 install matplotlib
pip3 install pillow
|
module SpreadsheetGoodies
end
require 'spreadsheet_goodies/version'
require 'spreadsheet_goodies/google_drive'
require 'spreadsheet_goodies/excel'
require 'roo'
module SpreadsheetGoodies
class << self
attr_accessor :configuration
end
def self.configuration
@configuration ||= Configuration.new
end
def self.reset
@configuration = Configuration.new
end
def self.configure
yield(configuration)
end
class Configuration
attr_accessor :service_account_key_json, :login_method,
:google_client_id, :client_secret, :refresh_token, :strip_values_on_read
def initialize
@login_method = :oauth2
end
end
end
|
def longest_increasing_subarray(array):
max_len = 0
temp_len = 0
for i in range(len(array)):
temp_len += 1
if i == len(array) - 1 or array[i] > array[i + 1]:
max_len = max(max_len, temp_len)
temp_len = 0
return max_len
|
#!/usr/bin/env bash
# ๆฃๆตๅบ
# -------------------------------------------------- -----------
# ๆฃๆฅ็ณป็ป
export LANG=en_US.UTF-8
echoContent() {
case $1 in
# ็บข่ฒ
"red")
# shellcheck disable=SC2154
${echoType} "\033[31m${printN}$2 \033[0m"
;;
# ๅคฉ่่ฒ
"skyBlue")
${echoType} "\033[1;36m${printN}$2 \033[0m"
;;
# ็ปฟ่ฒ
"green")
${echoType} "\033[32m${printN}$2 \033[0m"
;;
# ็ฝ่ฒ
"white")
${echoType} "\033[37m${printN}$2 \033[0m"
;;
"magenta")
${echoType} "\033[31m${printN}$2 \033[0m"
;;
# ้ป่ฒ
"yellow")
${echoType} "\033[33m${printN}$2 \033[0m"
;;
esac
}
checkSystem() {
if [[ -n $(find /etc -name "redhat-release") ]] || grep </proc/version -q -i "centos"; then
mkdir -p /etc/yum.repos.d
if [[ -f "/etc/centos-release" ]]; then
centosVersion=$(rpm -q centos-release | awk -F "[-]" '{print $3}' | awk -F "[.]" '{print $1}')
if [[ -z "${centosVersion}" ]] && grep </etc/centos-release -q -i "release 8"; then
centosVersion=8
fi
fi
release="centos"
installType='yum -y install'
removeType='yum -y remove'
upgrade="yum update -y --skip-broken"
elif grep </etc/issue -q -i "debian" && [[ -f "/etc/issue" ]] || grep </etc/issue -q -i "debian" && [[ -f "/proc/version" ]]; then
release="debian"
installType='apt -y install'
upgrade="apt update"
updateReleaseInfoChange='apt-get --allow-releaseinfo-change update'
removeType='apt -y autoremove'
elif grep </etc/issue -q -i "ubuntu" && [[ -f "/etc/issue" ]] || grep </etc/issue -q -i "ubuntu" && [[ -f "/proc/version" ]]; then
release="ubuntu"
installType='apt -y install'
upgrade="apt update"
updateReleaseInfoChange='apt-get --allow-releaseinfo-change update'
removeType='apt -y autoremove'
if grep </etc/issue -q -i "16."; then
release=
fi
fi
if [[ -z ${release} ]]; then
echoContent red "\nEste script nรฃo suporta este sistema, por favor, envie o log abaixo para o desenvolvedor\n"
echoContent yellow "$(cat /etc/issue)"
echoContent yellow "$(cat /proc/version)"
exit 0
fi
}
# ๆฃๆฅCPUๆไพๅ
checkCPUVendor() {
if [[ -n $(which uname) ]]; then
if [[ "$(uname)" == "Linux" ]]; then
case "$(uname -m)" in
'amd64' | 'x86_64')
xrayCoreCPUVendor="Xray-linux-64"
v2rayCoreCPUVendor="v2ray-linux-64"
;;
'armv8' | 'aarch64')
xrayCoreCPUVendor="Xray-linux-arm64-v8a"
v2rayCoreCPUVendor="v2ray-linux-arm64-v8a"
;;
*)
echo " ไธๆฏๆๆญคCPUๆถๆ--->"
exit 1
;;
esac
fi
else
echoContent red "Nรฃo รฉ possรญvel reconhecer esta arquitetura de CPU, padrรฃo amd64, x86_64--->"
xrayCoreCPUVendor="Xray-linux-64"
v2rayCoreCPUVendor="v2ray-linux-64"
fi
}
# ๅๅงๅๅ
จๅฑๅ้
initVar() {
installType='yum -y install'
removeType='yum -y remove'
upgrade="yum -y update"
echoType='echo -e'
# ๆ ธๅฟๆฏๆ็cpu็ๆฌ
xrayCoreCPUVendor=""
v2rayCoreCPUVendor=""
# ๅๅ
domain=
# CDN่็น็address
add=
# ๅฎ่ฃ
ๆป่ฟๅบฆ
totalProgress=1
# 1.xray-coreๅฎ่ฃ
# 2. v2ray-core ๅฎ่ฃ
# 3.v2ray-core[xtls] ๅฎ่ฃ
coreInstallType=
# ๆ ธๅฟๅฎ่ฃ
path
# coreInstallPath=
# v2ctl Path
ctlPath=
# 1.ๅ
จ้จๅฎ่ฃ
# 2.ไธชๆงๅๅฎ่ฃ
# v2rayAgentInstallType=
# ๅฝๅ็ไธชๆงๅๅฎ่ฃ
ๆนๅผ 01234
currentInstallProtocolType=
# ๅฝๅalpn็้กบๅบ
currentAlpn=
# ๅ็ฝฎ็ฑปๅ
frontingType=
# ้ๆฉ็ไธชๆงๅๅฎ่ฃ
ๆนๅผ
selectCustomInstallType=
# v2ray-coreใxray-core้
็ฝฎๆไปถ็่ทฏๅพ
configPath=
# ้
็ฝฎๆไปถ็path
currentPath=
# ้
็ฝฎๆไปถ็host
currentHost=
# ๅฎ่ฃ
ๆถ้ๆฉ็core็ฑปๅ
selectCoreType=
# ้ป่ฎคcore็ๆฌ
v2rayCoreVersion=
# ้ๆบ่ทฏๅพ
customPath=
# centos version
centosVersion=
# UUID
currentUUID=
# previousClients
previousClients=
localIP=
# ้ๆๆดๆฐ่ฏไนฆ้ป่พไธๅไฝฟ็จๅ็ฌ็่ๆฌ--RenewTLS
renewTLS=$1
# tlsๅฎ่ฃ
ๅคฑ่ดฅๅๅฐ่ฏ็ๆฌกๆฐ
installTLSCount=
# BTPanel็ถๆ
BTPanelStatus=
# nginx้
็ฝฎๆไปถ่ทฏๅพ
nginxConfigPath=/etc/nginx/conf.d/
}
# ๆฃๆตๅฎ่ฃ
ๆนๅผ
readInstallType() {
coreInstallType=
configPath=
# 1.ๆฃๆตๅฎ่ฃ
็ฎๅฝ
if [[ -d "/etc/v2ray-agent" ]]; then
# ๆฃๆตๅฎ่ฃ
ๆนๅผ v2ray-core
if [[ -d "/etc/v2ray-agent/v2ray" && -f "/etc/v2ray-agent/v2ray/v2ray" && -f "/etc/v2ray-agent/v2ray/v2ctl" ]]; then
if [[ -d "/etc/v2ray-agent/v2ray/conf" && -f "/etc/v2ray-agent/v2ray/conf/02_VLESS_TCP_inbounds.json" ]]; then
configPath=/etc/v2ray-agent/v2ray/conf/
if grep </etc/v2ray-agent/v2ray/conf/02_VLESS_TCP_inbounds.json -q '"security": "tls"'; then
# ไธๅธฆXTLS็v2ray-core
coreInstallType=2
ctlPath=/etc/v2ray-agent/v2ray/v2ctl
elif grep </etc/v2ray-agent/v2ray/conf/02_VLESS_TCP_inbounds.json -q '"security": "xtls"'; then
# ๅธฆXTLS็v2ray-core
ctlPath=/etc/v2ray-agent/v2ray/v2ctl
coreInstallType=3
fi
fi
fi
if [[ -d "/etc/v2ray-agent/xray" && -f "/etc/v2ray-agent/xray/xray" ]]; then
# ่ฟ้ๆฃๆตxray-core
if [[ -d "/etc/v2ray-agent/xray/conf" ]] && [[ -f "/etc/v2ray-agent/xray/conf/02_VLESS_TCP_inbounds.json" || -f "/etc/v2ray-agent/xray/conf/02_trojan_TCP_inbounds.json" ]]; then
# xray-core
configPath=/etc/v2ray-agent/xray/conf/
ctlPath=/etc/v2ray-agent/xray/xray
coreInstallType=1
fi
fi
fi
}
# ่ฏปๅๅ่ฎฎ็ฑปๅ
readInstallProtocolType() {
currentInstallProtocolType=
while read -r row; do
if echo "${row}" | grep -q 02_trojan_TCP_inbounds; then
currentInstallProtocolType=${currentInstallProtocolType}'trojan'
frontingType=02_trojan_TCP_inbounds
fi
if echo "${row}" | grep -q VLESS_TCP_inbounds; then
currentInstallProtocolType=${currentInstallProtocolType}'0'
frontingType=02_VLESS_TCP_inbounds
fi
if echo "${row}" | grep -q VLESS_WS_inbounds; then
currentInstallProtocolType=${currentInstallProtocolType}'1'
fi
if echo "${row}" | grep -q trojan_gRPC_inbounds; then
currentInstallProtocolType=${currentInstallProtocolType}'2'
fi
if echo "${row}" | grep -q VMess_WS_inbounds; then
currentInstallProtocolType=${currentInstallProtocolType}'3'
fi
if echo "${row}" | grep -q 04_trojan_TCP_inbounds; then
currentInstallProtocolType=${currentInstallProtocolType}'4'
fi
if echo "${row}" | grep -q VLESS_gRPC_inbounds; then
currentInstallProtocolType=${currentInstallProtocolType}'5'
fi
done < <(find ${configPath} -name "*inbounds.json" | awk -F "[.]" '{print $1}')
}
# ๆฃๆฅๆฏๅฆๅฎ่ฃ
ๅฎๅก
checkBTPanel() {
if pgrep -f "BT-Panel"; then
nginxConfigPath=/www/server/panel/vhost/nginx/
BTPanelStatus=true
fi
}
# ่ฏปๅๅฝๅalpn็้กบๅบ
readInstallAlpn() {
if [[ -n ${currentInstallProtocolType} ]]; then
local alpn
alpn=$(jq -r .inbounds[0].streamSettings.xtlsSettings.alpn[0] ${configPath}${frontingType}.json)
if [[ -n ${alpn} ]]; then
currentAlpn=${alpn}
fi
fi
}
# ๆฃๆฅ้ฒ็ซๅข
allowPort() {
# ๅฆๆ้ฒ็ซๅขๅฏๅจ็ถๆๅๆทปๅ ็ธๅบ็ๅผๆพ็ซฏๅฃ
if systemctl status netfilter-persistent 2>/dev/null | grep -q "active (exited)"; then
local updateFirewalldStatus=
if ! iptables -L | grep -q "http(mack-a)"; then
updateFirewalldStatus=true
iptables -I INPUT -p tcp --dport 80 -m comment --comment "allow http(mack-a)" -j ACCEPT
fi
if ! iptables -L | grep -q "https(mack-a)"; then
updateFirewalldStatus=true
iptables -I INPUT -p tcp --dport 443 -m comment --comment "allow https(mack-a)" -j ACCEPT
fi
if echo "${updateFirewalldStatus}" | grep -q "true"; then
netfilter-persistent save
fi
elif systemctl status ufw 2>/dev/null | grep -q "active (exited)"; then
if ! ufw status | grep -q 443; then
sudo ufw allow https
checkUFWAllowPort 443
fi
if ! ufw status | grep -q 80; then
sudo ufw allow 80
checkUFWAllowPort 80
fi
elif systemctl status firewalld 2>/dev/null | grep -q "active (running)"; then
local updateFirewalldStatus=
if ! firewall-cmd --list-ports --permanent | grep -qw "80/tcp"; then
updateFirewalldStatus=true
firewall-cmd --zone=public --add-port=80/tcp --permanent
checkFirewalldAllowPort 80
fi
if ! firewall-cmd --list-ports --permanent | grep -qw "443/tcp"; then
updateFirewalldStatus=true
firewall-cmd --zone=public --add-port=443/tcp --permanent
checkFirewalldAllowPort 443
fi
if echo "${updateFirewalldStatus}" | grep -q "true"; then
firewall-cmd --reload
fi
fi
}
# ๆฃๆฅ80ใ443็ซฏๅฃๅ ็จๆ
ๅต
checkPortUsedStatus() {
if lsof -i tcp:80 | grep -q LISTEN; then
echoContent red "\n---> A porta 80 estรก ocupada, feche e instale manualmente\n"
lsof -i tcp:80 | grep LISTEN
exit 0
fi
if lsof -i tcp:443 | grep -q LISTEN; then
echoContent red "\n---> A porta 443 estรก ocupada, feche e instale manualmente\n"
lsof -i tcp:80 | grep LISTEN
exit 0
fi
}
# ่พๅบufw็ซฏๅฃๅผๆพ็ถๆ
checkUFWAllowPort() {
if ufw status | grep -q "$1"; then
echoContent green " ---> $1็ซฏๅฃๅผๆพๆๅ"
else
echoContent red " ---> $1็ซฏๅฃๅผๆพๅคฑ่ดฅ"
exit 0
fi
}
# ่พๅบfirewall-cmd็ซฏๅฃๅผๆพ็ถๆ
checkFirewalldAllowPort() {
if firewall-cmd --list-ports --permanent | grep -q "$1"; then
echoContent green " ---> $1็ซฏๅฃๅผๆพๆๅ"
else
echoContent red " ---> $1็ซฏๅฃๅผๆพๅคฑ่ดฅ"
exit 0
fi
}
# ๆฃๆฅๆไปถ็ฎๅฝไปฅๅpath่ทฏๅพ
readConfigHostPathUUID() {
currentPath=
currentUUID=
currentHost=
currentPort=
currentAdd=
# ่ฏปๅpath
if [[ -n "${configPath}" ]]; then
local fallback
fallback=$(jq -r -c '.inbounds[0].settings.fallbacks[]|select(.path)' ${configPath}${frontingType}.json | head -1)
local path
path=$(echo "${fallback}" | jq -r .path | awk -F "[/]" '{print $2}')
if [[ $(echo "${fallback}" | jq -r .dest) == 31297 ]]; then
currentPath=$(echo "${path}" | awk -F "[w][s]" '{print $1}')
elif [[ $(echo "${fallback}" | jq -r .dest) == 31298 ]]; then
currentPath=$(echo "${path}" | awk -F "[t][c][p]" '{print $1}')
elif [[ $(echo "${fallback}" | jq -r .dest) == 31299 ]]; then
currentPath=$(echo "${path}" | awk -F "[v][w][s]" '{print $1}')
fi
fi
if [[ "${coreInstallType}" == "1" ]]; then
currentHost=$(jq -r .inbounds[0].streamSettings.xtlsSettings.certificates[0].certificateFile ${configPath}${frontingType}.json | awk -F '[t][l][s][/]' '{print $2}' | awk -F '[.][c][r][t]' '{print $1}')
currentUUID=$(jq -r .inbounds[0].settings.clients[0].id ${configPath}${frontingType}.json)
currentAdd=$(jq -r .inbounds[0].settings.clients[0].add ${configPath}${frontingType}.json)
if [[ "${currentAdd}" == "null" ]]; then
currentAdd=${currentHost}
fi
currentPort=$(jq .inbounds[0].port ${configPath}${frontingType}.json)
elif [[ "${coreInstallType}" == "2" || "${coreInstallType}" == "3" ]]; then
if [[ "${coreInstallType}" == "3" ]]; then
currentHost=$(jq -r .inbounds[0].streamSettings.xtlsSettings.certificates[0].certificateFile ${configPath}${frontingType}.json | awk -F '[t][l][s][/]' '{print $2}' | awk -F '[.][c][r][t]' '{print $1}')
else
currentHost=$(jq -r .inbounds[0].streamSettings.tlsSettings.certificates[0].certificateFile ${configPath}${frontingType}.json | awk -F '[t][l][s][/]' '{print $2}' | awk -F '[.][c][r][t]' '{print $1}')
fi
currentAdd=$(jq -r .inbounds[0].settings.clients[0].add ${configPath}${frontingType}.json)
if [[ "${currentAdd}" == "null" ]]; then
currentAdd=${currentHost}
fi
currentUUID=$(jq -r .inbounds[0].settings.clients[0].id ${configPath}${frontingType}.json)
currentPort=$(jq .inbounds[0].port ${configPath}${frontingType}.json)
fi
}
# ็ถๆๅฑ็คบ
showInstallStatus() {
if [[ -n "${coreInstallType}" ]]; then
if [[ "${coreInstallType}" == 1 ]]; then
if [[ -n $(pgrep -f xray/xray) ]]; then
echoContent yellow "\nๆ ธๅฟ: Xray-core[่ฟ่กไธญ]"
else
echoContent yellow "\nๆ ธๅฟ: Xray-core[ๆช่ฟ่ก]"
fi
elif [[ "${coreInstallType}" == 2 || "${coreInstallType}" == 3 ]]; then
if [[ -n $(pgrep -f v2ray/v2ray) ]]; then
echoContent yellow "\nๆ ธๅฟ: v2ray-core[่ฟ่กไธญ]"
else
echoContent yellow "\nๆ ธๅฟ: v2ray-core[ๆช่ฟ่ก]"
fi
fi
# ่ฏปๅๅ่ฎฎ็ฑปๅ
readInstallProtocolType
if [[ -n ${currentInstallProtocolType} ]]; then
echoContent yellow "ๅทฒๅฎ่ฃ
ๅ่ฎฎ: \c"
fi
if echo ${currentInstallProtocolType} | grep -q 0; then
if [[ "${coreInstallType}" == 2 ]]; then
echoContent yellow "VLESS+TCP[TLS] \c"
else
echoContent yellow "VLESS+TCP[TLS/XTLS] \c"
fi
fi
if echo ${currentInstallProtocolType} | grep -q trojan; then
if [[ "${coreInstallType}" == 1 ]]; then
echoContent yellow "Trojan+TCP[TLS/XTLS] \c"
fi
fi
if echo ${currentInstallProtocolType} | grep -q 1; then
echoContent yellow "VLESS+WS[TLS] \c"
fi
if echo ${currentInstallProtocolType} | grep -q 2; then
echoContent yellow "Trojan+gRPC[TLS] \c"
fi
if echo ${currentInstallProtocolType} | grep -q 3; then
echoContent yellow "VMess+WS[TLS] \c"
fi
if echo ${currentInstallProtocolType} | grep -q 4; then
echoContent yellow "Trojan+TCP[TLS] \c"
fi
if echo ${currentInstallProtocolType} | grep -q 5; then
echoContent yellow "VLESS+gRPC[TLS] \c"
fi
fi
}
# ๆธ
็ๆงๆฎ็
cleanUp() {
if [[ "$1" == "v2rayClean" ]]; then
rm -rf "$(find /etc/v2ray-agent/v2ray/* | grep -E '(config_full.json|conf)')"
handleV2Ray stop >/dev/null
rm -f /etc/systemd/system/v2ray.service
elif [[ "$1" == "xrayClean" ]]; then
rm -rf "$(find /etc/v2ray-agent/xray/* | grep -E '(config_full.json|conf)')"
handleXray stop >/dev/null
rm -f /etc/systemd/system/xray.service
elif [[ "$1" == "v2rayDel" ]]; then
rm -rf /etc/v2ray-agent/v2ray/*
elif [[ "$1" == "xrayDel" ]]; then
rm -rf /etc/v2ray-agent/xray/*
fi
}
initVar "$1"
checkSystem
checkCPUVendor
readInstallType
readInstallProtocolType
readConfigHostPathUUID
readInstallAlpn
checkBTPanel
# -------------------------------------------------- -----------
# ๅๅงๅๅฎ่ฃ
็ฎๅฝ
mkdirTools() {
mkdir -p /etc/v2ray-agent/tls
mkdir -p /etc/v2ray-agent/subscribe
mkdir -p /etc/v2ray-agent/subscribe_tmp
mkdir -p /etc/v2ray-agent/v2ray/conf
mkdir -p /etc/v2ray-agent/v2ray/tmp
mkdir -p /etc/v2ray-agent/xray/conf
mkdir -p /etc/v2ray-agent/xray/tmp
mkdir -p /etc/v2ray-agent/trojan
mkdir -p /etc/systemd/system/
mkdir -p /tmp/v2ray-agent-tls/
}
# ๅฎ่ฃ
ๅทฅๅ
ทๅ
installTools() {
echo 'ๅฎ่ฃ
ๅทฅๅ
ท'
echoContent skyBlue "\n่ฟๅบฆ $1/${totalProgress} : ๅฎ่ฃ
ๅทฅๅ
ท"
# ไฟฎๅคubuntuไธชๅซ็ณป็ป้ฎ้ข
if [[ "${release}" == "ubuntu" ]]; then
dpkg --configure -a
fi
if [[ -n $(pgrep -f "apt") ]]; then
pgrep -f apt | xargs kill -9
fi
echoContent green "---> Verifique e instale atualizaรงรตes [A nova mรกquina ficarรก muito lenta, se nรฃo houver resposta por muito tempo, pare-a manualmente e execute-a novamente]"
${upgrade} >/etc/v2ray-agent/install.log 2>&1
if grep <"/etc/v2ray-agent/install.log" -q "changed"; then
${updateReleaseInfoChange} >/dev/null 2>&1
fi
if [[ "${release}" == "centos" ]]; then
rm -rf /var/run/yum.pid
${installType} epel-release >/dev/null 2>&1
fi
# [[ -z `find /usr/bin /usr/sbin |grep -v grep|grep -w curl` ]]
if ! find /usr/bin /usr/sbin | grep -q -w wget; then
echoContent green "---> instala wget"
${installType} wget >/dev/null 2>&1
fi
if ! find /usr/bin /usr/sbin | grep -q -w curl; then
echoContent green "---> instalar curl"
${installType} curl >/dev/null 2>&1
fi
if ! find /usr/bin /usr/sbin | grep -q -w unzip; then
echoContent green "---> instalar descompactar"
${installType} unzip >/dev/null 2>&1
fi
if ! find /usr/bin /usr/sbin | grep -q -w socat; then
echoContent green "---> instalar socat"
${installType} socat >/dev/null 2>&1
fi
if ! find /usr/bin /usr/sbin | grep -q -w tar; then
echoContent green "---> instala o tar"
${installType} tar >/dev/null 2>&1
fi
if ! find /usr/bin /usr/sbin | grep -q -w cron; then
echoContent green "---> instalar crontabs"
if [[ "${release}" == "ubuntu" ]] || [[ "${release}" == "debian" ]]; then
${installType} cron >/dev/null 2>&1
else
${installType} crontabs >/dev/null 2>&1
fi
fi
if ! find /usr/bin /usr/sbin | grep -q -w jq; then
echoContent green "---> instalar jq"
${installType} jq >/dev/null 2>&1
fi
if ! find /usr/bin /usr/sbin | grep -q -w binutils; then
echoContent green "---> instalar binutils"
${installType} binutils >/dev/null 2>&1
fi
if ! find /usr/bin /usr/sbin | grep -q -w ping6; then
echoContent green "---> instalar ping6"
${installType} inetutils-ping >/dev/null 2>&1
fi
if ! find /usr/bin /usr/sbin | grep -q -w qrencode; then
echoContent green "---> instalar qrencode"
${installType} qrencode >/dev/null 2>&1
fi
if ! find /usr/bin /usr/sbin | grep -q -w sudo; then
echoContent green "---> instala o sudo"
${installType} sudo >/dev/null 2>&1
fi
if ! find /usr/bin /usr/sbin | grep -q -w lsb-release; then
echoContent green "---> instalar lsb-release"
${installType} lsb-release >/dev/null 2>&1
fi
if ! find /usr/bin /usr/sbin | grep -q -w lsof; then
echoContent green "---> instalar lsof"
${installType} lsof >/dev/null 2>&1
fi
# ๆฃๆตnginx็ๆฌ๏ผๅนถๆไพๆฏๅฆๅธ่ฝฝ็้้กน
if ! find /usr/bin /usr/sbin | grep -q -w nginx; then
echoContent green "---> instala o nginx"
installNginxTools
else
nginxVersion=$(nginx -v 2>&1)
nginxVersion=$(echo "${nginxVersion}" | awk -F "[n][g][i][n][x][/]" '{print $2}' | awk -F "[.]" '{print $2}')
if [[ ${nginxVersion} -lt 14 ]]; then
read -r -p "่ฏปๅๅฐๅฝๅ็Nginx็ๆฌไธๆฏๆgRPC๏ผไผๅฏผ่ดๅฎ่ฃ
ๅคฑ่ดฅ๏ผๆฏๅฆๅธ่ฝฝNginxๅ้ๆฐๅฎ่ฃ
๏ผ[y/n]:" unInstallNginxStatus
if [[ "${unInstallNginxStatus}" == "y" ]]; then
${removeType} nginx >/dev/null 2>&1
echoContent yellow "---> desinstalaรงรฃo do nginx concluรญda"
echoContent green "---> instala o nginx"
installNginxTools >/dev/null 2>&1
else
exit 0
fi
fi
fi
if ! find /usr/bin /usr/sbin | grep -q -w semanage; then
echoContent green "---> instalar semanage"
${installType} bash-completion >/dev/null 2>&1
if [[ "${centosVersion}" == "7" ]]; then
policyCoreUtils="policycoreutils-python.x86_64"
elif [[ "${centosVersion}" == "8" ]]; then
policyCoreUtils="policycoreutils-python-utils-2.9-9.el8.noarch"
fi
if [[ -n "${policyCoreUtils}" ]]; then
${installType} ${policyCoreUtils} >/dev/null 2>&1
fi
if [[ -n $(which semanage) ]]; then
semanage port -a -t http_port_t -p tcp 31300
fi
fi
if [[ ! -d "$HOME/.acme.sh" ]] || [[ -d "$HOME/.acme.sh" && -z $(find "$HOME/.acme.sh/acme.sh") ]]; then
echoContent green "---> instalar acme.sh"
curl -s https://get.acme.sh | sh -s >/etc/v2ray-agent/tls/acme.log 2>&1
if [[ ! -d "$HOME/.acme.sh" ]] || [[ -z $(find "$HOME/.acme.sh/acme.sh") ]]; then
echoContent red "falha na instalaรงรฃo do acme --->"
tail -n 100 /etc/v2ray-agent/tls/acme.log
echoContent yellow "Soluรงรฃo de problemas:"
echoContent red " 1.่ทๅGithubๆไปถๅคฑ่ดฅ๏ผ่ฏท็ญๅพ
Githubๆขๅคๅๅฐ่ฏ๏ผๆขๅค่ฟๅบฆๅฏๆฅ็ [https://www.githubstatus.com/]"
echoContent red " 2.acme.sh่ๆฌๅบ็ฐbug๏ผๅฏๆฅ็[https://github.com/acmesh-official/acme.sh] issues"
exit 0
fi
fi
}
# ๅฎ่ฃ
Nginx
installNginxTools() {
if [[ "${release}" == "debian" ]]; then
sudo apt install gnupg2 ca-certificates lsb-release -y >/dev/null 2>&1
echo "deb http://nginx.org/packages/mainline/debian $(lsb_release -cs) nginx" | sudo tee /etc/apt/sources.list.d/nginx.list >/dev/null 2>&1
echo -e "Package: *\nPin: origin nginx.org\nPin: release o=nginx\nPin-Priority: 900\n" | sudo tee /etc/apt/preferences.d/99nginx >/dev/null 2>&1
curl -o /tmp/nginx_signing.key https://nginx.org/keys/nginx_signing.key >/dev/null 2>&1
# gpg --dry-run --quiet --import --import-options import-show /tmp/nginx_signing.key
sudo mv /tmp/nginx_signing.key /etc/apt/trusted.gpg.d/nginx_signing.asc
sudo apt update >/dev/null 2>&1
elif [[ "${release}" == "ubuntu" ]]; then
sudo apt install gnupg2 ca-certificates lsb-release -y >/dev/null 2>&1
echo "deb http://nginx.org/packages/mainline/ubuntu $(lsb_release -cs) nginx" | sudo tee /etc/apt/sources.list.d/nginx.list >/dev/null 2>&1
echo -e "Package: *\nPin: origin nginx.org\nPin: release o=nginx\nPin-Priority: 900\n" | sudo tee /etc/apt/preferences.d/99nginx >/dev/null 2>&1
curl -o /tmp/nginx_signing.key https://nginx.org/keys/nginx_signing.key >/dev/null 2>&1
# gpg --dry-run --quiet --import --import-options import-show /tmp/nginx_signing.key
sudo mv /tmp/nginx_signing.key /etc/apt/trusted.gpg.d/nginx_signing.asc
sudo apt update >/dev/null 2>&1
elif [[ "${release}" == "centos" ]]; then
${installType} yum-utils >/dev/null 2>&1
cat <<EOF >/etc/yum.repos.d/nginx.repo
[nginx-stable]
name=nginx stable repo
baseurl=http://nginx.org/packages/centos/\$releasever/\$basearch/
gpgcheck=1
enabled=1
gpgkey=https://nginx.org/keys/nginx_signing.key
module_hotfixes=true
[nginx-mainline]
name=nginx mainline repo
baseurl=http://nginx.org/packages/mainline/centos/\$releasever/\$basearch/
gpgcheck=1
enabled=0
gpgkey=https://nginx.org/keys/nginx_signing.key
module_hotfixes=true
EOF
sudo yum-config-manager --enable nginx-mainline >/dev/null 2>&1
fi
${installType} nginx >/dev/null 2>&1
systemctl daemon-reload
systemctl enable nginx
}
# ๅฎ่ฃ
warp
installWarp() {
${installType} gnupg2 -y >/dev/null 2>&1
if [[ "${release}" == "debian" ]]; then
curl -s https://pkg.cloudflareclient.com/pubkey.gpg | sudo apt-key add - >/dev/null 2>&1
echo "deb http://pkg.cloudflareclient.com/ $(lsb_release -cs) main" | sudo tee /etc/apt/sources.list.d/cloudflare-client.list >/dev/null 2>&1
sudo apt update >/dev/null 2>&1
elif [[ "${release}" == "ubuntu" ]]; then
curl -s https://pkg.cloudflareclient.com/pubkey.gpg | sudo apt-key add - >/dev/null 2>&1
echo "deb http://pkg.cloudflareclient.com/ focal main" | sudo tee /etc/apt/sources.list.d/cloudflare-client.list >/dev/null 2>&1
sudo apt update >/dev/null 2>&1
elif [[ "${release}" == "centos" ]]; then
${installType} yum-utils >/dev/null 2>&1
sudo rpm -ivh "http://pkg.cloudflareclient.com/cloudflare-release-el${centosVersion}.rpm" >/dev/null 2>&1
fi
echoContent green "---> Instalar WARP"
${installType} cloudflare-warp >/dev/null 2>&1
if [[ -z $(which warp-cli) ]]; then
echoContent red "---> Instalar WARPๅคฑ่ดฅ"
exit 0
fi
systemctl enable warp-svc
warp-cli --accept-tos register
warp-cli --accept-tos set-mode proxy
warp-cli --accept-tos set-proxy-port 31303
warp-cli --accept-tos connect
warp-cli --accept-tos enable-always-on
# if [[]];then
# fi
# todo curl --socks5 127.0.0.1:31303 https://www.cloudflare.com/cdn-cgi/trace
# systemctl daemon-reload
# systemctl enable cloudflare-warp
}
# ๅๅงๅNginx็ณ่ฏท่ฏไนฆ้
็ฝฎ
initTLSNginxConfig() {
handleNginx stop
echoContent skyBlue "\nAgendar $1/${totalProgress} : Inicialize a configuraรงรฃo do certificado do aplicativo Nginx"
if [[ -n "${currentHost}" ]]; then
echo
read -r -p "Leia o รบltimo registro de instalaรงรฃo, vocรช usa o nome de domรญnio da รบltima instalaรงรฃo? [s/n]: " historyDomainStatus
if [[ "${historyDomainStatus}" == "y" ]]; then
domain=${currentHost}
echoContent yellow "\n ---> nome do domรญnio: ${domain}"
else
echo
echoContent yellow "Por favor, digite o nome de domรญnio a ser configurado Exemplo: www.v2ray-agent.com --->"
read -r -p "nome do domรญnio:" domain
fi
else
echo
echoContent yellow "Por favor, digite o nome de domรญnio a ser configurado Exemplo: www.v2ray-agent.com --->"
read -r -p "nome do domรญnio:" domain
fi
if [[ -z ${domain} ]]; then
echoContent red "O nome de domรญnio nรฃo pode estar vazio --->"
initTLSNginxConfig 3
else
# ไฟฎๆน้
็ฝฎ
touch ${nginxConfigPath}alone.conf
cat <<EOF >${nginxConfigPath}alone.conf
server {
listen 80;
listen [::]:80;
server_name ${domain};
root /usr/share/nginx/html;
location ~ /.well-known {
allow all;
}
location /test {
return 200 'fjkvymb6len';
}
location /ip {
proxy_set_header Host \$host;
proxy_set_header X-Real-IP \$remote_addr;
proxy_set_header REMOTE-HOST \$remote_addr;
proxy_set_header X-Forwarded-For \$proxy_add_x_forwarded_for;
default_type text/plain;
return 200 \$proxy_add_x_forwarded_for;
}
}
EOF
# ๅฏๅจnginx
handleNginx start
checkIP
fi
}
# ไฟฎๆนnginx้ๅฎๅ้
็ฝฎ
updateRedirectNginxConf() {
if [[ ${BTPanelStatus} == "true" ]]; then
cat <<EOF >${nginxConfigPath}alone.conf
server {
listen 127.0.0.1:31300;
server_name _;
return 403;
}
EOF
else
cat <<EOF >${nginxConfigPath}alone.conf
server {
listen 80;
listen [::]:80;
server_name ${domain};
# shellcheck disable=SC2154
return 301 https://${domain}\${request_uri};
}
server {
listen 127.0.0.1:31300;
server_name _;
return 403;
}
EOF
fi
if echo "${selectCustomInstallType}" | grep -q 2 && echo "${selectCustomInstallType}" | grep -q 5 || [[ -z "${selectCustomInstallType}" ]]; then
cat <<EOF >>${nginxConfigPath}alone.conf
server {
listen 127.0.0.1:31302 http2 so_keepalive=on;
server_name ${domain};
root /usr/share/nginx/html;
client_header_timeout 1071906480m;
keepalive_timeout 1071906480m;
location /s/ {
add_header Content-Type text/plain;
alias /etc/v2ray-agent/subscribe/;
}
location /${currentPath}grpc {
if (\$content_type !~ "application/grpc") {
return 404;
}
client_max_body_size 0;
grpc_set_header X-Real-IP \$proxy_add_x_forwarded_for;
client_body_timeout 1071906480m;
grpc_read_timeout 1071906480m;
grpc_pass grpc://127.0.0.1:31301;
}
location /${currentPath}trojangrpc {
if (\$content_type !~ "application/grpc") {
return 404;
}
client_max_body_size 0;
grpc_set_header X-Real-IP \$proxy_add_x_forwarded_for;
client_body_timeout 1071906480m;
grpc_read_timeout 1071906480m;
grpc_pass grpc://127.0.0.1:31304;
}
}
EOF
elif echo "${selectCustomInstallType}" | grep -q 5 || [[ -z "${selectCustomInstallType}" ]]; then
cat <<EOF >>${nginxConfigPath}alone.conf
server {
listen 127.0.0.1:31302 http2;
server_name ${domain};
root /usr/share/nginx/html;
location /s/ {
add_header Content-Type text/plain;
alias /etc/v2ray-agent/subscribe/;
}
location /${currentPath}grpc {
client_max_body_size 0;
# keepalive_time 1071906480m;
keepalive_requests 4294967296;
client_body_timeout 1071906480m;
send_timeout 1071906480m;
lingering_close always;
grpc_read_timeout 1071906480m;
grpc_send_timeout 1071906480m;
grpc_pass grpc://127.0.0.1:31301;
}
}
EOF
elif echo "${selectCustomInstallType}" | grep -q 2 || [[ -z "${selectCustomInstallType}" ]]; then
cat <<EOF >>${nginxConfigPath}alone.conf
server {
listen 127.0.0.1:31302 http2;
server_name ${domain};
root /usr/share/nginx/html;
location /s/ {
add_header Content-Type text/plain;
alias /etc/v2ray-agent/subscribe/;
}
location /${currentPath}trojangrpc {
client_max_body_size 0;
# keepalive_time 1071906480m;
keepalive_requests 4294967296;
client_body_timeout 1071906480m;
send_timeout 1071906480m;
lingering_close always;
grpc_read_timeout 1071906480m;
grpc_send_timeout 1071906480m;
grpc_pass grpc://127.0.0.1:31301;
}
}
EOF
else
cat <<EOF >>${nginxConfigPath}alone.conf
server {
listen 127.0.0.1:31302 http2;
server_name ${domain};
root /usr/share/nginx/html;
location /s/ {
add_header Content-Type text/plain;
alias /etc/v2ray-agent/subscribe/;
}
location / {
}
}
EOF
fi
cat <<EOF >>${nginxConfigPath}alone.conf
server {
listen 127.0.0.1:31300;
server_name ${domain};
root /usr/share/nginx/html;
location /s/ {
add_header Content-Type text/plain;
alias /etc/v2ray-agent/subscribe/;
}
location / {
add_header Strict-Transport-Security "max-age=15552000; preload" always;
}
}
EOF
}
# ๆฃๆฅip
checkIP() {
echoContent skyBlue "\n---> Verifique o ip do nome de domรญnio"
localIP=$(curl -s -m 2 "${domain}/ip")
handleNginx stop
if [[ -z ${localIP} ]] || ! echo "${localIP}" | sed '1{s/[^(]*(//;s/).*//;q}' | grep -q '\.' && ! echo "${localIP}" | sed '1{s/[^(]*(//;s/).*//;q}' | grep -q ':'; then
echoContent red "\n---> O ip do nome de domรญnio atual nรฃo foi detectado"
echoContent yellow "---> Verifique se o nome de domรญnio estรก escrito corretamente"
echoContent yellow "---> Verifique se a resoluรงรฃo de DNS do nome de domรญnio estรก correta"
echoContent yellow "---> Se a resoluรงรฃo estiver correta, aguarde o dns entrar em vigor, espera-se que ele entre em vigor em trรชs minutos"
echoContent yellow "---> Se as configuraรงรตes acima estiverem corretas, reinstale o sistema puro e tente novamente"
if [[ -n ${localIP} ]]; then
echoContent yellow "---> O valor de retorno de detecรงรฃo รฉ anormal, รฉ recomendado desinstalar manualmente o nginx e reexecutar o script"
fi
echoContent red "---> Por favor, verifique se as regras de firewall abrem 443, 80\n"
read -r -p "Vocรช modifica as regras de firewall para abrir as portas 443 e 80 por meio de scripts? [y/n]:" allPortFirewallStatus
if [[ ${allPortFirewallStatus} == "y" ]]; then
allowPort
handleNginx start
checkIP
else
exit 0
fi
else
if echo "${localIP}" | awk -F "[,]" '{print $2}' | grep -q "." || echo "${localIP}" | awk -F "[,]" '{print $2}' | grep -q ":"; then
echoContent red "\n---> Vรกrios IPs sรฃo detectados, confirme se deseja fechar a nuvem do cloudflare"
echoContent yellow "---> Apรณs fechar a nuvem, aguarde trรชs minutos e tente novamente"
echoContent yellow " ---> ๆฃๆตๅฐ็ipๅฆไธ:[${localIP}]"
exit 0
fi
echoContent green " ---> O IP do nome de domรญnio atual รฉ:[${localIP}]"
fi
}
# ๅฎ่ฃ
TLS
installTLS() {
echoContent skyBlue "\nAgendar $1/${totalProgress} : Solicitar um certificado TLS\n"
local tlsDomain=${domain}
# ๅฎ่ฃ
tls
if [[ -f "/etc/v2ray-agent/tls/${tlsDomain}.crt" && -f "/etc/v2ray-agent/tls/${tlsDomain}.key" && -n $(cat "/etc/v2ray-agent/tls/${tlsDomain}.crt") ]] || [[ -d "$HOME/.acme.sh/${tlsDomain}_ecc" && -f "$HOME/.acme.sh/${tlsDomain}_ecc/${tlsDomain}.key" && -f "$HOME/.acme.sh/${tlsDomain}_ecc/${tlsDomain}.cer" ]]; then
echoContent green "---> Certificado detectado"
# checkTLStatus
renewalTLS
if [[ -z $(find /etc/v2ray-agent/tls/ -name "${tlsDomain}.crt") ]] || [[ -z $(find /etc/v2ray-agent/tls/ -name "${tlsDomain}.key") ]] || [[ -z $(cat "/etc/v2ray-agent/tls/${tlsDomain}.crt") ]]; then
sudo "$HOME/.acme.sh/acme.sh" --installcert -d "${tlsDomain}" --fullchainpath "/etc/v2ray-agent/tls/${tlsDomain}.crt" --keypath "/etc/v2ray-agent/tls/${tlsDomain}.key" --ecc >/dev/null
else
echoContent yellow " ---> Se nรฃo expirou ou certificado personalizado, selecione [n]\n"
read -r -p "Deseja reinstalar? [y/n]:" reInstallStatus
if [[ "${reInstallStatus}" == "y" ]]; then
rm -rf /etc/v2ray-agent/tls/*
installTLS "$1"
fi
fi
elif [[ -d "$HOME/.acme.sh" ]] && [[ ! -f "$HOME/.acme.sh/${tlsDomain}_ecc/${tlsDomain}.cer" || ! -f "$HOME/.acme.sh/${tlsDomain}_ecc/${tlsDomain}.key" ]]; then
echoContent green "---> Instalar certificado TLS"
if echo "${localIP}" | grep -q ":"; then
sudo "$HOME/.acme.sh/acme.sh" --issue -d "${tlsDomain}" --standalone -k ec-256 --server letsencrypt --listen-v6 | tee -a /etc/v2ray-agent/tls/acme.log >/dev/null
else
sudo "$HOME/.acme.sh/acme.sh" --issue -d "${tlsDomain}" --standalone -k ec-256 --server letsencrypt | tee -a /etc/v2ray-agent/tls/acme.log >/dev/null
fi
if [[ -d "$HOME/.acme.sh/${tlsDomain}_ecc" && -f "$HOME/.acme.sh/${tlsDomain}_ecc/${tlsDomain}.key" && -f "$HOME/.acme.sh/${tlsDomain}_ecc/${tlsDomain}.cer" ]]; then
sudo "$HOME/.acme.sh/acme.sh" --installcert -d "${tlsDomain}" --fullchainpath "/etc/v2ray-agent/tls/${tlsDomain}.crt" --keypath "/etc/v2ray-agent/tls/${tlsDomain}.key" --ecc >/dev/null
fi
if [[ ! -f "/etc/v2ray-agent/tls/${tlsDomain}.crt" || ! -f "/etc/v2ray-agent/tls/${tlsDomain}.key" ]] || [[ -z $(cat "/etc/v2ray-agent/tls/${tlsDomain}.key") || -z $(cat "/etc/v2ray-agent/tls/${tlsDomain}.crt") ]]; then
tail -n 10 /etc/v2ray-agent/tls/acme.log
if [[ ${installTLSCount} == "1" ]]; then
echoContent red "---> Falha na instalaรงรฃo do TLS, verifique o log acme"
exit 0
fi
echoContent red "---> Falha na instalaรงรฃo do TLS, verificando se as portas 80 e 443 estรฃo abertas"
allowPort
echoContent yellow "---> Tente instalar novamente o certificado TLS"
installTLSCount=1
installTLS "$1"
fi
echoContent green "---> Geraรงรฃo TLS bem sucedida"
else
echoContent yellow "---> acme.sh nรฃo estรก instalado"
exit 0
fi
}
# ้
็ฝฎไผช่ฃ
ๅๅฎข
initNginxConfig() {
echoContent skyBlue "\nAgendanxo $1/${totalProgress} : Configurar Nginx"
cat <<EOF >${nginxConfigPath}alone.conf
server {
listen 80;
listen [::]:80;
server_name ${domain};
root /usr/share/nginx/html;
location ~ /.well-known {allow all;}
location /test {return 200 'fjkvymb6len';}
}
EOF
}
# ่ชๅฎไน/้ๆบ่ทฏๅพ
randomPathFunction() {
echoContent skyBlue "\nAgendar $1/${totalProgress} : Gerar caminhos aleatรณrios"
if [[ -n "${currentPath}" ]]; then
echo
read -r -p "Leia o รบltimo registro de instalaรงรฃo, vocรช usa o caminho da รบltima instalaรงรฃo? [y/n]:" historyPathStatus
echo
fi
if [[ "${historyPathStatus}" == "y" ]]; then
customPath=${currentPath}
echoContent green "---> Use com sucesso\n"
else
echoContent yellow "Insira um caminho personalizado [Exemplo: sozinho], sem necessidade de barras, [Enter] caminho aleatรณrio"
read -r -p 'Path:' customPath
if [[ -z "${customPath}" ]]; then
customPath=$(head -n 50 /dev/urandom | sed 's/[^a-z]//g' | strings -n 4 | tr '[:upper:]' '[:lower:]' | head -1)
currentPath=${customPath:0:4}
customPath=${currentPath}
else
currentPath=${customPath}
fi
fi
echoContent yellow "\n path:${currentPath}"
echoContent skyBlue "\n----------------------------"
}
# Nginxไผช่ฃ
ๅๅฎข
nginxBlog() {
echoContent skyBlue "\n่ฟๅบฆ $1/${totalProgress} : ๆทปๅ ไผช่ฃ
็ซ็น"
if [[ -d "/usr/share/nginx/html" && -f "/usr/share/nginx/html/check" ]]; then
echo
read -r -p "A instalaรงรฃo de um site falso รฉ detectada, vocรช precisa reinstalรก-lo?[y/n]:" nginxBlogInstallStatus
if [[ "${nginxBlogInstallStatus}" == "y" ]]; then
rm -rf /usr/share/nginx/html
randomNum=$((RANDOM % 6 + 1))
wget -q -P /usr/share/nginx https://raw.githubusercontent.com/mack-a/v2ray-agent/master/fodder/blog/unable/html${randomNum}.zip >/dev/null
unzip -o /usr/share/nginx/html${randomNum}.zip -d /usr/share/nginx/html >/dev/null
rm -f /usr/share/nginx/html${randomNum}.zip*
echoContent green "---> Adicionar site falso com sucesso"
fi
else
randomNum=$((RANDOM % 6 + 1))
rm -rf /usr/share/nginx/html
wget -q -P /usr/share/nginx https://raw.githubusercontent.com/mack-a/v2ray-agent/master/fodder/blog/unable/html${randomNum}.zip >/dev/null
unzip -o /usr/share/nginx/html${randomNum}.zip -d /usr/share/nginx/html >/dev/null
rm -f /usr/share/nginx/html${randomNum}.zip*
echoContent green "---> Adicionar site falso com sucesso"
fi
}
# ๆไฝNginx
handleNginx() {
if [[ -z $(pgrep -f "nginx") ]] && [[ "$1" == "start" ]]; then
systemctl start nginx
sleep 0.5
if [[ -z $(pgrep -f nginx) ]]; then
echoContent red "---> Nginx falhou ao iniciar"
echoContent red "---> Por favor, tente instalar o nginx manualmente e execute o script novamente"
exit 0
fi
elif [[ -n $(pgrep -f "nginx") ]] && [[ "$1" == "stop" ]]; then
systemctl stop nginx
sleep 0.5
if [[ -n $(pgrep -f "nginx") ]]; then
pgrep -f "nginx" | xargs kill -9
fi
fi
}
# ๅฎๆถไปปๅกๆดๆฐtls่ฏไนฆ
installCronTLS() {
echoContent skyBlue "\nAgendar $1/${totalProgress} : Adicionar certificado de manutenรงรฃo regular"
crontab -l >/etc/v2ray-agent/backup_crontab.cron
local historyCrontab
historyCrontab=$(sed '/v2ray-agent/d;/acme.sh/d' /etc/v2ray-agent/backup_crontab.cron)
echo "${historyCrontab}" >/etc/v2ray-agent/backup_crontab.cron
echo "30 1 * * * /bin/bash /etc/v2ray-agent/install.sh RenewTLS >> /etc/v2ray-agent/crontab_tls.log 2>&1" >>/etc/v2ray-agent/backup_crontab.cron
crontab /etc/v2ray-agent/backup_crontab.cron
echoContent green "\n---> Adicionar certificado de manutenรงรฃo cronometrado com sucesso"
}
# ๆดๆฐ่ฏไนฆ
renewalTLS() {
if [[ -n $1 ]]; then
echoContent skyBlue "\nAgendar $1/1 : Atualizar certificado"
fi
local domain=${currentHost}
if [[ -z "${currentHost}" && -n "${tlsDomain}" ]]; then
domain=${tlsDomain}
fi
if [[ -d "$HOME/.acme.sh/${domain}_ecc" ]] && [[ -f "$HOME/.acme.sh/${domain}_ecc/${domain}.key" ]] && [[ -f "$HOME/.acme.sh/${domain}_ecc/${domain}.cer" ]]; then
modifyTime=$(stat "$HOME/.acme.sh/${domain}_ecc/${domain}.cer" | sed -n '7,6p' | awk '{print $2" "$3" "$4" "$5}')
modifyTime=$(date +%s -d "${modifyTime}")
currentTime=$(date +%s)
((stampDiff = currentTime - modifyTime))
((days = stampDiff / 86400))
((remainingDays = 90 - days))
tlsStatus=${remainingDays}
if [[ ${remainingDays} -le 0 ]]; then
tlsStatus="ๅทฒ่ฟๆ"
fi
echoContent skyBlue " ---> ่ฏไนฆๆฃๆฅๆฅๆ:$(date "+%F %H:%M:%S")"
echoContent skyBlue " ---> ่ฏไนฆ็ๆๆฅๆ:$(date -d @"${modifyTime}" +"%F %H:%M:%S")"
echoContent skyBlue " ---> ่ฏไนฆ็ๆๅคฉๆฐ:${days}"
echoContent skyBlue "---> Dias de certificado restantes:"${tlsStatus}
echoContent skyBlue "---> O certificado serรก atualizado automaticamente no รบltimo dia antes da expiraรงรฃo do certificado. Se a atualizaรงรฃo falhar, atualize-o manualmente"
if [[ ${remainingDays} -le 1 ]]; then
echoContent yellow "---> Regenerar certificado"
handleNginx stop
sudo "$HOME/.acme.sh/acme.sh" --cron --home "$HOME/.acme.sh"
sudo "$HOME/.acme.sh/acme.sh" --installcert -d "${domain}" --fullchainpath /etc/v2ray-agent/tls/"${domain}.crt" --keypath /etc/v2ray-agent/tls/"${domain}.key" --ecc
reloadCore
handleNginx start
else
echoContent green "---> O certificado รฉ vรกlido"
fi
else
echoContent red "---> nรฃo instalado"
fi
}
# ๆฅ็TLS่ฏไนฆ็็ถๆ
checkTLStatus() {
if [[ -d "$HOME/.acme.sh/${currentHost}_ecc" ]] && [[ -f "$HOME/.acme.sh/${currentHost}_ecc/${currentHost}.key" ]] && [[ -f "$HOME/.acme.sh/${currentHost}_ecc/${currentHost}.cer" ]]; then
modifyTime=$(stat "$HOME/.acme.sh/${currentHost}_ecc/${currentHost}.cer" | sed -n '7,6p' | awk '{print $2" "$3" "$4" "$5}')
modifyTime=$(date +%s -d "${modifyTime}")
currentTime=$(date +%s)
((stampDiff = currentTime - modifyTime))
((days = stampDiff / 86400))
((remainingDays = 90 - days))
tlsStatus=${remainingDays}
if [[ ${remainingDays} -le 0 ]]; then
tlsStatus="ๅทฒ่ฟๆ"
fi
echoContent skyBlue " ---> ่ฏไนฆ็ๆๆฅๆ:$(date -d "@${modifyTime}" +"%F %H:%M:%S")"
echoContent skyBlue " ---> ่ฏไนฆ็ๆๅคฉๆฐ:${days}"
echoContent skyBlue "---> Dias de certificado restantes:${tlsStatus}"
fi
}
# ๅฎ่ฃ
V2Rayใๆๅฎ็ๆฌ
installV2Ray() {
readInstallType
echoContent skyBlue "\n่ฟๅบฆ $1/${totalProgress} : ๅฎ่ฃ
V2Ray"
if [[ "${coreInstallType}" != "2" && "${coreInstallType}" != "3" ]]; then
if [[ "${selectCoreType}" == "2" ]]; then
version=$(curl -s https://api.github.com/repos/v2fly/v2ray-core/releases | jq -r '.[]|select (.prerelease==false)|.tag_name' | head -1)
else
version=${v2rayCoreVersion}
fi
echoContent green " ---> v2ray-core็ๆฌ:${version}"
if wget --help | grep -q show-progress; then
wget -c -q --show-progress -P /etc/v2ray-agent/v2ray/ "https://github.com/v2fly/v2ray-core/releases/download/${version}/${v2rayCoreCPUVendor}.zip"
else
wget -c -P /etc/v2ray-agent/v2ray/ "https://github.com/v2fly/v2ray-core/releases/download/${version}/${v2rayCoreCPUVendor}.zip" >/dev/null 2>&1
fi
unzip -o "/etc/v2ray-agent/v2ray/${v2rayCoreCPUVendor}.zip" -d /etc/v2ray-agent/v2ray >/dev/null
rm -rf "/etc/v2ray-agent/v2ray/${v2rayCoreCPUVendor}.zip"
else
if [[ "${selectCoreType}" == "3" ]]; then
echoContent green "---> Bloquear a versรฃo v2ray-core para v4.32.1"
rm -f /etc/v2ray-agent/v2ray/v2ray
rm -f /etc/v2ray-agent/v2ray/v2ctl
installV2Ray "$1"
else
echoContent green " ---> v2ray-core็ๆฌ:$(/etc/v2ray-agent/v2ray/v2ray --version | awk '{print $2}' | head -1)"
read -r -p "ๆฏๅฆๆดๆฐใๅ็บง๏ผ[y/n]:" reInstallV2RayStatus
if [[ "${reInstallV2RayStatus}" == "y" ]]; then
rm -f /etc/v2ray-agent/v2ray/v2ray
rm -f /etc/v2ray-agent/v2ray/v2ctl
installV2Ray "$1"
fi
fi
fi
}
# ๅฎ่ฃ
xray
installXray() {
readInstallType
echoContent skyBlue "\n่ฟๅบฆ $1/${totalProgress} : ๅฎ่ฃ
Xray"
if [[ "${coreInstallType}" != "1" ]]; then
version=$(curl -s https://api.github.com/repos/XTLS/Xray-core/releases | jq -r '.[]|select (.prerelease==false)|.tag_name' | head -1)
echoContent green " ---> Xray-core็ๆฌ:${version}"
if wget --help | grep -q show-progress; then
wget -c -q --show-progress -P /etc/v2ray-agent/xray/ "https://github.com/XTLS/Xray-core/releases/download/${version}/${xrayCoreCPUVendor}.zip"
else
wget -c -P /etc/v2ray-agent/xray/ "https://github.com/XTLS/Xray-core/releases/download/${version}/${xrayCoreCPUVendor}.zip" >/dev/null 2>&1
fi
unzip -o "/etc/v2ray-agent/xray/${xrayCoreCPUVendor}.zip" -d /etc/v2ray-agent/xray >/dev/null
rm -rf "/etc/v2ray-agent/xray/${xrayCoreCPUVendor}.zip"
chmod 655 /etc/v2ray-agent/xray/xray
else
echoContent green " ---> Xray-core็ๆฌ:$(/etc/v2ray-agent/xray/xray --version | awk '{print $2}' | head -1)"
read -r -p "ๆฏๅฆๆดๆฐใๅ็บง๏ผ[y/n]:" reInstallXrayStatus
if [[ "${reInstallXrayStatus}" == "y" ]]; then
rm -f /etc/v2ray-agent/xray/xray
installXray "$1"
fi
fi
}
# v2ray็ๆฌ็ฎก็
v2rayVersionManageMenu() {
echoContent skyBlue "\n่ฟๅบฆ $1/${totalProgress} : V2Ray็ๆฌ็ฎก็"
if [[ ! -d "/etc/v2ray-agent/v2ray/" ]]; then
echoContent red "---> Nenhum diretรณrio de instalaรงรฃo detectado, execute o script para instalar o conteรบdo"
menu
exit 0
fi
echoContent red "\n================================================== === ==========="
echoContent yellow "1. Atualize o v2ray-core"
echoContent yellow "2. Fallback v2ray-core"
echoContent yellow "3. Feche o v2ray-core"
echoContent yellow "4. Abra v2ray-core"
echoContent yellow "5. Reinicie o v2ray-core"
echoContent red "================================================== === ==========="
read -r -p "por favor escolha:" selectV2RayType
if [[ "${selectV2RayType}" == "1" ]]; then
updateV2Ray
elif [[ "${selectV2RayType}" == "2" ]]; then
echoContent yellow "\n1. Apenas as รบltimas cinco versรตes podem ser revertidas"
echoContent yellow "2. Nรฃo hรก garantia de que possa ser usado normalmente apรณs a reversรฃo"
echoContent yellow "3. Se a versรฃo revertida nรฃo suportar a configuraรงรฃo atual, ela nรฃo poderรก se conectar, opere com cuidado"
echoContent skyBlue "------------------------Versรฃo------------------------- ------"
curl -s https://api.github.com/repos/v2fly/v2ray-core/releases | jq -r '.[]|select (.prerelease==false)|.tag_name' | head -5 | awk '{print ""NR""":"$0}'
echoContent skyBlue "-------------------------------------------------- ------------"
read -r -p "Insira a versรฃo que vocรช deseja reverter:" selectV2rayVersionType
version=$(curl -s https://api.github.com/repos/v2fly/v2ray-core/releases | jq -r '.[]|select (.prerelease==false)|.tag_name' | head -5 | awk '{print ""NR""":"$0}' | grep "${selectV2rayVersionType}:" | awk -F "[:]" '{print $2}')
if [[ -n "${version}" ]]; then
updateV2Ray "${version}"
else
echoContent red "\n---> A entrada estรก incorreta, por favor digite novamente"
v2rayVersionManageMenu 1
fi
elif [[ "${selectXrayType}" == "3" ]]; then
handleV2Ray stop
elif [[ "${selectXrayType}" == "4" ]]; then
handleV2Ray start
elif [[ "${selectXrayType}" == "5" ]]; then
reloadCore
fi
}
# xray็ๆฌ็ฎก็
xrayVersionManageMenu() {
echoContent skyBlue "\n่ฟๅบฆ $1/${totalProgress} : Xray็ๆฌ็ฎก็"
if [[ ! -d "/etc/v2ray-agent/xray/" ]]; then
echoContent red "---> Nenhum diretรณrio de instalaรงรฃo detectado, execute o script para instalar o conteรบdo"
menu
exit 0
fi
echoContent red "\n================================================== === ==========="
echoContent yellow "1. Atualize o Xray-core"
echoContent yellow "2. Xray-core de fallback"
echoContent yellow "3. Feche o Xray-core"
echoContent yellow "4. Abra o Xray-core"
echoContent yellow "5. Reinicie o Xray-core"
echoContent red "================================================== === ==========="
read -r -p "por favor escolha:" selectXrayType
if [[ "${selectXrayType}" == "1" ]]; then
updateXray
elif [[ "${selectXrayType}" == "2" ]]; then
echoContent yellow "\n1. Apenas as รบltimas cinco versรตes podem ser revertidas"
echoContent yellow "2. Nรฃo hรก garantia de que possa ser usado normalmente apรณs a reversรฃo"
echoContent yellow "3. Se a versรฃo revertida nรฃo suportar a configuraรงรฃo atual, ela nรฃo poderรก se conectar, opere com cuidado"
echoContent skyBlue "------------------------Versรฃo------------------------- ------"
curl -s https://api.github.com/repos/XTLS/Xray-core/releases | jq -r '.[]|select (.prerelease==false)|.tag_name' | head -5 | awk '{print ""NR""":"$0}'
echoContent skyBlue "-------------------------------------------------- ------------"
read -r -p "Insira a versรฃo que vocรช deseja reverter:" selectXrayVersionType
version=$(curl -s https://api.github.com/repos/XTLS/Xray-core/releases | jq -r '.[]|select (.prerelease==false)|.tag_name' | head -5 | awk '{print ""NR""":"$0}' | grep "${selectXrayVersionType}:" | awk -F "[:]" '{print $2}')
if [[ -n "${version}" ]]; then
updateXray "${version}"
else
echoContent red "\n---> A entrada estรก incorreta, por favor digite novamente"
xrayVersionManageMenu 1
fi
elif [[ "${selectXrayType}" == "3" ]]; then
handleXray stop
elif [[ "${selectXrayType}" == "4" ]]; then
handleXray start
elif [[ "${selectXrayType}" == "5" ]]; then
reloadCore
fi
}
# ๆดๆฐV2Ray
updateV2Ray() {
readInstallType
if [[ -z "${coreInstallType}" ]]; then
if [[ -n "$1" ]]; then
version=$1
else
version=$(curl -s https://api.github.com/repos/v2fly/v2ray-core/releases | jq -r '.[]|select (.prerelease==false)|.tag_name' | head -1)
fi
# ไฝฟ็จ้ๅฎ็็ๆฌ
if [[ -n "${v2rayCoreVersion}" ]]; then
version=${v2rayCoreVersion}
fi
echoContent green " ---> v2ray-core็ๆฌ:${version}"
if wget --help | grep -q show-progress; then
wget -c -q --show-progress -P /etc/v2ray-agent/v2ray/ "https://github.com/v2fly/v2ray-core/releases/download/${version}/${v2rayCoreCPUVendor}.zip"
else
wget -c -P "/etc/v2ray-agent/v2ray/ https://github.com/v2fly/v2ray-core/releases/download/${version}/${v2rayCoreCPUVendor}.zip" >/dev/null 2>&1
fi
unzip -o "/etc/v2ray-agent/v2ray/${v2rayCoreCPUVendor}.zip" -d /etc/v2ray-agent/v2ray >/dev/null
rm -rf "/etc/v2ray-agent/v2ray/${v2rayCoreCPUVendor}.zip"
handleV2Ray stop
handleV2Ray start
else
echoContent green " ---> ๅฝๅv2ray-core็ๆฌ:$(/etc/v2ray-agent/v2ray/v2ray --version | awk '{print $2}' | head -1)"
if [[ -n "$1" ]]; then
version=$1
else
version=$(curl -s https://api.github.com/repos/v2fly/v2ray-core/releases | jq -r '.[]|select (.prerelease==false)|.tag_name' | head -1)
fi
if [[ -n "${v2rayCoreVersion}" ]]; then
version=${v2rayCoreVersion}
fi
if [[ -n "$1" ]]; then
read -r -p "ๅ้็ๆฌไธบ${version}๏ผๆฏๅฆ็ปง็ปญ๏ผ[y/n]:" rollbackV2RayStatus
if [[ "${rollbackV2RayStatus}" == "y" ]]; then
if [[ "${coreInstallType}" == "2" || "${coreInstallType}" == "3" ]]; then
echoContent green " ---> ๅฝๅv2ray-core็ๆฌ:$(/etc/v2ray-agent/v2ray/v2ray --version | awk '{print $2}' | head -1)"
elif [[ "${coreInstallType}" == "1" ]]; then
echoContent green " ---> ๅฝๅXray-core็ๆฌ:$(/etc/v2ray-agent/xray/xray --version | awk '{print $2}' | head -1)"
fi
handleV2Ray stop
rm -f /etc/v2ray-agent/v2ray/v2ray
rm -f /etc/v2ray-agent/v2ray/v2ctl
updateV2Ray "${version}"
else
echoContent green "---> Abandone a versรฃo de reserva"
fi
elif [[ "${version}" == "v$(/etc/v2ray-agent/v2ray/v2ray --version | awk '{print $2}' | head -1)" ]]; then
read -r -p "ๅฝๅ็ๆฌไธๆๆฐ็็ธๅ๏ผๆฏๅฆ้ๆฐๅฎ่ฃ
๏ผ[y/n]:" reInstallV2RayStatus
if [[ "${reInstallV2RayStatus}" == "y" ]]; then
handleV2Ray stop
rm -f /etc/v2ray-agent/v2ray/v2ray
rm -f /etc/v2ray-agent/v2ray/v2ctl
updateV2Ray
else
echoContent green "---> Abortar a reinstalaรงรฃo"
fi
else
read -r -p "ๆๆฐ็ๆฌไธบ:${version}๏ผๆฏๅฆๆดๆฐ๏ผ[y/n]:" installV2RayStatus
if [[ "${installV2RayStatus}" == "y" ]]; then
rm -f /etc/v2ray-agent/v2ray/v2ray
rm -f /etc/v2ray-agent/v2ray/v2ctl
updateV2Ray
else
echoContent green "---> Abortar atualizaรงรฃo"
fi
fi
fi
}
# ๆดๆฐXray
updateXray() {
readInstallType
if [[ -z "${coreInstallType}" ]]; then
if [[ -n "$1" ]]; then
version=$1
else
version=$(curl -s https://api.github.com/repos/XTLS/Xray-core/releases | jq -r '.[]|select (.prerelease==false)|.tag_name' | head -1)
fi
echoContent green " ---> Xray-core็ๆฌ:${version}"
if wget --help | grep -q show-progress; then
wget -c -q --show-progress -P /etc/v2ray-agent/xray/ "https://github.com/XTLS/Xray-core/releases/download/${version}/${xrayCoreCPUVendor}.zip"
else
wget -c -P /etc/v2ray-agent/xray/ "https://github.com/XTLS/Xray-core/releases/download/${version}/${xrayCoreCPUVendor}.zip" >/dev/null 2>&1
fi
unzip -o "/etc/v2ray-agent/xray/${xrayCoreCPUVendor}.zip" -d /etc/v2ray-agent/xray >/dev/null
rm -rf "/etc/v2ray-agent/xray/${xrayCoreCPUVendor}.zip"
chmod 655 /etc/v2ray-agent/xray/xray
handleXray stop
handleXray start
else
echoContent green " ---> ๅฝๅXray-core็ๆฌ:$(/etc/v2ray-agent/xray/xray --version | awk '{print $2}' | head -1)"
if [[ -n "$1" ]]; then
version=$1
else
version=$(curl -s https://api.github.com/repos/XTLS/Xray-core/releases | jq -r '.[]|select (.prerelease==false)|.tag_name' | head -1)
fi
if [[ -n "$1" ]]; then
read -r -p "ๅ้็ๆฌไธบ${version}๏ผๆฏๅฆ็ปง็ปญ๏ผ[y/n]:" rollbackXrayStatus
if [[ "${rollbackXrayStatus}" == "y" ]]; then
echoContent green " ---> ๅฝๅXray-core็ๆฌ:$(/etc/v2ray-agent/xray/xray --version | awk '{print $2}' | head -1)"
handleXray stop
rm -f /etc/v2ray-agent/xray/xray
updateXray "${version}"
else
echoContent green "---> Abandone a versรฃo de reserva"
fi
elif [[ "${version}" == "v$(/etc/v2ray-agent/xray/xray --version | awk '{print $2}' | head -1)" ]]; then
read -r -p "ๅฝๅ็ๆฌไธๆๆฐ็็ธๅ๏ผๆฏๅฆ้ๆฐๅฎ่ฃ
๏ผ[y/n]:" reInstallXrayStatus
if [[ "${reInstallXrayStatus}" == "y" ]]; then
handleXray stop
rm -f /etc/v2ray-agent/xray/xray
rm -f /etc/v2ray-agent/xray/xray
updateXray
else
echoContent green "---> Abortar a reinstalaรงรฃo"
fi
else
read -r -p "ๆๆฐ็ๆฌไธบ:${version}๏ผๆฏๅฆๆดๆฐ๏ผ[y/n]:" installXrayStatus
if [[ "${installXrayStatus}" == "y" ]]; then
rm -f /etc/v2ray-agent/xray/xray
updateXray
else
echoContent green "---> Abortar atualizaรงรฃo"
fi
fi
fi
}
# ้ช่ฏๆดไธชๆๅกๆฏๅฆๅฏ็จ
checkGFWStatue() {
readInstallType
echoContent skyBlue "\n่ฟๅบฆ $1/${totalProgress} : ้ช่ฏๆๅกๅฏๅจ็ถๆ"
if [[ "${coreInstallType}" == "1" ]] && [[ -n $(pgrep -f xray/xray) ]]; then
echoContent green "---> Serviรงo iniciado com sucesso"
elif [[ "${coreInstallType}" == "2" || "${coreInstallType}" == "3" ]] && [[ -n $(pgrep -f v2ray/v2ray) ]]; then
echoContent green "---> Serviรงo iniciado com sucesso"
else
echoContent red "---> O serviรงo falhou ao iniciar, verifique se hรก uma impressรฃo de log no terminal"
exit 0
fi
}
# V2Rayๅผๆบ่ชๅฏ
installV2RayService() {
echoContent skyBlue "\n่ฟๅบฆ $1/${totalProgress} : ้
็ฝฎV2Rayๅผๆบ่ชๅฏ"
if [[ -n $(find /bin /usr/bin -name "systemctl") ]]; then
rm -rf /etc/systemd/system/v2ray.service
touch /etc/systemd/system/v2ray.service
execStart='/etc/v2ray-agent/v2ray/v2ray -confdir /etc/v2ray-agent/v2ray/conf'
cat <<EOF >/etc/systemd/system/v2ray.service
[Unit]
Description=V2Ray - A unified platform for anti-censorship
Documentation=https://v2ray.com https://guide.v2fly.org
After=network.target nss-lookup.target
Wants=network-online.target
[Service]
Type=simple
User=root
CapabilityBoundingSet=CAP_NET_BIND_SERVICE CAP_NET_RAW
NoNewPrivileges=yes
ExecStart=${execStart}
Restart=on-failure
RestartPreventExitStatus=23
[Install]
WantedBy=multi-user.target
EOF
systemctl daemon-reload
systemctl enable v2ray.service
echoContent green "---> Configure o V2Ray para iniciar automaticamente apรณs a inicializaรงรฃo"
fi
}
# Xrayๅผๆบ่ชๅฏ
installXrayService() {
echoContent skyBlue "\n่ฟๅบฆ $1/${totalProgress} : ้
็ฝฎXrayๅผๆบ่ชๅฏ"
if [[ -n $(find /bin /usr/bin -name "systemctl") ]]; then
rm -rf /etc/systemd/system/xray.service
touch /etc/systemd/system/xray.service
execStart='/etc/v2ray-agent/xray/xray run -confdir /etc/v2ray-agent/xray/conf'
cat <<EOF >/etc/systemd/system/xray.service
[Unit]
Description=Xray - A unified platform for anti-censorship
# Documentation=https://v2ray.com https://guide.v2fly.org
After=network.target nss-lookup.target
Wants=network-online.target
[Service]
Type=simple
User=root
CapabilityBoundingSet=CAP_NET_BIND_SERVICE CAP_NET_RAW
NoNewPrivileges=yes
ExecStart=${execStart}
Restart=on-failure
RestartPreventExitStatus=23
[Install]
WantedBy=multi-user.target
EOF
systemctl daemon-reload
systemctl enable xray.service
echoContent green "---> Configure o Xray para iniciar automaticamente apรณs a inicializaรงรฃo com sucesso"
fi
}
# ๆไฝV2Ray
handleV2Ray() {
# shellcheck disable=SC2010
if find /bin /usr/bin | grep -q systemctl && ls /etc/systemd/system/ | grep -q v2ray.service; then
if [[ -z $(pgrep -f "v2ray/v2ray") ]] && [[ "$1" == "start" ]]; then
systemctl start v2ray.service
elif [[ -n $(pgrep -f "v2ray/v2ray") ]] && [[ "$1" == "stop" ]]; then
systemctl stop v2ray.service
fi
fi
sleep 0.8
if [[ "$1" == "start" ]]; then
if [[ -n $(pgrep -f "v2ray/v2ray") ]]; then
echoContent green "---> V2Ray iniciado com sucesso"
else
echoContent red "V2Ray falhou ao iniciar"
echoContent red "Execute manualmente [/etc/v2ray-agent/v2ray/v2ray -confdir /etc/v2ray-agent/v2ray/conf] para visualizar o log de erros"
exit 0
fi
elif [[ "$1" == "stop" ]]; then
if [[ -z $(pgrep -f "v2ray/v2ray") ]]; then
echoContent green "---> V2Ray fechado com sucesso"
else
echoContent red "V2Ray falhou ao fechar"
echoContent red "่ฏทๆๅจๆง่กใps -ef|grep -v grep|grep v2ray|awk '{print \$2}'|xargs kill -9ใ"
exit 0
fi
fi
}
# ๆไฝxray
handleXray() {
if [[ -n $(find /bin /usr/bin -name "systemctl") ]] && [[ -n $(find /etc/systemd/system/ -name "xray.service") ]]; then
if [[ -z $(pgrep -f "xray/xray") ]] && [[ "$1" == "start" ]]; then
systemctl start xray.service
elif [[ -n $(pgrep -f "xray/xray") ]] && [[ "$1" == "stop" ]]; then
systemctl stop xray.service
fi
fi
sleep 0.8
if [[ "$1" == "start" ]]; then
if [[ -n $(pgrep -f "xray/xray") ]]; then
echoContent green "---> Xray iniciado com sucesso"
else
echoContent red "xray falhou ao iniciar"
echoContent red "Execute manualmente [/etc/v2ray-agent/xray/xray -confdir /etc/v2ray-agent/xray/conf] para visualizar o log de erros"
exit 0
fi
elif [[ "$1" == "stop" ]]; then
if [[ -z $(pgrep -f "xray/xray") ]]; then
echoContent green "---> x-ray fechado com sucesso"
else
echoContent red "falha no fechamento do x-ray"
echoContent red "่ฏทๆๅจๆง่กใps -ef|grep -v grep|grep xray|awk '{print \$2}'|xargs kill -9ใ"
exit 0
fi
fi
}
# ่ทๅclients้
็ฝฎ
getClients() {
local path=$1
local addClientsStatus=$2
previousClients=
if [[ ${addClientsStatus} == "true" ]]; then
if [[ ! -f "${path}" ]]; then
echo
local protocol=$(echo "${path}" | awk -F "[_]" '{print $2 $3}')
echoContent yellow "ๆฒกๆ่ฏปๅๅฐๆญคๅ่ฎฎ[${protocol}]ไธไธๆฌกๅฎ่ฃ
็้
็ฝฎๆไปถ๏ผ้็จ้
็ฝฎๆไปถ็็ฌฌไธไธชuuid"
else
previousClients=$(jq -r ".inbounds[0].settings.clients" "${path}")
fi
fi
}
# ๆทปๅ client้
็ฝฎ
addClients() {
local path=$1
local addClientsStatus=$2
if [[ ${addClientsStatus} == "true" && -n "${previousClients}" ]]; then
config=$(jq -r ".inbounds[0].settings.clients = ${previousClients}" "${path}")
echo "${config}" | jq . >"${path}"
fi
}
# ๅๅงๅV2Ray ้
็ฝฎๆไปถ
initV2RayConfig() {
echoContent skyBlue "\n่ฟๅบฆ $2/${totalProgress} : ๅๅงๅV2Ray้
็ฝฎ"
echo
read -r -p "ๆฏๅฆ่ชๅฎไนUUID ๏ผ[y/n]:" customUUIDStatus
echo
if [[ "${customUUIDStatus}" == "y" ]]; then
read -r -p "Insira um UUID vรกlido:" currentCustomUUID
if [[ -n "${currentCustomUUID}" ]]; then
uuid=${currentCustomUUID}
fi
fi
local addClientsStatus=
if [[ -n "${currentUUID}" && -z "${uuid}" ]]; then
read -r -p "่ฏปๅๅฐไธๆฌกๅฎ่ฃ
่ฎฐๅฝ๏ผๆฏๅฆไฝฟ็จไธๆฌกๅฎ่ฃ
ๆถ็UUID ๏ผ[y/n]:" historyUUIDStatus
if [[ "${historyUUIDStatus}" == "y" ]]; then
uuid=${currentUUID}
addClientsStatus=true
else
uuid=$(/etc/v2ray-agent/v2ray/v2ctl uuid)
fi
elif [[ -z "${uuid}" ]]; then
uuid=$(/etc/v2ray-agent/v2ray/v2ctl uuid)
fi
if [[ -z "${uuid}" ]]; then
addClientsStatus=
echoContent red "\n---> erro de leitura uuid, regenerar"
uuid=$(/etc/v2ray-agent/v2ray/v2ctl uuid)
fi
movePreviousConfig
# log
cat <<EOF >/etc/v2ray-agent/v2ray/conf/00_log.json
{
"log": {
"error": "/etc/v2ray-agent/v2ray/error.log",
"loglevel": "warning"
}
}
EOF
# outbounds
if [[ -n "${pingIPv6}" ]]; then
cat <<EOF >/etc/v2ray-agent/v2ray/conf/10_ipv6_outbounds.json
{
"outbounds": [
{
"protocol": "freedom",
"settings": {},
"tag": "direct"
}
]
}
EOF
else
cat <<EOF >/etc/v2ray-agent/v2ray/conf/10_ipv4_outbounds.json
{
"outbounds":[
{
"protocol":"freedom",
"settings":{
"domainStrategy":"UseIPv4"
},
"tag":"IPv4-out"
},
{
"protocol":"freedom",
"settings":{
"domainStrategy":"UseIPv6"
},
"tag":"IPv6-out"
},
{
"protocol":"blackhole",
"tag":"blackhole-out"
}
]
}
EOF
fi
# dns
cat <<EOF >/etc/v2ray-agent/v2ray/conf/11_dns.json
{
"dns": {
"servers": [
"localhost"
]
}
}
EOF
# VLESS_TCP_TLS
# ๅ่ฝnginx
local fallbacksList='{"dest":31300,"xver":0},{"alpn":"h2","dest":31302,"xver":0}'
# trojan
if echo "${selectCustomInstallType}" | grep -q 4 || [[ "$1" == "all" ]]; then
fallbacksList='{"dest":31296,"xver":1},{"alpn":"h2","dest":31302,"xver":0}'
getClients "${configPath}../tmp/04_trojan_TCP_inbounds.json" "${addClientsStatus}"
cat <<EOF >/etc/v2ray-agent/v2ray/conf/04_trojan_TCP_inbounds.json
{
"inbounds":[
{
"port": 31296,
"listen": "127.0.0.1",
"protocol": "trojan",
"tag":"trojanTCP",
"settings": {
"clients": [
{
"password": "${uuid}",
"email": "${domain}_trojan_tcp"
}
],
"fallbacks":[
{"dest":"31300"}
]
},
"streamSettings": {
"network": "tcp",
"security": "none",
"tcpSettings": {
"acceptProxyProtocol": true
}
}
}
]
}
EOF
addClients "/etc/v2ray-agent/v2ray/conf/04_trojan_TCP_inbounds.json" "${addClientsStatus}"
fi
# VLESS_WS_TLS
if echo "${selectCustomInstallType}" | grep -q 1 || [[ "$1" == "all" ]]; then
fallbacksList=${fallbacksList}',{"path":"/'${customPath}'ws","dest":31297,"xver":1}'
getClients "${configPath}../tmp/03_VLESS_WS_inbounds.json" "${addClientsStatus}"
cat <<EOF >/etc/v2ray-agent/v2ray/conf/03_VLESS_WS_inbounds.json
{
"inbounds":[
{
"port": 31297,
"listen": "127.0.0.1",
"protocol": "vless",
"tag":"VLESSWS",
"settings": {
"clients": [
{
"id": "${uuid}",
"email": "${domain}_VLESS_WS"
}
],
"decryption": "none"
},
"streamSettings": {
"network": "ws",
"security": "none",
"wsSettings": {
"acceptProxyProtocol": true,
"path": "/${customPath}ws"
}
}
}
]
}
EOF
addClients "/etc/v2ray-agent/v2ray/conf/03_VLESS_WS_inbounds.json" "${addClientsStatus}"
fi
# trojan_grpc
if echo "${selectCustomInstallType}" | grep -q 2 || [[ "$1" == "all" ]]; then
if ! echo "${selectCustomInstallType}" | grep -q 5 && [[ -n ${selectCustomInstallType} ]]; then
fallbacksList=${fallbacksList//31302/31304}
fi
getClients "${configPath}../tmp/04_trojan_gRPC_inbounds.json" "${addClientsStatus}"
cat <<EOF >/etc/v2ray-agent/v2ray/conf/04_trojan_gRPC_inbounds.json
{
"inbounds": [
{
"port": 31304,
"listen": "127.0.0.1",
"protocol": "trojan",
"tag": "trojangRPCTCP",
"settings": {
"clients": [
{
"password": "${uuid}",
"email": "${domain}_trojan_gRPC"
}
],
"fallbacks": [
{
"dest": "31300"
}
]
},
"streamSettings": {
"network": "ws",
"security": "none",
"wsSettings": {
"acceptProxyProtocol": true,
"path": "/${customPath}trojangrpc"
}
}
}
]
}
EOF
addClients "/etc/v2ray-agent/v2ray/conf/04_trojan_gRPC_inbounds.json" "${addClientsStatus}"
fi
# VMess_WS
if echo "${selectCustomInstallType}" | grep -q 3 || [[ "$1" == "all" ]]; then
fallbacksList=${fallbacksList}',{"path":"/'${customPath}'vws","dest":31299,"xver":1}'
getClients "${configPath}../tmp/05_VMess_WS_inbounds.json" "${addClientsStatus}"
cat <<EOF >/etc/v2ray-agent/v2ray/conf/05_VMess_WS_inbounds.json
{
"inbounds":[
{
"listen": "127.0.0.1",
"port": 31299,
"protocol": "vmess",
"tag":"VMessWS",
"settings": {
"clients": [
{
"id": "${uuid}",
"alterId": 0,
"add": "${add}",
"email": "${domain}_vmess_ws"
}
]
},
"streamSettings": {
"network": "ws",
"security": "none",
"wsSettings": {
"acceptProxyProtocol": true,
"path": "/${customPath}vws"
}
}
}
]
}
EOF
addClients "/etc/v2ray-agent/v2ray/conf/05_VMess_WS_inbounds.json" "${addClientsStatus}"
fi
if echo "${selectCustomInstallType}" | grep -q 5 || [[ "$1" == "all" ]]; then
getClients "${configPath}../tmp/06_VLESS_gRPC_inbounds.json" "${addClientsStatus}"
cat <<EOF >/etc/v2ray-agent/v2ray/conf/06_VLESS_gRPC_inbounds.json
{
"inbounds":[
{
"port": 31301,
"listen": "127.0.0.1",
"protocol": "vless",
"tag":"VLESSGRPC",
"settings": {
"clients": [
{
"id": "${uuid}",
"add": "${add}",
"email": "${domain}_VLESS_gRPC"
}
],
"decryption": "none"
},
"streamSettings": {
"network": "grpc",
"grpcSettings": {
"serviceName": "${customPath}grpc"
}
}
}
]
}
EOF
addClients "/etc/v2ray-agent/v2ray/conf/06_VLESS_gRPC_inbounds.json" "${addClientsStatus}"
fi
# VLESS_TCP
getClients "${configPath}../tmp/02_VLESS_TCP_inbounds.json" "${addClientsStatus}"
cat <<EOF >/etc/v2ray-agent/v2ray/conf/02_VLESS_TCP_inbounds.json
{
"inbounds":[
{
"port": 443,
"protocol": "vless",
"tag":"VLESSTCP",
"settings": {
"clients": [
{
"id": "${uuid}",
"add":"${add}",
"email": "${domain}_VLESS_TLS-direct_TCP"
}
],
"decryption": "none",
"fallbacks": [
${fallbacksList}
]
},
"streamSettings": {
"network": "tcp",
"security": "tls",
"tlsSettings": {
"minVersion": "1.2",
"alpn": [
"http/1.1",
"h2"
],
"certificates": [
{
"certificateFile": "/etc/v2ray-agent/tls/${domain}.crt",
"keyFile": "/etc/v2ray-agent/tls/${domain}.key",
"ocspStapling": 3600,
"usage":"encipherment"
}
]
}
}
}
]
}
EOF
addClients "/etc/v2ray-agent/v2ray/conf/02_VLESS_TCP_inbounds.json" "${addClientsStatus}"
}
# ๅๅงๅXray Trojan XTLS ้
็ฝฎๆไปถ
initXrayFrontingConfig() {
if [[ -z "${configPath}" ]]; then
echoContent red "---> nรฃo instalado๏ผ่ฏทไฝฟ็จ่ๆฌๅฎ่ฃ
"
menu
exit 0
fi
if [[ "${coreInstallType}" != "1" ]]; then
echoContent red "---> nรฃo instaladoๅฏ็จ็ฑปๅ"
fi
local xtlsType=
if echo ${currentInstallProtocolType} | grep -q trojan; then
xtlsType=VLESS
else
xtlsType=Trojan
fi
echoContent skyBlue "\nๅ่ฝ 1/${totalProgress} : ๅ็ฝฎๅๆขไธบ${xtlsType}"
echoContent red "\n================================================== === ==========="
echoContent yellow "# Precauรงรตes\n"
echoContent yellow "ไผๅฐๅ็ฝฎๆฟๆขไธบ${xtlsType}"
echoContent yellow "Se o prefixo for Trojan, ao visualizar a conta, haverรก dois nรณs do protocolo Trojan, um dos quais estรก indisponรญvel xtls"
echoContent yellow "Execute novamente para mudar para o preรขmbulo anterior\n"
echoContent yellow "1.ๅๆข่ณ${xtlsType}"
echoContent red "================================================== === ==========="
read -r -p "por favor escolha:" selectType
if [[ "${selectType}" == "1" ]]; then
if [[ "${xtlsType}" == "Trojan" ]]; then
local VLESSConfig
VLESSConfig=$(cat ${configPath}${frontingType}.json)
VLESSConfig=${VLESSConfig//"id"/"password"}
VLESSConfig=${VLESSConfig//VLESSTCP/TrojanTCPXTLS}
VLESSConfig=${VLESSConfig//VLESS/Trojan}
VLESSConfig=${VLESSConfig//"vless"/"trojan"}
VLESSConfig=${VLESSConfig//"id"/"password"}
echo "${VLESSConfig}" | jq . >${configPath}02_trojan_TCP_inbounds.json
rm ${configPath}${frontingType}.json
elif [[ "${xtlsType}" == "VLESS" ]]; then
local VLESSConfig
VLESSConfig=$(cat ${configPath}02_trojan_TCP_inbounds.json)
VLESSConfig=${VLESSConfig//"password"/"id"}
VLESSConfig=${VLESSConfig//TrojanTCPXTLS/VLESSTCP}
VLESSConfig=${VLESSConfig//Trojan/VLESS}
VLESSConfig=${VLESSConfig//"trojan"/"vless"}
VLESSConfig=${VLESSConfig//"password"/"id"}
echo "${VLESSConfig}" | jq . >${configPath}02_VLESS_TCP_inbounds.json
rm ${configPath}02_trojan_TCP_inbounds.json
fi
reloadCore
fi
exit 0
}
# ็งปๅจไธๆฌก้
็ฝฎๆไปถ่ณไธดๆถๆไปถ
movePreviousConfig() {
if [[ -n "${configPath}" ]] && [[ -f "${configPath}02_VLESS_TCP_inbounds.json" ]]; then
rm -rf ${configPath}../tmp/*
mv ${configPath}* ${configPath}../tmp/
fi
}
# ๅๅงๅXray ้
็ฝฎๆไปถ
initXrayConfig() {
echoContent skyBlue "\n่ฟๅบฆ $2/${totalProgress} : ๅๅงๅXray้
็ฝฎ"
echo
local uuid=
local addClientsStatus=
if [[ -n "${currentUUID}" ]]; then
read -r -p "่ฏปๅๅฐไธๆฌกๅฎ่ฃ
่ฎฐๅฝ๏ผๆฏๅฆไฝฟ็จไธๆฌกๅฎ่ฃ
ๆถ็UUID ๏ผ[y/n]:" historyUUIDStatus
if [[ "${historyUUIDStatus}" == "y" ]]; then
addClientsStatus=true
uuid=${currentUUID}
echoContent green "\n---> Use com sucesso"
fi
fi
if [[ -z "${uuid}" ]]; then
echoContent yellow "Insira um UUID personalizado [deve ser legal]: "
read -r -p 'UUID:' customUUID
if [[ -n ${customUUID} ]]; then
uuid=${customUUID}
else
uuid=$(/etc/v2ray-agent/xray/xray uuid)
fi
fi
if [[ -z "${uuid}" ]]; then
addClientsStatus=
echoContent red "\n---> erro de leitura uuid, regenerar"
uuid=$(/etc/v2ray-agent/xray/xray uuid)
fi
echoContent yellow "\n ${uuid}"
movePreviousConfig
# log
cat <<EOF >/etc/v2ray-agent/xray/conf/00_log.json
{
"log": {
"error": "/etc/v2ray-agent/xray/error.log",
"loglevel": "warning"
}
}
EOF
# outbounds
if [[ -n "${pingIPv6}" ]]; then
cat <<EOF >/etc/v2ray-agent/xray/conf/10_ipv6_outbounds.json
{
"outbounds": [
{
"protocol": "freedom",
"settings": {},
"tag": "direct"
}
]
}
EOF
else
cat <<EOF >/etc/v2ray-agent/xray/conf/10_ipv4_outbounds.json
{
"outbounds":[
{
"protocol":"freedom",
"settings":{
"domainStrategy":"UseIPv4"
},
"tag":"IPv4-out"
},
{
"protocol":"freedom",
"settings":{
"domainStrategy":"UseIPv6"
},
"tag":"IPv6-out"
},
{
"protocol":"blackhole",
"tag":"blackhole-out"
}
]
}
EOF
fi
# dns
cat <<EOF >/etc/v2ray-agent/xray/conf/11_dns.json
{
"dns": {
"servers": [
"localhost"
]
}
}
EOF
# VLESS_TCP_TLS/XTLS
# ๅ่ฝnginx
local fallbacksList='{"dest":31300,"xver":0},{"alpn":"h2","dest":31302,"xver":0}'
# trojan
if echo "${selectCustomInstallType}" | grep -q 4 || [[ "$1" == "all" ]]; then
fallbacksList='{"dest":31296,"xver":1},{"alpn":"h2","dest":31302,"xver":0}'
getClients "${configPath}../tmp/04_trojan_TCP_inbounds.json" "${addClientsStatus}"
cat <<EOF >/etc/v2ray-agent/xray/conf/04_trojan_TCP_inbounds.json
{
"inbounds":[
{
"port": 31296,
"listen": "127.0.0.1",
"protocol": "trojan",
"tag":"trojanTCP",
"settings": {
"clients": [
{
"password": "${uuid}",
"email": "${domain}_trojan_tcp"
}
],
"fallbacks":[
{"dest":"31300"}
]
},
"streamSettings": {
"network": "tcp",
"security": "none",
"tcpSettings": {
"acceptProxyProtocol": true
}
}
}
]
}
EOF
addClients "/etc/v2ray-agent/xray/conf/04_trojan_TCP_inbounds.json" "${addClientsStatus}"
fi
# VLESS_WS_TLS
if echo "${selectCustomInstallType}" | grep -q 1 || [[ "$1" == "all" ]]; then
fallbacksList=${fallbacksList}',{"path":"/'${customPath}'ws","dest":31297,"xver":1}'
getClients "${configPath}../tmp/03_VLESS_WS_inbounds.json" "${addClientsStatus}"
cat <<EOF >/etc/v2ray-agent/xray/conf/03_VLESS_WS_inbounds.json
{
"inbounds":[
{
"port": 31297,
"listen": "127.0.0.1",
"protocol": "vless",
"tag":"VLESSWS",
"settings": {
"clients": [
{
"id": "${uuid}",
"email": "${domain}_VLESS_WS"
}
],
"decryption": "none"
},
"streamSettings": {
"network": "ws",
"security": "none",
"wsSettings": {
"acceptProxyProtocol": true,
"path": "/${customPath}ws"
}
}
}
]
}
EOF
addClients "/etc/v2ray-agent/xray/conf/03_VLESS_WS_inbounds.json" "${addClientsStatus}"
fi
# trojan_grpc
if echo "${selectCustomInstallType}" | grep -q 2 || [[ "$1" == "all" ]]; then
if ! echo "${selectCustomInstallType}" | grep -q 5 && [[ -n ${selectCustomInstallType} ]]; then
fallbacksList=${fallbacksList//31302/31304}
fi
getClients "${configPath}../tmp/04_trojan_gRPC_inbounds.json" "${addClientsStatus}"
cat <<EOF >/etc/v2ray-agent/xray/conf/04_trojan_gRPC_inbounds.json
{
"inbounds": [
{
"port": 31304,
"listen": "127.0.0.1",
"protocol": "trojan",
"tag": "trojangRPCTCP",
"settings": {
"clients": [
{
"password": "${uuid}",
"email": "${domain}_trojan_gRPC"
}
],
"fallbacks": [
{
"dest": "31300"
}
]
},
"streamSettings": {
"network": "grpc",
"grpcSettings": {
"serviceName": "${customPath}trojangrpc"
}
}
}
]
}
EOF
addClients "/etc/v2ray-agent/xray/conf/04_trojan_gRPC_inbounds.json" "${addClientsStatus}"
fi
# VMess_WS
if echo "${selectCustomInstallType}" | grep -q 3 || [[ "$1" == "all" ]]; then
fallbacksList=${fallbacksList}',{"path":"/'${customPath}'vws","dest":31299,"xver":1}'
getClients "${configPath}../tmp/05_VMess_WS_inbounds.json" "${addClientsStatus}"
cat <<EOF >/etc/v2ray-agent/xray/conf/05_VMess_WS_inbounds.json
{
"inbounds":[
{
"listen": "127.0.0.1",
"port": 31299,
"protocol": "vmess",
"tag":"VMessWS",
"settings": {
"clients": [
{
"id": "${uuid}",
"alterId": 0,
"add": "${add}",
"email": "${domain}_vmess_ws"
}
]
},
"streamSettings": {
"network": "ws",
"security": "none",
"wsSettings": {
"acceptProxyProtocol": true,
"path": "/${customPath}vws"
}
}
}
]
}
EOF
addClients "/etc/v2ray-agent/xray/conf/05_VMess_WS_inbounds.json" "${addClientsStatus}"
fi
if echo "${selectCustomInstallType}" | grep -q 5 || [[ "$1" == "all" ]]; then
getClients "${configPath}../tmp/06_VLESS_gRPC_inbounds.json" "${addClientsStatus}"
cat <<EOF >/etc/v2ray-agent/xray/conf/06_VLESS_gRPC_inbounds.json
{
"inbounds":[
{
"port": 31301,
"listen": "127.0.0.1",
"protocol": "vless",
"tag":"VLESSGRPC",
"settings": {
"clients": [
{
"id": "${uuid}",
"add": "${add}",
"email": "${domain}_VLESS_gRPC"
}
],
"decryption": "none"
},
"streamSettings": {
"network": "grpc",
"grpcSettings": {
"serviceName": "${customPath}grpc"
}
}
}
]
}
EOF
addClients "/etc/v2ray-agent/xray/conf/06_VLESS_gRPC_inbounds.json" "${addClientsStatus}"
fi
# VLESS_TCP
getClients "${configPath}../tmp/02_VLESS_TCP_inbounds.json" "${addClientsStatus}"
cat <<EOF >/etc/v2ray-agent/xray/conf/02_VLESS_TCP_inbounds.json
{
"inbounds":[
{
"port": 443,
"protocol": "vless",
"tag":"VLESSTCP",
"settings": {
"clients": [
{
"id": "${uuid}",
"add":"${add}",
"flow":"xtls-rprx-direct",
"email": "${domain}_VLESS_XTLS/TLS-direct_TCP"
}
],
"decryption": "none",
"fallbacks": [
${fallbacksList}
]
},
"streamSettings": {
"network": "tcp",
"security": "xtls",
"xtlsSettings": {
"minVersion": "1.2",
"alpn": [
"http/1.1",
"h2"
],
"certificates": [
{
"certificateFile": "/etc/v2ray-agent/tls/${domain}.crt",
"keyFile": "/etc/v2ray-agent/tls/${domain}.key",
"ocspStapling": 3600,
"usage":"encipherment"
}
]
}
}
}
]
}
EOF
addClients "/etc/v2ray-agent/xray/conf/02_VLESS_TCP_inbounds.json" "${addClientsStatus}"
}
# ๅๅงๅTrojan-Go้
็ฝฎ
initTrojanGoConfig() {
echoContent skyBlue "\n่ฟๅบฆ $1/${totalProgress} : ๅๅงๅTrojan้
็ฝฎ"
cat <<EOF >/etc/v2ray-agent/trojan/config_full.json
{
"run_type": "server",
"local_addr": "127.0.0.1",
"local_port": 31296,
"remote_addr": "127.0.0.1",
"remote_port": 31300,
"disable_http_check":true,
"log_level":3,
"log_file":"/etc/v2ray-agent/trojan/trojan.log",
"password": [
"${uuid}"
],
"dns":[
"localhost"
],
"transport_plugin":{
"enabled":true,
"type":"plaintext"
},
"websocket": {
"enabled": true,
"path": "/${customPath}tws",
"host": "${domain}",
"add":"${add}"
},
"router": {
"enabled": false
}
}
EOF
}
# ่ชๅฎไนCDN IP
customCDNIP() {
echoContent skyBlue "\nAgendar $1/${totalProgress} : Adicionar CNAME personalizado da cloudflare"
echoContent red "\n================================================== === ==========="
echoContent yellow "# Precauรงรตes"
echoContent yellow "\nEndereรงo do tutorial:"
echoContent skyBlue "https://github.com/mack-a/v2ray-agent/blob/master/documents/optimize_V2Ray.md"
echoContent red "\nSe vocรช nรฃo conhece a otimizaรงรฃo da Cloudflare, nรฃo use"
echoContent yellow "\n1. Celular: 104.16.123.96"
echoContent yellow "2. Unicom: www.cloudflare.com"
echoContent yellow "3. Telecom: www.digitalocean.com"
echoContent skyBlue "----------------------------"
read -r -p "Selecione: " selectCloudflareType
case ${selectCloudflareType} in
1)
add="104.16.123.96"
;;
2)
add="www.cloudflare.com"
;;
3)
add="www.digitalocean.com"
;;
*)
add="${domain}"
echoContent yellow "\n---> nรฃo use"
;;
esac
}
# ้็จ
defaultBase64Code() {
local type=$1
local email=$2
local id=$3
local hostPort=$4
local host=
local port=
if echo "${hostPort}" | grep -q ":"; then
host=$(echo "${hostPort}" | awk -F "[:]" '{print $1}')
port=$(echo "${hostPort}" | awk -F "[:]" '{print $2}')
else
host=${hostPort}
port=443
fi
local path=$5
local add=$6
local subAccount
subAccount=${currentHost}_$(echo "${id}_currentHost" | md5sum | awk '{print $1}')
if [[ "${type}" == "vlesstcp" ]]; then
if [[ "${coreInstallType}" == "1" ]] && echo "${currentInstallProtocolType}" | grep -q 0; then
echoContent yellow "---> Formato comum (VLESS+TCP+TLS/xtls-rprx-direct)"
echoContent green " vless://${id}@${host}:${port}?encryption=none&security=xtls&type=tcp&host=${host}&headerType=none&sni=${host}&flow=xtls-rprx-direct#${email}\n"
echoContent yellow "---> Formatar texto simples (VLESS+TCP+TLS/xtls-rprx-direct)"
echoContent green "ๅ่ฎฎ็ฑปๅ:VLESS๏ผๅฐๅ:${host}๏ผ็ซฏๅฃ:${port}๏ผ็จๆทID:${id}๏ผๅฎๅ
จ:xtls๏ผไผ ่พๆนๅผ:tcp๏ผflow:xtls-rprx-direct๏ผ่ดฆๆทๅ:${email}\n"
cat <<EOF >>"/etc/v2ray-agent/subscribe_tmp/${subAccount}"
vless://${id}@${host}:${port}?encryption=none&security=xtls&type=tcp&host=${host}&headerType=none&sni=${host}&flow=xtls-rprx-direct#${email}
EOF
echoContent yellow "---> cรณdigo QR VLESS(VLESS+TCP+TLS/xtls-rprx-direct)"
echoContent green " https://api.qrserver.com/v1/create-qr-code/?size=400x400&data=vless%3A%2F%2F${id}%40${host}%3A${port}%3Fencryption%3Dnone%26security%3Dxtls%26type%3Dtcp%26${host}%3D${host}%26headerType%3Dnone%26sni%3D${host}%26flow%3Dxtls-rprx-direct%23${email}\n"
echoContent skyBlue "-------------------------------------------------- --------------------------------"
echoContent yellow "---> Formato geral (VLESS+TCP+TLS/xtls-rprx-splice)"
echoContent green " vless://${id}@${host}:${port}?encryption=none&security=xtls&type=tcp&host=${host}&headerType=none&sni=${host}&flow=xtls-rprx-splice#${email/direct/splice}\n"
echoContent yellow "---> Formatar texto simples (VLESS+TCP+TLS/xtls-rprx-splice)"
echoContent green " ๅ่ฎฎ็ฑปๅ:VLESS๏ผๅฐๅ:${host}๏ผ็ซฏๅฃ:${port}๏ผ็จๆทID:${id}๏ผๅฎๅ
จ:xtls๏ผไผ ่พๆนๅผ:tcp๏ผflow:xtls-rprx-splice๏ผ่ดฆๆทๅ:${email/direct/splice}\n"
cat <<EOF >>"/etc/v2ray-agent/subscribe_tmp/${subAccount}"
vless://${id}@${host}:${port}?encryption=none&security=xtls&type=tcp&host=${host}&headerType=none&sni=${host}&flow=xtls-rprx-splice#${email/direct/splice}
EOF
echoContent yellow "---> cรณdigo QR VLESS(VLESS+TCP+TLS/xtls-rprx-splice)"
echoContent green " https://api.qrserver.com/v1/create-qr-code/?size=400x400&data=vless%3A%2F%2F${id}%40${host}%3A${port}%3Fencryption%3Dnone%26security%3Dxtls%26type%3Dtcp%26${host}%3D${host}%26headerType%3Dnone%26sni%3D${host}%26flow%3Dxtls-rprx-splice%23${email/direct/splice}\n"
elif [[ "${coreInstallType}" == 2 || "${coreInstallType}" == "3" ]]; then
echoContent yellow "---> Formato comum (VLESS+TCP+TLS)"
echoContent green " vless://${id}@${host}:${port}?security=tls&encryption=none&host=${host}&headerType=none&type=tcp#${email}\n"
echoContent yellow "---> Formatar texto simples (VLESS+TCP+TLS/xtls-rprx-splice)"
echoContent green " ๅ่ฎฎ็ฑปๅ:VLESS๏ผๅฐๅ:${host}๏ผ็ซฏๅฃ:${port}๏ผ็จๆทID:${id}๏ผๅฎๅ
จ:tls๏ผไผ ่พๆนๅผ:tcp๏ผ่ดฆๆทๅ:${email/direct/splice}\n"
cat <<EOF >>"/etc/v2ray-agent/subscribe_tmp/${subAccount}"
vless://${id}@${host}:${port}?security=tls&encryption=none&host=${host}&headerType=none&type=tcp#${email}
EOF
echoContent yellow "---> cรณdigo QR VLESS(VLESS+TCP+TLS)"
echoContent green " https://api.qrserver.com/v1/create-qr-code/?size=400x400&data=vless%3a%2f%2f${id}%40${host}%3a${port}%3fsecurity%3dtls%26encryption%3dnone%26host%3d${host}%26headerType%3dnone%26type%3dtcp%23${email}\n"
fi
elif [[ "${type}" == "trojanTCPXTLS" ]]; then
echoContent yellow "---> Formato comum (Trojan+TCP+TLS/xtls-rprx-direct)"
echoContent green " trojan://${id}@${host}:${port}?encryption=none&security=xtls&type=tcp&host=${host}&headerType=none&sni=${host}&flow=xtls-rprx-direct#${email}\n"
echoContent yellow "---> Formatar texto simples (Trojan+TCP+TLS/xtls-rprx-direct)"
echoContent green "ๅ่ฎฎ็ฑปๅ:Trojan๏ผๅฐๅ:${host}๏ผ็ซฏๅฃ:${port}๏ผ็จๆทID:${id}๏ผๅฎๅ
จ:xtls๏ผไผ ่พๆนๅผ:tcp๏ผflow:xtls-rprx-direct๏ผ่ดฆๆทๅ:${email}\n"
cat <<EOF >>"/etc/v2ray-agent/subscribe_tmp/${subAccount}"
trojan://${id}@${host}:${port}?encryption=none&security=xtls&type=tcp&host=${host}&headerType=none&sni=${host}&flow=xtls-rprx-direct#${email}
EOF
echoContent yellow "---> QR code Trojan(Trojan+TCP+TLS/xtls-rprx-direct)"
echoContent green " https://api.qrserver.com/v1/create-qr-code/?size=400x400&data=trojan%3A%2F%2F${id}%40${host}%3A${port}%3Fencryption%3Dnone%26security%3Dxtls%26type%3Dtcp%26${host}%3D${host}%26headerType%3Dnone%26sni%3D${host}%26flow%3Dxtls-rprx-direct%23${email}\n"
echoContent skyBlue "-------------------------------------------------- --------------------------------"
echoContent yellow "---> Formato comum (Trojan+TCP+TLS/xtls-rprx-splice)"
echoContent green " trojan://${id}@${host}:${port}?encryption=none&security=xtls&type=tcp&host=${host}&headerType=none&sni=${host}&flow=xtls-rprx-splice#${email/direct/splice}\n"
echoContent yellow "---> Formatar texto simples (Trojan+TCP+TLS/xtls-rprx-splice)"
echoContent green " ๅ่ฎฎ็ฑปๅ:VLESS๏ผๅฐๅ:${host}๏ผ็ซฏๅฃ:${port}๏ผ็จๆทID:${id}๏ผๅฎๅ
จ:xtls๏ผไผ ่พๆนๅผ:tcp๏ผflow:xtls-rprx-splice๏ผ่ดฆๆทๅ:${email/direct/splice}\n"
cat <<EOF >>"/etc/v2ray-agent/subscribe_tmp/${subAccount}"
trojan://${id}@${host}:${port}?encryption=none&security=xtls&type=tcp&host=${host}&headerType=none&sni=${host}&flow=xtls-rprx-splice#${email/direct/splice}
EOF
echoContent yellow "---> QR code Trojan(Trojan+TCP+TLS/xtls-rprx-splice)"
echoContent green " https://api.qrserver.com/v1/create-qr-code/?size=400x400&data=trojan%3A%2F%2F${id}%40${host}%3A${port}%3Fencryption%3Dnone%26security%3Dxtls%26type%3Dtcp%26${host}%3D${host}%26headerType%3Dnone%26sni%3D${host}%26flow%3Dxtls-rprx-splice%23${email/direct/splice}\n"
elif [[ "${type}" == "vmessws" ]]; then
qrCodeBase64Default=$(echo -n "{\"port\":${port},\"ps\":\"${email}\",\"tls\":\"tls\",\"id\":\"${id}\",\"aid\":0,\"v\":2,\"host\":\"${host}\",\"type\":\"none\",\"path\":\"/${path}\",\"net\":\"ws\",\"add\":\"${add}\",\"allowInsecure\":0,\"method\":\"none\",\"peer\":\"${host}\",\"sni\":\"${host}\"}" | base64 -w 0)
qrCodeBase64Default="${qrCodeBase64Default// /}"
echoContent yellow "---> json genรฉrico (VMess+WS+TLS)"
echoContent green " {\"port\":${port},\"ps\":\"${email}\",\"tls\":\"tls\",\"id\":\"${id}\",\"aid\":0,\"v\":2,\"host\":\"${host}\",\"type\":\"none\",\"path\":\"${path}\",\"net\":\"ws\",\"add\":\"${add}\",\"allowInsecure\":0,\"method\":\"none\",\"peer\":\"${host}\",\"sni\":\"${host}\"}\n"
echoContent yellow "---> Link genรฉrico do vmess (VMess+WS+TLS)"
echoContent green " vmess://${qrCodeBase64Default}\n"
echoContent yellow "---> cรณdigo QR vmess(VMess+WS+TLS)"
cat <<EOF >>"/etc/v2ray-agent/subscribe_tmp/${subAccount}"
vmess://${qrCodeBase64Default}
EOF
echoContent green " https://api.qrserver.com/v1/create-qr-code/?size=400x400&data=vmess://${qrCodeBase64Default}\n"
elif [[ "${type}" == "vmesstcp" ]]; then
echoContent red "path:${path}"
qrCodeBase64Default=$(echo -n "{\"add\":\"${add}\",\"aid\":0,\"host\":\"${host}\",\"id\":\"${id}\",\"net\":\"tcp\",\"path\":\"${path}\",\"port\":${port},\"ps\":\"${email}\",\"scy\":\"none\",\"sni\":\"${host}\",\"tls\":\"tls\",\"v\":2,\"type\":\"http\",\"allowInsecure\":0,\"peer\":\"${host}\",\"obfs\":\"http\",\"obfsParam\":\"${host}\"}" | base64)
qrCodeBase64Default="${qrCodeBase64Default// /}"
echoContent yellow "---> json genรฉrico (VMess+TCP+TLS)"
echoContent green " {\"port\":'${port}',\"ps\":\"${email}\",\"tls\":\"tls\",\"id\":\"${id}\",\"aid\":0,\"v\":2,\"host\":\"${host}\",\"type\":\"http\",\"path\":\"${path}\",\"net\":\"http\",\"add\":\"${add}\",\"allowInsecure\":0,\"method\":\"post\",\"peer\":\"${host}\",\"obfs\":\"http\",\"obfsParam\":\"${host}\"}\n"
echoContent yellow "---> Link genรฉrico do vmess (VMess+TCP+TLS)"
echoContent green " vmess://${qrCodeBase64Default}\n"
cat <<EOF >>"/etc/v2ray-agent/subscribe_tmp/${subAccount}"
vmess://${qrCodeBase64Default}
EOF
echoContent yellow "---> QR code vmess(VMess+TCP+TLS)"
echoContent green " https://api.qrserver.com/v1/create-qr-code/?size=400x400&data=vmess://${qrCodeBase64Default}\n"
elif [[ "${type}" == "vlessws" ]]; then
echoContent yellow "---> Formato comum (VLESS+WS+TLS)"
echoContent green " vless://${id}@${add}:${port}?encryption=none&security=tls&type=ws&host=${host}&sni=${host}&path=%2f${path}#${email}\n"
echoContent yellow "---> Formatar texto simples (VLESS+WS+TLS)"
echoContent green " ๅ่ฎฎ็ฑปๅ:VLESS๏ผๅฐๅ:${add}๏ผไผช่ฃ
ๅๅ/SNI:${host}๏ผ็ซฏๅฃ:${port}๏ผ็จๆทID:${id}๏ผๅฎๅ
จ:tls๏ผไผ ่พๆนๅผ:ws๏ผ่ทฏๅพ:/${path}๏ผ่ดฆๆทๅ:${email}\n"
cat <<EOF >>"/etc/v2ray-agent/subscribe_tmp/${subAccount}"
vless://${id}@${add}:${port}?encryption=none&security=tls&type=ws&host=${host}&sni=${host}&path=%2f${path}#${email}
EOF
echoContent yellow "---> cรณdigo QR VLESS(VLESS+WS+TLS)"
echoContent green " https://api.qrserver.com/v1/create-qr-code/?size=400x400&data=vless%3A%2F%2F${id}%40${add}%3A${port}%3Fencryption%3Dnone%26security%3Dtls%26type%3Dws%26host%3D${host}%26sni%3D${host}%26path%3D%252f${path}%23${email}"
elif [[ "${type}" == "vlessgrpc" ]]; then
echoContent yellow "---> Formato genรฉrico (VLESS+gRPC+TLS)"
echoContent green " vless://${id}@${add}:${port}?encryption=none&security=tls&type=grpc&host=${host}&path=${path}&serviceName=${path}&alpn=h2&sni=${host}#${email}\n"
echoContent yellow "---> Formatar texto simples (VLESS+gRPC+TLS)"
echoContent green " ๅ่ฎฎ็ฑปๅ:VLESS๏ผๅฐๅ:${add}๏ผไผช่ฃ
ๅๅ/SNI:${host}๏ผ็ซฏๅฃ:${port}๏ผ็จๆทID:${id}๏ผๅฎๅ
จ:tls๏ผไผ ่พๆนๅผ:gRPC๏ผalpn:h2๏ผserviceName:${path}๏ผ่ดฆๆทๅ:${email}\n"
cat <<EOF >>"/etc/v2ray-agent/subscribe_tmp/${subAccount}"
vless://${id}@${add}:${port}?encryption=none&security=tls&type=grpc&host=${host}&path=${path}&serviceName=${path}&alpn=h2&sni=${host}#${email}
EOF
echoContent yellow "---> cรณdigo QR VLESS(VLESS+gRPC+TLS)"
echoContent green " https://api.qrserver.com/v1/create-qr-code/?size=400x400&data=vless%3A%2F%2F${id}%40${add}%3A${port}%3Fencryption%3Dnone%26security%3Dtls%26type%3Dgrpc%26host%3D${host}%26serviceName%3D${path}%26path%3D${path}%26sni%3D${host}%26alpn%3Dh2%23${email}"
elif [[ "${type}" == "trojan" ]]; then
# URLEncode
echoContent yellow "---> Trojan(TLS)"
echoContent green " trojan://${id}@${host}:${port}?peer=${host}&sni=${host}&alpn=http1.1#${host}_Trojan\n"
cat <<EOF >>"/etc/v2ray-agent/subscribe_tmp/${subAccount}"
trojan://${id}@${host}:${port}?peer=${host}&sni=${host}&alpn=http1.1#${host}_Trojan
EOF
echoContent yellow "---> Trojan de cรณdigo QR (TLS)"
echoContent green " https://api.qrserver.com/v1/create-qr-code/?size=400x400&data=trojan%3a%2f%2f${id}%40${host}%3a${port}%3fpeer%3d${host}%26sni%3d${host}%26alpn%3Dhttp1.1%23${host}_Trojan\n"
elif [[ "${type}" == "trojangrpc" ]]; then
# URLEncode
echoContent yellow "---> Trojan gRPC(TLS)"
echoContent green " trojan://${id}@${host}:${port}?encryption=none&peer=${host}&security=tls&type=grpc&sni=${host}&alpn=h2&path=${path}&serviceName=${path}#${host}_Trojan_gRPC\n"
cat <<EOF >>"/etc/v2ray-agent/subscribe_tmp/${subAccount}"
trojan://${id}@${host}:${port}?encryption=none&peer=${host}&security=tls&type=grpc&sni=${host}&alpn=h2&path=${path}&serviceName=${path}#${host}_Trojan_gRPC
EOF
echoContent yellow "---> QR code Trojan gRPC(TLS)"
echoContent green " https://api.qrserver.com/v1/create-qr-code/?size=400x400&data=trojan%3a%2f%2f${id}%40${host}%3a${port}%3Fencryption%3Dnone%26security%3Dtls%26peer%3d${host}%26type%3Dgrpc%26sni%3d${host}%26path%3D${path}%26alpn%3D=h2%26serviceName%3D${path}%23${host}_Trojan_gRPC\n"
fi
}
# ่ดฆๅท
showAccounts() {
readInstallType
readInstallProtocolType
readConfigHostPathUUID
echoContent skyBlue "\nAgendar $1/${totalProgress} : Conta"
local show
# VLESS TCP
if [[ -n "${configPath}" ]]; then
show=1
if echo "${currentInstallProtocolType}" | grep -q trojan; then
echoContent skyBlue "====================== Trojan TCP TLS/XTLS-direct/XTLS-splice ================== === ====\n"
jq .inbounds[0].settings.clients ${configPath}02_trojan_TCP_inbounds.json | jq -c '.[]' | while read -r user; do
echoContent skyBlue "\n ---> ๅธๅท:$(echo "${user}" | jq -r .email)_$(echo "${user}" | jq -r .password)"
echo
defaultBase64Code trojanTCPXTLS "$(echo "${user}" | jq -r .email)" "$(echo "${user}" | jq -r .password)" "${currentHost}:${currentPort}" "${currentHost}"
done
else
echoContent skyBlue "====================== VLESS TCP TLS/XTLS-direct/XTLS-splice ================= = ====\n"
jq .inbounds[0].settings.clients ${configPath}02_VLESS_TCP_inbounds.json | jq -c '.[]' | while read -r user; do
echoContent skyBlue "\n ---> ๅธๅท:$(echo "${user}" | jq -r .email)_$(echo "${user}" | jq -r .id)"
echo
defaultBase64Code vlesstcp "$(echo "${user}" | jq -r .email)" "$(echo "${user}" | jq -r .id)" "${currentHost}:${currentPort}" "${currentHost}"
done
fi
# VLESS WS
if echo ${currentInstallProtocolType} | grep -q 1; then
echoContent skyBlue "\n================================= VLESS WS TLS CDN ============== ====================\n"
jq .inbounds[0].settings.clients ${configPath}03_VLESS_WS_inbounds.json | jq -c '.[]' | while read -r user; do
echoContent skyBlue "\n ---> ๅธๅท:$(echo "${user}" | jq -r .email)_$(echo "${user}" | jq -r .id)"
echo
local path="${currentPath}ws"
# if [[ ${coreInstallType} == "1" ]]; then
# echoContent yellow "O caminho 0-RTT do Xray estarรก por trรกs dele. Nรฃo รฉ compatรญvel com clientes baseados em v2ray. Exclua-o manualmente e use-o.\n"
# path="${currentPath}ws"
# fi
defaultBase64Code vlessws "$(echo "${user}" | jq -r .email)" "$(echo "${user}" | jq -r .id)" "${currentHost}:${currentPort}" "${path}" "${currentAdd}"
done
fi
# VMess WS
if echo ${currentInstallProtocolType} | grep -q 3; then
echoContent skyBlue "\n================================= VMess WS TLS CDN ============== ====================\n"
local path="${currentPath}vws"
if [[ ${coreInstallType} == "1" ]]; then
path="${currentPath}vws"
fi
jq .inbounds[0].settings.clients ${configPath}05_VMess_WS_inbounds.json | jq -c '.[]' | while read -r user; do
echoContent skyBlue "\n ---> ๅธๅท:$(echo "${user}" | jq -r .email)_$(echo "${user}" | jq -r .id)"
echo
defaultBase64Code vmessws "$(echo "${user}" | jq -r .email)" "$(echo "${user}" | jq -r .id)" "${currentHost}:${currentPort}" "${path}" "${currentAdd}"
done
fi
# VLESS grpc
if echo ${currentInstallProtocolType} | grep -q 5; then
echoContent skyBlue "\n=============================== VLESS gRPC TLS CDN ================ ================\n"
echoContent red "\n---> gRPC estรก em fase de teste e pode nรฃo ser compatรญvel com o cliente que vocรช estรก usando, se nรฃo puder usรก-lo, ignore-o"
local serviceName
serviceName=$(jq -r .inbounds[0].streamSettings.grpcSettings.serviceName ${configPath}06_VLESS_gRPC_inbounds.json)
jq .inbounds[0].settings.clients ${configPath}06_VLESS_gRPC_inbounds.json | jq -c '.[]' | while read -r user; do
echoContent skyBlue "\n ---> ๅธๅท:$(echo "${user}" | jq -r .email)_$(echo "${user}" | jq -r .id)"
echo
defaultBase64Code vlessgrpc "$(echo "${user}" | jq -r .email)" "$(echo "${user}" | jq -r .id)" "${currentHost}:${currentPort}" "${serviceName}" "${currentAdd}"
done
fi
fi
# trojan tcp
if echo ${currentInstallProtocolType} | grep -q 4; then
echoContent skyBlue "\n=================================== Trojan TLS ============= == =====================\n"
jq .inbounds[0].settings.clients ${configPath}04_trojan_TCP_inbounds.json | jq -c '.[]' | while read -r user; do
echoContent skyBlue "\n ---> ๅธๅท:$(echo "${user}" | jq -r .email)_$(echo "${user}" | jq -r .password)"
echo
defaultBase64Code trojan trojan "$(echo "${user}" | jq -r .password)" "${currentHost}"
done
fi
if echo ${currentInstallProtocolType} | grep -q 2; then
echoContent skyBlue "\n================================= Trojan gRPC TLS =============== === ==================\n"
echoContent red "\n---> gRPC estรก em fase de teste e pode nรฃo ser compatรญvel com o cliente que vocรช estรก usando, se nรฃo puder usรก-lo, ignore-o"
local serviceName=
serviceName=$(jq -r .inbounds[0].streamSettings.grpcSettings.serviceName ${configPath}04_trojan_gRPC_inbounds.json)
jq .inbounds[0].settings.clients ${configPath}04_trojan_gRPC_inbounds.json | jq -c '.[]' | while read -r user; do
echoContent skyBlue "\n ---> ๅธๅท:$(echo "${user}" | jq -r .email)_$(echo "${user}" | jq -r .password)"
echo
defaultBase64Code trojangrpc "$(echo "${user}" | jq -r .email)" "$(echo "${user}" | jq -r .password)" "${currentHost}:${currentPort}" "${serviceName}" "${currentAdd}"
done
fi
if [[ -z ${show} ]]; then
echoContent red "---> nรฃo instalado"
fi
}
# ๆดๆฐไผช่ฃ
็ซ
updateNginxBlog() {
echoContent skyBlue "\n่ฟๅบฆ $1/${totalProgress} : ๆดๆขไผช่ฃ
็ซ็น"
echoContent red "================================================== === ==========="
echoContent yellow "# Para personalizaรงรฃo, copie manualmente o arquivo de modelo para /usr/share/nginx/html\n"
echoContent yellow "1. Guia para iniciantes"
echoContent yellow "2. Site do jogo"
echoContent yellow "3. Blog Pessoal 01"
echoContent yellow "4. Estaรงรฃo Empresarial"
echoContent yellow "5.่งฃ้ๅ ๅฏ็้ณไนๆไปถๆจก็[https://github.com/ix64/unlock-music]"
echoContent yellow "6.mikutap[https://github.com/HFIProgramming/mikutap]"
echoContent yellow "7. Estaรงรฃo Empresarial 02"
echoContent yellow "8. Blog Pessoal 02"
echoContent yellow "9.404 Saltar automaticamente para baidu"
echoContent red "================================================== === ==========="
read -r -p "por favor escolha:" selectInstallNginxBlogType
if [[ "${selectInstallNginxBlogType}" =~ ^[1-9]$ ]]; then
# rm -rf /usr/share/nginx/html
rm -rf /usr/share/nginx/*
if wget --help | grep -q show-progress; then
wget -c -q --show-progress -P /usr/share/nginx "https://raw.githubusercontent.com/mack-a/v2ray-agent/master/fodder/blog/unable/html${selectInstallNginxBlogType}.zip" >/dev/null
else
wget -c -P /usr/share/nginx "https://raw.githubusercontent.com/mack-a/v2ray-agent/master/fodder/blog/unable/html${selectInstallNginxBlogType}.zip" >/dev/null
fi
unzip -o "/usr/share/nginx/html${selectInstallNginxBlogType}.zip" -d /usr/share/nginx/html >/dev/null
rm -f "/usr/share/nginx/html${selectInstallNginxBlogType}.zip*"
echoContent green "---> Substitua a estaรงรฃo falsa com sucesso"
else
echoContent red "---> Seleรงรฃo errada, por favor selecione novamente"
updateNginxBlog
fi
}
# ๆทปๅ ๆฐ็ซฏๅฃ
addCorePort() {
echoContent skyBlue "\nๅ่ฝ 1/${totalProgress} : ๆทปๅ ๆฐ็ซฏๅฃ"
echoContent red "\n================================================== === ==========="
echoContent yellow "# Precauรงรตes\n"
echoContent yellow "Suporta adiรงรฃo em lote"
echoContent yellow "Nรฃo afeta o uso da porta 443"
echoContent yellow "Ao visualizar as contas, apenas as contas com a porta padrรฃo 443 serรฃo exibidas."
echoContent yellow "Caracteres especiais nรฃo sรฃo permitidos, preste atenรงรฃo ao formato das vรญrgulas"
echoContent yellow "Exemplo de entrada: 2053, 2083, 2087\n"
echoContent yellow "1. Adicionar porta"
echoContent yellow "2. Exclua a porta"
echoContent red "================================================== === ==========="
read -r -p "por favor escolha:" selectNewPortType
if [[ "${selectNewPortType}" == "1" ]]; then
read -r -p "Insira o nรบmero da porta:" newPort
if [[ -n "${newPort}" ]]; then
while read -r port; do
cat <<EOF >"${configPath}02_dokodemodoor_inbounds_${port}.json"
{
"inbounds": [
{
"listen": "0.0.0.0",
"port": ${port},
"protocol": "dokodemo-door",
"settings": {
"address": "127.0.0.1",
"port": 443,
"network": "tcp",
"followRedirect": false
},
"tag": "dokodemo-door-newPort-${port}"
}
]
}
EOF
done < <(echo "${newPort}" | tr ',' '\n')
echoContent green "---> Adicionar com sucesso"
reloadCore
fi
elif [[ "${selectNewPortType}" == "2" ]]; then
find ${configPath} -name "*dokodemodoor*" | awk -F "[c][o][n][f][/]" '{print ""NR""":"$2}'
read -r -p "Insira o nรบmero da porta para excluir:" portIndex
local dokoConfig
dokoConfig=$(find ${configPath} -name "*dokodemodoor*" | awk -F "[c][o][n][f][/]" '{print ""NR""":"$2}' | grep "${portIndex}:")
if [[ -n "${dokoConfig}" ]]; then
rm "${configPath}/$(echo "${dokoConfig}" | awk -F "[:]" '{print $2}')"
reloadCore
else
echoContent yellow "\n---> O nรบmero de entrada estรก errado, selecione novamente"
addCorePort
fi
fi
}
# ๅธ่ฝฝ่ๆฌ
unInstall() {
read -r -p "ๆฏๅฆ็กฎ่ฎคๅธ่ฝฝๅฎ่ฃ
ๅ
ๅฎน๏ผ[y/n]:" unInstallStatus
if [[ "${unInstallStatus}" != "y" ]]; then
echoContent green "---> Abortar a desinstalaรงรฃo"
menu
exit 0
fi
handleNginx stop
if [[ -z $(pgrep -f "nginx") ]]; then
echoContent green "---> Pare o Nginx com sucesso"
fi
handleV2Ray stop
# handleTrojanGo stop
if [[ -f "/root/.acme.sh/acme.sh.env" ]] && grep -q 'acme.sh.env' </root/.bashrc; then
sed -i 's/. "\/root\/.acme.sh\/acme.sh.env"//g' "$(grep '. "/root/.acme.sh/acme.sh.env"' -rl /root/.bashrc)"
fi
rm -rf /root/.acme.sh
echoContent green "---> Excluir acme.sh concluรญdo"
rm -rf /etc/systemd/system/v2ray.service
echoContent green "---> Excluir inicializaรงรฃo do V2Ray e iniciar automaticamente"
rm -rf /tmp/v2ray-agent-tls/*
if [[ -d "/etc/v2ray-agent/tls" ]] && [[ -n $(find /etc/v2ray-agent/tls/ -name "*.key") ]] && [[ -n $(find /etc/v2ray-agent/tls/ -name "*.crt") ]]; then
mv /etc/v2ray-agent/tls /tmp/v2ray-agent-tls
if [[ -n $(find /tmp/v2ray-agent-tls -name '*.key') ]]; then
echoContent yellow " ---> ๅคไปฝ่ฏไนฆๆๅ๏ผ่ฏทๆณจๆ็ๅญใ[/tmp/v2ray-agent-tls]"
fi
fi
rm -rf /etc/v2ray-agent
rm -rf ${nginxConfigPath}alone.conf
rm -rf /usr/bin/vasma
rm -rf /usr/sbin/vasma
echoContent green "---> Atalho de desinstalaรงรฃo concluรญdo"
echoContent green "---> Desinstalaรงรฃo do script v2ray-agent concluรญdo"
}
# ไฟฎๆนV2Ray CDN่็น
updateV2RayCDN() {
# todo ้ๆๆญคๆนๆณ
echoContent skyBlue "\n่ฟๅบฆ $1/${totalProgress} : ไฟฎๆนCDN่็น"
if [[ -n "${currentAdd}" ]]; then
echoContent red "================================================== === ==========="
echoContent yellow "1. CNAME www.digitalocean.com"
echoContent yellow "2. CNAME www.cloudflare.com"
echoContent yellow "3. CNAME hostmonit.com"
echoContent yellow "4. Entrada manual"
echoContent red "================================================== === ==========="
read -r -p "por favor escolha:" selectCDNType
case ${selectCDNType} in
1)
setDomain="www.digitalocean.com"
;;
2)
setDomain="www.cloudflare.com"
;;
3)
setDomain="hostmonit.com"
;;
4)
read -r -p "Por favor digite o IP que deseja personalizar o CDN ou nome do domรญnio:" setDomain
;;
esac
if [[ -n ${setDomain} ]]; then
if [[ -n "${currentAdd}" ]]; then
sed -i "s/\"${currentAdd}\"/\"${setDomain}\"/g" "$(grep "${currentAdd}" -rl ${configPath}${frontingType}.json)"
fi
if [[ $(jq -r .inbounds[0].settings.clients[0].add ${configPath}${frontingType}.json) == "${setDomain}" ]]; then
echoContent green "---> CDN modificado com sucesso"
reloadCore
else
echoContent red "---> Falha ao modificar CDN"
fi
fi
else
echoContent red "---> nรฃo instaladoๅฏ็จ็ฑปๅ"
fi
}
# manageUser ็จๆท็ฎก็
manageUser() {
echoContent skyBlue "\n่ฟๅบฆ $1/${totalProgress} : ๅค็จๆท็ฎก็"
echoContent skyBlue "-------------------------------------------------- ---"
echoContent yellow "1. Adicionar usuรกrio"
echoContent yellow "2. Excluir usuรกrio"
echoContent skyBlue "-------------------------------------------------- ---"
read -r -p "por favor escolha:" manageUserType
if [[ "${manageUserType}" == "1" ]]; then
addUser
elif [[ "${manageUserType}" == "2" ]]; then
removeUser
else
echoContent red "---> Erro de seleรงรฃo"
fi
}
# ่ชๅฎไนuuid
customUUID() {
# read -r -p "ๆฏๅฆ่ชๅฎไนUUID ๏ผ[y/n]:" customUUIDStatus
# echo
# if [[ "${customUUIDStatus}" == "y" ]]; then
read -r -p "Insira um UUID vรกlido, [Vazio = Random UUID]:" currentCustomUUID
echo
if [[ -z "${currentCustomUUID}" ]]; then
# echoContent red "---> UUID nรฃo pode ser nulo"
currentCustomUUID=$(${ctlPath} uuid)
echoContent yellow "uuid:${currentCustomUUID}\n"
else
jq -r -c '.inbounds[0].settings.clients[].id' ${configPath}${frontingType}.json | while read -r line; do
if [[ "${line}" == "${currentCustomUUID}" ]]; then
echo >/tmp/v2ray-agent
fi
done
if [[ -f "/tmp/v2ray-agent" && -n $(cat /tmp/v2ray-agent) ]]; then
echoContent red "---> UUID nรฃo รฉ repetรญvel"
rm /tmp/v2ray-agent
exit 0
fi
fi
# fi
}
# ่ชๅฎไนemail
customUserEmail() {
# read -r -p "ๆฏๅฆ่ชๅฎไนemail ๏ผ[y/n]:" customEmailStatus
# echo
# if [[ "${customEmailStatus}" == "y" ]]; then
read -r -p "่ฏท่พๅ
ฅๅๆณ็email๏ผ[ๅ่ฝฆ]้ๆบemail:" currentCustomEmail
echo
if [[ -z "${currentCustomEmail}" ]]; then
currentCustomEmail="${currentHost}_${currentCustomUUID}"
echoContent yellow "email: ${currentCustomEmail}\n"
# echoContent red "---> e-mail nรฃo pode ficar vazio"
else
jq -r -c '.inbounds[0].settings.clients[].email' ${configPath}${frontingType}.json | while read -r line; do
if [[ "${line}" == "${currentCustomEmail}" ]]; then
echo >/tmp/v2ray-agent
fi
done
if [[ -f "/tmp/v2ray-agent" && -n $(cat /tmp/v2ray-agent) ]]; then
echoContent red "---> e-mail nรฃo pode ser repetido"
rm /tmp/v2ray-agent
exit 0
fi
fi
# fi
}
# ๆทปๅ ็จๆท
addUser() {
echoContent yellow "Depois de adicionar um novo usuรกrio, a assinatura precisa ser revisada novamente"
read -r -p "Insira o nรบmero de usuรกrios a serem adicionados:" userNum
echo
if [[ -z ${userNum} || ${userNum} -le 0 ]]; then
echoContent red "---> A entrada estรก incorreta, por favor digite novamente"
exit 0
fi
# ็ๆ็จๆท
if [[ "${userNum}" == "1" ]]; then
customUUID
customUserEmail
fi
while [[ ${userNum} -gt 0 ]]; do
local users=
((userNum--)) || true
if [[ -n "${currentCustomUUID}" ]]; then
uuid=${currentCustomUUID}
else
uuid=$(${ctlPath} uuid)
fi
if [[ -n "${currentCustomEmail}" ]]; then
email=${currentCustomEmail}
else
email=${currentHost}_${uuid}
fi
# ๅ
ผๅฎนv2ray-core
users="{\"id\":\"${uuid}\",\"flow\":\"xtls-rprx-direct\",\"email\":\"${email}\",\"alterId\":0}"
if [[ "${coreInstallType}" == "2" ]]; then
users="{\"id\":\"${uuid}\",\"email\":\"${email}\",\"alterId\":0}"
fi
if echo ${currentInstallProtocolType} | grep -q 0; then
local vlessUsers="${users//\,\"alterId\":0/}"
local vlessTcpResult
vlessTcpResult=$(jq -r ".inbounds[0].settings.clients += [${vlessUsers}]" ${configPath}${frontingType}.json)
echo "${vlessTcpResult}" | jq . >${configPath}${frontingType}.json
fi
if echo ${currentInstallProtocolType} | grep -q trojan; then
local trojanXTLSUsers="${users//\,\"alterId\":0/}"
trojanXTLSUsers=${trojanXTLSUsers//"id"/"password"}
local trojanXTLSResult
trojanXTLSResult=$(jq -r ".inbounds[0].settings.clients += [${trojanXTLSUsers}]" ${configPath}${frontingType}.json)
echo "${trojanXTLSResult}" | jq . >${configPath}${frontingType}.json
fi
if echo ${currentInstallProtocolType} | grep -q 1; then
local vlessUsers="${users//\,\"alterId\":0/}"
vlessUsers="${vlessUsers//\"flow\":\"xtls-rprx-direct\"\,/}"
local vlessWsResult
vlessWsResult=$(jq -r ".inbounds[0].settings.clients += [${vlessUsers}]" ${configPath}03_VLESS_WS_inbounds.json)
echo "${vlessWsResult}" | jq . >${configPath}03_VLESS_WS_inbounds.json
fi
if echo ${currentInstallProtocolType} | grep -q 2; then
local trojangRPCUsers="${users//\"flow\":\"xtls-rprx-direct\"\,/}"
trojangRPCUsers="${trojangRPCUsers//\,\"alterId\":0/}"
trojangRPCUsers=${trojangRPCUsers//"id"/"password"}
local trojangRPCResult
trojangRPCResult=$(jq -r ".inbounds[0].settings.clients += [${trojangRPCUsers}]" ${configPath}04_trojan_gRPC_inbounds.json)
echo "${trojangRPCResult}" | jq . >${configPath}04_trojan_gRPC_inbounds.json
fi
if echo ${currentInstallProtocolType} | grep -q 3; then
local vmessUsers="${users//\"flow\":\"xtls-rprx-direct\"\,/}"
local vmessWsResult
vmessWsResult=$(jq -r ".inbounds[0].settings.clients += [${vmessUsers}]" ${configPath}05_VMess_WS_inbounds.json)
echo "${vmessWsResult}" | jq . >${configPath}05_VMess_WS_inbounds.json
fi
if echo ${currentInstallProtocolType} | grep -q 5; then
local vlessGRPCUsers="${users//\"flow\":\"xtls-rprx-direct\"\,/}"
vlessGRPCUsers="${vlessGRPCUsers//\,\"alterId\":0/}"
local vlessGRPCResult
vlessGRPCResult=$(jq -r ".inbounds[0].settings.clients += [${vlessGRPCUsers}]" ${configPath}06_VLESS_gRPC_inbounds.json)
echo "${vlessGRPCResult}" | jq . >${configPath}06_VLESS_gRPC_inbounds.json
fi
if echo ${currentInstallProtocolType} | grep -q 4; then
local trojanUsers="${users//\"flow\":\"xtls-rprx-direct\"\,/}"
trojanUsers="${trojanUsers//id/password}"
trojanUsers="${trojanUsers//\,\"alterId\":0/}"
local trojanTCPResult
trojanTCPResult=$(jq -r ".inbounds[0].settings.clients += [${trojanUsers}]" ${configPath}04_trojan_TCP_inbounds.json)
echo "${trojanTCPResult}" | jq . >${configPath}04_trojan_TCP_inbounds.json
fi
done
reloadCore
echoContent green "---> Adicionar completo"
manageAccount 1
}
# ็งป้ค็จๆท
removeUser() {
if echo ${currentInstallProtocolType} | grep -q 0 || echo ${currentInstallProtocolType} | grep -q trojan; then
jq -r -c .inbounds[0].settings.clients[].email ${configPath}${frontingType}.json | awk '{print NR""":"$0}'
read -r -p "Selecione o ID do usuรกrio para excluir [somente a exclusรฃo รบnica รฉ suportada]:" delUserIndex
if [[ $(jq -r '.inbounds[0].settings.clients|length' ${configPath}${frontingType}.json) -lt ${delUserIndex} ]]; then
echoContent red "---> Erro de seleรงรฃo"
else
delUserIndex=$((delUserIndex - 1))
local vlessTcpResult
vlessTcpResult=$(jq -r 'del(.inbounds[0].settings.clients['${delUserIndex}'])' ${configPath}${frontingType}.json)
echo "${vlessTcpResult}" | jq . >${configPath}${frontingType}.json
fi
fi
if [[ -n "${delUserIndex}" ]]; then
if echo ${currentInstallProtocolType} | grep -q 1; then
local vlessWSResult
vlessWSResult=$(jq -r 'del(.inbounds[0].settings.clients['${delUserIndex}'])' ${configPath}03_VLESS_WS_inbounds.json)
echo "${vlessWSResult}" | jq . >${configPath}03_VLESS_WS_inbounds.json
fi
if echo ${currentInstallProtocolType} | grep -q 2; then
local trojangRPCUsers
trojangRPCUsers=$(jq -r 'del(.inbounds[0].settings.clients['${delUserIndex}'])' ${configPath}04_trojan_gRPC_inbounds.json)
echo "${trojangRPCUsers}" | jq . >${configPath}04_trojan_gRPC_inbounds.json
fi
if echo ${currentInstallProtocolType} | grep -q 3; then
local vmessWSResult
vmessWSResult=$(jq -r 'del(.inbounds[0].settings.clients['${delUserIndex}'])' ${configPath}05_VMess_WS_inbounds.json)
echo "${vmessWSResult}" | jq . >${configPath}05_VMess_WS_inbounds.json
fi
if echo ${currentInstallProtocolType} | grep -q 5; then
local vlessGRPCResult
vlessGRPCResult=$(jq -r 'del(.inbounds[0].settings.clients['${delUserIndex}'])' ${configPath}06_VLESS_gRPC_inbounds.json)
echo "${vlessGRPCResult}" | jq . >${configPath}06_VLESS_gRPC_inbounds.json
fi
if echo ${currentInstallProtocolType} | grep -q 4; then
local trojanTCPResult
trojanTCPResult=$(jq -r 'del(.inbounds[0].settings.clients['${delUserIndex}'])' ${configPath}04_trojan_TCP_inbounds.json)
echo "${trojanTCPResult}" | jq . >${configPath}04_trojan_TCP_inbounds.json
fi
reloadCore
fi
manageAccount 1
}
# ๆดๆฐ่ๆฌ
updateV2RayAgent() {
echoContent skyBlue "\n่ฟๅบฆ $1/${totalProgress} : ๆดๆฐv2ray-agent่ๆฌ"
rm -rf /etc/v2ray-agent/install.sh
if wget --help | grep -q show-progress; then
wget -c -q --show-progress -P /etc/v2ray-agent/ -N --no-check-certificate "https://raw.githubusercontent.com/mack-a/v2ray-agent/master/install.sh"
else
wget -c -q -P /etc/v2ray-agent/ -N --no-check-certificate "https://raw.githubusercontent.com/mack-a/v2ray-agent/master/install.sh"
fi
sudo chmod 700 /etc/v2ray-agent/install.sh
local version
version=$(grep 'ๅฝๅ็ๆฌ:v' "/etc/v2ray-agent/install.sh" | awk -F "[v]" '{print $2}' | tail -n +2 | head -n 1 | awk -F "[\"]" '{print $1}')
echoContent green "\n---> Atualizaรงรฃo concluรญda"
echoContent yellow " ---> ่ฏทๆๅจๆง่ก[vasma]ๆๅผ่ๆฌ"
echoContent green " ---> ๅฝๅ็ๆฌ:${version}\n"
echoContent yellow "Se a atualizaรงรฃo nรฃo for bem-sucedida, execute manualmente o seguinte comando\n"
echoContent skyBlue "wget -P /root -N --no-check-certificate https://raw.githubusercontent.com/mack-a/v2ray-agent/master/install.sh"
echo
exit 0
}
# ้ฒ็ซๅข
handleFirewall() {
if systemctl status ufw 2>/dev/null | grep -q "active (exited)" && [[ "$1" == "stop" ]]; then
systemctl stop ufw >/dev/null 2>&1
systemctl disable ufw >/dev/null 2>&1
echoContent green "---> ufw fechado com sucesso"
fi
if systemctl status firewalld 2>/dev/null | grep -q "active (running)" && [[ "$1" == "stop" ]]; then
systemctl stop firewalld >/dev/null 2>&1
systemctl disable firewalld >/dev/null 2>&1
echoContent green "---> firewalld fechado com sucesso"
fi
}
# ๅฎ่ฃ
BBR
bbrInstall() {
echoContent red "\n================================================== === ==========="
echoContent green "BBRใDD่ๆฌ็จ็[ylx2016]็ๆ็ไฝๅ๏ผๅฐๅ[https://github.com/ylx2016/Linux-NetSpeed]๏ผ่ฏท็็ฅ"
echoContent yellow "1. Script de instalaรงรฃo [BBR+FQ original recomendado]"
echoContent yellow "2. Volte para o diretรณrio inicial"
echoContent red "================================================== === ==========="
read -r -p "por favor escolha:" installBBRStatus
if [[ "${installBBRStatus}" == "1" ]]; then
wget -N --no-check-certificate "https://raw.githubusercontent.com/ylx2016/Linux-NetSpeed/master/tcp.sh" && chmod +x tcp.sh && ./tcp.sh
else
menu
fi
}
# ๆฅ็ใๆฃๆฅๆฅๅฟ
checkLog() {
if [[ -z ${configPath} ]]; then
echoContent red "---> Nenhum diretรณrio de instalaรงรฃo detectado, execute o script para instalar o conteรบdo"
fi
local logStatus=false
if grep -q "access" ${configPath}00_log.json; then
logStatus=true
fi
echoContent skyBlue "\nๅ่ฝ $1/${totalProgress} : ๆฅ็ๆฅๅฟ"
echoContent red "\n================================================== === ==========="
echoContent yellow "# Recomenda-se abrir o log de acesso apenas durante a depuraรงรฃo\n"
if [[ "${logStatus}" == "false" ]]; then
echoContent yellow "1. Abra o registro de acesso"
else
echoContent yellow "1. Desligue o log de acesso"
fi
echoContent yellow "2. Monitore o log de acesso"
echoContent yellow "3. Monitore o log de erros"
echoContent yellow "4. Visualize o log de tarefas de tempo de certificado"
echoContent yellow "5. Visualize o log de instalaรงรฃo do certificado"
echoContent yellow "6. Limpe o registro"
echoContent red "================================================== === ==========="
read -r -p "por favor escolha:" selectAccessLogType
local configPathLog=${configPath//conf\//}
case ${selectAccessLogType} in
1)
if [[ "${logStatus}" == "false" ]]; then
cat <<EOF >${configPath}00_log.json
{
"log": {
"access":"${configPathLog}access.log",
"error": "${configPathLog}error.log",
"loglevel": "debug"
}
}
EOF
elif [[ "${logStatus}" == "true" ]]; then
cat <<EOF >${configPath}00_log.json
{
"log": {
"error": "${configPathLog}error.log",
"loglevel": "warning"
}
}
EOF
fi
reloadCore
checkLog 1
;;
2)
tail -f ${configPathLog}access.log
;;
3)
tail -f ${configPathLog}error.log
;;
4)
tail -n 100 /etc/v2ray-agent/crontab_tls.log
;;
5)
tail -n 100 /etc/v2ray-agent/tls/acme.log
;;
6)
echo >${configPathLog}access.log
echo >${configPathLog}error.log
;;
esac
}
# ่ๆฌๅฟซๆทๆนๅผ
aliasInstall() {
if [[ -f "$HOME/install.sh" ]] && [[ -d "/etc/v2ray-agent" ]] && grep <"$HOME/install.sh" -q "================================================== === ==========="; then
mv "$HOME/install.sh" /etc/v2ray-agent/install.sh
local vasmaType=
if [[ -d "/usr/bin/" ]]; then
if [[ ! -f "/usr/bin/vasma" ]]; then
ln -s /etc/v2ray-agent/install.sh /usr/bin/vasma
chmod 700 /usr/bin/vasma
vasmaType=true
fi
rm -rf "$HOME/install.sh"
elif [[ -d "/usr/sbin" ]]; then
if [[ ! -f "/usr/sbin/vasma" ]]; then
ln -s /etc/v2ray-agent/install.sh /usr/sbin/vasma
chmod 700 /usr/sbin/vasma
vasmaType=true
fi
rm -rf "$HOME/install.sh"
fi
if [[ "${vasmaType}" == "true" ]]; then
echoContent green "ๅฟซๆทๆนๅผๅๅปบๆๅ๏ผๅฏๆง่ก[vasma]้ๆฐๆๅผ่ๆฌ"
fi
fi
}
# ๆฃๆฅipv6ใipv4
checkIPv6() {
# pingIPv6=$(ping6 -c 1 www.google.com | sed '2{s/[^(]*(//;s/).*//;q;}' | tail -n +2)
pingIPv6=$(ping6 -c 1 www.google.com | sed -n '1p' | sed 's/.*(//g;s/).*//g')
if [[ -z "${pingIPv6}" ]]; then
echoContent red "---> nรฃo suporta ipv6"
exit 0
fi
}
# ipv6 ๅๆต
ipv6Routing() {
if [[ -z "${configPath}" ]]; then
echoContent red "---> nรฃo instalado๏ผ่ฏทไฝฟ็จ่ๆฌๅฎ่ฃ
"
menu
exit 0
fi
checkIPv6
echoContent skyBlue "\nๅ่ฝ 1/${totalProgress} : IPv6ๅๆต"
echoContent red "\n================================================== === ==========="
echoContent yellow "1. Adicione um nome de domรญnio"
echoContent yellow "2. Descarregue o descarregamento do IPv6"
echoContent red "================================================== === ==========="
read -r -p "por favor escolha:" ipv6Status
if [[ "${ipv6Status}" == "1" ]]; then
echoContent red "================================================== === ==========="
echoContent yellow "# Precauรงรตes\n"
echoContent yellow "1.่งๅไป
ๆฏๆ้ขๅฎไนๅๅๅ่กจ[https://github.com/v2fly/domain-list-community]"
echoContent yellow "2.่ฏฆ็ปๆๆกฃ[https://www.v2fly.org/config/routing.html]"
echoContent yellow "3. Se o kernel nรฃo iniciar, verifique o nome de domรญnio e adicione o nome de domรญnio novamente"
echoContent yellow "4.Caracteres especiais nรฃo sรฃo permitidos, preste atenรงรฃo ao formato das vรญrgulas"
echoContent yellow "5. Toda vez que vocรช o adicionar, ele serรก adicionado novamente e o รบltimo nome de domรญnio nรฃo serรก retido."
echoContent yellow "6. Exemplo de entrada: google, youtube, facebook\n"
read -r -p "Por favor, digite nome do domรญnio de acordo com o exemplo acima:" domainList
if [[ -f "${configPath}09_routing.json" ]]; then
unInstallRouting IPv6-out outboundTag
routing=$(jq -r ".routing.rules += [{\"type\":\"field\",\"domain\":[\"geosite:${domainList//,/\",\"geosite:}\"],\"outboundTag\":\"IPv6-out\"}]" ${configPath}09_routing.json)
echo "${routing}" | jq . >${configPath}09_routing.json
else
cat <<EOF >"${configPath}09_routing.json"
{
"routing":{
"domainStrategy": "IPOnDemand",
"rules": [
{
"type": "field",
"domain": [
"geosite:${domainList//,/\",\"geosite:}"
],
"outboundTag": "IPv6-out"
}
]
}
}
EOF
fi
unInstallOutbounds IPv6-out
outbounds=$(jq -r '.outbounds += [{"protocol":"freedom","settings":{"domainStrategy":"UseIPv6"},"tag":"IPv6-out"}]' ${configPath}10_ipv4_outbounds.json)
echo "${outbounds}" | jq . >${configPath}10_ipv4_outbounds.json
echoContent green "---> Adicionar com sucesso"
elif [[ "${ipv6Status}" == "2" ]]; then
unInstallRouting IPv6-out outboundTag
unInstallOutbounds IPv6-out
echoContent green "---> Descarregamento de IPv6 bem-sucedido"
else
echoContent red "---> Erro de seleรงรฃo"
exit 0
fi
reloadCore
}
# btไธ่ฝฝ็ฎก็
btTools() {
if [[ -z "${configPath}" ]]; then
echoContent red "---> nรฃo instalado๏ผ่ฏทไฝฟ็จ่ๆฌๅฎ่ฃ
"
menu
exit 0
fi
echoContent skyBlue "\nๅ่ฝ 1/${totalProgress} : btไธ่ฝฝ็ฎก็"
echoContent red "\n================================================== === ==========="
if [[ -f ${configPath}09_routing.json ]] && grep -q bittorrent <${configPath}09_routing.json; then
echoContent yellow "Status Atual: Desativado"
else
echoContent yellow "Status atual: nรฃo desativado"
fi
echoContent yellow "1. Desativar"
echoContent yellow "2. Abrir"
echoContent red "================================================== === ==========="
read -r -p "por favor escolha:" btStatus
if [[ "${btStatus}" == "1" ]]; then
if [[ -f "${configPath}09_routing.json" ]]; then
unInstallRouting blackhole-out outboundTag
routing=$(jq -r '.routing.rules += [{"type":"field","outboundTag":"blackhole-out","protocol":["bittorrent"]}]' ${configPath}09_routing.json)
echo "${routing}" | jq . >${configPath}09_routing.json
else
cat <<EOF >${configPath}09_routing.json
{
"routing":{
"domainStrategy": "IPOnDemand",
"rules": [
{
"type": "field",
"outboundTag": "blackhole-out",
"protocol": [ "bittorrent" ]
}
]
}
}
EOF
fi
installSniffing
unInstallOutbounds blackhole-out
outbounds=$(jq -r '.outbounds += [{"protocol":"blackhole","tag":"blackhole-out"}]' ${configPath}10_ipv4_outbounds.json)
echo "${outbounds}" | jq . >${configPath}10_ipv4_outbounds.json
echoContent green "---> Download do BT desativado com sucesso"
elif [[ "${btStatus}" == "2" ]]; then
unInstallSniffing
unInstallRouting blackhole-out outboundTag bittorrent
# unInstallOutbounds blackhole-out
echoContent green "---> Download do BT aberto com sucesso"
else
echoContent red "---> Erro de seleรงรฃo"
exit 0
fi
reloadCore
}
# ๅๅ้ปๅๅ
blacklist() {
if [[ -z "${configPath}" ]]; then
echoContent red "---> nรฃo instalado๏ผ่ฏทไฝฟ็จ่ๆฌๅฎ่ฃ
"
menu
exit 0
fi
echoContent skyBlue "\n่ฟๅบฆ $1/${totalProgress} : ๅๅ้ปๅๅ"
echoContent red "\n================================================== === ==========="
echoContent yellow "1. Adicione um nome de domรญnio"
echoContent yellow "2. Exclua a lista negra"
echoContent red "================================================== === ==========="
read -r -p "por favor escolha:" blacklistStatus
if [[ "${blacklistStatus}" == "1" ]]; then
echoContent red "================================================== === ==========="
echoContent yellow "# Precauรงรตes\n"
echoContent yellow "1.่งๅไป
ๆฏๆ้ขๅฎไนๅๅๅ่กจ[https://github.com/v2fly/domain-list-community]"
echoContent yellow "2.่ฏฆ็ปๆๆกฃ[https://www.v2fly.org/config/routing.html]"
echoContent yellow "3. Se o kernel nรฃo iniciar, verifique o nome de domรญnio e adicione o nome de domรญnio novamente"
echoContent yellow "4.Caracteres especiais nรฃo sรฃo permitidos, preste atenรงรฃo ao formato das vรญrgulas"
echoContent yellow "5. Toda vez que vocรช o adicionar, ele serรก adicionado novamente e o รบltimo nome de domรญnio nรฃo serรก retido."
echoContent yellow "6. Exemplo de entrada: speedtest, facebook\n"
read -r -p "Por favor, digite nome do domรญnio de acordo com o exemplo acima:" domainList
if [[ -f "${configPath}09_routing.json" ]]; then
unInstallRouting blackhole-out outboundTag
routing=$(jq -r ".routing.rules += [{\"type\":\"field\",\"domain\":[\"geosite:${domainList//,/\",\"geosite:}\"],\"outboundTag\":\"blackhole-out\"}]" ${configPath}09_routing.json)
echo "${routing}" | jq . >${configPath}09_routing.json
else
cat <<EOF >${configPath}09_routing.json
{
"routing":{
"domainStrategy": "IPOnDemand",
"rules": [
{
"type": "field",
"domain": [
"geosite:${domainList//,/\",\"geosite:}"
],
"outboundTag": "blackhole-out"
}
]
}
}
EOF
fi
echoContent green "---> Adicionar com sucesso"
elif [[ "${blacklistStatus}" == "2" ]]; then
unInstallRouting blackhole-out outboundTag
echoContent green "---> Lista negra de domรญnio excluรญda com sucesso"
else
echoContent red "---> Erro de seleรงรฃo"
exit 0
fi
reloadCore
}
# ๆ นๆฎtagๅธ่ฝฝRouting
unInstallRouting() {
local tag=$1
local type=$2
local protocol=$3
if [[ -f "${configPath}09_routing.json" ]]; then
local routing
if grep -q "${tag}" ${configPath}09_routing.json && grep -q "${type}" ${configPath}09_routing.json; then
jq -c .routing.rules[] ${configPath}09_routing.json | while read -r line; do
local index=$((index + 1))
local delStatus=0
if [[ "${type}" == "outboundTag" ]] && echo "${line}" | jq .outboundTag | grep -q "${tag}"; then
delStatus=1
elif [[ "${type}" == "inboundTag" ]] && echo "${line}" | jq .inboundTag | grep -q "${tag}"; then
delStatus=1
fi
if [[ -n ${protocol} ]] && echo "${line}" | jq .protocol | grep -q "${protocol}"; then
delStatus=1
elif [[ -z ${protocol} ]] && [[ $(echo "${line}" | jq .protocol) != "null" ]]; then
delStatus=0
fi
if [[ ${delStatus} == 1 ]]; then
routing=$(jq -r 'del(.routing.rules['"$(("${index}" - 1))"'])' ${configPath}09_routing.json)
echo "${routing}" | jq . >${configPath}09_routing.json
fi
done
fi
fi
}
# ๆ นๆฎtagๅธ่ฝฝๅบ็ซ
unInstallOutbounds() {
local tag=$1
if grep -q "${tag}" ${configPath}10_ipv4_outbounds.json; then
local ipv6OutIndex
ipv6OutIndex=$(jq .outbounds[].tag ${configPath}10_ipv4_outbounds.json | awk '{print ""NR""":"$0}' | grep "${tag}" | awk -F "[:]" '{print $1}' | head -1)
if [[ ${ipv6OutIndex} -gt 0 ]]; then
routing=$(jq -r 'del(.outbounds['$(("${ipv6OutIndex}" - 1))'])' ${configPath}10_ipv4_outbounds.json)
echo "${routing}" | jq . >${configPath}10_ipv4_outbounds.json
fi
fi
}
# ๅธ่ฝฝๅ
ๆข
unInstallSniffing() {
find ${configPath} -name "*inbounds.json*" | awk -F "[c][o][n][f][/]" '{print $2}' | while read -r inbound; do
sniffing=$(jq -r 'del(.inbounds[0].sniffing)' "${configPath}${inbound}")
echo "${sniffing}" | jq . >"${configPath}${inbound}"
done
}
# ๅฎ่ฃ
ๅ
ๆข
installSniffing() {
find ${configPath} -name "*inbounds.json*" | awk -F "[c][o][n][f][/]" '{print $2}' | while read -r inbound; do
sniffing=$(jq -r '.inbounds[0].sniffing = {"enabled":true,"destOverride":["http","tls"]}' "${configPath}${inbound}")
echo "${sniffing}" | jq . >"${configPath}${inbound}"
done
}
# warpๅๆต
warpRouting() {
echoContent skyBlue "\n่ฟๅบฆ $1/${totalProgress} : WARPๅๆต"
echoContent red "================================================== === ==========="
# echoContent yellow "# Precauรงรตes\n"
# echoContent yellow "1. Existem bugs no warp oficial apรณs vรกrias rodadas de testes. Reiniciar o warp farรก com que o warp falhe e nรฃo inicie. Tambรฉm รฉ possรญvel que o uso da CPU dispare."
# echoContent yellow "2. A mรกquina pode ser usada normalmente sem reiniciar a mรกquina. Se vocรช tiver que usar o warp oficial, รฉ recomendรกvel nรฃo reiniciar a mรกquina"
# echoContent yellow "3. Algumas mรกquinas ainda funcionam normalmente apรณs a reinicializaรงรฃo"
# echoContent yellow "4. Nรฃo pode ser usado apรณs a reinicializaรงรฃo, vocรช tambรฉm pode desinstalar e reinstalar"
# ๅฎ่ฃ
warp
if [[ -z $(which warp-cli) ]]; then
echo
read -r -p "WARP nรฃo estรก instalado, estรก instalado? [y/n]:" installCloudflareWarpStatus
if [[ "${installCloudflareWarpStatus}" == "y" ]]; then
installWarp
else
echoContent yellow "---> Abortar a instalaรงรฃo"
exit 0
fi
fi
echoContent red "\n================================================== === ==========="
echoContent yellow "1. Adicione um nome de domรญnio"
echoContent yellow "2. Desinstale o descarregamento WARP"
echoContent red "================================================== === ==========="
read -r -p "por favor escolha:" warpStatus
if [[ "${warpStatus}" == "1" ]]; then
echoContent red "================================================== === ==========="
echoContent yellow "# Precauรงรตes\n"
echoContent yellow "1.่งๅไป
ๆฏๆ้ขๅฎไนๅๅๅ่กจ[https://github.com/v2fly/domain-list-community]"
echoContent yellow "2.่ฏฆ็ปๆๆกฃ[https://www.v2fly.org/config/routing.html]"
echoContent yellow "3. Somente o trรกfego pode ser distribuรญdo para o warp, nรฃo para IPv4 ou IPv6"
echoContent yellow "4. Se o kernel nรฃo iniciar, verifique o nome de domรญnio e adicione o nome de domรญnio novamente"
echoContent yellow "5.Caracteres especiais nรฃo sรฃo permitidos, preste atenรงรฃo ao formato das vรญrgulas"
echoContent yellow "6. Toda vez que vocรช o adicionar, ele serรก adicionado novamente e o รบltimo nome de domรญnio nรฃo serรก retido"
echoContent yellow "7. Exemplo de entrada: google, youtube, facebook\n"
read -r -p "Por favor, digite nome do domรญnio de acordo com o exemplo acima:" domainList
if [[ -f "${configPath}09_routing.json" ]]; then
unInstallRouting warp-socks-out outboundTag
routing=$(jq -r ".routing.rules += [{\"type\":\"field\",\"domain\":[\"geosite:${domainList//,/\",\"geosite:}\"],\"outboundTag\":\"warp-socks-out\"}]" ${configPath}09_routing.json)
echo "${routing}" | jq . >${configPath}09_routing.json
else
cat <<EOF >${configPath}09_routing.json
{
"routing":{
"domainStrategy": "IPOnDemand",
"rules": [
{
"type": "field",
"domain": [
"geosite:${domainList//,/\",\"geosite:}"
],
"outboundTag": "warp-socks-out"
}
]
}
}
EOF
fi
unInstallOutbounds warp-socks-out
local outbounds
outbounds=$(jq -r '.outbounds += [{"protocol":"socks","settings":{"servers":[{"address":"127.0.0.1","port":31303}]},"tag":"warp-socks-out"}]' ${configPath}10_ipv4_outbounds.json)
echo "${outbounds}" | jq . >${configPath}10_ipv4_outbounds.json
echoContent green "---> Adicionar com sucesso"
elif [[ "${warpStatus}" == "2" ]]; then
${removeType} cloudflare-warp >/dev/null 2>&1
unInstallRouting warp-socks-out outboundTag
unInstallOutbounds warp-socks-out
echoContent green "---> WARP descarregando com sucesso"
else
echoContent red "---> Erro de seleรงรฃo"
exit 0
fi
reloadCore
}
# ๆตๅชไฝๅทฅๅ
ท็ฎฑ
streamingToolbox() {
echoContent skyBlue "\nๅ่ฝ 1/${totalProgress} : ๆตๅชไฝๅทฅๅ
ท็ฎฑ"
echoContent red "\n================================================== === ==========="
# echoContent yellow "1. Detecรงรฃo da Netflix"
echoContent yellow "1. Qualquer mรกquina de desembarque de porta para desbloquear mรญdia de streaming"
echoContent yellow "2. Transmissรฃo de desbloqueio de DNS"
read -r -p "por favor escolha:" selectType
case ${selectType} in
1)
dokodemoDoorUnblockStreamingMedia
;;
2)
dnsUnlockNetflix
;;
esac
}
# ไปปๆ้จ่งฃ้ๆตๅชไฝ
dokodemoDoorUnblockStreamingMedia() {
echoContent skyBlue "\nๅ่ฝ 1/${totalProgress} : ไปปๆ้จ่ฝๅฐๆบ่งฃ้ๆตๅชไฝ"
echoContent red "\n================================================== === ==========="
echoContent yellow "# Precauรงรตes"
echoContent yellow "ไปปๆ้จ่งฃ้่ฏฆ่งฃ๏ผ่ฏทๆฅ็ๆญคๆ็ซ [https://github.com/mack-a/v2ray-agent/blob/master/documents/netflix/dokodemo-unblock_netflix.md]\n"
echoContent yellow "1. Adicionar saรญda"
echoContent yellow "2. Adicionar entrada"
echoContent yellow "3. Desinstalar"
read -r -p "por favor escolha:" selectType
case ${selectType} in
1)
setDokodemoDoorUnblockStreamingMediaOutbounds
;;
2)
setDokodemoDoorUnblockStreamingMediaInbounds
;;
3)
removeDokodemoDoorUnblockStreamingMedia
;;
esac
}
# ่ฎพ็ฝฎไปปๆ้จ่งฃ้Netflixใๅบ็ซใ
setDokodemoDoorUnblockStreamingMediaOutbounds() {
read -r -p "Por favor, digite o IP para desbloquear o vps de streaming:" setIP
echoContent red "================================================== === ==========="
echoContent yellow "# Precauรงรตes\n"
echoContent yellow "1.่งๅไป
ๆฏๆ้ขๅฎไนๅๅๅ่กจ[https://github.com/v2fly/domain-list-community]"
echoContent yellow "2.่ฏฆ็ปๆๆกฃ[https://www.v2fly.org/config/routing.html]"
echoContent yellow "3. Se o kernel nรฃo iniciar, verifique o nome de domรญnio e adicione o nome de domรญnio novamente"
echoContent yellow "4.Caracteres especiais nรฃo sรฃo permitidos, preste atenรงรฃo ao formato das vรญrgulas"
echoContent yellow "5. Toda vez que vocรช o adicionar, ele serรก adicionado novamente e o รบltimo nome de domรญnio nรฃo serรก retido."
echoContent yellow "6. Exemplo de entrada: netflix, disney, hulu\n"
read -r -p "่ฏทๆ็
งไธ้ข็คบไพๅฝๅ
ฅnome do domรญnio:" domainList
if [[ -z ${domainList} ]]; then
echoContent red "---> O nome do domรญnio nรฃo pode estar vazio"
setDokodemoDoorUnblockStreamingMediaOutbounds
fi
if [[ -n "${setIP}" ]]; then
unInstallOutbounds streamingMedia-80
unInstallOutbounds streamingMedia-443
outbounds=$(jq -r ".outbounds += [{\"tag\":\"streamingMedia-80\",\"protocol\":\"freedom\",\"settings\":{\"domainStrategy\":\"AsIs\",\"redirect\":\"${setIP}:22387\"}},{\"tag\":\"streamingMedia-443\",\"protocol\":\"freedom\",\"settings\":{\"domainStrategy\":\"AsIs\",\"redirect\":\"${setIP}:22388\"}}]" ${configPath}10_ipv4_outbounds.json)
echo "${outbounds}" | jq . >${configPath}10_ipv4_outbounds.json
if [[ -f "${configPath}09_routing.json" ]]; then
unInstallRouting streamingMedia-80 outboundTag
unInstallRouting streamingMedia-443 outboundTag
local routing
routing=$(jq -r ".routing.rules += [{\"type\":\"field\",\"port\":80,\"domain\":[\"ip.sb\",\"geosite:${domainList//,/\",\"geosite:}\"],\"outboundTag\":\"streamingMedia-80\"},{\"type\":\"field\",\"port\":443,\"domain\":[\"ip.sb\",\"geosite:${domainList//,/\",\"geosite:}\"],\"outboundTag\":\"streamingMedia-443\"}]" ${configPath}09_routing.json)
echo "${routing}" | jq . >${configPath}09_routing.json
else
cat <<EOF >${configPath}09_routing.json
{
"routing": {
"domainStrategy": "AsIs",
"rules": [
{
"type": "field",
"port": 80,
"domain": [
"ip.sb",
"geosite:${domainList//,/\",\"geosite:}"
],
"outboundTag": "streamingMedia-80"
},
{
"type": "field",
"port": 443,
"domain": [
"ip.sb",
"geosite:${domainList//,/\",\"geosite:}"
],
"outboundTag": "streamingMedia-443"
}
]
}
}
EOF
fi
reloadCore
echoContent green "---> Adicionar desbloqueio de saรญda com sucesso"
exit 0
fi
echoContent red "---> ip nรฃo pode estar vazio"
}
# ่ฎพ็ฝฎไปปๆ้จ่งฃ้Netflixใๅ
ฅ็ซใ
setDokodemoDoorUnblockStreamingMediaInbounds() {
echoContent skyBlue "\nๅ่ฝ 1/${totalProgress} : ไปปๆ้จๆทปๅ ๅ
ฅ็ซ"
echoContent red "\n================================================== === ==========="
echoContent yellow "# Precauรงรตes\n"
echoContent yellow "1.่งๅไป
ๆฏๆ้ขๅฎไนๅๅๅ่กจ[https://github.com/v2fly/domain-list-community]"
echoContent yellow "2.่ฏฆ็ปๆๆกฃ[https://www.v2fly.org/config/routing.html]"
echoContent yellow "3. Se o kernel nรฃo iniciar, verifique o nome de domรญnio e adicione o nome de domรญnio novamente"
echoContent yellow "4.Caracteres especiais nรฃo sรฃo permitidos, preste atenรงรฃo ao formato das vรญrgulas"
echoContent yellow "5. Toda vez que vocรช o adicionar, ele serรก adicionado novamente e o รบltimo nome de domรญnio nรฃo serรก retido."
echoContent yellow "6. Exemplo de entrada de IP: 1.1.1.1, 1.1.1.2"
echoContent yellow "7. O nome de domรญnio a seguir deve ser consistente com o vps de saรญda"
echoContent yellow "8. Se houver um firewall, abra manualmente as portas 22387 e 22388"
echoContent yellow "9. Exemplo de entrada de nome de domรญnio: netflix, disney, hulu\n"
read -r -p "Por favor, digite o IP que tem permissรฃo para acessar os vps desbloqueados:" setIPs
if [[ -n "${setIPs}" ]]; then
read -r -p "่ฏทๆ็
งไธ้ข็คบไพๅฝๅ
ฅnome do domรญnio:" domainList
cat <<EOF >${configPath}01_netflix_inbounds.json
{
"inbounds": [
{
"listen": "0.0.0.0",
"port": 22387,
"protocol": "dokodemo-door",
"settings": {
"address": "0.0.0.0",
"port": 80,
"network": "tcp",
"followRedirect": false
},
"sniffing": {
"enabled": true,
"destOverride": [
"http"
]
},
"tag": "streamingMedia-80"
},
{
"listen": "0.0.0.0",
"port": 22388,
"protocol": "dokodemo-door",
"settings": {
"address": "0.0.0.0",
"port": 443,
"network": "tcp",
"followRedirect": false
},
"sniffing": {
"enabled": true,
"destOverride": [
"tls"
]
},
"tag": "streamingMedia-443"
}
]
}
EOF
cat <<EOF >${configPath}10_ipv4_outbounds.json
{
"outbounds":[
{
"protocol":"freedom",
"settings":{
"domainStrategy":"UseIPv4"
},
"tag":"IPv4-out"
},
{
"protocol":"freedom",
"settings":{
"domainStrategy":"UseIPv6"
},
"tag":"IPv6-out"
},
{
"protocol":"blackhole",
"tag":"blackhole-out"
}
]
}
EOF
if [[ -f "${configPath}09_routing.json" ]]; then
unInstallRouting streamingMedia-80 inboundTag
unInstallRouting streamingMedia-443 inboundTag
local routing
routing=$(jq -r ".routing.rules += [{\"source\":[\"${setIPs//,/\",\"}\"],\"type\":\"field\",\"inboundTag\":[\"streamingMedia-80\",\"streamingMedia-443\"],\"outboundTag\":\"direct\"},{\"domains\":[\"geosite:${domainList//,/\",\"geosite:}\"],\"type\":\"field\",\"inboundTag\":[\"streamingMedia-80\",\"streamingMedia-443\"],\"outboundTag\":\"blackhole-out\"}]" ${configPath}09_routing.json)
echo "${routing}" | jq . >${configPath}09_routing.json
else
cat <<EOF >${configPath}09_routing.json
{
"routing": {
"rules": [
{
"source": [
"${setIPs//,/\",\"}"
],
"type": "field",
"inboundTag": [
"streamingMedia-80",
"streamingMedia-443"
],
"outboundTag": "direct"
},
{
"domains": [
"geosite:${domainList//,/\",\"geosite:}"
],
"type": "field",
"inboundTag": [
"streamingMedia-80",
"streamingMedia-443"
],
"outboundTag": "blackhole-out"
}
]
}
}
EOF
fi
reloadCore
echoContent green "---> Adicionar desbloqueio de entrada da mรกquina de pouso com sucesso"
exit 0
fi
echoContent red "---> ip nรฃo pode estar vazio"
}
# ็งป้คไปปๆ้จ่งฃ้Netflix
removeDokodemoDoorUnblockStreamingMedia() {
unInstallOutbounds streamingMedia-80
unInstallOutbounds streamingMedia-443
unInstallRouting streamingMedia-80 inboundTag
unInstallRouting streamingMedia-443 inboundTag
unInstallRouting streamingMedia-80 outboundTag
unInstallRouting streamingMedia-443 outboundTag
rm -rf ${configPath}01_netflix_inbounds.json
reloadCore
echoContent green "---> Desinstalaรงรฃo bem sucedida"
}
# ้ๅฏๆ ธๅฟ
reloadCore() {
if [[ "${coreInstallType}" == "1" ]]; then
handleXray stop
handleXray start
elif [[ "${coreInstallType}" == "2" || "${coreInstallType}" == "3" ]]; then
handleV2Ray stop
handleV2Ray start
fi
}
# dns่งฃ้Netflix
dnsUnlockNetflix() {
if [[ -z "${configPath}" ]]; then
echoContent red "---> nรฃo instalado๏ผ่ฏทไฝฟ็จ่ๆฌๅฎ่ฃ
"
menu
exit 0
fi
echoContent skyBlue "\nๅ่ฝ 1/${totalProgress} : DNS่งฃ้ๆตๅชไฝ"
echoContent red "\n================================================== === ==========="
echoContent yellow "1. Adicionar"
echoContent yellow "2. Desinstalar"
read -r -p "por favor escolha:" selectType
case ${selectType} in
1)
setUnlockDNS
;;
2)
removeUnlockDNS
;;
esac
}
# ่ฎพ็ฝฎdns
setUnlockDNS() {
read -r -p "Digite Desbloquear DNS de streaming:" setDNS
if [[ -n ${setDNS} ]]; then
echoContent red "================================================== === ==========="
echoContent yellow "# Precauรงรตes\n"
echoContent yellow "1.่งๅไป
ๆฏๆ้ขๅฎไนๅๅๅ่กจ[https://github.com/v2fly/domain-list-community]"
echoContent yellow "2.่ฏฆ็ปๆๆกฃ[https://www.v2fly.org/config/routing.html]"
echoContent yellow "3. Se o kernel nรฃo iniciar, verifique o nome de domรญnio e adicione o nome de domรญnio novamente"
echoContent yellow "4.Caracteres especiais nรฃo sรฃo permitidos, preste atenรงรฃo ao formato das vรญrgulas"
echoContent yellow "5. Toda vez que vocรช o adicionar, ele serรก adicionado novamente e o รบltimo nome de domรญnio nรฃo serรก retido."
echoContent yellow "6. Exemplo de entrada: netflix, disney, hulu"
echoContent yellow "7. Insira 1 para o esquema padrรฃo, o esquema padrรฃo inclui o seguinte"
echoContent yellow "netflix,bahamut,hulu,hbo,disney,bbc,4chan,raposa,abema,niconico,pixiv,bilibili,viu"
read -r -p "่ฏทๆ็
งไธ้ข็คบไพๅฝๅ
ฅnome do domรญnio:" domainList
if [[ "${domainList}" == "1" ]]; then
cat <<EOF >${configPath}11_dns.json
{
"dns": {
"servers": [
{
"address": "${setDNS}",
"port": 53,
"domains": [
"geosite:netflix",
"geosite:bahamut",
"geosite:hulu",
"geosite:hbo",
"geosite:disney",
"geosite:bbc",
"geosite:4chan",
"geosite:fox",
"geosite:abema",
"geosite:dmm",
"geosite:niconico",
"geosite:pixiv",
"geosite:bilibili",
"geosite:viu"
]
},
"localhost"
]
}
}
EOF
elif [[ -n "${domainList}" ]]; then
cat <<EOF >${configPath}11_dns.json
{
"dns": {
"servers": [
{
"address": "${setDNS}",
"port": 53,
"domains": [
"geosite:${domainList//,/\",\"geosite:}"
]
},
"localhost"
]
}
}
EOF
fi
reloadCore
echoContent yellow "\n---> Se vocรช ainda nรฃo conseguir assistir, tente as duas soluรงรตes a seguir"
echoContent yellow "1. Reinicie o vps"
echoContent yellow " 2. Desinstalardns่งฃ้ๅ๏ผไฟฎๆนๆฌๅฐ็[/etc/resolv.conf]DNS่ฎพ็ฝฎๅนถ้ๅฏvps\n"
else
echoContent red "---> dns nรฃo pode estar vazio"
fi
exit 0
}
# ็งป้คNetflix่งฃ้
removeUnlockDNS() {
cat <<EOF >${configPath}11_dns.json
{
"dns": {
"servers": [
"localhost"
]
}
}
EOF
reloadCore
echoContent green "---> Desinstalaรงรฃo bem sucedida"
exit 0
}
# v2ray-coreไธชๆงๅๅฎ่ฃ
customV2RayInstall() {
echoContent skyBlue "\n================================================== =Instalaรงรฃo personalizada ====="
echoContent yellow "VLESS รฉ prรฉ-instalado e 0 รฉ instalado por padrรฃo. Se apenas 0 precisar ser instalado, apenas 0 poderรก ser selecionado."
echoContent yellow "0. VLESS+TLS/XTLS+TCP"
echoContent yellow "1.VLESS+TLS+WS[CDN]"
echoContent yellow "2.Trojan+TLS+gRPC[CDN]"
echoContent yellow "3.VMess+TLS+WS[CDN]"
echoContent yellow "4. Cavalo de Troia"
echoContent yellow "5.VLESS+TLS+gRPC[CDN]"
read -r -p "่ฏท้ๆฉ[ๅค้]๏ผ[ไพๅฆ:123]:" selectCustomInstallType
echoContent skyBlue "-------------------------------------------------- ------------"
if [[ -z ${selectCustomInstallType} ]]; then
selectCustomInstallType=0
fi
if [[ "${selectCustomInstallType}" =~ ^[0-5]+$ ]]; then
cleanUp xrayClean
totalProgress=17
installTools 1
# ็ณ่ฏทtls
initTLSNginxConfig 2
installTLS 3
handleNginx stop
# ้ๆบpath
if echo ${selectCustomInstallType} | grep -q 1 || echo ${selectCustomInstallType} | grep -q 3 || echo ${selectCustomInstallType} | grep -q 4; then
randomPathFunction 5
customCDNIP 6
fi
nginxBlog 7
updateRedirectNginxConf
handleNginx start
# ๅฎ่ฃ
V2Ray
installV2Ray 8
installV2RayService 9
initV2RayConfig custom 10
cleanUp xrayDel
installCronTLS 14
handleV2Ray stop
handleV2Ray start
# ็ๆ่ดฆๅท
checkGFWStatue 15
showAccounts 16
else
echoContent red "---> Entrada ilegal"
customV2RayInstall
fi
}
# Xray-coreไธชๆงๅๅฎ่ฃ
customXrayInstall() {
echoContent skyBlue "\n================================================== =Instalaรงรฃo personalizada ====="
echoContent yellow "VLESS รฉ prรฉ-instalado e 0 รฉ instalado por padrรฃo. Se apenas 0 precisar ser instalado, apenas 0 poderรก ser selecionado."
echoContent yellow "0. VLESS+TLS/XTLS+TCP"
echoContent yellow "1.VLESS+TLS+WS[CDN]"
echoContent yellow "2.Trojan+TLS+gRPC[CDN]"
echoContent yellow "3.VMess+TLS+WS[CDN]"
echoContent yellow "4. Cavalo de Troia"
echoContent yellow "5.VLESS+TLS+gRPC[CDN]"
read -r -p "่ฏท้ๆฉ[ๅค้]๏ผ[ไพๅฆ:123]:" selectCustomInstallType
echoContent skyBlue "-------------------------------------------------- ------------"
if [[ -z ${selectCustomInstallType} ]]; then
echoContent red "---> nรฃo anulรกvel"
customXrayInstall
elif [[ "${selectCustomInstallType}" =~ ^[0-5]+$ ]]; then
cleanUp v2rayClean
totalProgress=17
installTools 1
# ็ณ่ฏทtls
initTLSNginxConfig 2
installTLS 3
handleNginx stop
# ้ๆบpath
if echo "${selectCustomInstallType}" | grep -q 1 || echo "${selectCustomInstallType}" | grep -q 2 || echo "${selectCustomInstallType}" | grep -q 3 || echo "${selectCustomInstallType}" | grep -q 5; then
randomPathFunction 5
customCDNIP 6
fi
nginxBlog 7
updateRedirectNginxConf
handleNginx start
# ๅฎ่ฃ
V2Ray
installXray 8
installXrayService 9
initXrayConfig custom 10
cleanUp v2rayDel
installCronTLS 14
handleXray stop
handleXray start
# ็ๆ่ดฆๅท
checkGFWStatue 15
showAccounts 16
else
echoContent red "---> Entrada ilegal"
customXrayInstall
fi
}
# ้ๆฉๆ ธๅฟๅฎ่ฃ
---v2ray-coreใxray-core
selectCoreInstall() {
echoContent skyBlue "\nๅ่ฝ 1/${totalProgress} : ้ๆฉๆ ธๅฟๅฎ่ฃ
"
echoContent red "\n================================================== === ==========="
echoContent yellow "1. Nรบcleo de raios-X"
echoContent yellow "2. v2ray-core"
echoContent red "================================================== === ==========="
read -r -p "por favor escolha:" selectCoreType
case ${selectCoreType} in
1)
if [[ "${selectInstallType}" == "2" ]]; then
customXrayInstall
else
xrayCoreInstall
fi
;;
2)
v2rayCoreVersion=
if [[ "${selectInstallType}" == "2" ]]; then
customV2RayInstall
else
v2rayCoreInstall
fi
;;
3)
v2rayCoreVersion=v4.32.1
if [[ "${selectInstallType}" == "2" ]]; then
customV2RayInstall
else
v2rayCoreInstall
fi
;;
*)
echoContent red '---> Erro de seleรงรฃo๏ผ้ๆฐ้ๆฉ'
selectCoreInstall
;;
esac
}
# v2ray-core ๅฎ่ฃ
v2rayCoreInstall() {
cleanUp xrayClean
selectCustomInstallType=
totalProgress=13
installTools 2
# ็ณ่ฏทtls
initTLSNginxConfig 3
installTLS 4
handleNginx stop
# initNginxConfig 5
randomPathFunction 5
# ๅฎ่ฃ
V2Ray
installV2Ray 6
installV2RayService 7
customCDNIP 8
initV2RayConfig all 9
cleanUp xrayDel
installCronTLS 10
nginxBlog 11
updateRedirectNginxConf
handleV2Ray stop
sleep 2
handleV2Ray start
handleNginx start
# ็ๆ่ดฆๅท
checkGFWStatue 12
showAccounts 13
}
# xray-core ๅฎ่ฃ
xrayCoreInstall() {
cleanUp v2rayClean
selectCustomInstallType=
totalProgress=13
installTools 2
# ็ณ่ฏทtls
initTLSNginxConfig 3
installTLS 4
handleNginx stop
randomPathFunction 5
# ๅฎ่ฃ
Xray
# handleV2Ray stop
installXray 6
installXrayService 7
customCDNIP 8
initXrayConfig all 9
cleanUp v2rayDel
installCronTLS 10
nginxBlog 11
updateRedirectNginxConf
handleXray stop
sleep 2
handleXray start
handleNginx start
# ็ๆ่ดฆๅท
checkGFWStatue 12
showAccounts 13
}
# ๆ ธๅฟ็ฎก็
coreVersionManageMenu() {
if [[ -z "${coreInstallType}" ]]; then
echoContent red "\n---> Nenhum diretรณrio de instalaรงรฃo detectado, execute o script para instalar o conteรบdo"
menu
exit 0
fi
if [[ "${coreInstallType}" == "1" ]]; then
xrayVersionManageMenu 1
elif [[ "${coreInstallType}" == "2" ]]; then
v2rayCoreVersion=
v2rayVersionManageMenu 1
elif [[ "${coreInstallType}" == "3" ]]; then
v2rayCoreVersion=v4.32.1
v2rayVersionManageMenu 1
fi
}
# ๅฎๆถไปปๅกๆฃๆฅ่ฏไนฆ
cronRenewTLS() {
if [[ "${renewTLS}" == "RenewTLS" ]]; then
renewalTLS
exit 0
fi
}
# ่ดฆๅท็ฎก็
manageAccount() {
echoContent skyBlue "\nๅ่ฝ 1/${totalProgress} : ่ดฆๅท็ฎก็"
echoContent red "\n================================================== === ==========="
echoContent yellow "# Toda vez que vocรช excluir ou adicionar uma conta, precisarรก verificar novamente a assinatura para gerar uma assinatura\n"
echoContent yellow "1. Verifique sua conta"
echoContent yellow "2. Ver assinaturas"
echoContent yellow "3. Adicionar usuรกrios"
echoContent yellow "4. Excluir usuรกrio"
echoContent red "================================================== === ==========="
read -r -p "Por favor, insira:" manageAccountStatus
if [[ "${manageAccountStatus}" == "1" ]]; then
showAccounts 1
elif [[ "${manageAccountStatus}" == "2" ]]; then
subscribe 1
elif [[ "${manageAccountStatus}" == "3" ]]; then
addUser
elif [[ "${manageAccountStatus}" == "4" ]]; then
removeUser
else
echoContent red "---> Erro de seleรงรฃo"
fi
}
# ่ฎข้
subscribe() {
if [[ -n "${configPath}" ]]; then
echoContent skyBlue "-------------------------Observaรงรฃo------------------------ ---------"
echoContent yellow "# As assinaturas serรฃo regeneradas ao visualizar as assinaturas"
echoContent yellow "# Toda vez que vocรช adiciona ou exclui uma conta, precisa verificar novamente a assinatura"
rm -rf /etc/v2ray-agent/subscribe/*
rm -rf /etc/v2ray-agent/subscribe_tmp/*
showAccounts >/dev/null
mv /etc/v2ray-agent/subscribe_tmp/* /etc/v2ray-agent/subscribe/
if [[ -n $(ls /etc/v2ray-agent/subscribe/) ]]; then
find /etc/v2ray-agent/subscribe/* | while read -r email; do
email=$(echo "${email}" | awk -F "[s][u][b][s][c][r][i][b][e][/]" '{print $2}')
local base64Result
base64Result=$(base64 -w 0 "/etc/v2ray-agent/subscribe/${email}")
echo "${base64Result}" >"/etc/v2ray-agent/subscribe/${email}"
echoContent skyBlue "-------------------------------------------------- ------------"
echoContent yellow "email:$(echo "${email}" | awk -F "[_]" '{print $1}')\n"
echoContent yellow "url:https://${currentHost}/s/${email}\n"
echoContent yellow "ๅจ็บฟไบ็ปด็ :https://api.qrserver.com/v1/create-qr-code/?size=400x400&data=https://${currentHost}/s/${email}\n"
echo "https://${currentHost}/s/${email}" | qrencode -s 10 -m 1 -t UTF8
echoContent skyBlue "-------------------------------------------------- ------------"
done
fi
else
echoContent red "---> nรฃo instalado"
fi
}
# ๅๆขalpn
switchAlpn() {
echoContent skyBlue "\nๅ่ฝ 1/${totalProgress} : ๅๆขalpn"
if [[ -z ${currentAlpn} ]]; then
echoContent red "---> Nรฃo foi possรญvel ler o alpn, verifique se estรก instalado"
exit 0
fi
echoContent red "\n================================================== === ==========="
echoContent green "ๅฝๅalpn้ฆไฝไธบ:${currentAlpn}"
echoContent yellow "1. Quando o http/1.1 vem primeiro, o trojan estรก disponรญvel e alguns clientes gRPC estรฃo disponรญveis [os clientes suportam a seleรงรฃo manual de alpn disponรญvel]"
echoContent yellow "2. Quando h2 รฉ o primeiro, gRPC estรก disponรญvel, e alguns clientes trojan estรฃo disponรญveis [clientes suportam seleรงรฃo manual de alpn disponรญvel]"
echoContent yellow "3. Se o cliente nรฃo suportar a substituiรงรฃo manual do alpn, รฉ recomendรกvel usar esta funรงรฃo para alterar a ordem do alpn do servidor para usar o protocolo correspondente"
echoContent red "================================================== === ==========="
if [[ "${currentAlpn}" == "http/1.1" ]]; then
echoContent yellow "1. Mude a primeira posiรงรฃo de alpn h2"
elif [[ "${currentAlpn}" == "h2" ]]; then
echoContent yellow "1. Alterne primeiro alpn http/1.1"
else
echoContent red 'ไธ็ฌฆๅ'
fi
echoContent red "================================================== === ==========="
read -r -p "por favor escolha:" selectSwitchAlpnType
if [[ "${selectSwitchAlpnType}" == "1" && "${currentAlpn}" == "http/1.1" ]]; then
local frontingTypeJSON
frontingTypeJSON=$(jq -r ".inbounds[0].streamSettings.xtlsSettings.alpn = [\"h2\",\"http/1.1\"]" ${configPath}${frontingType}.json)
echo "${frontingTypeJSON}" | jq . >${configPath}${frontingType}.json
elif [[ "${selectSwitchAlpnType}" == "1" && "${currentAlpn}" == "h2" ]]; then
local frontingTypeJSON
frontingTypeJSON=$(jq -r ".inbounds[0].streamSettings.xtlsSettings.alpn =[\"http/1.1\",\"h2\"]" ${configPath}${frontingType}.json)
echo "${frontingTypeJSON}" | jq . >${configPath}${frontingType}.json
else
echoContent red "---> Erro de seleรงรฃo"
exit 0
fi
reloadCore
}
# ไธป่ๅ
menu() {
cd "$HOME" || exit
echoContent red "\n================================================== === ==========="
echoContent green "================================================== === ==========="
echoContent green "Autor: mack-a"
echoContent green "Versรฃo atual: v2.5.55"
echoContent green "ๆ่ฟฐ:ๅ
ซๅไธๅ
ฑๅญ่ๆฌ\c"
showInstallStatus
echoContent red "\n================================================== === ==========="
if [[ -n "${coreInstallType}" ]]; then
echoContent yellow "================================================== === ==========="
else
echoContent yellow "1. Reinstale"
fi
echoContent yellow "1. Instalaรงรฃo"
if echo ${currentInstallProtocolType} | grep -q trojan; then
echoContent yellow "3.ๅๆขVLESS[XTLS]"
elif echo ${currentInstallProtocolType} | grep -q 0; then
echoContent yellow "3.ๅๆขTrojan[XTLS]"
fi
echoContent skyBlue "3. Alternar Trojan [XTLS]"
echoContent yellow "-------------------------Gerenciamento de ferramentas ----------------------- ------"
echoContent yellow "4. Gerenciamento de contas"
echoContent yellow "5. Substitua a estaรงรฃo de camuflagem"
echoContent yellow "6. Atualize o certificado"
echoContent yellow "7. Substitua o nรณ CDN"
echoContent yellow "8. Descarregamento IPv6"
echoContent yellow "9. Derivaรงรฃo WARP"
echoContent yellow "11. Adicionarๆฐ็ซฏๅฃ"
echoContent yellow "11. Adicione uma nova porta"
echoContent yellow "12.Gestรฃo de downloads BT"
echoContent yellow "13. Alternar alpn"
echoContent skyBlue "14. Lista negra de domรญnios"
echoContent yellow "-------------------------Gerenciamento de versรตes ----------------------- ------"
echoContent yellow "15. gerenciamento de nรบcleo"
echoContent yellow "16. Atualize o script"
echoContent skyBlue "17. Instale scripts BBR, DD"
echoContent yellow "-------------------------Gerenciamento de scripts ----------------------- ------"
echoContent yellow "18. Ver registros"
echoContent red "================================================== === ==========="
mkdirTools
aliasInstall
read -r -p "por favor escolha:" selectInstallType
case ${selectInstallType} in
1)
selectCoreInstall
;;
2)
selectCoreInstall
;;
3)
initXrayFrontingConfig 1
;;
4)
manageAccount 1
;;
5)
updateNginxBlog 1
;;
6)
renewalTLS 1
;;
7)
updateV2RayCDN 1
;;
8)
ipv6Routing 1
;;
9)
warpRouting 1
;;
10)
streamingToolbox 1
;;
11)
addCorePort 1
;;
12)
btTools 1
;;
13)
switchAlpn 1
;;
14)
blacklist 1
;;
15)
coreVersionManageMenu 1
;;
16)
updateV2RayAgent 1
;;
17)
bbrInstall
;;
18)
checkLog 1
;;
19)
unInstall 1
;;
esac
}
cronRenewTLS
menu
|
<reponame>smagill/opensphere-desktop<filename>open-sphere-base/core/src/main/java/io/opensphere/core/server/HttpServer.java
package io.opensphere.core.server;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.net.Proxy;
import java.net.URISyntaxException;
import java.net.URL;
import java.util.Map;
import io.opensphere.core.util.io.CancellableInputStream;
import io.opensphere.core.util.lang.Pair;
/**
* Sends Http requests to a specified server.
*
*/
public interface HttpServer
{
/**
* Gets the host name of the server.
*
* @return The server host name.
*/
String getHost();
/**
* Gets the protocol used to communicate with the server.
*
* @return The server's protocol.
*/
String getProtocol();
/**
* Sends a file to the specified url.
*
* @param postToURL the post to url
* @param metaDataParts map of name to data for parts to precede the main
* file part
* @param fileToPost the file to post
* @param response the response
* @return the input stream
* @throws IOException Signals that an I/O exception has occurred.
* @throws URISyntaxException Thrown if an error occurs converting the URL
* to a URI.
*/
CancellableInputStream postFile(URL postToURL, Map<String, String> metaDataParts, File fileToPost, ResponseValues response)
throws IOException, URISyntaxException;
/**
* Sends a file to the specified url.
*
* @param postToURL the post to url
* @param fileToPost the file to post
* @param response the response
* @return the input stream
* @throws IOException Signals that an I/O exception has occurred.
* @throws URISyntaxException Thrown if an error occurs converting the URL
* to a URI.
*/
CancellableInputStream postFile(URL postToURL, File fileToPost, ResponseValues response)
throws IOException, URISyntaxException;
/**
* Gets a host and port to connect to based on the configured proxy settings
* for this server.
*
* @param destination The url to the destination.
* @return The proxy host and port or null if a proxy server is not
* configured for this guy.
*/
Pair<String, Integer> resolveProxy(URL destination);
/**
* Gets a Proxy based on the configured proxy settings for this server.
*
* @param destination The url to the destination.
* @return The ProxyHostConfig or null if a proxy server is not configured
* for this guy.
*/
Proxy resolveProxyConfig(URL destination);
/**
* Sends a delete request to the server.
*
* @param url The url to the server which should include any parameters.
* @param response The response code and message returned from the delete
* request.
* @return The input stream containing the data returned by the delete
* request.
* @throws IOException Thrown if an error happens when communicating with
* the server.
* @throws URISyntaxException Thrown if an error occurs converting the URL
* to a URI.
*/
CancellableInputStream sendDelete(URL url, ResponseValues response) throws IOException, URISyntaxException;
/**
* Sends a delete request to the server.
*
* @param url The url to the server which should include any parameters.
* @param extraHeaderValues Header values to add to the request header.
* @param response The response code and message returned from the delete
* request.
* @return The input stream containing the data returned by the delete
* request.
* @throws IOException Thrown if an error happens when communicating with
* the server.
* @throws URISyntaxException Thrown if an error occurs converting the URL
* to a URI.
*/
CancellableInputStream sendDelete(URL url, Map<String, String> extraHeaderValues, ResponseValues response)
throws IOException, URISyntaxException;
/**
* Sends a get request to the server.
*
* @param url The url to the server which should include any parameters.
* @param extraHeaderValues Header values to add to the request header.
* @param response The response code and message returned from the get
* request.
* @return The input stream containing the data returned by the get request.
* @throws IOException Thrown if an error happens when communicating with
* the server.
* @throws URISyntaxException Thrown if an error occurs converting the URL
* to a URI.
*/
CancellableInputStream sendGet(URL url, Map<String, String> extraHeaderValues, ResponseValues response)
throws IOException, URISyntaxException;
/**
* Sends a get request to the server.
*
* @param url The url to the server which should include any parameters.
* @param response The response code and message returned from the get
* request.
* @return The input stream containing the data returned by the get request.
* @throws IOException Thrown if an error happens when communicating with
* the server.
* @throws URISyntaxException Thrown if an error occurs converting the URL
* to a URI.
*/
CancellableInputStream sendGet(URL url, ResponseValues response) throws IOException, URISyntaxException;
/**
* Sends a HEAD request to the server.
*
* @param url The url to the server which should include any parameters.
* @param extraHeaderValues Header values to add to the request header.
* @param response The response code and message returned from the get
* request.
* @throws IOException Thrown if an error happens when communicating with
* the server.
* @throws URISyntaxException Thrown if an error occurs converting the URL
* to a URI.
*/
void sendHead(URL url, Map<String, String> extraHeaderValues, ResponseValues response) throws IOException, URISyntaxException;
/**
* Sends a HEAD request to the server.
*
* @param url The url to the server which should include any parameters.
* @param response The response code and message returned from the get
* request.
* @throws IOException Thrown if an error happens when communicating with
* the server.
* @throws URISyntaxException Thrown if an error occurs converting the URL
* to a URI.
*/
void sendHead(URL url, ResponseValues response) throws IOException, URISyntaxException;
/**
* Sends a post request to the server.
*
* @param url The url to send the post request to.
* @param postData The data to send to the post.
* @param extraHeaderValues Any extra header information to add to the post
* request.
* @param response The response code and message returned from the server.
* @param contentType The content type of the post data.
* @return The input stream containing the data returned by the post
* request.
* @throws IOException Thrown if an error occurs while communicating with
* the server.
* @throws URISyntaxException Thrown if an error occurs converting the URL
* to a URI.
*/
CancellableInputStream sendPost(URL url, InputStream postData, Map<String, String> extraHeaderValues, ResponseValues response,
ContentType contentType)
throws IOException, URISyntaxException;
/**
* Sends a post request to the server.
*
* @param url The url to send the post request to.
* @param postData The data to send to the post.
* @param response The response code and message returned from the server.
* @return The input stream containing the data returned by the post
* request.
* @throws IOException Thrown if an error occurs while communicating with
* the server.
* @throws URISyntaxException Thrown if an error occurs converting the URL
* to a URI.
*/
CancellableInputStream sendPost(URL url, InputStream postData, ResponseValues response)
throws IOException, URISyntaxException;
/**
* Sends a post request to the server.
*
* @param url The url to send the post request to.
* @param postData The data to send to the post.
* @param response The response code and message returned from the server.
* @param contentType The content type of the post data.
* @return The input stream containing the data returned by the post
* request.
* @throws IOException Thrown if an error occurs while communicating with
* the server.
* @throws URISyntaxException Thrown if an error occurs converting the URL
* to a URI.
*/
CancellableInputStream sendPost(URL url, InputStream postData, ResponseValues response, ContentType contentType)
throws IOException, URISyntaxException;
/**
* Sends a post request to the server.
*
* @param url The url to send the post request to.
* @param extraHeaderValues Any extra header information to add to the post
* request.
* @param postData The data to send to the post.
* @param response The response code and message returned from the server.
* @return The input stream containing the data returned by the post
* request.
* @throws IOException Thrown if an error occurs while communicating with
* the server.
* @throws URISyntaxException Thrown if an error occurs converting the URL
* to a URI.
*/
CancellableInputStream sendPost(URL url, Map<String, String> extraHeaderValues, Map<String, String> postData,
ResponseValues response)
throws IOException, URISyntaxException;
/**
* Sends a post request to the server.
*
* @param url The url to send the post request to.
* @param postData The data to send to the post.
* @param response The response code and message returned from the server.
* @return The input stream containing the data returned by the post
* request.
* @throws IOException Thrown if an error occurs while communicating with
* the server.
* @throws URISyntaxException Thrown if an error occurs converting the URL
* to a URI.
*/
CancellableInputStream sendPost(URL url, Map<String, String> postData, ResponseValues response)
throws IOException, URISyntaxException;
/**
* Sets the size of the buffer used when reading http messages.
*
* @param bufferSize The size of the buffer to use in bytes, must be greater
* than 0.
*/
void setBufferSize(int bufferSize);
/**
* Sets the timeouts.
*
* @param readTimeout The read timeout.
* @param connectTimeout The connect timeout.
*/
void setTimeouts(int readTimeout, int connectTimeout);
}
|
#
# Sets general shell options and defines environment variables.
#
# Authors:
# Sorin Ionescu <sorin.ionescu@gmail.com>
#
#
# Smart URLs
#
# This logic comes from an old version of zim. Essentially, bracketed-paste was
# added as a requirement of url-quote-magic in 5.1, but in 5.1.1 bracketed
# paste had a regression. Additionally, 5.2 added bracketed-paste-url-magic
# which is generally better than url-quote-magic so we load that when possible.
autoload -Uz is-at-least
if [[ ${ZSH_VERSION} != 5.1.1 && ${TERM} != "dumb" ]]; then
if is-at-least 5.2; then
autoload -Uz bracketed-paste-url-magic
zle -N bracketed-paste bracketed-paste-url-magic
else
if is-at-least 5.1; then
autoload -Uz bracketed-paste-magic
zle -N bracketed-paste bracketed-paste-magic
fi
fi
autoload -Uz url-quote-magic
zle -N self-insert url-quote-magic
fi
#
# General
#
setopt COMBINING_CHARS # Combine zero-length punctuation characters (accents)
# with the base character.
setopt INTERACTIVE_COMMENTS # Enable comments in interactive shell.
setopt RC_QUOTES # Allow 'Henry''s Garage' instead of 'Henry'\''s Garage'.
unsetopt MAIL_WARNING # Don't print a warning message if a mail file has been accessed.
#
# Jobs
#
setopt LONG_LIST_JOBS # List jobs in the long format by default.
setopt AUTO_RESUME # Attempt to resume existing job before creating a new process.
setopt NOTIFY # Report status of background jobs immediately.
unsetopt BG_NICE # Don't run all background jobs at a lower priority.
unsetopt HUP # Don't kill jobs on shell exit.
unsetopt CHECK_JOBS # Don't report on jobs when shell exit.
#
# Termcap
#
if zstyle -t ':prezto:environment:termcap' color; then
export LESS_TERMCAP_mb=$'\E[01;31m' # Begins blinking.
export LESS_TERMCAP_md=$'\E[01;31m' # Begins bold.
export LESS_TERMCAP_me=$'\E[0m' # Ends mode.
export LESS_TERMCAP_se=$'\E[0m' # Ends standout-mode.
export LESS_TERMCAP_so=$'\E[00;47;30m' # Begins standout-mode.
export LESS_TERMCAP_ue=$'\E[0m' # Ends underline.
export LESS_TERMCAP_us=$'\E[01;32m' # Begins underline.
fi
|
import React, {useState, useEffect} from 'react'
import './chronometer.css'
import { getAll } from '../timeTable/timeTable.js'
import axios from 'axios'
const Chronometer = () =>{
const [time, setTime] = useState(0)
const [start, setStart] = useState(false)
const [saveTimes, setSaveTimes] = useState([{}])
let minu = "0" + Math.floor((time / 60000) % 60)
let minute = minu.slice(-2)
let sec = "0" + Math.floor((time / 1000) % 60)
let second = sec.slice(-2)
let mill = "0" + Math.floor((time / 10) % 100)
let millisecond = mill.slice(-2)
let total = `${minute}:${second}:${millisecond}`
//////USEeffect//////////
const stoptime = async (saveTimes) => {
const url = 'http://localhost:4000/api/post'
axios.post(url, {times: total})
.then(res => {
setSaveTimes([res.data])
})
.catch((erro) => {
console.log(erro)
})
setTime(0)
}
useEffect(() => {
let interval = null
if(start){
interval = setInterval(() => {
setTime(pTime => pTime + 10)
}, 10)
}else{
clearInterval(interval)
}
return () => clearInterval(interval)
}, [start])
return (
<div className="App">
<div className='timeNumber'>
<span id='minute' >{minute}:</span>
<span id='second' >{second}:</span>
<span id='millisecond' >{millisecond}</span>
</div>
<div className='bx'>
<div >
{!start && time === 0 && (
<a href='#' className='bxstart' onClick={() => setStart(true)}><h3>START</h3></a>
)}
</div>
<div>
{start && (
<a href='#' className='bxpause' onClick={() => setStart(false)}><h3>PAUSE</h3></a>
)}
</div>
<div>
{!start && time !== 0 && (
<a href='#' className='bxresumen' onClick={() => setStart(true)}>RESUMEN</a>
)}
</div>
<div >
{!start && (
<a href='#' className='bxstop' onClick={stoptime}><h3>STOP</h3></a>
)}
</div>
</div>
</div>
);
}
export default Chronometer;
|
#!/bin/bash
mysql -u user1 -pTest623@! <<MY_QUERY
use testdb;
desc Authors;
MY_QUERY
|
-- Deploy authed_buildings:init to pg
BEGIN;
CREATE USER service_user with encrypted password '<PASSWORD>';
GRANT ALL PRIVILEGES ON DATABASE buildings_db TO service_user;
ALTER DEFAULT PRIVILEGES IN SCHEMA public GRANT ALL PRIVILEGES ON TABLES TO service_user;
-- Base definition of an account. Authentication records reference this object.
CREATE TABLE accounts (
id SERIAL PRIMARY KEY,
name VARCHAR NOT NULL,
login_enabled BOOLEAN NOT NULL DEFAULT TRUE
);
-- Auth records for Google OAuth
CREATE TABLE accounts_google (
id SERIAL PRIMARY KEY,
account_id INTEGER REFERENCES accounts(id),
name VARCHAR NOT NULL,
email VARCHAR NOT NULL
);
-- Hash generation type for standard authentication. This just denotes versions of
-- hashing strategies, which makes it useful for tracking credential migrations.
CREATE TYPE hash_gen AS ENUM (
'gen_0',
'gen_1'
);
-- Auth records for "Standard" authentication, using a traditional username/password.
CREATE TABLE accounts_standard (
id SERIAL PRIMARY KEY,
account_id INTEGER REFERENCES accounts(id) UNIQUE,
username VARCHAR NOT NULL UNIQUE,
password VARCHAR NOT NULL,
compromised BOOLEAN NOT NULL,
hash_gen hash_gen NOT NULL
);
COMMIT;
|
# Treechop
python ppo.py --gpu 0 --env MineRLTreechop-v0 --outdir results/MineRLTreechop-v0/ppo --arch nature --update-interval 1024 --monitor --lr 0.00025 --frame-stack 4 --frame-skip 4 --gamma 0.99 --epochs 3 --always-keys attack --reverse-keys forward --exclude-keys back left right sneak sprint
# # Navigate
# python3 ppo.py \
# --gpu 0 --env MineRLNavigate-v0 --outdir results/MineRLNavigate-v0/ppo \
# --arch nature --update-interval 1024 --monitor --lr 0.00025 --frame-stack 4 --frame-skip 4 --gamma 0.99 --epochs 3 \
# --always-keys forward sprint attack --exclude-keys back left right sneak place
# # NavigateDense
# python3 ppo.py \
# --gpu 0 --env MineRLNavigateDense-v0 --outdir results/MineRLNavigateDense-v0/ppo \
# --arch nature --update-interval 1024 --monitor --lr 0.00025 --frame-stack 4 --frame-skip 4 --gamma 0.99 --epochs 3 \
# --always-keys forward sprint attack --exclude-keys back left right sneak place
# # ObtainDiamond
# python3 ppo.py \
# --gpu 0 --env MineRLObtainDiamond-v0 --outdir results/MineRLObtainDiamond-v0/20190701_v17/check_ppo \
# --arch nature --update-interval 1024 --monitor --lr 0.00025 --frame-stack 4 --frame-skip 4 --gamma 0.99 --epochs 3 \
# --disable-action-prior
|
# Pure
# by Sindre Sorhus
# https://github.com/sindresorhus/pure
# MIT License
# For my own and others sanity
# git:
# %b => current branch
# %a => current action (rebase/merge)
# prompt:
# %F => color dict
# %f => reset color
# %~ => current path
# %* => time
# %n => username
# %m => shortname host
# %(?..) => prompt conditional - %(condition.true.false)
# terminal codes:
# \e7 => save cursor position
# \e[2A => move cursor 2 lines up
# \e[1G => go to position 1 in terminal
# \e8 => restore cursor position
# \e[K => clears everything after the cursor on the current line
# \e[2K => clear everything on the current line
# Turns seconds into human readable time.
# 165392 => 1d 21h 56m 32s
# https://github.com/sindresorhus/pretty-time-zsh
prompt_pure_human_time_to_var() {
local human total_seconds=$1 var=$2
local days=$(( total_seconds / 60 / 60 / 24 ))
local hours=$(( total_seconds / 60 / 60 % 24 ))
local minutes=$(( total_seconds / 60 % 60 ))
local seconds=$(( total_seconds % 60 ))
(( days > 0 )) && human+="${days}d "
(( hours > 0 )) && human+="${hours}h "
(( minutes > 0 )) && human+="${minutes}m "
human+="${seconds}s"
# Store human readable time in a variable as specified by the caller
typeset -g "${var}"="${human}"
}
# Stores (into prompt_pure_cmd_exec_time) the execution
# time of the last command if set threshold was exceeded.
prompt_pure_check_cmd_exec_time() {
integer elapsed
(( elapsed = EPOCHSECONDS - ${prompt_pure_cmd_timestamp:-$EPOCHSECONDS} ))
typeset -g prompt_pure_cmd_exec_time=
(( elapsed > ${PURE_CMD_MAX_EXEC_TIME:-5} )) && {
prompt_pure_human_time_to_var $elapsed "prompt_pure_cmd_exec_time"
}
}
prompt_pure_set_title() {
setopt localoptions noshwordsplit
# Emacs terminal does not support settings the title.
(( ${+EMACS} || ${+INSIDE_EMACS} )) && return
case $TTY in
# Don't set title over serial console.
/dev/ttyS[0-9]*) return;;
esac
# Show hostname if connected via SSH.
local hostname=
if [[ -n $prompt_pure_state[username] ]]; then
# Expand in-place in case ignore-escape is used.
hostname="${(%):-(%m) }"
fi
local -a opts
case $1 in
expand-prompt) opts=(-P);;
ignore-escape) opts=(-r);;
esac
# Set title atomically in one print statement so that it works when XTRACE is enabled.
print -n $opts $'\e]0;'${hostname}${2}$'\a'
}
prompt_pure_preexec() {
if [[ -n $prompt_pure_git_fetch_pattern ]]; then
# Detect when Git is performing pull/fetch, including Git aliases.
local -H MATCH MBEGIN MEND match mbegin mend
if [[ $2 =~ (git|hub)\ (.*\ )?($prompt_pure_git_fetch_pattern)(\ .*)?$ ]]; then
# We must flush the async jobs to cancel our git fetch in order
# to avoid conflicts with the user issued pull / fetch.
async_flush_jobs 'prompt_pure'
fi
fi
typeset -g prompt_pure_cmd_timestamp=$EPOCHSECONDS
# Shows the current directory and executed command in the title while a process is active.
prompt_pure_set_title 'ignore-escape' "$PWD:t: $2"
# Disallow Python virtualenv from updating the prompt. Set it to 12 if
# untouched by the user to indicate that Pure modified it. Here we use
# the magic number 12, same as in `psvar`.
export VIRTUAL_ENV_DISABLE_PROMPT=${VIRTUAL_ENV_DISABLE_PROMPT:-12}
}
# Change the colors if their value are different from the current ones.
prompt_pure_set_colors() {
local color_temp key value
for key value in ${(kv)prompt_pure_colors}; do
zstyle -t ":prompt:pure:$key" color "$value"
case $? in
1) # The current style is different from the one from zstyle.
zstyle -s ":prompt:pure:$key" color color_temp
prompt_pure_colors[$key]=$color_temp ;;
2) # No style is defined.
prompt_pure_colors[$key]=$prompt_pure_colors_default[$key] ;;
esac
done
}
prompt_pure_preprompt_render() {
setopt localoptions noshwordsplit
unset prompt_pure_async_render_requested
# Set color for Git branch/dirty status and change color if dirty checking has been delayed.
local git_color=$prompt_pure_colors[git:branch]
local git_dirty_color=$prompt_pure_colors[git:dirty]
[[ -n ${prompt_pure_git_last_dirty_check_timestamp+x} ]] && git_color=$prompt_pure_colors[git:branch:cached]
# Initialize the preprompt array.
local -a preprompt_parts
# Add Prompt symbol
local prompt_indicator='%(?.%F{$prompt_pure_colors[prompt:success]}.%F{$prompt_pure_colors[prompt:error]})${prompt_pure_state[prompt]}%f'
preprompt_parts+=$prompt_indicator
# Username and machine, if applicable.
[[ -n $prompt_pure_state[username] ]] && preprompt_parts+=($prompt_pure_state[username])
# Set the path %1~ = CWD (%~ = fullpath).
preprompt_parts+=('%F{${prompt_pure_colors[path]}}%1~%f')
# Git branch and dirty status info.
local -a preprompt_parts_git
typeset -gA prompt_pure_vcs_info
if [[ -n $prompt_pure_vcs_info[branch] ]]; then
preprompt_parts_git+=("%F{$git_color}"'${prompt_pure_vcs_info[branch]}'"%F{$git_dirty_color}"'${prompt_pure_git_dirty}%f')
fi
# Git action (for example, merge).
if [[ -n $prompt_pure_vcs_info[action] ]]; then
preprompt_parts_git+=("%F{$prompt_pure_colors[git:action]}"'$prompt_pure_vcs_info[action]%f')
fi
# Git pull/push arrows.
if [[ -n $prompt_pure_git_arrows ]]; then
preprompt_parts_git+=('%F{$prompt_pure_colors[git:arrow]}${prompt_pure_git_arrows}%f')
fi
# Git stash symbol (if opted in).
if [[ -n $prompt_pure_git_stash ]]; then
preprompt_parts_git+=('%F{$prompt_pure_colors[git:stash]}${PURE_GIT_STASH_SYMBOL:-โก}%f')
fi
preprompt_parts+=(${(j..)preprompt_parts_git})
# Execution time.
[[ -n $prompt_pure_cmd_exec_time ]] && preprompt_parts+=('%F{$prompt_pure_colors[execution_time]}${prompt_pure_cmd_exec_time}%f')
local cleaned_ps1=$PROMPT
local -H MATCH MBEGIN MEND
if [[ $PROMPT = *$prompt_newline* ]]; then
# Remove everything from the prompt until the newline. This
# removes the preprompt and only the original PROMPT remains.
cleaned_ps1=${PROMPT##*${prompt_newline}}
fi
unset MATCH MBEGIN MEND
# Construct the new prompt with a clean preprompt.
local -ah ps1
ps1=(
${(j. .)preprompt_parts} # Join parts, space separated.
# $prompt_newline # Separate preprompt and prompt.
# $cleaned_ps1
)
PROMPT="${(j..)ps1} "
# Expand the prompt for future comparision.
local expanded_prompt
expanded_prompt="${(S%%)PROMPT}"
if [[ $1 == precmd ]]; then
# Initial newline, for spaciousness.
# print
elif [[ $prompt_pure_last_prompt != $expanded_prompt ]]; then
# Redraw the prompt.
prompt_pure_reset_prompt
fi
typeset -g prompt_pure_last_prompt=$expanded_prompt
}
prompt_pure_precmd() {
setopt localoptions noshwordsplit
# Check execution time and store it in a variable.
prompt_pure_check_cmd_exec_time
unset prompt_pure_cmd_timestamp
# Shows the full path in the title.
prompt_pure_set_title 'expand-prompt' '%~'
# Modify the colors if some have changed..
prompt_pure_set_colors
# Perform async Git dirty check and fetch.
prompt_pure_async_tasks
# Check if we should display the virtual env. We use a sufficiently high
# index of psvar (12) here to avoid collisions with user defined entries.
psvar[12]=
# Check if a Conda environment is active and display its name.
if [[ -n $CONDA_DEFAULT_ENV ]]; then
psvar[12]="${CONDA_DEFAULT_ENV//[$'\t\r\n']}"
fi
# When VIRTUAL_ENV_DISABLE_PROMPT is empty, it was unset by the user and
# Pure should take back control.
if [[ -n $VIRTUAL_ENV ]] && [[ -z $VIRTUAL_ENV_DISABLE_PROMPT || $VIRTUAL_ENV_DISABLE_PROMPT = 12 ]]; then
psvar[12]="${VIRTUAL_ENV:t}"
export VIRTUAL_ENV_DISABLE_PROMPT=12
fi
# Make sure VIM prompt is reset.
prompt_pure_reset_prompt_symbol
# Print the preprompt.
prompt_pure_preprompt_render "precmd"
if [[ -n $ZSH_THEME ]]; then
print "WARNING: Oh My Zsh themes are enabled (ZSH_THEME='${ZSH_THEME}'). Pure might not be working correctly."
print "For more information, see: https://github.com/sindresorhus/pure#oh-my-zsh"
unset ZSH_THEME # Only show this warning once.
fi
}
prompt_pure_async_git_aliases() {
setopt localoptions noshwordsplit
local -a gitalias pullalias
# List all aliases and split on newline.
gitalias=(${(@f)"$(command git config --get-regexp "^alias\.")"})
for line in $gitalias; do
parts=(${(@)=line}) # Split line on spaces.
aliasname=${parts[1]#alias.} # Grab the name (alias.[name]).
shift parts # Remove `aliasname`
# Check alias for pull or fetch. Must be exact match.
if [[ $parts =~ ^(.*\ )?(pull|fetch)(\ .*)?$ ]]; then
pullalias+=($aliasname)
fi
done
print -- ${(j:|:)pullalias} # Join on pipe, for use in regex.
}
prompt_pure_async_vcs_info() {
setopt localoptions noshwordsplit
# Configure `vcs_info` inside an async task. This frees up `vcs_info`
# to be used or configured as the user pleases.
zstyle ':vcs_info:*' enable git
zstyle ':vcs_info:*' use-simple true
# Only export four message variables from `vcs_info`.
zstyle ':vcs_info:*' max-exports 3
# Export branch (%b), Git toplevel (%R), action (rebase/cherry-pick) (%a)
zstyle ':vcs_info:git*' formats '%b' '%R' '%a'
zstyle ':vcs_info:git*' actionformats '%b' '%R' '%a'
vcs_info
local -A info
info[pwd]=$PWD
info[branch]=$vcs_info_msg_0_
info[top]=$vcs_info_msg_1_
info[action]=$vcs_info_msg_2_
print -r - ${(@kvq)info}
}
# Fastest possible way to check if a Git repo is dirty.
prompt_pure_async_git_dirty() {
setopt localoptions noshwordsplit
local untracked_dirty=$1
local untracked_git_mode=$(command git config --get status.showUntrackedFiles)
if [[ "$untracked_git_mode" != 'no' ]]; then
untracked_git_mode='normal'
fi
if [[ $untracked_dirty = 0 ]]; then
command git diff --no-ext-diff --quiet --exit-code
else
test -z "$(GIT_OPTIONAL_LOCKS=0 command git status --porcelain --ignore-submodules -u${untracked_git_mode})"
fi
return $?
}
prompt_pure_async_git_fetch() {
setopt localoptions noshwordsplit
local only_upstream=${1:-0}
# Sets `GIT_TERMINAL_PROMPT=0` to disable authentication prompt for Git fetch (Git 2.3+).
export GIT_TERMINAL_PROMPT=0
# Set SSH `BachMode` to disable all interactive SSH password prompting.
export GIT_SSH_COMMAND="${GIT_SSH_COMMAND:-"ssh"} -o BatchMode=yes"
local -a remote
if ((only_upstream)); then
local ref
ref=$(command git symbolic-ref -q HEAD)
# Set remote to only fetch information for the current branch.
remote=($(command git for-each-ref --format='%(upstream:remotename) %(refname)' $ref))
if [[ -z $remote[1] ]]; then
# No remote specified for this branch, skip fetch.
return 97
fi
fi
# Default return code, which indicates Git fetch failure.
local fail_code=99
# Guard against all forms of password prompts. By setting the shell into
# MONITOR mode we can notice when a child process prompts for user input
# because it will be suspended. Since we are inside an async worker, we
# have no way of transmitting the password and the only option is to
# kill it. If we don't do it this way, the process will corrupt with the
# async worker.
setopt localtraps monitor
# Make sure local HUP trap is unset to allow for signal propagation when
# the async worker is flushed.
trap - HUP
trap '
# Unset trap to prevent infinite loop
trap - CHLD
if [[ $jobstates = suspended* ]]; then
# Set fail code to password prompt and kill the fetch.
fail_code=98
kill %%
fi
' CHLD
# Do git fetch and avoid fetching tags or
# submodules to speed up the process.
command git -c gc.auto=0 fetch \
--quiet \
--no-tags \
--recurse-submodules=no \
$remote &>/dev/null &
wait $! || return $fail_code
unsetopt monitor
# Check arrow status after a successful `git fetch`.
prompt_pure_async_git_arrows
}
prompt_pure_async_git_arrows() {
setopt localoptions noshwordsplit
command git rev-list --left-right --count HEAD...@'{u}'
}
prompt_pure_async_git_stash() {
git rev-list --walk-reflogs --count refs/stash
}
# Try to lower the priority of the worker so that disk heavy operations
# like `git status` has less impact on the system responsivity.
prompt_pure_async_renice() {
setopt localoptions noshwordsplit
if command -v renice >/dev/null; then
command renice +15 -p $$
fi
if command -v ionice >/dev/null; then
command ionice -c 3 -p $$
fi
}
prompt_pure_async_init() {
typeset -g prompt_pure_async_inited
if ((${prompt_pure_async_inited:-0})); then
return
fi
prompt_pure_async_inited=1
async_start_worker "prompt_pure" -u -n
async_register_callback "prompt_pure" prompt_pure_async_callback
async_worker_eval "prompt_pure" prompt_pure_async_renice
}
prompt_pure_async_tasks() {
setopt localoptions noshwordsplit
# Initialize the async worker.
prompt_pure_async_init
# Update the current working directory of the async worker.
async_worker_eval "prompt_pure" builtin cd -q $PWD
typeset -gA prompt_pure_vcs_info
local -H MATCH MBEGIN MEND
if [[ $PWD != ${prompt_pure_vcs_info[pwd]}* ]]; then
# Stop any running async jobs.
async_flush_jobs "prompt_pure"
# Reset Git preprompt variables, switching working tree.
unset prompt_pure_git_dirty
unset prompt_pure_git_last_dirty_check_timestamp
unset prompt_pure_git_arrows
unset prompt_pure_git_stash
unset prompt_pure_git_fetch_pattern
prompt_pure_vcs_info[branch]=
prompt_pure_vcs_info[top]=
fi
unset MATCH MBEGIN MEND
async_job "prompt_pure" prompt_pure_async_vcs_info
# Only perform tasks inside a Git working tree.
[[ -n $prompt_pure_vcs_info[top] ]] || return
prompt_pure_async_refresh
}
prompt_pure_async_refresh() {
setopt localoptions noshwordsplit
if [[ -z $prompt_pure_git_fetch_pattern ]]; then
# We set the pattern here to avoid redoing the pattern check until the
# working tree has changed. Pull and fetch are always valid patterns.
typeset -g prompt_pure_git_fetch_pattern="pull|fetch"
async_job "prompt_pure" prompt_pure_async_git_aliases
fi
async_job "prompt_pure" prompt_pure_async_git_arrows
# Do not perform `git fetch` if it is disabled or in home folder.
if (( ${PURE_GIT_PULL:-1} )) && [[ $prompt_pure_vcs_info[top] != $HOME ]]; then
zstyle -t :prompt:pure:git:fetch only_upstream
local only_upstream=$((? == 0))
async_job "prompt_pure" prompt_pure_async_git_fetch $only_upstream
fi
# If dirty checking is sufficiently fast,
# tell the worker to check it again, or wait for timeout.
integer time_since_last_dirty_check=$(( EPOCHSECONDS - ${prompt_pure_git_last_dirty_check_timestamp:-0} ))
if (( time_since_last_dirty_check > ${PURE_GIT_DELAY_DIRTY_CHECK:-1800} )); then
unset prompt_pure_git_last_dirty_check_timestamp
# Check check if there is anything to pull.
async_job "prompt_pure" prompt_pure_async_git_dirty ${PURE_GIT_UNTRACKED_DIRTY:-1}
fi
# If stash is enabled, tell async worker to count stashes
if zstyle -t ":prompt:pure:git:stash" show; then
async_job "prompt_pure" prompt_pure_async_git_stash
else
unset prompt_pure_git_stash
fi
}
prompt_pure_check_git_arrows() {
setopt localoptions noshwordsplit
local arrows left=${1:-0} right=${2:-0}
(( right > 0 )) && arrows+=${PURE_GIT_DOWN_ARROW:-โฃ}
(( left > 0 )) && arrows+=${PURE_GIT_UP_ARROW:-โก}
[[ -n $arrows ]] || return
typeset -g REPLY=$arrows
}
prompt_pure_async_callback() {
setopt localoptions noshwordsplit
local job=$1 code=$2 output=$3 exec_time=$4 next_pending=$6
local do_render=0
case $job in
\[async])
# Handle all the errors that could indicate a crashed
# async worker. See zsh-async documentation for the
# definition of the exit codes.
if (( code == 2 )) || (( code == 3 )) || (( code == 130 )); then
# Our worker died unexpectedly, try to recover immediately.
# TODO(mafredri): Do we need to handle next_pending
# and defer the restart?
typeset -g prompt_pure_async_inited=0
async_stop_worker prompt_pure
prompt_pure_async_init # Reinit the worker.
prompt_pure_async_tasks # Restart all tasks.
# Reset render state due to restart.
unset prompt_pure_async_render_requested
fi
;;
\[async/eval])
if (( code )); then
# Looks like async_worker_eval failed,
# rerun async tasks just in case.
prompt_pure_async_tasks
fi
;;
prompt_pure_async_vcs_info)
local -A info
typeset -gA prompt_pure_vcs_info
# Parse output (z) and unquote as array (Q@).
info=("${(Q@)${(z)output}}")
local -H MATCH MBEGIN MEND
if [[ $info[pwd] != $PWD ]]; then
# The path has changed since the check started, abort.
return
fi
# Check if Git top-level has changed.
if [[ $info[top] = $prompt_pure_vcs_info[top] ]]; then
# If the stored pwd is part of $PWD, $PWD is shorter and likelier
# to be top-level, so we update pwd.
if [[ $prompt_pure_vcs_info[pwd] = ${PWD}* ]]; then
prompt_pure_vcs_info[pwd]=$PWD
fi
else
# Store $PWD to detect if we (maybe) left the Git path.
prompt_pure_vcs_info[pwd]=$PWD
fi
unset MATCH MBEGIN MEND
# The update has a Git top-level set, which means we just entered a new
# Git directory. Run the async refresh tasks.
[[ -n $info[top] ]] && [[ -z $prompt_pure_vcs_info[top] ]] && prompt_pure_async_refresh
# Always update branch, top-level and stash.
prompt_pure_vcs_info[branch]=$info[branch]
prompt_pure_vcs_info[top]=$info[top]
prompt_pure_vcs_info[action]=$info[action]
do_render=1
;;
prompt_pure_async_git_aliases)
if [[ -n $output ]]; then
# Append custom Git aliases to the predefined ones.
prompt_pure_git_fetch_pattern+="|$output"
fi
;;
prompt_pure_async_git_dirty)
local prev_dirty=$prompt_pure_git_dirty
if (( code == 0 )); then
unset prompt_pure_git_dirty
else
typeset -g prompt_pure_git_dirty="*"
fi
[[ $prev_dirty != $prompt_pure_git_dirty ]] && do_render=1
# When `prompt_pure_git_last_dirty_check_timestamp` is set, the Git info is displayed
# in a different color. To distinguish between a "fresh" and a "cached" result, the
# preprompt is rendered before setting this variable. Thus, only upon the next
# rendering of the preprompt will the result appear in a different color.
(( $exec_time > 5 )) && prompt_pure_git_last_dirty_check_timestamp=$EPOCHSECONDS
;;
prompt_pure_async_git_fetch|prompt_pure_async_git_arrows)
# `prompt_pure_async_git_fetch` executes `prompt_pure_async_git_arrows`
# after a successful fetch.
case $code in
0)
local REPLY
prompt_pure_check_git_arrows ${(ps:\t:)output}
if [[ $prompt_pure_git_arrows != $REPLY ]]; then
typeset -g prompt_pure_git_arrows=$REPLY
do_render=1
fi
;;
97)
# No remote available, make sure to clear git arrows if set.
if [[ -n $prompt_pure_git_arrows ]]; then
typeset -g prompt_pure_git_arrows=
do_render=1
fi
;;
99|98)
# Git fetch failed.
;;
*)
# Non-zero exit status from `prompt_pure_async_git_arrows`,
# indicating that there is no upstream configured.
if [[ -n $prompt_pure_git_arrows ]]; then
unset prompt_pure_git_arrows
do_render=1
fi
;;
esac
;;
prompt_pure_async_git_stash)
local prev_stash=$prompt_pure_git_stash
typeset -g prompt_pure_git_stash=$output
[[ $prev_stash != $prompt_pure_git_stash ]] && do_render=1
;;
esac
if (( next_pending )); then
(( do_render )) && typeset -g prompt_pure_async_render_requested=1
return
fi
[[ ${prompt_pure_async_render_requested:-$do_render} = 1 ]] && prompt_pure_preprompt_render
unset prompt_pure_async_render_requested
}
prompt_pure_reset_prompt() {
if [[ $CONTEXT == cont ]]; then
# When the context is "cont", PS2 is active and calling
# reset-prompt will have no effect on PS1, but it will
# reset the execution context (%_) of PS2 which we don't
# want. Unfortunately, we can't save the output of "%_"
# either because it is only ever rendered as part of the
# prompt, expanding in-place won't work.
return
fi
zle && zle .reset-prompt
}
prompt_pure_reset_prompt_symbol() {
prompt_pure_state[prompt]=${PURE_PROMPT_SYMBOL:-โฏ}
}
prompt_pure_update_vim_prompt_widget() {
setopt localoptions noshwordsplit
prompt_pure_state[prompt]=${${KEYMAP/vicmd/${PURE_PROMPT_VICMD_SYMBOL:-โฎ}}/(main|viins)/${PURE_PROMPT_SYMBOL:-โฏ}}
prompt_pure_reset_prompt
}
prompt_pure_reset_vim_prompt_widget() {
setopt localoptions noshwordsplit
prompt_pure_reset_prompt_symbol
# We can't perform a prompt reset at this point because it
# removes the prompt marks inserted by macOS Terminal.
}
prompt_pure_state_setup() {
setopt localoptions noshwordsplit
# Check SSH_CONNECTION and the current state.
local ssh_connection=${SSH_CONNECTION:-$PROMPT_PURE_SSH_CONNECTION}
local username hostname
if [[ -z $ssh_connection ]] && (( $+commands[who] )); then
# When changing user on a remote system, the $SSH_CONNECTION
# environment variable can be lost. Attempt detection via `who`.
local who_out
who_out=$(who -m 2>/dev/null)
if (( $? )); then
# Who am I not supported, fallback to plain who.
local -a who_in
who_in=( ${(f)"$(who 2>/dev/null)"} )
who_out="${(M)who_in:#*[[:space:]]${TTY#/dev/}[[:space:]]*}"
fi
local reIPv6='(([0-9a-fA-F]+:)|:){2,}[0-9a-fA-F]+' # Simplified, only checks partial pattern.
local reIPv4='([0-9]{1,3}\.){3}[0-9]+' # Simplified, allows invalid ranges.
# Here we assume two non-consecutive periods represents a
# hostname. This matches `foo.bar.baz`, but not `foo.bar`.
local reHostname='([.][^. ]+){2}'
# Usually the remote address is surrounded by parenthesis, but
# not on all systems (e.g. busybox).
local -H MATCH MBEGIN MEND
if [[ $who_out =~ "\(?($reIPv4|$reIPv6|$reHostname)\)?\$" ]]; then
ssh_connection=$MATCH
# Export variable to allow detection propagation inside
# shells spawned by this one (e.g. tmux does not always
# inherit the same tty, which breaks detection).
export PROMPT_PURE_SSH_CONNECTION=$ssh_connection
fi
unset MATCH MBEGIN MEND
fi
hostname='%F{$prompt_pure_colors[host]}@%m%f'
# Show `username@host` if logged in through SSH.
[[ -n $ssh_connection ]] && username='%F{$prompt_pure_colors[user]}%n%f'"$hostname"
# Show `username@host` if inside a container.
prompt_pure_is_inside_container && username='%F{$prompt_pure_colors[user]}%n%f'"$hostname"
# Show `username@host` if root, with username in default color.
[[ $UID -eq 0 ]] && username='%F{$prompt_pure_colors[user:root]}%n%f'"$hostname"
typeset -gA prompt_pure_state
prompt_pure_state[version]="1.13.0"
prompt_pure_state+=(
username "$username"
prompt "${PURE_PROMPT_SYMBOL:-โฏ}"
)
}
# Return true if executing inside a Docker or LXC container.
prompt_pure_is_inside_container() {
local -r cgroup_file='/proc/1/cgroup'
[[ -r "$cgroup_file" && "$(< $cgroup_file)" = *(lxc|docker)* ]] \
|| [[ "$container" == "lxc" ]]
}
prompt_pure_system_report() {
setopt localoptions noshwordsplit
local shell=$SHELL
if [[ -z $shell ]]; then
shell=$commands[zsh]
fi
print - "- Zsh: $($shell --version) ($shell)"
print -n - "- Operating system: "
case "$(uname -s)" in
Darwin) print "$(sw_vers -productName) $(sw_vers -productVersion) ($(sw_vers -buildVersion))";;
*) print "$(uname -s) ($(uname -r) $(uname -v) $(uname -m) $(uname -o))";;
esac
print - "- Terminal program: ${TERM_PROGRAM:-unknown} (${TERM_PROGRAM_VERSION:-unknown})"
print -n - "- Tmux: "
[[ -n $TMUX ]] && print "yes" || print "no"
local git_version
git_version=($(git --version)) # Remove newlines, if hub is present.
print - "- Git: $git_version"
print - "- Pure state:"
for k v in "${(@kv)prompt_pure_state}"; do
print - " - $k: \`${(q-)v}\`"
done
print - "- zsh-async version: \`${ASYNC_VERSION}\`"
print - "- PROMPT: \`$(typeset -p PROMPT)\`"
print - "- Colors: \`$(typeset -p prompt_pure_colors)\`"
print - "- TERM: \`$(typeset -p TERM)\`"
print - "- Virtualenv: \`$(typeset -p VIRTUAL_ENV_DISABLE_PROMPT)\`"
print - "- Conda: \`$(typeset -p CONDA_CHANGEPS1)\`"
local ohmyzsh=0
typeset -la frameworks
(( $+ANTIBODY_HOME )) && frameworks+=("Antibody")
(( $+ADOTDIR )) && frameworks+=("Antigen")
(( $+ANTIGEN_HS_HOME )) && frameworks+=("Antigen-hs")
(( $+functions[upgrade_oh_my_zsh] )) && {
ohmyzsh=1
frameworks+=("Oh My Zsh")
}
(( $+ZPREZTODIR )) && frameworks+=("Prezto")
(( $+ZPLUG_ROOT )) && frameworks+=("Zplug")
(( $+ZPLGM )) && frameworks+=("Zplugin")
(( $#frameworks == 0 )) && frameworks+=("None")
print - "- Detected frameworks: ${(j:, :)frameworks}"
if (( ohmyzsh )); then
print - " - Oh My Zsh:"
print - " - Plugins: ${(j:, :)plugins}"
fi
}
prompt_pure_setup() {
# Prevent percentage showing up if output doesn't end with a newline.
export PROMPT_EOL_MARK=''
prompt_opts=(subst percent)
# Borrowed from `promptinit`. Sets the prompt options in case Pure was not
# initialized via `promptinit`.
setopt noprompt{bang,cr,percent,subst} "prompt${^prompt_opts[@]}"
if [[ -z $prompt_newline ]]; then
# This variable needs to be set, usually set by promptinit.
typeset -g prompt_newline=$'\n%{\r%}'
fi
zmodload zsh/datetime
zmodload zsh/zle
zmodload zsh/parameter
zmodload zsh/zutil
autoload -Uz add-zsh-hook
autoload -Uz vcs_info
autoload -Uz async && async
# The `add-zle-hook-widget` function is not guaranteed to be available.
# It was added in Zsh 5.3.
autoload -Uz +X add-zle-hook-widget 2>/dev/null
# Set the colors.
typeset -gA prompt_pure_colors_default prompt_pure_colors
prompt_pure_colors_default=(
execution_time yellow
git:arrow cyan
git:stash cyan
git:branch 242
git:branch:cached red
git:action yellow
git:dirty 218
host 242
path blue
prompt:error red
prompt:success magenta
prompt:continuation 242
user 242
user:root default
virtualenv 242
)
prompt_pure_colors=("${(@kv)prompt_pure_colors_default}")
add-zsh-hook precmd prompt_pure_precmd
add-zsh-hook preexec prompt_pure_preexec
prompt_pure_state_setup
zle -N prompt_pure_reset_prompt
zle -N prompt_pure_update_vim_prompt_widget
zle -N prompt_pure_reset_vim_prompt_widget
if (( $+functions[add-zle-hook-widget] )); then
add-zle-hook-widget zle-line-finish prompt_pure_reset_vim_prompt_widget
add-zle-hook-widget zle-keymap-select prompt_pure_update_vim_prompt_widget
fi
# If a virtualenv is activated, display it in grey.
PROMPT='%(12V.%F{$prompt_pure_colors[virtualenv]}%12v%f .)'
# Prompt turns red if the previous command didn't exit with 0.
local prompt_indicator='%(?.%F{$prompt_pure_colors[prompt:success]}.%F{$prompt_pure_colors[prompt:error]})${prompt_pure_state[prompt]}%f '
PROMPT+=$prompt_indicator
# Indicate continuation prompt by โฆ and use a darker color for it.
PROMPT2='%F{$prompt_pure_colors[prompt:continuation]}โฆ %(1_.%_ .%_)%f'$prompt_indicator
# Store prompt expansion symbols for in-place expansion via (%). For
# some reason it does not work without storing them in a variable first.
typeset -ga prompt_pure_debug_depth
prompt_pure_debug_depth=('%e' '%N' '%x')
# Compare is used to check if %N equals %x. When they differ, the main
# prompt is used to allow displaying both filename and function. When
# they match, we use the secondary prompt to avoid displaying duplicate
# information.
local -A ps4_parts
ps4_parts=(
depth '%F{yellow}${(l:${(%)prompt_pure_debug_depth[1]}::+:)}%f'
compare '${${(%)prompt_pure_debug_depth[2]}:#${(%)prompt_pure_debug_depth[3]}}'
main '%F{blue}${${(%)prompt_pure_debug_depth[3]}:t}%f%F{242}:%I%f %F{242}@%f%F{blue}%N%f%F{242}:%i%f'
secondary '%F{blue}%N%f%F{242}:%i'
prompt '%F{242}>%f '
)
# Combine the parts with conditional logic. First the `:+` operator is
# used to replace `compare` either with `main` or an ampty string. Then
# the `:-` operator is used so that if `compare` becomes an empty
# string, it is replaced with `secondary`.
local ps4_symbols='${${'${ps4_parts[compare]}':+"'${ps4_parts[main]}'"}:-"'${ps4_parts[secondary]}'"}'
# Improve the debug prompt (PS4), show depth by repeating the +-sign and
# add colors to highlight essential parts like file and function name.
PROMPT4="${ps4_parts[depth]} ${ps4_symbols}${ps4_parts[prompt]}"
# Guard against Oh My Zsh themes overriding Pure.
unset ZSH_THEME
# Guard against (ana)conda changing the PS1 prompt
# (we manually insert the env when it's available).
export CONDA_CHANGEPS1=no
}
prompt_pure_setup "$@"
|
--
-- patch-pl-tl-il-unique-index.sql
--
-- Make reorderings of UNIQUE indices UNIQUE as well
DROP INDEX /*i*/pl_namespace ON /*_*/pagelinks;
CREATE UNIQUE INDEX /*i*/pl_namespace ON /*_*/pagelinks (pl_namespace, pl_title, pl_from);
DROP INDEX /*i*/tl_namespace ON /*_*/templatelinks;
CREATE UNIQUE INDEX /*i*/tl_namespace ON /*_*/templatelinks (tl_namespace, tl_title, tl_from);
DROP INDEX /*i*/il_to ON /*_*/imagelinks;
CREATE UNIQUE INDEX /*i*/il_to ON /*_*/imagelinks (il_to, il_from);
|
from typing import List
def calculate_total_duration(durations: List[str]) -> int:
total_seconds = 0
for duration in durations:
try:
hours, minutes, seconds = map(int, duration.split(':'))
if hours >= 0 and minutes >= 0 and seconds >= 0:
total_seconds += hours * 3600 + minutes * 60 + seconds
except (ValueError, IndexError):
continue
return total_seconds
|
<gh_stars>10-100
function(page, done) {
return done(this.createResult('TEST', '%API_KEY%', 'info'));
}
|
<gh_stars>0
package atas.logic.commands.atas;
import static java.util.Objects.requireNonNull;
import atas.logic.commands.Command;
import atas.logic.commands.CommandResult;
import atas.logic.commands.exceptions.CommandException;
import atas.model.Model;
import atas.ui.Tab;
//Solution of SwitchCommand and its related classes/methods was inspired by
//https://github.com/AY1920S2-CS2103T-T10-1/main/blob/master/src/main/
//java/seedu/recipe/logic/commands/common/SwitchCommand.java
//with a slightly different implementation.
/**
* Switches tabs using the name of the destination tab.
* Name of destination tab is case insensitive.
*/
public class SwitchCommand extends Command {
public static final String COMMAND_WORD = "switch";
public static final String MESSAGE_USAGE = COMMAND_WORD + ": Switches to the specified tab (case-insensitive).\n"
+ "Parameters: TAB_NAME (must be an existing tab)\n"
+ "Examples: "
+ COMMAND_WORD + " atas, "
+ COMMAND_WORD + " students, "
+ COMMAND_WORD + " sessions, "
+ COMMAND_WORD + " current, "
+ COMMAND_WORD + " memo";
public static final String MESSAGE_SWITCH_TAB_SUCCESS = "Switched to %1$s tab";
public static final String MESSAGE_INVALID_TAB = "Tab does not exist!";
public static final String MESSAGE_ALREADY_ON_TAB = "Already at %1$s tab!";
private final String tabName;
/**
* Constructs a SwitchCommand.
*
* @param tabName Name of the tab to switch to.
*/
public SwitchCommand(String tabName) {
this.tabName = tabName;
}
@Override
public CommandResult execute(Model model) throws CommandException {
Tab tab;
requireNonNull(tabName);
assert !tabName.equals("") : "tabName should not be empty.";
String trimmedTab = tabName.toLowerCase();
switch(trimmedTab) {
case "atas":
tab = Tab.ATAS;
break;
case "students":
tab = Tab.STUDENTS;
break;
case "sessions":
tab = Tab.SESSIONS;
break;
case "current":
tab = Tab.CURRENT;
break;
case "memo":
tab = Tab.MEMO;
break;
default:
throw new CommandException(MESSAGE_INVALID_TAB);
}
return new CommandResult(String.format(MESSAGE_SWITCH_TAB_SUCCESS, tab.toDisplayName()),
false, tab, false, false, false);
}
@Override
public boolean equals(Object other) {
return other == this // short circuit if same object
|| (other instanceof SwitchCommand // instanceof handles nulls
&& tabName.equals(((SwitchCommand) other).tabName)); // state check
}
}
|
<reponame>ArcheSpace/Arche.js
import { WGSLEncoder } from "../WGSLEncoder";
import { ShaderMacroCollection } from "../../shader";
export class WGSLCommon {
execute(encoder: WGSLEncoder, macros: ShaderMacroCollection) {
encoder.addStruct("let PI:f32 = 3.14159265359;\n");
encoder.addStruct("let RECIPROCAL_PI:f32 = 0.31830988618;\n");
encoder.addStruct("let EPSILON:f32 = 1.0e-6;\n");
encoder.addStruct("let LOG2:f32 = 1.442695;\n");
let source: string = "fn saturate(a:f32)->f32 { return clamp( a, 0.0, 1.0 );}\n";
source += "fn whiteCompliment(a:f32)->f32 { return 1.0 - saturate( a );}\n";
source += "fn RGBMToLinear(value: vec4<f32>, maxRange: f32)-> vec4<f32> {\n";
source += " return vec4<f32>( value.rgb * value.a * maxRange, 1.0 );\n";
source += "}\n";
source += "fn gammaToLinear(srgbIn: vec4<f32>)-> vec4<f32> {\n";
source += " return vec4<f32>( pow(srgbIn.rgb, vec3<f32>(2.2)), srgbIn.a);\n";
source += "}\n";
source += "fn linearToGamma(linearIn: vec4<f32>)-> vec4<f32> {\n";
source += " return vec4<f32>( pow(linearIn.rgb, vec3<f32>(1.0 / 2.2)), linearIn.a);\n";
source += "}\n";
encoder.addFunction(source);
}
}
|
#!/bin/sh
# Copyright (c) 2014 The Chromium OS Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
exec awk '
match($0, /m4_define\(\[qmi_(major|minor|micro)_version\], \[([0-9]+)\]\)/,
matches) { version[matches[1]] = matches[2] }
END { print version["major"] "." version["minor"] "." version["micro"] }' \
"$1/configure.ac"
|
def leastCommonAncestor(node1, node2):
#Returns the least common ancestor of two given nodes.
#Initializing the traverse pointer to root
current_node = root
#Loop until both nodes have been found
while node1 is not None and node2 is not None:
#Navigate left if both nodes are on the left
if node1.data < current_node.data and node2.data < current_node.data:
current_node = current_node.left
#Navigate right if both nodes are on the right
elif node1.data > current_node.data and node2.data > current_node.data:
current_node = current_node.right
#Return if we find the common ancestor
else:
return current_node
return None
|
package physical
import (
"github.com/jacobsimpson/mtsql/metadata"
)
type SortOrder string
const (
Asc SortOrder = "Asc"
Desc SortOrder = "Desc"
)
type SortScanCriteria struct {
Column *metadata.Column
SortOrder SortOrder
}
//func NewQueryPlan(q ast.Query) (RowReader, error) {
// var sfw *ast.SFW
// if p, ok := q.(*ast.Profile); ok {
// sfw = p.SFW
// } else if s, ok := q.(*ast.SFW); ok {
// sfw = s
// } else {
// return nil, fmt.Errorf("expected a select query, but got something else")
// }
//
// var rowReader RowReader
// if rel, ok := sfw.From.(*ast.Relation); ok {
// rr, err := NewTableScan(rel.Name, rel.Name+".csv")
// if err != nil {
// return nil, err
// }
// rowReader = rr
// } else if ij, ok := sfw.From.(*ast.InnerJoin); ok {
// left, err := NewTableScan(ij.Left.Name, ij.Left.Name+".csv")
// if err != nil {
// return nil, err
// }
// right, err := NewTableScan(ij.Right.Name, ij.Right.Name+".csv")
// if err != nil {
// return nil, err
// }
// rowReader, err = NewNestedLoopJoin(left, right)
// if err != nil {
// return nil, err
// }
// rowReader, err = NewColumnFilter(rowReader,
// &metadata.Column{
// Qualifier: ij.On.Left.Qualifier,
// Name: ij.On.Left.Name,
// },
// &metadata.Column{
// Qualifier: ij.On.Right.Qualifier,
// Name: ij.On.Right.Name,
// })
// if err != nil {
// return nil, err
// }
// } else {
// return nil, fmt.Errorf("expected a relation in the FROM clause, but got something else")
// }
//
// if sfw.OrderBy != nil {
// columns := []SortScanCriteria{}
// for _, c := range sfw.OrderBy.Criteria {
// sc := SortScanCriteria{
// Column: &metadata.Column{
// Qualifier: c.Attribute.Qualifier,
// Name: c.Attribute.Name,
// },
// SortOrder: Asc,
// }
// if c.SortOrder == ast.Desc {
// sc.SortOrder = Desc
// }
// columns = append(columns, sc)
// }
// rr, err := NewSortScan(rowReader, columns)
// if err != nil {
// return nil, err
// }
// rowReader = rr
// }
//
// if sfw.Where != nil {
// eq, ok := sfw.Where.(*ast.EqualCondition)
// if !ok {
// return nil, fmt.Errorf("only = conditions are currently supported")
// }
// rr, err := NewFilter(rowReader,
// &metadata.Column{Qualifier: eq.LHS.Qualifier, Name: eq.LHS.Name},
// eq.RHS)
// if err != nil {
// return nil, err
// }
// rowReader = rr
// }
//
// columns := []*metadata.Column{}
// for _, a := range sfw.SelList.Attributes {
// columns = append(columns, &metadata.Column{
// Qualifier: a.Qualifier,
// Name: a.Name,
// })
// }
// rr, err := NewProjection(rowReader, columns)
// if err != nil {
// return nil, err
// }
// rowReader = rr
//
// return rowReader, nil
//}
|
#ifdef NOARDUINO
#ifndef DummyPort_h
#define DummyPort_h
#include <iterator>
#include <vector>
#include "Types.h"
class Port {
private:
vector<byte> _buffer;
string _serial;
public:
Port(string serial);
Port();
int id;
void read();
void write(vector<char> serializedPacket);
packet_t getPacketFromBuffer();
};
#endif
#endif
|
<filename>package/spack-autogen/package.py
##############################################################################
# Copyright (c) 2013-2018, Lawrence Livermore National Security, LLC.
# Produced at the Lawrence Livermore National Laboratory.
#
# This file is part of Spack.
# Created by <NAME>, <EMAIL>, All rights reserved.
# LLNL-CODE-647188
#
# For details, see https://github.com/spack/spack
# Please also see the NOTICE and LICENSE files for our notice and the LGPL.
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU Lesser General Public License (as
# published by the Free Software Foundation) version 2.1, February 1999.
#
# This program is distributed in the hope that it will be useful, but
# WITHOUT ANY WARRANTY; without even the IMPLIED WARRANTY OF
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the terms and
# conditions of the GNU Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public
# License along with this program; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
##############################################################################
from spack import *
class Autogen(AutotoolsPackage):
"""AutoGen is a tool designed to simplify the creation and maintenance of
programs that contain large amounts of repetitious text. It is especially
valuable in programs that have several blocks of text that must be kept
synchronized."""
homepage = "https://www.gnu.org/software/autogen/index.html"
url = "https://ftp.gnu.org/gnu/autogen/rel5.18.12/autogen-5.18.12.tar.gz"
list_url = "https://ftp.gnu.org/gnu/autogen"
list_depth = 1
version('5.18.12', '551d15ccbf5b5fc5658da375d5003389')
variant('xml', default=True, description='Enable XML support')
depends_on('pkgconfig', type='build')
depends_on('guile@1.8:2.0')
depends_on('libxml2', when='+xml')
def configure_args(self):
spec = self.spec
args = [
# `make check` fails without this
# Adding a gettext dependency does not help
'--disable-nls',
]
if '+xml' in spec:
args.append('--with-libxml2={0}'.format(spec['libxml2'].prefix))
else:
args.append('--without-libxml2')
return args
|
<gh_stars>1-10
salario = int(input("Insira o salรกrio: "))
if salario == 750:
salario *= 0.15
print("Salarios de 750,00 serรฃo acrescidos em 15%")
print(salario)
|
import pandas as pd
from lxml import html
import requests
import time
def scrape_and_save_patent_data(url, endRow, filePath, searchValue):
patentRank = list(range(1, endRow-1))
patentNumber = []
patentTitle = []
patentLink = []
for x in range(2, endRow):
page = requests.get(url)
tree = html.fromstring(page.content)
patentNumber.append(tree.xpath('//table[1]//tr[' + str(x) + ']/td[2]//text()')[0])
patentTitle.append(tree.xpath('//table[1]//tr[' + str(x) + ']/td[4]//text()')[0])
patentLink.append('http://patft.uspto.gov' + tree.xpath('//table[1]//tr[' + str(x) + ']/td[4]/a/@href')[0])
time.sleep(2)
patentDict = {'Rank': patentRank, 'PatentNumber': patentNumber, 'PatentTitle': patentTitle, 'PatentLink': patentLink}
patentFrame = pd.DataFrame.from_dict(patentDict)
patentFrame.to_csv(filePath + searchValue + '.txt', sep='\t')
|
<reponame>powerc9000/some-blog<gh_stars>0
module.exports = function(db, config){
var fs = require("fs");
var Q = require("q");
var path = require("path");
var helpers = require("../helpers");
//Returns the names of all the directories in a directory
getDirs = function(rootDir) {
var q = Q.defer();
fs.readdir(rootDir, function(err, files) {
var dirs, file, filePath, index, _i, _len, _results;
dirs = [];
_results = [];
files.forEach(function(file, i){
if(file[0] !== '.'){
filePath = "" + rootDir + "/" + file;
fs.stat(filePath, function(err, stat){
if(stat.isDirectory()){
dirs.push(file);
}
if (files.length === (i + 1)) {
q.resolve(dirs);
}
});
}
});
});
return q.promise;
};
return{
//Finds all the names of the theme folders in the theme directory
//May need to change to find like a <theme-name>/theme.json so that it can have an img and a name along with it
//besides just the directory name
allThemes: function(req, res){
var themes = [];
getDirs(path.join(process.cwd(), "themes")).then(function(dirs){
dirs.forEach(function(d, i){
fs.readFile(path.join(process.cwd(), "themes", d, "theme.json"), "utf8", function(err, data){
if(err) return;
var t = JSON.parse(data);
t.tag = d;
themes.push(t);
if(i + 1=== dirs.length){
res.send({
currentTheme: config.theme || "default",
themes: themes
});
}
});
});
});
},
changeBlogDescription: function(req, res){
config.description = req.body.blogDescription;
fs.writeFile(path.join(process.cwd(), "config.json"), JSON.stringify(config, null, " "), function(err){
res.send(200);
});
},
changeTheme: function(req, res){
var theme = req.body.theme;
if(theme !== config.theme){
config.theme = theme;
fs.writeFile(path.join(process.cwd(), "config.json"), JSON.stringify(config, null, " "), function(err){
res.send(200);
});
}else{
res.send(200);
}
},
changeBlogName: function(req, res){
config["blog-name"] = req.body.blogName;
fs.writeFile(path.join(process.cwd(), "config.json"), JSON.stringify(config, null, " "), function(err){
res.send(200);
});
}
};
};
|
var regs = {
// ๆฏๅฆไธบ็ฉบ
required: function(value, param, item) {
if (this.checkable(item)) {
return item[0].checked;
}
return $.trim(value).length > 0;
},
checkable: function(item) {
return (/radio|checkbox/i).test(item[0].type);
},
// ้ๅค
equalTo: function(newvalue, oldvalue) {
return newvalue === $('[name=' + oldvalue + ']').val();
},
// ๆๅฐ้ฟๅบฆ
min: function(value, min) {
return value.length >= min;
},
// ๆๅคง้ฟๅบฆ
max: function(value, max) {
return value.length <= max;
},
// ้ฟๅบฆ่ๅด
range: function(value, range) {
return value.length >= range.min && value.length <= range.max;
},
//ๆๅฐๆฐๅผ
minNumber: function(value, minnmber) {
return Number(value) >= Number(minnmber);
},
//ๆๅคงๆฐๅผ
maxNumber: function(value, maxnmber) {
return Number(value) <= Number(maxnmber);
},
// ๆๆบ
isPhone: function(value) {
return /^1[3|4|7|5|8][0-9]\d{8}$/.test(value);
},
// ๅ
จไธญๆ
isChinese: function(value) {
return /^[\u4e00-\u9fa5]+$/.test(value);
},
// ๅ
จๆฐๅญ
isNum: function(value) {
return /^[0-9]+$/.test(value);
},
// ๅ
จ่ฑๆ
isEnglish: function(value) {
return /^[a-zA-Z]+$/.test(value);
},
// ่ฑๆใๆฐๅญ
isPwd: function(value) {
return /^[a-zA-Z0-9]+$/.test(value);
},
// ่ฑๆใๆฐๅญใๆฑๅญ
isUname: function(value) {
return /^[a-zA-Z0-9\u4E00-\u9FA5]+$/.test(value);
},
// ๆฏๅฆไธบRMB
isMoney: function(data, isPositive) {
return isPositive ? /^\d+(\.\d{1,2})?$/.test(data) && parseFloat(data) > 0 : /^(-)?\d+(\.\d{1,2})?$/.test(data);
},
// ่บซไปฝ่ฏ
isIdCard: function(idCard) {
//15ไฝๅ18ไฝ่บซไปฝ่ฏๅท็ ็ๆญฃๅ่กจ่พพๅผ
var regIdCard = /^(^[1-9]\d{7}((0\d)|(1[0-2]))(([0|1|2]\d)|3[0-1])\d{3}$)|(^[1-9]\d{5}[1-9]\d{3}((0\d)|(1[0-2]))(([0|1|2]\d)|3[0-1])((\d{4})|\d{3}[Xx])$)$/;
//ๅฆๆ้่ฟ่ฏฅ้ช่ฏ๏ผ่ฏดๆ่บซไปฝ่ฏๆ ผๅผๆญฃ็กฎ๏ผไฝๅ็กฎๆง่ฟ้่ฎก็ฎ
if (regIdCard.test(idCard)) {
if (idCard.length == 18) {
var idCardWi = new Array(7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2); //ๅฐๅ17ไฝๅ ๆๅ ๅญไฟๅญๅจๆฐ็ป้
var idCardY = new Array(1, 0, 10, 9, 8, 7, 6, 5, 4, 3, 2); //่ฟๆฏ้คไปฅ11ๅ๏ผๅฏ่ฝไบง็็11ไฝไฝๆฐใ้ช่ฏ็ ๏ผไนไฟๅญๆๆฐ็ป
var idCardWiSum = 0; //็จๆฅไฟๅญๅ17ไฝๅ่ชไนไปฅๅ ๆๅ ๅญๅ็ๆปๅ
for (var i = 0; i < 17; i++) {
idCardWiSum += idCard.substring(i, i + 1) * idCardWi[i];
}
var idCardMod = idCardWiSum % 11; //่ฎก็ฎๅบๆ ก้ช็ ๆๅจๆฐ็ป็ไฝ็ฝฎ
var idCardLast = idCard.substring(17); //ๅพๅฐๆๅไธไฝ่บซไปฝ่ฏๅท็
//ๅฆๆ็ญไบ2๏ผๅ่ฏดๆๆ ก้ช็ ๆฏ10๏ผ่บซไปฝ่ฏๅท็ ๆๅไธไฝๅบ่ฏฅๆฏX
if (idCardMod == 2) {
if (idCardLast == 'X' || idCardLast == 'x') {
return true;
} else {
return false;
}
} else {
//็จ่ฎก็ฎๅบ็้ช่ฏ็ ไธๆๅไธไฝ่บซไปฝ่ฏๅท็ ๅน้
๏ผๅฆๆไธ่ด๏ผ่ฏดๆ้่ฟ๏ผๅฆๅๆฏๆ ๆ็่บซไปฝ่ฏๅท็
if (idCardLast == idCardY[idCardMod]) {
return true;
} else {
return false;
}
}
}
} else {
return false;
}
return true;
},
//้ช่ฏ้ถ่กๅกๅท
isBankCard: function(bankCard) {
var strBin = '10,18,30,35,37,40,41,42,43,44,45,46,47,48,49,50,51,52,53,54,55,56,58,60,62,65,68,69,84,87,88,94,95,98,99';
var lastNum = bankCard.substr(bankCard.length - 1, 1); //ๅๅบๆๅไธไฝ๏ผไธluhm่ฟ่กๆฏ่พ๏ผ
var first15Num = bankCard.substr(0, bankCard.length - 1); //ๅ15ๆ18ไฝ
var newArr = new Array();
for (var i = first15Num.length - 1; i > -1; i--) { //ๅ15ๆ18ไฝๅๅบๅญ่ฟๆฐ็ป
newArr.push(first15Num.substr(i, 1));
}
var arrJiShu = new Array(); //ๅฅๆฐไฝ*2็็งฏ <9
var arrJiShu2 = new Array(); //ๅฅๆฐไฝ*2็็งฏ >9
var arrOuShu = new Array(); //ๅถๆฐไฝๆฐ็ป
for (var j = 0; j < newArr.length; j++) {
if ((j + 1) % 2 == 1) { //ๅฅๆฐไฝ
if (parseInt(newArr[j]) * 2 < 9)
arrJiShu.push(parseInt(newArr[j]) * 2);
else
arrJiShu2.push(parseInt(newArr[j]) * 2);
} else //ๅถๆฐไฝ
arrOuShu.push(newArr[j]);
}
var jishu_child1 = new Array(); //ๅฅๆฐไฝ*2 >9 ็ๅๅฒไนๅ็ๆฐ็ปไธชไฝๆฐ
var jishu_child2 = new Array(); //ๅฅๆฐไฝ*2 >9 ็ๅๅฒไนๅ็ๆฐ็ปๅไฝๆฐ
for (var h = 0; h < arrJiShu2.length; h++) {
jishu_child1.push(parseInt(arrJiShu2[h]) % 10);
jishu_child2.push(parseInt(arrJiShu2[h]) / 10);
}
var sumJiShu = 0; //ๅฅๆฐไฝ*2 < 9 ็ๆฐ็ปไนๅ
var sumOuShu = 0; //ๅถๆฐไฝๆฐ็ปไนๅ
var sumJiShuChild1 = 0; //ๅฅๆฐไฝ*2 >9 ็ๅๅฒไนๅ็ๆฐ็ปไธชไฝๆฐไนๅ
var sumJiShuChild2 = 0; //ๅฅๆฐไฝ*2 >9 ็ๅๅฒไนๅ็ๆฐ็ปๅไฝๆฐไนๅ
var sumTotal = 0;
for (var m = 0; m < arrJiShu.length; m++) {
sumJiShu = sumJiShu + parseInt(arrJiShu[m]);
}
for (var n = 0; n < arrOuShu.length; n++) {
sumOuShu = sumOuShu + parseInt(arrOuShu[n]);
}
for (var p = 0; p < jishu_child1.length; p++) {
sumJiShuChild1 = sumJiShuChild1 + parseInt(jishu_child1[p]);
sumJiShuChild2 = sumJiShuChild2 + parseInt(jishu_child2[p]);
}
//่ฎก็ฎๆปๅ
sumTotal = parseInt(sumJiShu) + parseInt(sumOuShu) + parseInt(sumJiShuChild1) + parseInt(sumJiShuChild2);
//่ฎก็ฎLuhmๅผ
var k = parseInt(sumTotal) % 10 == 0 ? 10 : parseInt(sumTotal) % 10;
var luhm = 10 - k;
if (strBin.indexOf(bankCard.substring(0, 2)) == -1) {
return false;
}
if (!(lastNum == luhm)) {
return false;
}
return true;
},
// ้ฎไปถ
isEmail: function(value) {
return /^[a-zA-Z0-9.!#$%&'*+\/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$/.test(value);
}
}
|
import { screen } from '@testing-library/react';
import { customRender } from 'test-client/test-utils';
import UsersView from 'views/Users';
import { fakeUsers } from 'test-client/server/fake-data';
describe('Users View', () => {
// almost same like HomeView
test('renders pagination section and users cards list', async () => {
customRender(<UsersView />);
// assert title
const title = await screen.findByRole('heading', {
name: /users/i,
});
expect(title).toBeInTheDocument();
// assert pagination button 1
const paginationButton = screen.getByRole('button', {
name: /1/i,
});
expect(paginationButton).toBeInTheDocument();
// assert search input
const searchInput = screen.getByRole('textbox', {
name: /search/i,
});
expect(searchInput).toBeInTheDocument();
// assert first users's username link
const usernameLink = screen.getAllByRole('link', {
name: RegExp(`@${fakeUsers.items[0].username}`, 'i'),
})[0];
expect(usernameLink).toBeInTheDocument();
});
// test search filters users - same as in HomeView
});
|
package io.github.ibuildthecloud.gdapi.request.handler;
import io.github.ibuildthecloud.gdapi.request.ApiRequest;
public abstract class AbstractApiRequestHandler implements ApiRequestHandler {
@Override
public boolean handleException(ApiRequest request, Throwable e) {
return false;
}
}
|
<gh_stars>1-10
/**
* Copyright (c) Microsoft Corporation.
*
* 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.
*/
import { createGuid } from 'playwright-core/lib/utils';
import { spawnAsync } from 'playwright-core/lib/utils/spawnAsync';
import type { TestRunnerPlugin } from './';
import type { FullConfig } from '../../types/testReporter';
const GIT_OPERATIONS_TIMEOUT_MS = 1500;
export const gitCommitInfo = (options?: GitCommitInfoPluginOptions): TestRunnerPlugin => {
return {
name: 'playwright:git-commit-info',
setup: async (config: FullConfig, configDir: string) => {
const info = {
...linksFromEnv(),
...options?.info ? options.info : await gitStatusFromCLI(options?.directory || configDir),
timestamp: Date.now(),
};
// Normalize dates
const timestamp = info['revision.timestamp'];
if (timestamp instanceof Date)
info['revision.timestamp'] = timestamp.getTime();
config.metadata = config.metadata || {};
Object.assign(config.metadata, info);
},
};
};
export interface GitCommitInfoPluginOptions {
directory?: string;
info?: Info;
}
export interface Info {
'revision.id'?: string;
'revision.author'?: string;
'revision.email'?: string;
'revision.subject'?: string;
'revision.timestamp'?: number | Date;
'revision.link'?: string;
'ci.link'?: string;
}
const linksFromEnv = (): Pick<Info, 'revision.link' | 'ci.link'> => {
const out: { 'revision.link'?: string; 'ci.link'?: string; } = {};
// Jenkins: https://www.jenkins.io/doc/book/pipeline/jenkinsfile/#using-environment-variables
if (process.env.BUILD_URL)
out['ci.link'] = process.env.BUILD_URL;
// GitLab: https://docs.gitlab.com/ee/ci/variables/predefined_variables.html
if (process.env.CI_PROJECT_URL && process.env.CI_COMMIT_SHA)
out['revision.link'] = `${process.env.CI_PROJECT_URL}/-/commit/${process.env.CI_COMMIT_SHA}`;
if (process.env.CI_JOB_URL)
out['ci.link'] = process.env.CI_JOB_URL;
// GitHub: https://docs.github.com/en/actions/learn-github-actions/environment-variables#default-environment-variables
if (process.env.GITHUB_SERVER_URL && process.env.GITHUB_REPOSITORY && process.env.GITHUB_SHA)
out['revision.link'] = `${process.env.GITHUB_SERVER_URL}/${process.env.GITHUB_REPOSITORY}/commit/${process.env.GITHUB_SHA}`;
if (process.env.GITHUB_SERVER_URL && process.env.GITHUB_REPOSITORY && process.env.GITHUB_RUN_ID)
out['ci.link'] = `${process.env.GITHUB_SERVER_URL}/${process.env.GITHUB_REPOSITORY}/actions/runs/${process.env.GITHUB_RUN_ID}`;
return out;
};
export const gitStatusFromCLI = async (gitDir: string): Promise<Info | undefined> => {
const separator = `:${createGuid().slice(0, 4)}:`;
const { code, stdout } = await spawnAsync(
'git',
['show', '-s', `--format=%H${separator}%s${separator}%an${separator}%ae${separator}%ct`, 'HEAD'],
{ stdio: 'pipe', cwd: gitDir, timeout: GIT_OPERATIONS_TIMEOUT_MS }
);
if (code)
return;
const showOutput = stdout.trim();
const [id, subject, author, email, rawTimestamp] = showOutput.split(separator);
let timestamp: number = Number.parseInt(rawTimestamp, 10);
timestamp = Number.isInteger(timestamp) ? timestamp * 1000 : 0;
return {
'revision.id': id,
'revision.author': author,
'revision.email': email,
'revision.subject': subject,
'revision.timestamp': timestamp,
};
};
|
#!/bin/bash
#
# Licensed to the Apache Software Foundation (ASF) under one or more
# contributor license agreements. See the NOTICE file distributed with
# this work for additional information regarding copyright ownership.
# The ASF licenses this file to You 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.
#
WORK_DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" >/dev/null 2>&1 && pwd )"
CURRENT_DIR=$(pwd)
source $WORK_DIR/set_project_home.sh
# check cmake version
MAVEN_VERSION=3.6.3
MAVEN_DOWNLOAD_URL=https://mirrors.sonic.net/apache/maven/maven-3/3.6.3/binaries/apache-maven-3.6.3-bin.tar.gz
CURRENT_MAVEN_VERSION_STR="$(mvn --version)"
if [[ "$CURRENT_MAVEN_VERSION_STR" == "Apache Maven "* ]]; then
echo "Maven is installed in the system"
else
echo "Maven is not installed in the system. Will download one."
if [ ! -d "$THIRD_PARTY_DIR/maven/apache-maven-$MAVEN_VERSION" ]; then
mkdir -p $THIRD_PARTY_DIR
cd $THIRD_PARTY_DIR
mkdir -p maven
cd maven
echo "Will use $THIRD_PARTY_DIR/maven/apache-maven-$MAVEN_VERSION-bin.tar.gz"
if [ ! -f "apache-maven-$MAVEN_VERSION-bin.tar.gz" ]; then
wget $MAVEN_DOWNLOAD_URL
fi
tar xvf apache-maven-$MAVEN_VERSION-bin.tar.gz
fi
export MAVEN_HOME=$THIRD_PARTY_DIR/maven/apache-maven-$MAVEN_VERSION
PATH=$PATH:$MAVEN_HOME/bin
export PATH
cd $CURRENT_DIR
fi
|
#!/bin/bash
PROJECTID=$(gcloud config get-value project)
cd pipeline
bq mk babyweight
bq rm -rf babyweight.predictions
mvn compile exec:java \
-Dexec.mainClass=com.google.cloud.training.mlongcp.AddPrediction \
-Dexec.args="--realtime --input=babies --output=babyweight.predictions --project=$PROJECTID"
|
<gh_stars>1-10
import hbs from 'htmlbars-inline-precompile';
import {describe, it} from 'mocha';
import {expect} from 'chai';
import {render} from '@ember/test-helpers';
import {setupRenderingTest} from 'ember-mocha';
describe('Integration: Component: gh-alert', function () {
setupRenderingTest();
it('renders', async function () {
this.set('message', {message: 'Test message', type: 'success'});
await render(hbs`{{gh-alert message=message}}`);
let alert = this.element.querySelector('article.gh-alert');
expect(alert).to.exist;
expect(alert).to.contain.text('Test message');
});
it('maps message types to CSS classes', async function () {
this.set('message', {message: 'Test message', type: 'success'});
await render(hbs`{{gh-alert message=message}}`);
let alert = this.element.querySelector('article.gh-alert');
this.set('message.type', 'success');
expect(alert, 'success class is green').to.have.class('gh-alert-green');
this.set('message.type', 'error');
expect(alert, 'error class is red').to.have.class('gh-alert-red');
this.set('message.type', 'warn');
expect(alert, 'warn class is yellow').to.have.class('gh-alert-blue');
this.set('message.type', 'info');
expect(alert, 'info class is blue').to.have.class('gh-alert-blue');
});
});
|
import random
# Number of sample points
n = 100000
# Number of points inside the circle
c = 0
for i in range(n):
x = random.random()
y = random.random()
if (x*x + y*y) <= 1:
c += 1
# pi = 4 * (points inside the circle / total points)
pi = 4 * (c / n)
print("Estimated value of pi:", pi)
|
<gh_stars>1-10
#ifndef _SORT_H_
#define _SORT_H_
#include <vector>
template<class Heap>
long long int Benchmark<Heap>::sort(int N, int* nums) {
log("running sort\n");
std::vector<int> numbers;
std::vector<int> results;
log("generating numbers\n");
for (int i = 0; i < N; i++)
numbers.push_back(nums[i]);
log("inserting and retrieving numbers\n");
long long int pre_insert = elapsed();
Heap h;
for (int i = 0; i < N; i++)
h.push(numbers[i], numbers[i]);
while (!h.empty()) {
results.push_back(*h.find_min());
h.delete_min();
}
long long int post_retrieval = elapsed();
log("elapsed: %lld us\n", post_retrieval - pre_insert);
log("sorting using STL\n");
std::sort(numbers.begin(), numbers.end());
log("verifying\n");
if (numbers.size() != results.size()) {
log("incorrect: numbers.size() != results.size() (%d != %d)\n",
numbers.size(), results.size());
return -1;
}
else {
for (int i = 0; i < results.size(); i++) {
if (numbers[i] != results[i]) {
log("incorrect: numbers[%d] != results[%d] (%d != %d)\n",
i, i, numbers[i], results[i]);
return -1;
}
}
log("correct!\n", heap_name);
return post_retrieval - pre_insert;
}
}
#endif // _SORT_H_
|
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package com.mycompany.jobfinder;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Scanner;
import java.util.Set;
/**
*
* @author Owais
*/
public class Menu extends javax.swing.JFrame {
/**
* Creates new form Menu
*/
public Menu() {
initComponents();
}
/**
* This method is called from within the constructor to initialize the form.
* WARNING: Do NOT modify this code. The content of this method is always
* regenerated by the Form Editor.
*/
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
private void initComponents() {
promptLabel = new javax.swing.JLabel();
whatField = new javax.swing.JTextField();
goButton = new javax.swing.JButton();
whereField = new javax.swing.JTextField();
jLabel1 = new javax.swing.JLabel();
jLabel2 = new javax.swing.JLabel();
jScrollPane1 = new javax.swing.JScrollPane();
skillsTextArea = new javax.swing.JTextArea();
jLabel3 = new javax.swing.JLabel();
jLabel4 = new javax.swing.JLabel();
usernameField = new javax.swing.JTextField();
saveButton = new javax.swing.JButton();
loadButton = new javax.swing.JButton();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
setTitle("Find the Right Job for YOU");
getContentPane().setLayout(null);
promptLabel.setFont(new java.awt.Font("Segoe UI", 1, 36)); // NOI18N
promptLabel.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
promptLabel.setText("Job Finder");
promptLabel.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
getContentPane().add(promptLabel);
promptLabel.setBounds(0, 10, 550, 50);
whatField.setText("software");
getContentPane().add(whatField);
whatField.setBounds(130, 110, 320, 22);
goButton.setText("Go");
goButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
goButtonActionPerformed(evt);
}
});
getContentPane().add(goButton);
goButton.setBounds(160, 380, 230, 40);
whereField.setText("Toronto");
getContentPane().add(whereField);
whereField.setBounds(130, 150, 320, 22);
jLabel1.setText("What:");
getContentPane().add(jLabel1);
jLabel1.setBounds(70, 100, 60, 40);
jLabel2.setText("Where:");
getContentPane().add(jLabel2);
jLabel2.setBounds(70, 140, 60, 40);
skillsTextArea.setColumns(20);
skillsTextArea.setLineWrap(true);
skillsTextArea.setRows(5);
skillsTextArea.setWrapStyleWord(true);
jScrollPane1.setViewportView(skillsTextArea);
getContentPane().add(jScrollPane1);
jScrollPane1.setBounds(50, 220, 450, 140);
jLabel3.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
jLabel3.setText(" Skills (separated by commas in the format \"SKILL - SCORE\"):");
jLabel3.setVerticalAlignment(javax.swing.SwingConstants.TOP);
getContentPane().add(jLabel3);
jLabel3.setBounds(50, 190, 450, 80);
jLabel4.setText("UserName:");
getContentPane().add(jLabel4);
jLabel4.setBounds(30, 60, 80, 30);
usernameField.setText("owais");
getContentPane().add(usernameField);
usernameField.setBounds(110, 60, 240, 30);
saveButton.setText("Save");
saveButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
saveButtonActionPerformed(evt);
}
});
getContentPane().add(saveButton);
saveButton.setBounds(360, 60, 70, 30);
loadButton.setText("Load");
loadButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
loadButtonActionPerformed(evt);
}
});
getContentPane().add(loadButton);
loadButton.setBounds(450, 60, 80, 30);
setSize(new java.awt.Dimension(567, 484));
setLocationRelativeTo(null);
}// </editor-fold>//GEN-END:initComponents
private void goButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_goButtonActionPerformed
JobScraper j = new JobScraper();
String what = whatField.getText();
String where = whereField.getText();
String skills = skillsTextArea.getText().toLowerCase();
boolean noSkill = skills.isEmpty();
//timer
double start=System.currentTimeMillis();
if (noSkill) {
System.out.println("please enter skills in proper textArea");
} else {
// information for all the jobs
j.getJobInfo(what, where);
//get number of jobs, job titles, companies, urls and descriptions
LinkedList<String> jobTitle = j.getJobTitle();
LinkedList<String> jobCompany = j.getJobCompany();
LinkedList<String> jobDesc = j.getJobDesc();
LinkedList<String> jobURL = j.getJobURL();
int numOfJobs = j.getNumOfJobs();
//get skills info (skill name and score from 1-10) from GUI
//split skills by ', '
String[] skillAndScore = skills.split(", ");
//split name and score by ' - '
int numOfSkills = skillAndScore.length;
String[] skillName = new String[numOfSkills];
int[] skillScore = new int[numOfSkills];
int count = 0;
for (String s : skillAndScore) {
String[] temp = s.split(" - ");
skillName[count] = temp[0];
skillScore[count] = Integer.parseInt(temp[1]);
//if score >10, make it 10 and if score < 1, make it 1
if (skillScore[count] > 10) {
skillScore[count] = 10;
} else if (skillScore[count] < 1) {
skillScore[count] = 1;
}
count++;
}
//test array by outputting
/*for (int i = 0; i < numOfSkills; i++) {
System.out.println("Mastery of " + skillName[i] + " with a rating of " + skillScore[i] + "/10");
}*/
//skillpoints
int[] skillPoints = new int[numOfJobs];
//initialize each skillcount to 0
for (int init : skillPoints) {
init = 0;
}
//define list of clutter to remove and speed up the program (marginally)
String[] clutterList = {"a ", "and ", "the ", "of ", ",", "\'", "\"", "\n", "\r", "to ", "our ", "we "};
//create a map to store job index in OG list as well as score
Map<Integer, Integer> jobIndexScore = new HashMap<>();
// clean descsriptions and find iterations
for (int i = 0; i < jobDesc.size(); i++) {
//remove all clutter
for (String clutter : clutterList) {
jobDesc.set(i, jobDesc.get(i).replace(clutter, ""));
}
//for each job description if desc contains skill then add score onto jobScore for job index
for (int a = 0; a < numOfSkills; a++) {
if (jobDesc.get(i).contains(skillName[a])) {
skillPoints[i] += skillScore[a];
}
}
//TEST
//output job titles then the points
// System.out.println("Job " + i + ": " + skillPoints[i]);
//if (i==0)System.out.println(jobDesc.get(i));
jobIndexScore.put(i, skillPoints[i]);
}
//sort jobIndexScore from highest jobScore to lowest
//get set of entries
Set<Entry<Integer, Integer>> entrySet = jobIndexScore.entrySet();
//get list (sortable collection) based on entries
List<Entry<Integer, Integer>> list = new ArrayList<>(entrySet);
//sort
Collections.sort(list, (Entry<Integer, Integer> a, Entry<Integer, Integer> b) -> b.getValue().compareTo(a.getValue()));
//sorted
//end timer
double end=System.currentTimeMillis();
double elapsedTime=(end-start)/1000;
System.out.println("calculations completed: "+elapsedTime+" seconds");
//send sorted list of jobTitles, jobScores, jobCompanies and jobURL to the output
System.out.println("\nJOBS IN ORDER FROM HIGHEST SCORE TO LOWEST:\n");
for (var element : list) {
int jobIndex = element.getKey();
int jobScore = element.getValue();
if (jobScore == 0) {
break;
} else {
System.out.println("Job Title: " + jobTitle.get(jobIndex));
System.out.println("Company: " + jobCompany.get(jobIndex));
System.out.println("Score: " + jobScore);
System.out.println(jobURL.get(jobIndex) + "\n");
}
}
}
}//GEN-LAST:event_goButtonActionPerformed
private void saveButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_saveButtonActionPerformed
// save skills to a file (later a database)
String user = usernameField.getText();
String filename = "./profiles/" + user + ".txt";
if (user.isEmpty()) {
System.out.println("Please enter a valid username");
} else {
try {
//create file
File saveFile = new File(filename);
if (saveFile.createNewFile()) {
//file created
System.out.println("New User \"" + user + "\" created: " + saveFile.getName());
} else {
//file exists
System.out.println("User \"" + user + "\" update in progress...");
}
//write to file
FileWriter myWriter = new FileWriter(filename);
myWriter.write(skillsTextArea.getText());
myWriter.close();
System.out.println("Successfully updated \"" + user + "\".");
} catch (IOException e) {
System.out.println("An error occurred.");
e.printStackTrace();
}
}
}//GEN-LAST:event_saveButtonActionPerformed
private void loadButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_loadButtonActionPerformed
// load skills from a file (later a database)
String skills = "";
String user = usernameField.getText();
String filename = "./profiles/" + user + ".txt";
if (user.isEmpty()) {
System.out.println("Please enter a valid username");
} else {
try {
File loadFile = new File(filename);
Scanner myReader = new Scanner(loadFile);
while (myReader.hasNextLine()) {
String data = myReader.nextLine();
skills = data;
}
myReader.close();
System.out.println("User \"" + user + "\" loaded.");
} catch (FileNotFoundException e) {
System.out.println("That user does not exist,\nPlease enter a valid username");
}
skillsTextArea.setText(skills);
}
}//GEN-LAST:event_loadButtonActionPerformed
/**
* @param args the command line arguments
*/
public static void main(String args[]) {
/* Set the Nimbus look and feel */
//<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
/* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
* For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
*/
try {
for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
if ("Nimbus".equals(info.getName())) {
javax.swing.UIManager.setLookAndFeel(info.getClassName());
break;
}
}
} catch (ClassNotFoundException ex) {
java.util.logging.Logger.getLogger(Menu.class
.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(Menu.class
.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(Menu.class
.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(Menu.class
.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
//</editor-fold>
/* Create and display the form */
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new Menu().setVisible(true);
}
});
}
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JButton goButton;
private javax.swing.JLabel jLabel1;
private javax.swing.JLabel jLabel2;
private javax.swing.JLabel jLabel3;
private javax.swing.JLabel jLabel4;
private javax.swing.JScrollPane jScrollPane1;
private javax.swing.JButton loadButton;
private javax.swing.JLabel promptLabel;
private javax.swing.JButton saveButton;
private javax.swing.JTextArea skillsTextArea;
private javax.swing.JTextField usernameField;
private javax.swing.JTextField whatField;
private javax.swing.JTextField whereField;
// End of variables declaration//GEN-END:variables
}
|
package thinkingdata
import (
"encoding/json"
"errors"
"fmt"
"os"
"sync"
"time"
)
type RotateMode int32
const (
ChannelSize = 1000 // channel ็ผๅฒๅบ
ROTATE_DAILY RotateMode = 0 // ๆๅคฉๅๅ
ROTATE_HOURLY RotateMode = 1 // ๆๅฐๆถๅๅ
)
type LogConsumer struct {
directory string // ๆฅๅฟๆไปถๅญๆพ็ฎๅฝ
dateFormat string // ไธๆฅๅฟๅๅๆๅ
ณ็ๆถ้ดๆ ผๅผ
fileSize int64 // ๅไธชๆฅๅฟๆไปถๅคงๅฐ๏ผๅไฝ Byte
fileNamePrefix string // ๆฅๅฟๆไปถๅ็ผๅ
currentFile *os.File // ๅฝๅๆฅๅฟๆไปถ
ch chan string // ๆฐๆฎไผ ่พไฟก้
wg sync.WaitGroup
}
type LogConfig struct {
Directory string // ๆฅๅฟๆไปถๅญๆพ็ฎๅฝ
RotateMode RotateMode // ไธๆฅๅฟๅๅๆๅ
ณ็ๆถ้ดๆ ผๅผ
FileSize int // ๅไธชๆฅๅฟๆไปถๅคงๅฐ๏ผๅไฝ Byte
FileNamePrefix string // ๆฅๅฟๆไปถๅ็ผๅ
AutoFlush bool // ่ชๅจไธไผ
Interval int // ่ชๅจไธไผ ้ด้
}
// ๅๅปบ LogConsumer. ไผ ๅ
ฅๆฅๅฟ็ฎๅฝๅๅๅๆจกๅผ
func NewLogConsumer(directory string, r RotateMode) (Consumer, error) {
return NewLogConsumerWithFileSize(directory, r, 0)
}
// ๅๅปบ LogConsumer. ไผ ๅ
ฅๆฅๅฟ็ฎๅฝๅๅๅๆจกๅผๅๅไธชๆไปถๅคงๅฐ้ๅถ
// directory: ๆฅๅฟๆไปถๅญๆพ็ฎๅฝ
// r: ๆไปถๅๅๆจกๅผ(ๆๆฅๅๅใๆๅฐๆถๅๅ)
// size: ๅไธชๆฅๅฟๆไปถไธ้๏ผๅไฝ MB
func NewLogConsumerWithFileSize(directory string, r RotateMode, size int) (Consumer, error) {
config := LogConfig{
Directory: directory,
RotateMode: r,
FileSize: size,
}
return NewLogConsumerWithConfig(config)
}
func NewLogConsumerWithConfig(config LogConfig) (Consumer, error) {
var df string
switch config.RotateMode {
case ROTATE_DAILY:
df = "2006-01-02"
case ROTATE_HOURLY:
df = "2006-01-02-15"
default:
return nil, errors.New("Unknown rotate mode.")
}
c := &LogConsumer{
directory: config.Directory,
dateFormat: df,
fileSize: int64(config.FileSize * 1024 * 1024),
fileNamePrefix: config.FileNamePrefix,
ch: make(chan string, ChannelSize),
}
return c, c.init()
}
func (c *LogConsumer) Add(d Data) error {
bdata, err := json.Marshal(d)
if err != nil {
return err
}
select {
case c.ch <- string(bdata):
default:
return errors.New("ta logger channel full")
}
return nil
}
func (c *LogConsumer) Flush() error {
return c.currentFile.Sync()
}
func (c *LogConsumer) Close() error {
close(c.ch)
c.wg.Wait()
return nil
}
func (c *LogConsumer) constructFileName(i int) string {
fileNamePrefix := ""
if len(c.fileNamePrefix) != 0 {
fileNamePrefix = c.fileNamePrefix + "."
}
if c.fileSize > 0 {
return fmt.Sprintf("%s/%slog.%s_%d", c.directory, fileNamePrefix, time.Now().Format(c.dateFormat), i)
} else {
return fmt.Sprintf("%s/%slog.%s", c.directory, fileNamePrefix, time.Now().Format(c.dateFormat))
}
}
// ๅผๅฏไธไธช Go ็จไปไฟก้ไธญ่ฏปๅ
ฅๆฐๆฎ๏ผๅนถๅๅ
ฅๆไปถ
func (c *LogConsumer) init() error {
//ๅคๆญ็ฎๅฝๆฏๅฆๅญๅจ
_, err := os.Stat(c.directory)
if err != nil && os.IsNotExist(err) {
e := os.MkdirAll(c.directory, os.ModePerm)
if e != nil {
return e
}
}
fd, err := os.OpenFile(c.constructFileName(0), os.O_WRONLY|os.O_APPEND|os.O_CREATE, 0644)
if err != nil {
fmt.Printf("open failed: %s\n", err)
return err
}
c.currentFile = fd
c.wg.Add(1)
go func() {
defer func() {
if c.currentFile != nil {
c.currentFile.Sync()
c.currentFile.Close()
}
c.wg.Done()
}()
i := 0
for {
select {
case rec, ok := <-c.ch:
if !ok {
return
}
// ๅคๆญๆฏๅฆ่ฆๅๅๆฅๅฟ: ๆ นๆฎๅๅๆจกๅผๅๅฝๅๆฅๅฟๆไปถๅคงๅฐๆฅๅคๆญ
var newName string
fname := c.constructFileName(i)
if c.currentFile.Name() != fname {
newName = fname
} else if c.fileSize > 0 {
stat, _ := c.currentFile.Stat()
if stat.Size() > c.fileSize {
i++
newName = c.constructFileName(i)
}
}
if newName != "" {
c.currentFile.Close()
c.currentFile, err = os.OpenFile(fname, os.O_WRONLY|os.O_APPEND|os.O_CREATE, 0644)
if err != nil {
fmt.Printf("open failed: %s\n", err)
return
}
}
_, err = fmt.Fprintln(c.currentFile, rec)
if err != nil {
fmt.Fprintf(os.Stderr, "LoggerWriter(%q): %s\n", c.currentFile.Name(), err)
return
}
}
}
}()
return nil
}
|
#!/bin/bash
# Creates documentation using Jazzy.
FRAMEWORK_VERSION=2.1.1
jazzy \
--clean \
--author "Fabrizio Brancati" \
--author_url https://www.fabriziobrancati.com \
--github_url https://github.com/FabrizioBrancati/Queuer \
--github-file-prefix https://github.com/FabrizioBrancati/Queuer/tree/$FRAMEWORK_VERSION \
--module-version $FRAMEWORK_VERSION \
--xcodebuild-arguments -scheme,"Queuer iOS" \
--module Queuer \
--root-url https://github.com/FabrizioBrancati/Queuer \
--output Docs/ \
--theme jony \
--docset-icon Resources/Icon-32.png \
--root-url https://github.fabriziobrancati.com/documentation/Queuer/ \
--dash_url https://github.fabriziobrancati.com/documentation/Queuer/docsets/Queuer.xml
cp -r Resources Docs/Resources
|
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package exp2;
import java.util.Scanner;
/**
*
* @author prakash
*/
public class Prg4exp2 {
public static void main(String []argh)
{
Scanner sc = new Scanner(System.in);
int t=sc.nextInt();
for(int i=0;i<t;i++)
{
try
{
long x=sc.nextLong();
System.out.println(x+" can be fitted in:");
if(x>=-128 && x<=127)System.out.println("* byte");
if(x>=-32768 && x<=32767)System.out.println("* short");
if(x>= -Math.pow(2, 31) && x<= Math.pow(2, 31) - 1)System.out.println("* int");
if(x >= -Math.pow(2, 63) && x <= Math.pow(2, 63) - 1) System.out.println("* long");
}
catch(Exception e)
{
System.out.println(sc.next()+" can't be fitted anywhere.");
}
}
}
}
/*Sample Input
5
-150
150000
1500000000
213333333333333333333333333333333333
-100000000000000
Sample Output
-150 can be fitted in:
* short
* int
* long
150000 can be fitted in:
* int
* long
1500000000 can be fitted in:
* int
* long
213333333333333333333333333333333333 can't be fitted anywhere.
-100000000000000 can be fitted in:
* long*/
|
for arr in [[2, 3], [4, 5], [6, 7]]:
for elem in arr:
print(elem)
|
userdel contra
|
<reponame>wmathurin/SalesforceMobileSDK-Package<gh_stars>10-100
/*
* Copyright (c) 2019-present, salesforce.com, inc.
* All rights reserved.
* Redistribution and use of this software in source and binary forms, with or
* without modification, are permitted provided that the following conditions
* are met:
* - Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
* - Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
* - Neither the name of salesforce.com, inc. nor the names of its contributors
* may be used to endorse or promote products derived from this software without
* specific prior written permission of salesforce.com, inc.
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
// Dependencies
var fs = require('fs'),
path = require('path'),
COLOR = require('./outputColors'),
utils = require('./utils'),
Ajv = require('ajv'),
jsonlint = require('jsonlint')
;
// Config type to schema map
var SCHEMA = {
store: path.resolve(__dirname, 'store.schema.json'),
syncs: path.resolve(__dirname, 'syncs.schema.json')
};
//
// Validate config against schema
//
function validateJson(configPath, configType) {
var config = readJsonFile(configPath)
var schema = readJsonFile(SCHEMA[configType])
var ajv = new Ajv({allErrors: true});
var valid = ajv.validate(schema, config);
if (!valid) {
utils.logError(JSON.stringify(ajv.errors, null, " "))
} else {
utils.logInfo(`${configPath} conforms to ${configType} schema\n`, COLOR.green)
}
}
//
// Read json from file and validates that is valid json
//
function readJsonFile(filePath) {
try {
var content = fs.readFileSync(filePath, "UTF-8");
var json = jsonlint.parse(content);
return json;
} catch (error) {
utils.logError(`Error parsing ${filePath}: ${error}\n`);
process.exit(1);
}
}
module.exports = {
validateJson
};
|
package list4.e2;
import org.junit.*;
import java.util.*;
import static org.junit.Assert.*;
import br.edu.fatecfranca.list4.e2.*;
public class PassengerTest {
private Passenger passenger;
@Before public void setUp() {
passenger = new Passenger();
}
@Test public void testCreationPlace() {
assertEquals(10, passenger.getPlace());
}
@Test public void testCreationName() {
assertEquals("Daniel", passenger.getName());
}
@Test public void testShow() {
assertEquals("Place: 10; Name: Daniel", passenger.show());
}
}
|
#!/bin/bash
# Backup script
# Create a tar archive of the directory
tar -zcvf backup.tar.gz directoryName
# Copy the resulting archive to the backup directory
sudo cp backup.tar.gz /path/to/backup/directory
# List the contents of the backup directory
ls /path/to/backup/directory
|
import { isValidMatchUpFormat } from './isValidMatchUpFormat';
import { stringify } from './stringify';
import { parse } from './parse';
const matchUpFormatCode = (function() {
return {
stringify: matchUpFormatObject => stringify(matchUpFormatObject),
parse: matchUpFormat => parse(matchUpFormat),
isValidMatchUpFormat: matchUpFormat => isValidMatchUpFormat(matchUpFormat)
};
})();
exports.matchUpFormatCode = matchUpFormatCode;
|
(function () {
'use strict';
angular
.module('eeo')
.factory('Eeo', Eeo)
function Eeo($resource, $state, $stateParams) {
var Eeo = $resource('eeo/:eeoId', {eeoId: '@_id'}, {
update: {
method: 'PUT'
},
create: {
method: 'POST',
url: 'eeo/create/:applicationId',
params: { applicationId : '@applicationId'}
}
});
var methods = {
createEeo: function () {
$state.go('main.createEeo', {applicationID: $stateParams.applicationID});
}
};
/**
* Methods to add to each result returned by $resource
* @type {Object} itemMethods
*/
var itemMethods = {
};
/**
* Methods to add to the Model
* @type {{listEeo: Function, getActions: Function}}
*/
var modelMethods = {
listEeo: function () {
$state.go('main.listEeo');
},
getActions: function () {
var modelActions = [
];
return angular.copy(modelActions);
},
getOptions: function () {
var options = {
ethnicities: [
{
code: 'h',
description: 'Hispanic or Latino',
detail: 'Of Cuban, Mexican, Puerto Rican, South or Central American, or other Spanish culture or origin regardless of race.'
},
{
code: 'n',
description: 'Not Hispanic or Latino'
},
{
code: 'd',
description: 'Declined to Answer'
}
],
genders: [
{
code: 'f',
description: 'Female',
},
{
code: 'm',
description: 'Male'
},
{
code: 'd',
description: 'Declined to Answer'
}
],
races: [{
code: 'native',
description: 'American Indian or Alaskan Native',
detail: 'Having origins in any of the original peoples of North and South America (including Central America), and who maintain tribal affiliation or community attachment'
},
{
code: 'asian',
description: 'Asian',
detail: 'Having origins in any of the original peoples of the Far East, Southeast Asia, or the Indian Subcontinent, including, for example, Cambodia, China, India, Japan, Korea, Malaysia, Pakistan, the Philippine Islands, Thailand, and Vietnam'
},
{
code: 'black',
description: 'Black or African American',
detail: 'Having origins in any of the black racial groups of Africa'
},
{
code: 'pacific',
description: 'Native Hawaiian or Other Pacific Islander',
detail: 'Having origins in any of the peoples of Hawaii, Guam, Samoa, or other Pacific Islands'
},
{
code: 'white',
description: 'White',
detail: 'A person having origins in any of the original peoples of Europe, the Middle East, or North Africa'
},
{code: 'other', description: 'Other'}
],
vetClasses: [
{code: 'disabled', description: 'Disabled Veteran'},
{
code: 'recent',
description: 'Recently Separated Veteran',
detail: 'Discharged or released from active duty within 36 months'
},
{
code: 'active',
description: 'Active Duty Wartime or Campaign Badge Veteran',
detail: 'Served on active duty in the U.S. military during a war or in a campaign or expedition for which a campaign badge is awarded'
},
{
code: 'medal',
description: 'Armed Forces Service Medal Veteran',
detail: 'While serving on active duty in the Armed Forces, participated in a United States military operation for which an Armed Forces service medal was awarded pursuant to Executive Order 12985.'
}
],
disabilities: [
{description: 'Blindness'},
{description: 'Deafness'},
{description: 'Cancer'},
{description: 'Diabetes'},
{description: 'Autism'},
{description: 'Cerebral palsy'},
{description: 'HIV/AIDS'},
{description: 'Schizophrenia'},
{description: 'Muscular dystrophy'},
{description: 'Bipolar disorder'},
{description: 'Major depression'},
{description: 'Multiple sclerosis (MS)'},
{description: 'Missing limbs or partially missing limbs'},
{description: 'Post-traumatic stress disorder (PTSD)'},
{description: 'Obsessive compulsive disorder'},
{description: 'Impairments requiring the use of a wheelchair'},
{description: 'Intellectual disability (previously called mental retardation)'}
]
}
return options;
}
};
/**
* Extend Eeo with the methods
*/
angular.extend(Eeo.prototype, itemMethods);
angular.extend(Eeo, modelMethods);
return Eeo;
}
})();
|
def compare_versions(version1: str, version2: str) -> int:
v1_parts = list(map(int, version1.split('.')))
v2_parts = list(map(int, version2.split('.'))
for v1, v2 in zip(v1_parts, v2_parts):
if v1 > v2:
return 1
elif v1 < v2:
return -1
if len(v1_parts) > len(v2_parts):
return 1
elif len(v1_parts) < len(v2_parts):
return -1
else:
return 0
|
import random
num = random.randint(1,10)
guess = 0
attempts = 0
while guess != num and attempts < 3:
guess = int(input("Guess a number between 1 and 10: "))
attempts += 1
if guess == num:
print("You guessed correctly in", attempts, "attempts")
elif guess > num:
print("Too High")
else:
print("Too Low")
if guess != num:
print("You failed to guess the number")
|
#!/bin/bash
git pull origin main
sudo supervisorctl stop ffs
# flask db upgrade
sudo supervisorctl start ffs
|
<reponame>dbathon/adventofcode-2021
import { p, readLines } from "./util/util";
const lines = readLines("input/a08.txt");
let count1 = 0;
for (const line of lines) {
count1 += line
.split(" | ")[1]
.split(" ")
.map((part) => part.length)
.filter((l) => l === 2 || l === 3 || l === 4 || l === 7).length;
}
p(count1);
const DIGITS: Record<string, string> = {
abcefg: "0",
cf: "1",
acdeg: "2",
acdfg: "3",
bcdf: "4",
abdfg: "5",
abdefg: "6",
acf: "7",
abcdefg: "8",
abcdfg: "9",
};
function readDigits(digits: string[], segmentMap: Record<string, string | undefined>): number | undefined {
const mappedDigits = digits.map((digit) =>
digit
.split("")
.map((segment) => segmentMap[segment] || "-")
.sort()
.join("")
);
const numberString = mappedDigits.map((mappedDigit) => DIGITS[mappedDigit] || "-").join("");
return numberString.indexOf("-") >= 0 ? undefined : parseInt(numberString);
}
const LETTERS = "abcdefg".split("");
let sum = 0;
outer: for (const line of lines) {
const [notes, input] = line.split(" | ");
const notedDigits = notes.split(" ");
const digits = input.split(" ");
const segmentMap: Record<string, string | undefined> = {};
for (let a = 0; a < 7; a++) {
const ma = LETTERS[a];
segmentMap[ma] = "a";
for (let b = 0; b < 7; b++) {
const mb = LETTERS[b];
if (segmentMap[mb]) continue;
segmentMap[mb] = "b";
for (let c = 0; c < 7; c++) {
const mc = LETTERS[c];
if (segmentMap[mc]) continue;
segmentMap[mc] = "c";
for (let d = 0; d < 7; d++) {
const md = LETTERS[d];
if (segmentMap[md]) continue;
segmentMap[md] = "d";
for (let e = 0; e < 7; e++) {
const me = LETTERS[e];
if (segmentMap[me]) continue;
segmentMap[me] = "e";
for (let f = 0; f < 7; f++) {
const mf = LETTERS[f];
if (segmentMap[mf]) continue;
segmentMap[mf] = "f";
for (let g = 0; g < 7; g++) {
const mg = LETTERS[g];
if (segmentMap[mg]) continue;
segmentMap[mg] = "g";
if (readDigits(notedDigits, segmentMap)) {
sum += readDigits(digits, segmentMap)!;
continue outer;
}
segmentMap[mg] = undefined;
}
segmentMap[mf] = undefined;
}
segmentMap[me] = undefined;
}
segmentMap[md] = undefined;
}
segmentMap[mc] = undefined;
}
segmentMap[mb] = undefined;
}
segmentMap[ma] = undefined;
}
}
p(sum);
|
<gh_stars>0
// Copyright (C) 2019-2021, <NAME>.
// @author xiongfa.li
// @version V1.0
// Description:
package stage
import (
"context"
"fmt"
"github.com/xfali/gobatis-cmd/pkg"
"github.com/xfali/gobatis-cmd/pkg/config"
"github.com/xfali/gobatis-cmd/pkg/generator"
"github.com/xfali/neve-gen/pkg/database"
"github.com/xfali/neve-gen/pkg/model"
"github.com/xfali/neve-gen/pkg/stringfunc"
"github.com/xfali/neve-gen/pkg/utils"
"github.com/xfali/xlog"
"os"
"path/filepath"
"strings"
)
type GenGobatisMapperStage struct {
logger xlog.Logger
target string
tmplSpec model.TemplateSepc
files []string
}
func NeGenGobatisMapperStage(target string, tmplSpec model.TemplateSepc) *GenGobatisMapperStage {
return &GenGobatisMapperStage{
logger: xlog.GetLogger(),
tmplSpec: tmplSpec,
target: target,
}
}
func (s *GenGobatisMapperStage) Name() string {
return s.tmplSpec.Name
}
func (s *GenGobatisMapperStage) ShouldSkip(ctx context.Context, model *model.ModelData) bool {
return !CheckCondition(ctx, s.tmplSpec.Condition, model)
}
func (s *GenGobatisMapperStage) Generate(ctx context.Context, model *model.ModelData) error {
select {
case <-ctx.Done():
return context.Canceled
default:
select {
case <-ctx.Done():
return context.Canceled
default:
infos, have := database.GetTableInfo(ctx)
if have {
for _, m := range model.Value.App.Modules {
info, ok := infos[m.Name]
if ok {
output := filepath.Join(s.target, s.tmplSpec.Target)
output = strings.Replace(output, "${MODULE}", stringfunc.FirstLower(m.Name), -1)
err := utils.Mkdir(output)
if err != nil {
s.logger.Errorln(err)
return fmt.Errorf("Create Module dir : %s failed. ", output)
}
conf := config.Config{
Driver: info.DriverName,
Path: output + "/",
PackageName: m.Pkg,
ModelFile: pkg.Camel2snake(m.Name),
TagName: "xfield,json,yaml,xml",
Keyword: model.Config.Gobatis.Keyword,
Namespace: fmt.Sprintf("%s.%s", m.Pkg, m.Name),
}
conf.MapperFile = info.Format
if strings.ToLower(info.Format) == "xml" {
s.files = append(s.files, filepath.Join(output, "xml", strings.ToLower(m.Name)+"_mapper.xml"))
generator.GenXml(conf, info.TableName, info.Info)
} else if strings.ToLower(info.Format) == "template" {
s.files = append(s.files, filepath.Join(output, "template", strings.ToLower(m.Name)+"_mapper.tmpl"))
generator.GenTemplate(conf, info.TableName, info.Info)
}
}
}
}
}
}
return nil
}
func (s *GenGobatisMapperStage) Rollback(ctx context.Context) error {
var last error
for _, v := range s.files {
err := os.Remove(v)
if err != nil {
last = err
s.logger.Errorln(err)
}
}
return last
}
|
import tensorflow as tf
import pandas as pd
from tensorflow.keras.layers import Input, Embedding, Dense, Flatten
from tensorflow.keras.models import Model
# Preprocess data
customers = pd.read_csv('customers.csv', usecols=['customer_id', 'name', 'purchase_history'])
customers['purchase_history'] = customers['purchase_history'].str.split(';')
# Create model
inputs = Input(shape=(1,))
emb_layer = Embedding(input_dim=customers.shape[0], output_dim=5)(inputs)
flatten = Flatten()(emb_layer)
dense_1 = Dense(10, activation='relu')(flatten)
outputs = Dense(1, activation='sigmoid')(dense_1)
model = Model(inputs=inputs, outputs=outputs)
model.compile(optimizer='adam', loss='binary_crossentropy', metrics=['accuracy'])
# Train model
model.fit(x_train, y_train,
epochs=50,
batch_size=32,
validation_data=(x_test, y_test))
# Deploy model in web service
api = tf.keras.models.load_model('purchase_prediction.h5')
|
#pragma once
#include <cmath>
#include <Dependencies/glm/glm/gtx/transform.hpp>
#include <Core/Base/include/Types.hpp>
namespace AVLIT {
using glm::cross;
using glm::dot;
using glm::epsilon;
using glm::inverse;
using glm::length;
using glm::lookAt;
using glm::normalize;
using glm::ortho;
using glm::perspective;
using glm::transpose;
using std::acos;
using std::asin;
using std::atan2;
using std::cos;
using std::sin;
using std::sqrt;
inline Mat4 rotate(const Vec3 &axis, float angle) { return glm::rotate(angle, axis); }
inline float pi() { return glm::pi<float>(); }
} // namespace AVLIT
|
<filename>try_spring_webmvc/src/main/java/com/github/gbz3/try_spring_webmvc/app/EchoController.java
package com.github.gbz3.try_spring_webmvc.app;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DataAccessException;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseStatus;
import com.github.gbz3.authlib.domain.mapper.AuthUserMapper;
import com.github.gbz3.authlib.domain.model.AuthUser;
@Controller
@RequestMapping("echo")
public class EchoController {
private static final Logger logger = LoggerFactory.getLogger( EchoController.class );
@Autowired
AuthUserMapper authUserMapper;
@RequestMapping(method = RequestMethod.GET)
public String viewInput(Model model) {
EchoForm form = new EchoForm();
model.addAttribute(form);
return "echo/input";
}
@Transactional
@RequestMapping(method = RequestMethod.POST)
public String echo(@Validated EchoForm form, BindingResult result, Model model) {
if(result.hasErrors()) {
return "echo/input";
//throw new IllegalStateException("dummy.");
}
logger.info( "OK?" );
try {
AuthUser user = authUserMapper.findOne( form.getText() );
logger.info( user.toString() );
} catch (DataAccessException e) {
logger.error(e.getLocalizedMessage(), e);
throw e;
}
return "echo/output";
}
@ExceptionHandler
@ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
public String handleException(Exception e) {
return "error";
}
}
|
// @flow
import React from 'react';
import { View } from 'react-native';
import { List } from 'immutable';
import { MenuComponent } from './registration/MenuComponent';
import { TermsScreen } from './registration/TermsScreen';
import { InputEmailComponent } from './registration/InputEmailComponent';
import { ConfirmEmailComponent } from './registration/ConfirmEmailComponent';
import { ValidateEmailComponent } from './registration/ValidateEmailComponent';
import { InputPreparedAccountComponent } from './registration/InputPreparedAccountComponent';
import { InputNameComponent } from './registration/InputNameComponent';
import { ConfirmNameComponent } from './registration/ConfirmNameComponent';
import { GS } from '../style';
import { FIXED_COURSE } from '../../version';
import * as storage from '../../models/typed_storage';
import type { UserInfo } from '../../types';
type Scene =
| 'menu'
| 'termsEmail'
| 'termsPreparedAccount'
| 'termsNoAccount'
| 'inputEmail'
| 'confirmEmail'
| 'validateEmail'
| 'inputPreparedAccount'
| 'inputName'
| 'confirmName';
type Route = {| scene: Scene | null |};
type Props = {|
complete: (myInfo: UserInfo) => void,
|};
type State = {|
email: string,
name: string,
course: string,
loginId: string,
myInfo: UserInfo | null,
routes: List<Route>,
|};
export class RegistrationComponent extends React.PureComponent {
props: Props;
state: State = {
email: '',
name: '',
course: '',
loginId: '',
myInfo: null,
routes: List([{ scene: 'menu' }]),
};
componentDidMount() {
this.init();
}
goBack() {
const { routes } = this.state;
this.setState({ routes: routes.pop() });
}
goto(scene: Scene) {
const { routes } = this.state;
this.setState({ routes: routes.push({ scene }) });
}
async init() {
const cache = await getCache();
if (cache.email) this.setState({ email: cache.email });
if (cache.name) this.setState({ name: cache.name });
}
renderScene(route: Route) {
const back = () => this.goBack();
switch (route.scene) {
case 'menu': {
return (
<MenuComponent
gotoTermsEmail={() => this.goto('termsEmail')}
gotoTermsPreparedAccount={() => this.goto('termsPreparedAccount')}
gotoTermsNoAccount={() => this.goto('termsNoAccount')}
/>
);
}
case 'termsEmail':
case 'termsPreparedAccount':
case 'termsNoAccount': {
const nextScene = {
termsEmail: 'inputEmail',
termsPreparedAccount: 'inputPreparedAccount',
termsNoAccount: 'inputName',
}[route.scene];
const next = () => {
this.goto(nextScene);
};
return <TermsScreen next={next} back={back} showAlert={false} />;
}
case 'inputEmail': {
const next = async (email: string) => {
this.setState({ email });
await storage.startupCache.patch({ email });
this.goto('confirmEmail');
};
return <InputEmailComponent initialEmail={this.state.email} next={next} back={back} />;
}
case 'confirmEmail': {
const next = async () => {
await storage.startupCache.patch({ emailRegistered: true });
this.goto('validateEmail');
};
return <ConfirmEmailComponent email={this.state.email} next={next} back={back} />;
}
case 'validateEmail':
case 'inputPreparedAccount': {
const next = async (myInfo: UserInfo) => {
await storage.userId.set(myInfo.id);
await storage.startupCache.patch({ id: myInfo.id });
if (myInfo.ready) {
this.props.complete(myInfo);
} else {
const name = myInfo.name || this.state.name;
this.setState({ myInfo, name });
this.goto('inputName');
}
};
if (route.scene === 'validateEmail') {
return <ValidateEmailComponent email={this.state.email} next={next} back={back} />;
} else {
return <InputPreparedAccountComponent next={next} back={back} />;
}
}
case 'inputName': {
const fixedCourse = FIXED_COURSE || (this.state.myInfo && this.state.myInfo.course) || null;
const next = async (name: string, course: string) => {
this.setState({ name, course });
await storage.startupCache.patch({ name, course });
this.goto('confirmName');
};
return (
<InputNameComponent
initialName={this.state.name}
initialCourse={this.state.course}
fixedCourse={fixedCourse}
next={next}
back={back}
/>
);
}
case 'confirmName': {
const next = async (myInfo: UserInfo) => {
await storage.userId.set(myInfo.id);
console.log('userId', myInfo.id);
return this.props.complete(myInfo);
};
return (
<ConfirmNameComponent
name={this.state.name}
course={this.state.course}
myInfo={this.state.myInfo}
next={next}
back={back}
/>
);
}
}
return null;
}
render() {
const { routes } = this.state;
const route = routes.last();
return <View style={[GS.flex, GS.bgWhite]}>{route && this.renderScene(route)}</View>;
}
}
export type StartupRecord = {
email: string,
name: string,
};
async function getCache(): Promise<StartupRecord> {
const cache = await storage.startupCache.get();
if (cache) return cache;
await storage.startupCache.set(DEFAULT_STARTUP_RECORD);
return { ...DEFAULT_STARTUP_RECORD };
}
const DEFAULT_STARTUP_RECORD: StartupRecord = {
email: '',
name: '',
};
|
#!/bin/bash
set -e
if [[ ! "$TRAVIS_BRANCH" =~ ^release/.*$ ]]; then
echo "Skipping release because this is not a 'release/*' branch"
exit 0
fi
# Travis executes this script from the repository root, so at the same level than package.json
VERSION=$(node -p -e "require('./package.json').version")
# Make sure that the associated tag doesn't already exist
GITTAG=$(git ls-remote origin refs/tags/v$VERSION)
if [ "$GITTAG" != "" ]; then
echo "Tag for package.json version already exists, aborting release"
exit 1
fi
git remote add auth-origin https://$GITHUB_AUTH_TOKEN@github.com/$TRAVIS_REPO_SLUG.git
git config --global user.email "$GITHUB_AUTH_EMAIL"
git config --global user.name "kurkle"
git checkout --detach --quiet
git add -f dist/*.js bower.json
git commit -m "Release $VERSION"
git tag -a "v$VERSION" -m "Version $VERSION"
git push -q auth-origin refs/tags/v$VERSION 2>/dev/null
git remote rm auth-origin
git checkout -f @{-1}
|
def removeDuplicates(arr):
uniqueList = []
for elem in arr:
if elem not in uniqueList:
uniqueList.append(elem)
arr = uniqueList
return arr
|
<gh_stars>1000+
/**
* Copyright 2013 Google Inc. All Rights Reserved.
*
* 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.
*/
'use strict';
/**
* Extends the testharness assert functions to support style checking and
* transform checking.
*
* >> This script must be loaded after testharness. <<
*
* Keep this file under same formatting as testharness itself.
*/
(function() {
/**
* These functions come from testharness.js but can't be access because
* testharness uses an anonymous function to hide them.
**************************************************************************
*/
function forEach(array, callback, thisObj) {
for (var i=0; i < array.length; i++) {
if (array.hasOwnProperty(i)) {
callback.call(thisObj, array[i], i, array);
}
}
}
/* ********************************************************************* */
var pageerror_test = async_test('Page contains no errors');
function pageerror_onerror_callback(evt) {
var msg = 'Error in ' + evt.filename + '\n' +
'Line ' + evt.lineno + ': ' + evt.message + '\n';
pageerror_test.is_done = true;
pageerror_test.step(function() {
assert_true(false, msg);
});
pageerror_test.is_done = false;
};
addEventListener('error', pageerror_onerror_callback);
var pageerror_tests;
function pageerror_othertests_finished(test, harness) {
if (harness == null && pageerror_tests == null) {
return;
}
if (pageerror_tests == null) {
pageerror_tests = harness;
}
if (pageerror_tests.all_loaded && pageerror_tests.num_pending == 1) {
pageerror_test.done();
}
}
add_result_callback(pageerror_othertests_finished);
addEventListener('load', pageerror_othertests_finished);
/* ********************************************************************* */
var svg_properties = {
cx: 1,
width: 1,
x: 1,
y: 1
};
var is_svg_attrib = function(property, target) {
return target.namespaceURI == 'http://www.w3.org/2000/svg' &&
property in svg_properties;
};
var svg_namespace_uri = 'http://www.w3.org/2000/svg';
var features = (function() {
var style = document.createElement('style');
style.textContent = '' +
'dummyRuleForTesting {' +
'width: calc(0px);' +
'width: -webkit-calc(0px); }';
document.head.appendChild(style);
var transformCandidates = [
'transform',
'webkitTransform',
'msTransform'
];
var transformProperty = transformCandidates.filter(function(property) {
return property in style.sheet.cssRules[0].style;
})[0];
var calcFunction = style.sheet.cssRules[0].style.width.split('(')[0];
document.head.removeChild(style);
return {
transformProperty: transformProperty,
calcFunction: calcFunction
};
})();
/**
* Figure out a useful name for an element.
*
* @param {Element} element Element to get the name for.
*
* @private
*/
function _element_name(element) {
if (element.id) {
return element.id;
} else {
return 'An anonymous ' + element.tagName;
}
}
/**
* Get the style for a given element.
*
* @param {Array.<Object.<string, string>>|Object.<string, string>} style
* Either;
* * A list of dictionaries, each node returned is checked against the
* associated dictionary, or
* * A single dictionary, each node returned is checked against the
* given dictionary.
* Each dictionary should be of the form {style_name: style_value}.
*
* @private
*/
function _assert_style_get(style, i) {
if (typeof style[i] === 'undefined') {
return style;
} else {
return style[i];
}
}
/**
* asserts that actual has the same styles as the dictionary given by
* expected.
*
* @param {Element} object DOM node to check the styles on
* @param {Object.<string, string>} styles Dictionary of {style_name: style_value} to check
* on the object.
* @param {String} description Human readable description of what you are
* trying to check.
*
* @private
*/
function _assert_style_element(object, style, description) {
// Create an element of the same type as testing so the style can be applied
// from the test. This is so the css property (not the -webkit-does-something
// tag) can be read.
var reference_element = (object.namespaceURI == svg_namespace_uri) ?
document.createElementNS(svg_namespace_uri, object.nodeName) :
document.createElement(object.nodeName);
var computedObjectStyle = getComputedStyle(object, null);
for (var i = 0; i < computedObjectStyle.length; i++) {
var property = computedObjectStyle[i];
reference_element.style.setProperty(property,
computedObjectStyle.getPropertyValue(property));
}
reference_element.style.position = 'absolute';
if (object.parentNode) {
object.parentNode.appendChild(reference_element);
}
try {
// Apply the style
for (var prop_name in style) {
// If the passed in value is an element then grab its current style for
// that property
if (style[prop_name] instanceof HTMLElement ||
style[prop_name] instanceof SVGElement) {
var prop_value = getComputedStyle(style[prop_name], null)[prop_name];
} else {
var prop_value = style[prop_name];
}
if (prop_name == 'transform') {
var output_prop_name = features.transformProperty;
} else {
var output_prop_name = prop_name;
}
var is_svg = is_svg_attrib(prop_name, object);
if (is_svg) {
reference_element.setAttribute(prop_name, prop_value);
var current_style = object.attributes;
var target_style = reference_element.attributes;
} else {
reference_element.style[output_prop_name] = prop_value;
var current_style = computedObjectStyle;
var target_style = getComputedStyle(reference_element, null);
}
if (prop_name == 'ctm') {
var ctm = object.getCTM();
var curr = '{' + ctm.a + ', ' +
ctm.b + ', ' + ctm.c + ', ' + ctm.d + ', ' +
ctm.e + ', ' + ctm.f + '}';
var target = prop_value;
} else if (is_svg) {
var target = target_style[prop_name].value;
var curr = current_style[prop_name].value;
} else {
var target = target_style[output_prop_name];
var curr = current_style[output_prop_name];
}
if (target) {
var t = target.replace(/[^0-9.\s-]/g, '');
} else {
var t = '';
}
if (curr) {
var c = curr.replace(/[^0-9.\s-]/g, '');
} else {
var c = '';
}
if (t.length == 0) {
// Assume it's a word property so do an exact assert
assert_equals(
curr, target,
prop_name + ' is not ' + target + ', actually ' + curr);
} else {
t = t.split(' ');
c = c.split(' ');
for (var x in t) {
assert_equals(
Number(c[x]), Number(t[x]),
prop_name + ' is not ' + target + ', actually ' + curr);
}
}
}
} finally {
if (reference_element.parentNode) {
reference_element.parentNode.removeChild(reference_element);
}
}
}
/**
* asserts that elements in the list have given styles.
*
* @param {Array.<Element>} objects List of DOM nodes to check the styles on
* @param {Array.<Object.<string, string>>|Object.<string, string>} style
* See _assert_style_get for information.
* @param {String} description Human readable description of what you are
* trying to check.
*
* @private
*/
function _assert_style_element_list(objects, style, description) {
var error = '';
forEach(objects, function(object, i) {
try {
_assert_style_element(
object, _assert_style_get(style, i),
description + ' ' + _element_name(object)
);
} catch (e) {
if (error) {
error += '; ';
}
error += _element_name(object) + ' at index ' + i + ' failed ' + e.message + '\n';
}
});
if (error) {
throw error;
}
}
/**
* asserts that elements returned from a query selector have a list of styles.
*
* @param {string} qs A query selector to use to get the DOM nodes.
* @param {Array.<Object.<string, string>>|Object.<string, string>} style
* See _assert_style_get for information.
* @param {String} description Human readable description of what you are
* trying to check.
*
* @private
*/
function _assert_style_queryselector(qs, style, description) {
var objects = document.querySelectorAll(qs);
assert_true(objects.length > 0, description +
' is invalid, no elements match query selector: ' + qs);
_assert_style_element_list(objects, style, description);
}
/**
* asserts that elements returned from a query selector have a list of styles.
*
* Assert the element with id #hello is 100px wide;
* assert_styles(document.getElementById('hello'), {'width': '100px'})
* assert_styles('#hello'), {'width': '100px'})
*
* Assert all divs are 100px wide;
* assert_styles(document.getElementsByTagName('div'), {'width': '100px'})
* assert_styles('div', {'width': '100px'})
*
* Assert all objects with class 'red' are 100px wide;
* assert_styles(document.getElementsByClassName('red'), {'width': '100px'})
* assert_styles('.red', {'width': '100px'})
*
* Assert first div is 100px wide, second div is 200px wide;
* assert_styles(document.getElementsByTagName('div'),
* [{'width': '100px'}, {'width': '200px'}])
* assert_styles('div',
* [{'width': '100px'}, {'width': '200px'}])
*
* @param {string|Element|Array.<Element>} objects Either;
* * A query selector to use to get DOM nodes,
* * A DOM node.
* * A list of DOM nodes.
* @param {Array.<Object.<string, string>>|Object.<string, string>} style
* See _assert_style_get for information.
*/
function assert_styles(objects, style, description) {
switch (typeof objects) {
case 'string':
_assert_style_queryselector(objects, style, description);
break;
case 'object':
if (objects instanceof Array || objects instanceof NodeList) {
_assert_style_element_list(objects, style, description);
} else if (objects instanceof Element) {
_assert_style_element(objects, style, description);
} else {
throw new Error('Expected Array, NodeList or Element but got ' + objects);
}
break;
}
}
window.assert_styles = assert_styles;
})();
|
#!/bin/bash
# exit immediately if a command exits with a non-zero status
set -e
# Define some environment variables
# Automatic export to the environment of subsequently executed commands
# source: the command 'help export' run in Terminal
export IMAGE_NAME="vqa-app-frontend-simple"
export BASE_DIR=$(pwd)
# Build the image based on the Dockerfile
docker build -t $IMAGE_NAME -f Dockerfile_dev .
# Run the container
# --mount: Attach a filesystem mount to the container
# -p: Publish a container's port(s) to the host (host_port: container_port) (source: https://dockerlabs.collabnix.com/intermediate/networking/ExposingContainerPort.html)
# TODO: CHANGE TO 8080:8080
docker run --rm --name $IMAGE_NAME -ti \
--mount type=bind,source="$BASE_DIR",target=/app \
-p 3000:8080 $IMAGE_NAME
|
package next_permutation;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.Arrays;
/**
*
* @author minchoba
* ๋ฐฑ์ค 1342๋ฒ: ํ์ด์ ๋ฌธ์์ด
*
* @see https://www.acmicpc.net/problem/1342/
*
*/
public class Boj1342 {
public static void main(String[] args) throws Exception{
// ๋ฒํผ๋ฅผ ํตํ ๊ฐ ์
๋ ฅ
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
char[] seq = br.readLine().toCharArray();
int res = 0;
boolean isGood = true;
Arrays.sort(seq);
for(int i = 1; i < seq.length; i++) { // ์ ๋ ฌ ๋ ์ฒซ ๋ฌธ์์ด์ด ํ์ด์ ๋ฌธ์์ด์ธ์ง ๊ฒ์ฌ
if(seq[i - 1] == seq[i]) {
isGood = false;
break;
}
}
if(isGood) res++;
while(true) {
StringBuilder sb = new StringBuilder();
int idx = -1;
isGood = true;
for(int i = 1; i < seq.length; i++) { // ๊ฐ์ฅ ํฐ ์๊ฐ ์กด์ฌํ๋ ๋ฐ๋ก ์ด์ ์ธ๋ฑ์ค๋ฅผ ๊ฐ์ ธ์์ ์ ์ฅ
if(seq[i - 1] < seq[i]) idx = i - 1;
}
if(idx == -1) break; // ๋ฌธ์์ด์ด ๊ฐ์ฅ ๋ง์ง๋ง ์์ด์ด ์ง๋ ๊ฒฝ์ฐ ์ข
๋ฃ
for(int i = seq.length - 1; i > idx; i--) {
if(seq[idx] < seq[i]) { // ๋ฝ์๋ธ ์๋ณด๋ค ํฐ ์๊ฐ ์๋ฐ๋ฉด ์๋ฆฌ ๋ฐ๊ฟ
char tmp = seq[i];
seq[i] = seq[idx];
seq[idx] = tmp;
break;
}
}
for(int i = 0; i < idx + 1; i++) sb.append(seq[i]); // ๊ตฌํ ๋ค์ ์์ด์ ๋ฒํผ์ ์ ์ฅ
for(int i = seq.length - 1; i > idx; i--) sb.append(seq[i]);
for(int i = 0; i < seq.length; i++) { // ๋ค์ ์์ด๋ก ๋ณธ๋ ๋ฐฐ์ด์ ๊ฐฑ
seq[i] = sb.toString().charAt(i);
if(i > 0) { // ๊ทธ ์์ด์ด ํ์ด์ ๋ฌธ์์ด์ธ์ง ์ฒดํฌ
if(seq[i - 1] == seq[i]) isGood = false;
}
}
if(isGood) res++; // ๊ฐฏ์ +1
}
System.out.println(res); // ํ์ด์ ๋ฌธ์์ด ๊ฐฏ์ ์ถ๋ ฅ
}
}
|
import axios from 'axios';
import Config from 'react-native-config';
import {IMAGE_SERVERS} from '~/constants/blockchain';
const IMAGE_API = IMAGE_SERVERS[0];
//// upload image
export const uploadImage = (media, username: string, sign) => {
const file = {
uri: media.path,
type: media.mime,
name: media.filename || `img_${Math.random()}.jpg`,
size: media.size,
};
const fData = new FormData();
fData.append('file', file);
return _upload(fData, username, sign);
};
const _upload = (fd, username: string, signature) => {
console.log(
'[imageApi|_upload] baseURL',
`${IMAGE_API}/${username}/${signature}`,
);
const image = axios.create({
baseURL: `${IMAGE_API}/${username}/${signature}`,
headers: {
Authorization: IMAGE_API,
'Content-Type': 'multipart/form-data',
},
});
return image.post('', fd);
};
//// upload image
// e.g. "profile_image":"https://images.blurt.buzz/DQmP1NegAx2E3agYjgdzn4Min9eVVxSdyXxgQ2DWLwHBKbi/helpus_icon.png"
// export const uploadProfileImage = (media, username: string, signature) => {
// const file = {
// uri: media.path,
// type: media.mime,
// name: media.filename || `img_${Math.random()}.jpg`,
// size: media.size,
// };
// const fData = new FormData();
// fData.append('file', file);
// console.log(
// '[imageApi|_upload] baseURL',
// `${PROFILE_IMAGE_API}/${signature}`,
// );
// const image = axios.create({
// baseURL: `${PROFILE_IMAGE_API}/${signature}/${media.filename}`,
// headers: {
// Authorization: PROFILE_IMAGE_API,
// 'Content-Type': 'multipart/form-data',
// },
// });
// return image.post('', fData);
// };
|
<reponame>rohankumardubey/Batchman<gh_stars>10-100
package com.flipkart.batching.core.batch;
import com.flipkart.batching.core.data.Tag;
import junit.framework.Assert;
import org.junit.Test;
import java.util.Collections;
/**
* Created by anirudh.r on 11/08/16.
* Test for {@link TagBatch}
*/
public class TagBatchTest {
/**
* Test for get tag
*
* @throws Exception
*/
@Test
public void testGetTag() throws Exception {
TagBatch tagBatch = new TagBatch(new Tag("test"), new SizeBatch(Collections.EMPTY_LIST, 10));
Tag tag = tagBatch.getTag();
String id = tag.getId();
//assert that the id are same
Assert.assertTrue(id.equals("test"));
}
/**
* Test for equals method
*
* @throws Exception
*/
@Test
public void testEqualsMethod() throws Exception {
TagBatch tagBatch = new TagBatch(new Tag("test"), new SizeBatch(Collections.EMPTY_LIST, 10));
TagBatch tagBatch1 = new TagBatch(new Tag("test"), new SizeBatch(Collections.EMPTY_LIST, 10));
//assert that both tag batch are same
Assert.assertTrue(tagBatch.equals(tagBatch1));
tagBatch = new TagBatch(new Tag("test"), new SizeBatch(Collections.EMPTY_LIST, 10));
tagBatch1 = new TagBatch(new Tag("test1"), new SizeBatch(Collections.EMPTY_LIST, 10));
//assert that both tag batch are not same since they have diff tag
Assert.assertTrue(!tagBatch.equals(tagBatch1));
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.