text stringlengths 1 1.05M |
|---|
const digits = ['','one', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight', 'nine', 'ten'];
const teens = [ 'eleven', 'twelve', 'thirteen','fourteen', 'fifteen','sixteen','seventeen','eighteen','nineteen'];
const decimals = ['twenty', 'thirty', 'forty','fifty', 'sixty', 'seventy', 'eighty', 'ninety'];
module.exports = function toReadable (num) {
if(num === 0) {
return 'zero';
}
if(typeof(num) == "undefined") return;
switch(num.toString().length) {
case 1 :
return digits[num];
case 2 :
return showDecimals(num);
case 3:
return `${digits[num.toString()[0]]} hundred ${showDecimals(num.toString().slice(1,3))}`.trim();
}
}
const showDecimals = (num) => {
num = +num;
if (num < 11) {
return showSimpleDigits(num);
}else if (num < 20) {
return teens[num.toString().slice(1,2)-1];
} else if(num === 20) {
return decimals[0];
} else {
return `${decimals[num.toString()[0]-2]} ${digits[num.toString()[1]]}`.trim();
}
};
const showSimpleDigits = (num) => {
return digits[+num];
};
|
#
# Copyright (c) 2010, 2016 Tender.Pro http://tender.pro.
#
# pgm.sh - Postgresql schema control script
#
# ------------------------------------------------------------------------------
# See project home for details: https://github.com/TenderPro/pgm
#
VERSION="1.1"
db_help() {
cat <<EOF
Usage:
$0 COMMAND [PKG]
Where COMMAND is one from
check - check for required programs presense
init - create config file (if PKG not set)
init - create PKG skeleton files
create - create PKG objects
creatif - create PKG objects if not exists
recreate - drop PKG objects if exists and create
make - compile PKG code
drop - drop PKG objects intender to rebuild
erase - drop all of PKG objects including persistent data
createdb - create database (if shell user granted)
dump - dump schema SRC (Default: all)
restore - restore dump from SRC
PKG - package, dirname(s) inside sql/ dir. Default: "ws"
EOF
}
# ------------------------------------------------------------------------------
db_init() {
local file=$1
[ -f $file ] && return
cat > $file <<EOF
#
# PGM config file
#
# Database name
DB_NAME=pgm01
# User name
DB_USER=op
# User password
DB_PASS=op_secret
# Database host
PG_HOST=localhost
# Template database
DB_TEMPLATE=tpro-template
# Directory of Postgresql binaries (psql, pg_dump, pg_restore, createdb, createlang)
# Empty if they are in search path
# Command to check: dirname "\$(whereis -b psql)"
PG_BINDIR=""
# Do not remove sql preprocess files (var/build)
KEEP_SQL="1"
EOF
}
sql_template() {
cat <<EOF
/*
pgm. $1
*/
-- ----------------------------------------------------------------------------
EOF
case "$1" in
drop)
echo "DROP SCHEMA :SCH CASCADE;"
;;
create)
echo "CREATE SCHEMA :SCH;"
echo "COMMENT ON SCHEMA :SCH IS 'created by pgm';"
;;
test)
echo "SELECT test('testname');"
echo "SELECT TRUE AS result;"
;;
esac
}
# ------------------------------------------------------------------------------
# copy of psql output
sql_template_test() {
cat <<EOF
test
-----------------------
***** testname *****
result
--------
t
EOF
}
# ------------------------------------------------------------------------------
db_init_pkg() {
local dir=sql
for p in $@ ; do
echo $p
[ -d $dir/$p ] || mkdir -p $dir/$p
[ -f $dir/$p/02_drop.sql ] || sql_template drop > $dir/$p/02_drop.sql
[ -f $dir/$p/11_create.sql ] || sql_template create > $dir/$p/11_create.sql
[ -f $dir/$p/90_test.sql ] || sql_template test > $dir/$p/90_test.sql
[ -f $dir/$p/90_test.md ] || sql_template_test > $dir/$p/90_test.md
done
}
# ------------------------------------------------------------------------------
db_show_logfile() {
cat <<EOF
Logfile: $LOGFILE
---------------------------------------------------------
EOF
}
# ------------------------------------------------------------------------------
db_run_sql_begin() {
local file=$1
cat > $file <<EOF
/* ------------------------------------------------------------------------- */
\qecho '-- _build.sql / BEGIN --'
\cd $ROOT/var/build
\timing on
\set ECHO all
BEGIN;
\set ON_ERROR_STOP 1
SET CLIENT_ENCODING TO 'utf-8';
-- SET CONSTRAINTS ALL DEFERRED;
EOF
if [[ "$BUILD_DEBUG" ]] ; then
echo "SET CLIENT_MIN_MESSAGES TO 'DEBUG';" >> $file
else
echo "SET CLIENT_MIN_MESSAGES TO 'WARNING';" >> $file
fi
}
# ------------------------------------------------------------------------------
db_run_sql_end() {
local file=$1
if [[ "$NO_COMMIT" ]] ; then
echo 'ROLLBACK;' >> $file
else
echo 'COMMIT;' >> $file
if [[ "$NOTIFY" != "--" ]] ; then
local signal=${NOTIFY:-dbrpc_reset}
echo "NOTIFY $signal;" >> $file
fi
fi
cat >> $file <<EOF
\qecho '-- _build.psql / END --'
/* ------------------------------------------------------------------------- */
EOF
}
# ------------------------------------------------------------------------------
db_run_test() {
local bd=$1
local test=$2
local name=$3
local point=$4
local file=$5
local out=$bd/$name.md
cat >> $file <<EOF
SAVEPOINT ${point}_test;
\set TEST $bd/$name
\set OUTW '| echo ''\`\`\`sql'' >> $out ; cat >> $out ; echo '';\n\`\`\`'' >> $out'
\set OUTG '| $AWK_BIN ''{ gsub(/--\\\+--/, "--|--"); print }'' >> $out'
\set OUTT '| echo -n ''##'' >> $out ; cat >> $out'
\! echo "# $bd:$name\n" > $out
\o
\i $bd/$n
ROLLBACK TO SAVEPOINT ${point}_test;
EOF
}
# ------------------------------------------------------------------------------
db_run_test_end() {
local file=$1
cat >> $file <<EOF
delete from $PGM_SCHEMA.compile_errors;
\copy $PGM_SCHEMA.compile_errors(data) from errors.diff
\! cat errors.diff
select $PGM_SCHEMA.compile_errors_chk();
EOF
}
# ------------------------------------------------------------------------------
file_protected_csum() {
local pkg=$1
local schema=$2
local file=$3
local sql="SELECT csum FROM $PGM_STORE.pkg_script_protected WHERE pkg = '$pkg' AND schema = '$schema' AND code = '$file'"
#PGPASSWORD=$DB_NAME ${PG_BINDIR}$cmd -U $u -h $h $pre "$@" $last
dbd psql -X -P tuples_only -c "$sql" 2>> /dev/null | while read result ; do
echo $result
done
}
# ------------------------------------------------------------------------------
TEST_CNT="0"
TEST_TTL="0"
log() {
local test_total=$1
local filenew
local fileold
ret="0"
echo "1..$test_total"
while read data
do
d=${data#* WARNING: ::}
if [[ "$data" != "$d" ]] ; then
filenew=${data%.sql*}
filenew=${filenew#*psql:}
if [[ "$fileold" != "$filenew" ]] ; then
tput setaf 2 2>/dev/null #set green color
[[ "$TEST_CNT" == "0" ]] || echo "ok $out"
TEST_CNT=$(($TEST_CNT+1))
[[ "$filenew" ]] && out="$TEST_CNT - ${filenew%.macro}.sql"
fileold=$filenew
tput setaf 9 2>/dev/null #set default color
fi
[[ "$d" ]] && echo "#$d"
else
tput setaf 1 2>/dev/null #set red color
[[ "$ret" != "0" ]] || echo "not ok $out"
echo "$data" >> ${LOGFILE}.err
echo "$data"
ret="1"
fi
done
tput setaf 9 2>/dev/null #set default color
return $ret
}
# ------------------------------------------------------------------------------
generate_build_sql() {
echo "Seeking files..."
local cat_cmd="cat"
[[ "$op_is_del" ]] && cat_cmd=$TAC_BIN # Проходим каталоги в обратном порядке
local p_pre=""
echo -n "0" > $BLD/test.cnt
$cat_cmd $dirs | while read path p s ; do
pn=${p%%/sql} # package name without suffix
sn=${s#??_} # schema name
bd=$pn # build dir
if [[ "$sn" ]] ; then
bd=$bd-$sn
else
sn=$pn
fi
debug " ********* $pn / $sn / $bd "
if [[ "$p" != "$p_pre" ]] ; then
echo -n "$pn: "
echo "\\qecho '-- ******* Package: $pn --'" >> $BLD/build.sql
echo "\\set PKG $pn" >> $BLD/build.sql
fi
echo "\\set SCH $sn" >> $BLD/build.sql
echo "\\qecho '-- ------- Schema: $sn'" >> $BLD/build.sql
if [[ "$pn:$sn" != "$PGM_PKG:$PGM_SCHEMA" || "$run_op" != "create" ]] ; then
# начало выполнения операции (не вызывается только для create схемы $PGM_SCHEMA пакета $PGM_PKG)
echo "SELECT $PGM_SCHEMA.pkg_op_before('$run_op', '$pn', '$sn', '$LOGNAME', '$USERNAME', '$SSH_CLIENT');" >> $BLD/build.sql
fi
[ -d "$BLD/$bd" ] || mkdir $BLD/$bd
echo -n > $BLD/errors.diff
pushd $path/$p > /dev/null
[[ "$s" ]] && pushd $s > /dev/null
local search_set=""
debug "Search $file_mask in $PWD"
for f in $file_mask ; do
[ -f "$f" ] || continue
echo -n "."
n=$(basename $f)
debug "Found: $s/$f ($n)"
echo "Processing file: $s/$f" >> $LOGFILE
local csum=""
if test $f -nt $BLD/$bd/$n ; then
# $f is newer than $BLD/$bd/$n
csum0=$($CSUM_BIN $f)
csum=${csum0% *}
echo "\\qecho '----- ($csum) $pn:$sn:$n -----'">> $BLD/build.sql
# вариант с заменой 1го вхождения + поддержка plperl
$AWK_BIN "{ print gensub(/(\\\$_\\\$)($| +#?)/, \"\\\1\\\2 /* $pn:$sn:\" FILENAME \" / \" FNR \" */ \",\"g\")};" $f > $BLD/$bd/$n
# вариант без удаления прошлых комментариев
# awk "{gsub(/\\\$_\\\$(\$| #?)/, \"/* $pn:$sn:$n / \" FNR \" */ \$_\$ /* $pn:$sn:$n / \" FNR \" */ \")}; 1" $f > $BLD/$bd/$n
# вариант с удалением прошлых комментариев
# awk "{gsub(/(\/\* .+ \/ [0-9]+ \*\/ )?\\\$_\\\$( \/\* .+ \/ [0-9]+ \*\/)?/, \"/* $pn:$sn:$n / \" FNR \" */ \$_\$ /* $pn:$sn:$n / \" FNR \" */ \")}; 1" $f > $BLD/$bd/$n
fi
# настройка search_path для create и make
if [[ ! "$search_set" ]] && [[ "$n" > "12_00" ]]; then
echo "DO \$_\$ BEGIN IF (SELECT count(1) FROM pg_namespace WHERE nspname = '$sn') > 0 AND '$sn' <> '$PGM_SCHEMA' THEN SET search_path = $sn, $PGM_SCHEMA, public; ELSE SET search_path = $PGM_SCHEMA, public; END IF; END; \$_\$;" >> $BLD/build.sql
search_set=1
fi
local db_csum=""
local skip_file=""
if [[ "$n" =~ .+_${PGM_STORE}_[0-9]{3}\.sql ]]; then # old bash: ${X%_wsd_[0-9][0-9][0-9].sql}
# protected script
[[ "$csum" == "" ]] && csum0=$($CSUM_BIN $f) && csum=${csum0% *}
local db_csum=$(file_protected_csum $pn $sn $n)
debug "$f protected: $db_csum /$csum"
if [[ "$db_csum" ]]; then
if [[ "$db_csum" != "$csum" ]]; then
echo "!!!WARNING!!! Changed control sum of protected file $f. Use 'db erase' or 'git checkout -- $f'"
skip_file=1
else
# already installed. Skip
skip_file=1
fi
else
# save csum
db_csum=$csum
fi
fi
# однократный запуск PROTECTED
if [[ ! "$skip_file" ]]; then
echo "\\set FILE $n" >> $BLD/build.sql
echo "\i $bd/$n" >> $BLD/build.sql
[[ "$db_csum" ]] && echo "INSERT INTO $PGM_STORE.pkg_script_protected (pkg, schema, code, csum) VALUES ('$pn', '$sn', '$n', '$db_csum');" >> $BLD/build.sql
else
echo "\\qecho '----- SKIPPED PROTECTED FILE -----'" >> $BLD/build.sql
[[ "$db_csum" != "$csum" ]] && echo "\\qecho '!!!WARNING!!! db csum $db_csum <> file csum $csum'" >> $BLD/build.sql
fi
done
if [[ ! "$op_is_del" ]] ; then
# тесты для create и make
echo "SET LOCAL search_path = $PGM_SCHEMA, public;" >> $BLD/build.sql
# TODO: 01_require.sql
# файлы 9?_*.macro.sql просто копируем - они вспомогательные
if ls 9?_*.macro.sql 1> /dev/null 2>&1; then
cp 9?_*.macro.sql $BLD/$bd/
fi
# если есть каталог с данными - создаем симлинк
[ -d data ] && [ ! -L $BLD/$bd/data ] && ln -s $PWD/data $BLD/$bd/data
c="1"
for f in 9?_*.sql ; do
[ -s "$f" ] || continue
[[ "${f%.macro.sql}" == "$f" ]] || continue # skip .macro.sql
echo -n "."
n=$(basename $f)
debug "Found test: $f"
echo "Processing file: $f" >> $LOGFILE
[[ "$c" ]] && echo -n "+$c" >> $BLD/test.cnt
cp -p $f $BLD/$bd/$n # no replaces in test file
n1=${n%.sql} # remove ext
# заменим "; -- BOT" на "\g :OUTT"
$AWK_BIN -i inplace "{ gsub(/; *-- *BOT/, \"\n\\\pset t on\n\\\g :OUTT\n\\\pset t off\"); print }" $BLD/$bd/$n
search="; *-- *EOT"
psqlcommand="\n\\\w :OUTW\n\\\g :OUTG"
# заменим "; -- EOT" на "\w \g"
$AWK_BIN -i inplace "{ gsub(/$search/, \"$psqlcommand\"); print }" $BLD/$bd/$n
[[ -s "$n1.macro.sql" ]] && $AWK_BIN -i inplace "{ gsub(/$search/,\"$psqlcommand\"); print}" $BLD/$bd/$n1.macro.sql
db_run_test $bd $n $n1 $sn $BLD/build.sql
cp $n1.md $BLD/$bd/$n1.md.orig 2>> $BLD/errors.diff
echo "\! diff -c $bd/$n1.md.orig $bd/$n1.md | tr \"\t\" \" \" >> errors.diff" >> $BLD/build.sql
db_run_test_end $BLD/build.sql
done
fi
[[ "$s" ]] && popd > /dev/null # $s
popd > /dev/null # $p
[[ "KEEP_SQL" ]] || echo "\! rm -rf $bd" >> $BLD/build.sql
# завершение выполнения операции (не вызывается только для drop/erase схемы $PGM_SCHEMA пакета $PGM_PKG)
( [[ "$pn:$sn" != "$PGM_PKG:$PGM_SCHEMA" ]] || [[ ! "$op_is_del" ]] ) \
&& echo "SELECT $PGM_SCHEMA.pkg_op_after('$run_op', '$pn', '$sn', '$LOGNAME', '$USERNAME', '$SSH_CLIENT');" >> $BLD/build.sql
p_pre=$p
echo .
done
}
# ------------------------------------------------------------------------------
is_pkg_exists() {
local sql="SELECT EXISTS(SELECT id FROM ws.pkg WHERE code='$1');"
echo -n $(dbd psql -X -P tuples_only -c "$sql" 2>> /dev/null)
}
# ------------------------------------------------------------------------------
lookup_dirs() {
local path=$1
local mask=$2
local tag=$3
# look for
# A: tag/*.sql (if schema = tag)
# B: tag/sql/NN_schema/*.sql
# C: tag/NN_schema/*.sql
local s=""
for f in $tag/*.sql; do
# A: tag/*.sql (if schema = tag)
[ -e "$f" ] && s=$tag
break
done
if [[ "$s" ]]; then
echo "Found: $path/$s"
echo "$path $tag" >> $dirs
else
[ -d sql ] && tag=$tag/sql # B: tag/sql/NN_schema/*.sql
for s in $tag/$schema_mask ; do
echo "Found: $path/$s"
echo "$path $tag ${s#*/}" >> $dirs
done
fi
}
# ------------------------------------------------------------------------------
db_run() {
local run_op_arg=$1 ; shift
local file_mask=$1 ; shift
local file_mask_ext=none
if test "$#" -eq 2; then
# осталось два аргумента, первый - маска файлов для второго прохода
file_mask_ext=$1 ; shift
fi
local pkg=$@
local use_flag
local run_op=$run_op_arg
[[ "$pkg" ]] || pkg=$PGM_PKG
cat <<EOF
DB Package: $pkg
EOF
db_show_logfile
schema_mask="??_*"
db_run_sql_begin $BLD/build.sql
op_is_del=""
[[ "$run_op" == "drop" || "$run_op" == "erase" ]] && op_is_del=1
pushd $ROOT > /dev/null
echo "Seeking dirs in $pkg..."
local dirs=$BLD/build.dirs
local mask_create=""
local skip_step1="" # no skip 1st by default
[[ "$run_op_arg" == "recreate" ]] && skip_step1="1" # skip 1st by default
echo -n > $dirs
for tag in $pkg ; do
# pkg tag - dir relation:
# x -> sql/x
# x/y -> x/sql/y
# x/y/z -> x/y/sql/z
local pkg_dir=${tag%/*}
local pkg_name=${tag##*/}
if [[ $pkg_dir == $tag ]] ; then
# ROOT/sql/
pkg_dir=$SQLROOT
else
# ROOT/DIR/sql
pkg_dir=$pkg_dir/$SQLROOT
fi
pushd $pkg_dir > /dev/null
if [ ! -d "$pkg_name" ] ; then
echo -n "** WARNING: $pkg_dir/$pkg_name does not exists"
popd > /dev/null
continue
fi
if [[ "$run_op_arg" == "creatif" ]] ; then
echo -n "Check if package $pkg_name exists: "
# do nothing if pkg exists, create otherwise
local exists=$(is_pkg_exists $pkg_name)
if [[ $exists == "t" ]] ; then
echo "Yes, skip"
popd > /dev/null
continue
else
# Will create atleast one
echo "No"
run_op="create"
fi
fi
if [[ "$run_op_arg" == "recreate" ]] ; then
echo -n "Check if package $pkg_name exists: "
local exists=$(is_pkg_exists $pkg_name)
if [[ $exists == "t" ]] ; then
# Will drop atleast one
echo "Yes, will drop"
run_op="drop"
op_is_del=1
skip_step1="" # no skip 1st
else
echo "No, just create"
popd > /dev/null
continue
fi
fi
lookup_dirs $pkg_dir $schema_mask $pkg_name
popd > /dev/null
done
[[ "$skip_step1" ]] || generate_build_sql
if [[ "$run_op_arg" == "recreate" ]] ; then
# pkg dropped, create it
op_is_del=""
run_op="create"
file_mask=$file_mask_ext
echo "Recreate: 1st step dirs:" && cat $dirs
echo -n > $dirs
for tag in $pkg ; do
local pkg_dir=${tag%/*}
local pkg_name=${tag##*/}
if [[ $pkg_dir == $tag ]] ; then
# ROOT/sql/
pkg_dir=$SQLROOT
else
# ROOT/DIR/sql
pkg_dir=$pkg_dir/$SQLROOT
fi
[ -d "$pkg_dir/$pkg_name" ] || continue
pushd $pkg_dir > /dev/null
lookup_dirs $pkg_dir $schema_mask $pkg_name
popd > /dev/null
done
generate_build_sql
fi
test_op=$(cat $BLD/test.cnt)
TEST_TTL=$(($test_op))
rm $BLD/test.cnt
popd > /dev/null
db_run_sql_end $BLD/build.sql
# print last "Ok"
[[ "$op_is_del" ]] || echo "SELECT $PGM_SCHEMA.test(NULL);" >> $BLD/build.sql
pushd $BLD > /dev/null
echo "Running build.sql..."
dbd psql -X -P footer=off -f build.sql 3>&1 1>$LOGFILE 2>&3 | log $TEST_TTL
RETVAL=$?
popd > /dev/null
if [[ $RETVAL -eq 0 ]] ; then
[ -f "$BLD/errors.diff" ] && rm "$BLD/errors.diff"
echo "Completed at "`date`
elif [ -s "$BLD/errors.diff" ] ; then
echo "*** Diff:" ; cat "$BLD/errors.diff"
exit 1
else
echo "*** Error(s) found"
exit 1
fi
}
# ------------------------------------------------------------------------------
db_dump() {
local schema=$1
local format=$2
[[ "$schema" ]] || schema="all"
[[ "$format" == "t" ]] || format="p --inserts -O"
local ext=".tar"
[[ "$format" == "t" ]] || ext=".sql"
local key=$(date "+%y%m%d_%H%M")
local file=$ROOT/var/dump-$schema-$key$ext
[ -f $file ] && rm -f $file
local schema_arg="-n $schema"
[[ "$schema" == "all" ]] && schema_arg=""
echo " Dumping $file .."
dbl pg_dump -F $format -f $file $schema_arg --no-tablespaces -E UTF-8;
echo " Gzipping $file.gz .."
gzip -9 $file
echo " Dump of $schema schema(s) complete"
}
# ------------------------------------------------------------------------------
db_restore() {
local key=$1
local file=$ROOT/var/$key
[ -f "$file" ] || { echo "Error: Dump file $file not found. " ; exit 1 ; }
db_show_logfile
[[ "$key" != ${key%.gz} ]] && { gunzip $file ; file=${file%.gz} ; }
# [ -L $file.gz ] && { filegz=$(readlink $file.gz); file=${filegz%.gz} ; }
echo "Restoring schema from $file.."
if [[ "$file" != ${file%.tar} ]] ; then
dbd pg_restore --single-transaction -O $file > $LOGFILE 2>&1
RETVAL=$?
else
dbd psql -X -P footer=off -f $file > $LOGFILE 2>&1
RETVAL=$?
fi
if [[ $RETVAL -eq 0 ]] ; then
echo "Restore complete."
else
echo "*** Errors:"
grep ERROR $LOGFILE || echo " None."
fi
}
# ------------------------------------------------------------------------------
db_create() {
if [[ ! `command -v createdb > /dev/null 2>&1` ]] ; then
echo "createdb must be in search path to use this feature"
exit
fi
echo -n "Create database '$DB_NAME' ..."
dbd psql -X -P tuples_only -c "SELECT NULL" > /dev/null 2>> $LOGFILE && { echo "Database already exists" ; exit ; }
dbl createdb -O $u -E UTF8 -T $DB_TEMPLATE && echo "OK"
# && dbl createlang plperl
# TODO: ALTER DATABASE $c SET lc_messages='en_US.utf8';
}
# ------------------------------------------------------------------------------
# Имя БД передается последним аргументом
dbl() {
do_db last $@
}
# Имя БД передается как -d
dbd() {
do_db arg "$@"
}
do_db() {
dbarg=$1 ; shift
cmd=$1 ; shift
h=$PG_HOST
d=$DB_NAME
u=$DB_USER
if [[ "$dbarg" == "last" ]] ; then
last=$d ; pre=""
else
last="" ; pre="-d $d"
fi
arr=$@
#echo ${#arr[@]} >> $ROOT/var/log.sql
#echo $cmd -U $u -h $h $pre $@ $last >> $ROOT/var/log.sql
[[ "$DO_SQL" ]] && PGPASSWORD=$DB_PASS ${PG_BINDIR}$cmd -U $u -h $h $pre "$@" $last
}
debug() {
[[ "$DEBUG" ]] && echo "[DEBUG]: " $@
}
# ------------------------------------------------------------------------------
setup() {
AWK_BIN=gawk
CSUM_BIN=sha1sum
if command -v tac > /dev/null 2>&1 ; then
TAC_BIN="tac"
else
TAC_BIN="tail -r" # TODO check if tail exists
fi
}
# ------------------------------------------------------------------------------
do_check() {
local bad=""
echo "Checking used programs.."
for app in gawk psql createdb pg_dump pg_restore gzip ; do
echo -n " $app.."
printf '%*.*s' 0 $((20 - ${#app})) "......................"
if command -v $app > /dev/null 2>&1 ; then
echo " Ok"
else
echo " Does not exists"
bad="1"
fi
done
if [[ "$bad" ]] ; then
echo "Some used programs are not installed. This may cause errors"
exit 1
fi
exit 0
}
# ------------------------------------------------------------------------------
cmd=$1
shift
pkg=$@
[[ "$cmd" == "check" ]] && do_check
PGM_CONFIG=${PGM_CONFIG:-.config}
ROOT=${ROOT:-$PWD}
[[ "$PWD" == "/" ]] && ROOT="/var/log/supervisor"
if [ -z "$DB_NAME" ]; then
cd $ROOT
echo "DB_NAME does not set, loading config from $PGM_CONFIG"
if [[ "$cmd" == "init" ]] ; then
if [[ "$pkg" ]] ; then
db_init_pkg $pkg
else
db_init $PGM_CONFIG
fi
echo "Init complete"
exit 0
fi
. $PGM_CONFIG
fi
[[ "$DB_USER" ]] || DB_USER=$DB_NAME
[[ "$DB_TEMPLATE" ]] || DB_TEMPLATE=template0
DO_SQL=${DO_SQL:-1}
BLD=$ROOT/var/build
STAMP=$(date +%y%m%d-%H%m)-$$
LOGDIR=$ROOT/var/build/log
LOGFILE=$LOGDIR/$cmd-$STAMP.log
[ -d $LOGDIR ] || mkdir -p $LOGDIR
# Where sql packages are
SQLROOT=${SQLROOT:-sql}
setup
PGM_PKG=${PGM_PKG:-ws}
PGM_SCHEMA=${PGM_SCHEMA:-ws}
PGM_STORE=${PGM_STORE:-wsd}
date=$(date)
[[ "$cmd" == "anno" ]] || cat <<EOF
---------------------------------------------------------
PgM. Postgresql Database Manager
Connect: "dbname=$DB_NAME;user=$DB_USER;host=$PG_HOST;password="
Command: $cmd
Started: $date
---------------------------------------------------------
EOF
# ------------------------------------------------------------------------------
case "$cmd" in
create)
db_run create "[1-8]?_*.sql" "$pkg"
;;
creatif)
db_run creatif "[1-8]?_*.sql" "$pkg"
;;
recreate)
db_run recreate "00_*.sql 02_*.sql" "[1-8]?_*.sql" "$pkg"
;;
drop)
db_run drop "00_*.sql 02_*.sql" "$pkg"
;;
erase)
db_run erase "0?_*.sql" "$pkg"
;;
make)
db_run make "1[4-9]_*.sql [3-6]?_*.sql" "$pkg"
;;
dump)
db_dump $src $@
;;
restore)
db_restore $src $@
;;
createdb)
db_create
;;
anno)
db_anno
;;
*)
echo "Unknown command"
db_help
;;
esac
|
<filename>lib/external/nodejs-fs-utils/fs/walk/index.js
const slash = require('slash');
var _classes = {
fs : require("fs"),
path : require("path")
};
function isMatch(path, filters)
{
var xPath = slash(path);
if (filters) {
for(var re of filters) {
if (!xPath.match(re)) {
return false;
}
}
}
return true;
}
var walk = function(path, opts, callback, onend_callback) {
path = _classes.path.normalize(path);
var fs;
var separator = _classes.path.sep;
var filters = [];
if (opts.filter) {
for(var x of opts.filter) {
if (typeof stringValue == "string") {
filters.push(new RegExp(x, "g"));
} else {
filters.push(x);
}
}
}
if (typeof(opts) === "function") {
callback = opts;
opts = {};
if (typeof(callback) === "function") {
onend_callback = callback;
}
}
if (typeof(onend_callback) !== "function") {
onend_callback = function () {};
}
if (typeof(opts) !== "object") {
opts = {};
}
if (typeof(opts.symbolicLinks) === "undefined") {
opts.symbolicLinks = true;
}
if (typeof(opts.skipErrors) === "undefined") {
opts.skipErrors = false;
}
if (typeof(opts.logErrors) === "undefined") {
opts.logErrors = false;
}
if (typeof(opts.stackPushEnd) === "undefined") {
opts.stackPushEnd = false;
}
if (!fs) {
fs = opts.fs || _classes.fs;
}
var cache = {
stack : [],
count : 0,
get wait() {
return cache.stack.length;
},
files : 0,
dirs : 0,
fsnodes : 0,
errors : []
};
var finalCallback = false;
var fnc = 0;
var errorsSend = false;
var _addToStack = function(path, file) {
var newPath = _classes.path.join(path, file);
if (!isMatch(newPath, filters)) {
return;
}
if (opts.stackPushEnd) {
cache.stack.push(newPath);
} else {
cache.stack.unshift(newPath);
}
}
var _tick = function () {
if (cache.errors.length && !opts.skipErrors) {
if (!errorsSend) {
errorsSend = true;
if (!finalCallback) {
finalCallback = true;
onend_callback((opts.logErrors ? cache.errors : cache.errors[0]), cache);
}
}
return;
} else if (cache.stack.length === 0) {
if (!finalCallback) {
finalCallback = true;
onend_callback((opts.logErrors ? cache.errors : cache.errors[0]), cache);
}
} else {
var path = cache.stack.shift();
cache.fsnodes++;
fs[opts.symbolicLinks ? 'lstat' : 'stat'](path, function(err, stats) {
if (err) {
if (opts.logErrors || !cache.errors.length) {
cache.errors.push(err);
}
callback(err, path, stats, _tick, cache);
} else if (!stats.isDirectory() || stats.isSymbolicLink()) {
cache.count++;
cache.files++;
callback(err, path, stats, _tick, cache);
} else {
if (!isMatch(path, filters)) {
return
}
cache.count++;
cache.dirs++;
fs.readdir(path, function(err, files) {
if(err) {
if (opts.logErrors || !cache.errors.length) {
cache.errors.push(err);
}
} else {
files.forEach(function (file) {
_addToStack(path, file);
});
}
callback(err, path, stats, _tick, cache);
});
}
});
}
};
cache.stack.push(path);
_tick();
};
var walkSync = function(path, opts, callback, onend_callback) {
path = _classes.path.normalize(path);
var fs;
var separator = _classes.path.sep;
if (typeof(opts) === "function") {
callback = opts;
opts = {};
if (typeof(callback) === "function") {
onend_callback = callback;
}
}
if (typeof(onend_callback) !== "function") {
onend_callback = function () {};
}
if (typeof(opts) !== "object") {
opts = {};
}
if (typeof(opts.symbolicLinks) === "undefined") {
opts.symbolicLinks = true;
}
if (typeof(opts.skipErrors) === "undefined") {
opts.skipErrors = false;
}
if (typeof(opts.logErrors) === "undefined") {
opts.logErrors = false;
}
if (!fs)
fs = opts.fs || _classes.fs;
var cache = {
files : 0,
dirs : 0,
fsnodes : 0,
errors : []
};
var errorsSend = false;
var _tick = function (err, path, stats, next) {
if (cache.errors.length && !opts.skipErrors) {
throw(cache.errors[0]);
} else if (next) {
callback(err, path, stats, next, cache);
}
};
var _next_empty = function () {};
var _next = function (path) {
if (path) {
var er, err;
var stats;
try {
stats = fs[opts.symbolicLinks ? 'lstatSync' : 'statSync'](path);
} catch (er) {
err = er;
};
if (err) {
if (opts.logErrors || !cache.errors.length) {
cache.errors.push(err);
}
_tick(err, path, stats, _next_empty);
} else if (!stats.isDirectory() || stats.isSymbolicLink()) {
_tick(err, path, stats, _next_empty);
cache.files++;
} else {
err = undefined;
er = undefined;
cache.dirs++;
_tick(err, path, stats, function () {
var files;
try {
files = fs.readdirSync(path);
} catch (er) {
err = er;
};
if(err) {
if (opts.logErrors || !cache.errors.length) {
cache.errors.push(err);
_next();
}
} else {
if (Array.isArray(files)) {
files.forEach(function (file) {
_next(path + ( path[path.length -1] === separator ? "" : separator ) + file);
});
}
}
});
}
}
};
_next(path);
onend_callback((opts.logErrors ? cache.errors : cache.errors[0]), cache);
};
walk.walk = walk;
walk.sync = walkSync;
module.exports = walk; |
# coding: utf-8
# In[1]:
"""
a simple script to run GNOME
This one uses:
- the GeoProjection
- wind mover
- random mover
- cats shio mover
- cats ossm mover
- plain cats mover
"""
import os
from datetime import datetime, timedelta
import numpy as np
from gnome import scripting
from gnome.basic_types import datetime_value_2d
from gnome.utilities.projections import GeoProjection
from gnome.utilities.remote_data import get_datafile
from gnome.environment import Wind, Tide
from gnome.map import MapFromBNA
from gnome.model import Model
from gnome.spill import point_line_release_spill
from gnome.movers import RandomMover, WindMover, CatsMover, ComponentMover
from gnome.outputters import Renderer
from gnome.outputters import NetCDFOutput
# define base directory
base_dir = os.path.dirname(__file__)
def make_model(images_dir=os.path.join(base_dir, 'images')):
# create the maps:
print 'creating the maps'
mapfile = get_datafile(os.path.join(base_dir, './MassBayMap.bna'))
gnome_map = MapFromBNA(mapfile, refloat_halflife=1) # hours
renderer = Renderer(mapfile, images_dir, size=(800, 800),
projection_class=GeoProjection)
print 'initializing the model'
start_time = datetime(2013, 3, 12, 10, 0)
# 15 minutes in seconds
# Default to now, rounded to the nearest hour
model = Model(time_step=900, start_time=start_time,
duration=timedelta(days=1),
map=gnome_map, uncertain=False)
print 'adding outputters'
model.outputters += renderer
netcdf_file = os.path.join(base_dir, 'script_boston.nc')
scripting.remove_netcdf(netcdf_file)
model.outputters += NetCDFOutput(netcdf_file, which_data='all')
print 'adding a RandomMover:'
model.movers += RandomMover(diffusion_coef=100000)
print 'adding a wind mover:'
series = np.zeros((2, ), dtype=datetime_value_2d)
series[0] = (start_time, (5, 180))
series[1] = (start_time + timedelta(hours=18), (5, 180))
w_mover = WindMover(Wind(timeseries=series, units='m/s'))
model.movers += w_mover
model.environment += w_mover.wind
print 'adding a cats shio mover:'
curr_file = get_datafile(os.path.join(base_dir, r"./EbbTides.cur"))
tide_file = get_datafile(os.path.join(base_dir, r"./EbbTidesShio.txt"))
c_mover = CatsMover(curr_file, tide=Tide(tide_file))
# this is the value in the file (default)
c_mover.scale_refpoint = (-70.8875, 42.321333)
c_mover.scale = True
c_mover.scale_value = -1
model.movers += c_mover
# TODO: cannot add this till environment base class is created
model.environment += c_mover.tide
print 'adding a cats ossm mover:'
# ossm_file = get_datafile(os.path.join(base_dir,
# r"./MerrimackMassCoastOSSM.txt"))
curr_file = get_datafile(os.path.join(base_dir,
r"./MerrimackMassCoast.cur"))
tide_file = get_datafile(os.path.join(base_dir,
r"./MerrimackMassCoastOSSM.txt"))
c_mover = CatsMover(curr_file, tide=Tide(tide_file))
# but do need to scale (based on river stage)
c_mover.scale = True
c_mover.scale_refpoint = (-70.65, 42.58333)
c_mover.scale_value = 1.
model.movers += c_mover
model.environment += c_mover.tide
print 'adding a cats mover:'
curr_file = get_datafile(os.path.join(base_dir, r"MassBaySewage.cur"))
c_mover = CatsMover(curr_file)
# but do need to scale (based on river stage)
c_mover.scale = True
c_mover.scale_refpoint = (-70.78333, 42.39333)
# the scale factor is 0 if user inputs no sewage outfall effects
c_mover.scale_value = .04
model.movers += c_mover
# pat1Angle 315;
# pat1Speed 19.44; pat1SpeedUnits knots;
# pat1ScaleToValue 0.138855
#
# pat2Angle 225;
# pat2Speed 19.44; pat2SpeedUnits knots;
# pat2ScaleToValue 0.05121
#
# scaleBy WindStress
print "adding a component mover:"
component_file1 = get_datafile(os.path.join(base_dir, r"./WAC10msNW.cur"))
component_file2 = get_datafile(os.path.join(base_dir, r"./WAC10msSW.cur"))
comp_mover = ComponentMover(component_file1, component_file2, w_mover.wind)
# todo: callback did not work correctly below - fix!
# comp_mover = ComponentMover(component_file1,
# component_file2,
# Wind(timeseries=series, units='m/s'))
comp_mover.scale_refpoint = (-70.855, 42.275)
comp_mover.pat1_angle = 315
comp_mover.pat1_speed = 19.44
comp_mover.pat1_speed_units = 1
comp_mover.pat1ScaleToValue = .138855
comp_mover.pat2_angle = 225
comp_mover.pat2_speed = 19.44
comp_mover.pat2_speed_units = 1
comp_mover.pat2ScaleToValue = .05121
model.movers += comp_mover
print 'adding a spill'
end_time = start_time + timedelta(hours=12)
spill = point_line_release_spill(num_elements=1000,
start_position=(-70.911432,
42.369142, 0.0),
release_time=start_time,
end_release_time=end_time)
model.spills += spill
return model
if __name__ == "__main__":
scripting.make_images_dir()
model = make_model()
model.full_run()
# In[ ]:
|
class AlbumsController < ApplicationController
def index
@albums = Album.includes(:artist).order(:title)
end
def show
@album = Album.includes(:artist).find(params[:id])
end
def new
@album = Album.new
end
def create
@album = Album.new(album_creation_params)
if @album.save
redirect_to album_path(@album)
else
render :new
end
end
private
def album_creation_params
params.require(:album).permit(:title, :label_code, :format, :released_year)
end
end
|
<gh_stars>1-10
import React from 'react'
import { shallow } from 'enzyme'
import ShowIf, { IsTrue, OrElse, IsFalseAnd } from '../src/ShowIf'
describe('IsTrue', () => {
it('should return children', () => {
const wrapper = shallow(
<IsTrue><span>test</span></IsTrue>
)
expect(wrapper.find('span').exists()).toBeTruthy()
expect(wrapper).toMatchSnapshot()
})
it('should show if condition is truthy', () => {
const wrapper = shallow(
<ShowIf condition={true}>
<IsTrue><span id='show'>works</span></IsTrue>
</ShowIf>
)
expect(wrapper.find('span#show').exists()).toBeTruthy()
expect(wrapper).toMatchSnapshot()
})
it('should show nothing if condition is falsy', () => {
const wrapper = shallow(
<ShowIf condition={false}>
<IsTrue><span id='show'>works</span></IsTrue>
</ShowIf>
)
expect(wrapper.find('span#show').exists()).toBeFalsy()
expect(wrapper).toMatchSnapshot()
})
})
describe('IsFalseAnd', () => {
it('should return children', () => {
const wrapper = shallow(
<IsFalseAnd condition={true}><span>test</span></IsFalseAnd>
)
expect(wrapper.find('span').exists()).toBeTruthy()
expect(wrapper).toMatchSnapshot()
})
it('should show if condition is falsy (F)[T]', () => {
const wrapper = shallow(
<ShowIf condition={false}>
<IsFalseAnd condition={true}><span id='show'>works</span></IsFalseAnd>
</ShowIf>
)
expect(wrapper.find('span#show').exists()).toBeTruthy()
expect(wrapper).toMatchSnapshot()
})
it('should show nothing if condition is falsy but component condition is false (F)[F]', () => {
const wrapper = shallow(
<ShowIf condition={false}>
<IsFalseAnd condition={false}><span id='show'>works</span></IsFalseAnd>
</ShowIf>
)
expect(wrapper.find('span#show').exists()).toBeFalsy()
expect(wrapper).toMatchSnapshot()
})
it('should show nothing if condition is truthy (T)[T,F]', () => {
const wrapper = shallow(
<ShowIf condition={true}>
<IsFalseAnd condition={true}><span id='show'>works</span></IsFalseAnd>
<IsFalseAnd condition={false}><span id='show2'>works</span></IsFalseAnd>
</ShowIf>
)
expect(wrapper.find('span#show').exists()).toBeFalsy()
expect(wrapper.find('span#show2').exists()).toBeFalsy()
expect(wrapper).toMatchSnapshot()
})
it('should show only true conditions and in order (F)[T,F,T,F,T]', () => {
const wrapper = shallow(
<ShowIf condition={false}>
<IsFalseAnd condition={true}><span id='show'>works</span></IsFalseAnd>
<IsFalseAnd condition={false}><span id='show2'>works</span></IsFalseAnd>
<IsFalseAnd condition={true}><span id='show3'>works</span></IsFalseAnd>
<IsFalseAnd condition={false}><span id='show4'>works</span></IsFalseAnd>
<IsFalseAnd condition={true}><span id='show5'>works</span></IsFalseAnd>
</ShowIf>
)
// test existance
expect(wrapper.find('span#show').exists()).toBeTruthy()
expect(wrapper.find('span#show2').exists()).toBeFalsy()
expect(wrapper.find('span#show3').exists()).toBeTruthy()
expect(wrapper.find('span#show4').exists()).toBeFalsy()
expect(wrapper.find('span#show5').exists()).toBeTruthy()
// test ordering
expect(wrapper.find('span').first().prop('id') === 'show').toBeTruthy()
expect(wrapper.find('span').at(1).prop('id') === 'show3').toBeTruthy()
expect(wrapper.find('span').at(2).prop('id') === 'show5').toBeTruthy()
expect(wrapper).toMatchSnapshot()
})
it('should accept functions as condition', () => {
const truthyFunc = () => true
const falsyFunc = () => false
const wrapper = shallow(
<ShowIf condition={false}>
<IsFalseAnd condition={truthyFunc}><span id='show'>works</span></IsFalseAnd>
<IsFalseAnd condition={falsyFunc}><span id='show2'>works</span></IsFalseAnd>
</ShowIf>
)
expect(wrapper.find('span#show').exists()).toBeTruthy()
expect(wrapper.find('span#show2').exists()).toBeFalsy()
expect(wrapper).toMatchSnapshot()
})
})
describe('OrElse', () => {
it('should return children', () => {
const wrapper = shallow(
<OrElse><span>test</span></OrElse>
)
expect(wrapper.find('span').exists()).toBeTruthy()
expect(wrapper).toMatchSnapshot()
})
it('should show if condition is falsy', () => {
const wrapper = shallow(
<ShowIf condition={false}>
<OrElse><span id='show'>works</span></OrElse>
</ShowIf>
)
expect(wrapper.find('span#show').exists()).toBeTruthy()
expect(wrapper).toMatchSnapshot()
})
it('should show nothing if condition is truthy', () => {
const wrapper = shallow(
<ShowIf condition={true}>
<OrElse><span id='show'>works</span></OrElse>
</ShowIf>
)
expect(wrapper.find('span#show').exists()).toBeFalsy()
expect(wrapper).toMatchSnapshot()
})
})
describe('ShowIf', () => {
it('should accept functions as condition', () => {
const truthyFunc = () => true
const falsyFunc = () => false
const wrapper = shallow(
<div>
<ShowIf condition={truthyFunc}>
<IsTrue><span id='show'>works</span></IsTrue>
</ShowIf>
<ShowIf condition={falsyFunc}>
<OrElse><span id='show2'>works</span></OrElse>
</ShowIf>
</div>
)
expect(wrapper.find('span#show').exists()).toBeTruthy()
expect(wrapper.find('span#show2').exists()).toBeTruthy()
expect(wrapper).toMatchSnapshot()
})
it('works', () => {
const wrapper = shallow(
<ShowIf condition={true}>
<IsTrue><span id='show'>works</span></IsTrue>
<IsFalseAnd condition={true}><span id='show2'>works</span></IsFalseAnd>
<IsFalseAnd condition={false}><span id='show3'>works</span></IsFalseAnd>
<OrElse><span id='show4'>works</span></OrElse>
</ShowIf>
)
expect(wrapper).toMatchSnapshot()
expect(wrapper.find('span#show').exists()).toBeTruthy()
expect(wrapper.find('span#show2').exists()).toBeFalsy()
expect(wrapper.find('span#show3').exists()).toBeFalsy()
expect(wrapper.find('span#show4').exists()).toBeFalsy()
wrapper.setProps({ condition: false })
expect(wrapper.find('span#show').exists()).toBeFalsy()
expect(wrapper.find('span#show2').exists()).toBeTruthy()
expect(wrapper.find('span#show3').exists()).toBeFalsy()
expect(wrapper.find('span#show4').exists()).toBeFalsy()
const firstChange = [
(<IsTrue><span id='show'>works</span></IsTrue>),
(<IsFalseAnd condition={true}><span id='show2'>works</span></IsFalseAnd>),
(<IsFalseAnd condition={true}><span id='show3'>works</span></IsFalseAnd>),
(<OrElse><span id='show4'>works</span></OrElse>)
]
wrapper.setProps({ children: firstChange })
expect(wrapper.find('span#show').exists()).toBeFalsy()
expect(wrapper.find('span#show2').exists()).toBeTruthy()
expect(wrapper.find('span#show3').exists()).toBeTruthy()
expect(wrapper.find('span#show4').exists()).toBeFalsy()
const secondChange = [
(<IsTrue><span id='show'>works</span></IsTrue>),
(<IsFalseAnd condition={false}><span id='show2'>works</span></IsFalseAnd>),
(<IsFalseAnd condition={false}><span id='show3'>works</span></IsFalseAnd>),
(<OrElse><span id='show4'>works</span></OrElse>)
]
wrapper.setProps({ children: secondChange })
expect(wrapper.find('span#show').exists()).toBeFalsy()
expect(wrapper.find('span#show2').exists()).toBeFalsy()
expect(wrapper.find('span#show3').exists()).toBeFalsy()
expect(wrapper.find('span#show4').exists()).toBeTruthy()
})
it('should throw an error if wrong child', () => {
const wrapper = () => shallow(
<ShowIf condition={true}>
<span>wrong</span>
</ShowIf>
)
expect(wrapper).toThrowError('ShowIf child[0] is invalid!')
})
it('should throw an error if wrong children', () => {
const wrapper = () => shallow(
<ShowIf condition={true}>
<IsTrue><span>test</span></IsTrue>
<span>wrong</span>
</ShowIf>
)
expect(wrapper).toThrowError('ShowIf child[1] is invalid!')
})
})
|
#!/usr/bin/env bash
# checks out Spack and Arbor and builds it with the package.py from Arbor's repo
# Spack can be the latest release or the develop branch
set -Eeuo pipefail
if [[ "$#" -ne 2 ]]; then
echo "Builds the in-repo Spack package of Arbor against the latest Spack release or a given Spack branch"
echo "usage: build_spack_package.sh arbor_source_directory latest_release|develop"
exit 1
fi
trap cleanup SIGINT SIGTERM ERR EXIT
cleanup() {
trap - SIGINT SIGTERM ERR EXIT
rm -rf "$TMP_DIR"
}
TMP_DIR=$(mktemp -d)
ARBOR_SOURCE=$1
ARBOR_DIR=$TMP_DIR/arbor
mkdir $ARBOR_DIR
cp -r $ARBOR_SOURCE/* $ARBOR_DIR
cd "$TMP_DIR"
SPACK_DIR=spack
SPACK_REPO=https://github.com/spack/spack
SPACK_CUSTOM_REPO=custom_repo
SPACK_VERSION=$2 # latest_release or develop
SPACK_BRANCH=develop # only used for develop
case $SPACK_VERSION in
"develop")
git clone --depth 1 --branch $SPACK_BRANCH $SPACK_REPO $SPACK_DIR
;;
"latest_release")
wget "$(curl -sH "Accept: application/vnd.github.v3+json" https://api.github.com/repos/spack/spack/releases/latest | grep browser_download_url | cut -d '"' -f 4)"
tar xfz spack*.tar.gz
ln -s spack*/ $SPACK_DIR
;;
*)
echo "SPACK_VERSION" must be \"latest_release\" or \"develop\"
exit 1
esac
source $SPACK_DIR/share/spack/setup-env.sh
spack repo create $SPACK_CUSTOM_REPO
mkdir -p $SPACK_CUSTOM_REPO/packages/arbor
spack repo add $SPACK_CUSTOM_REPO
cp $ARBOR_DIR/spack/package.py $SPACK_CUSTOM_REPO/packages/arbor
cd $ARBOR_DIR
spack dev-build arbor@with-package-from-repo
|
<html>
<head>
<title>Recipe Search</title>
</head>
<body>
<h1>Search for Recipes</h1>
<form id="search-form" action="recipes.php" method="POST">
<input type="text" name="ingredients" placeholder="Enter ingredients separated by commas"><br>
<input type="submit" value="Search">
</form>
</body>
</html>
<?php
// Connect to database
$conn = new mysqli('host', 'username', 'password', 'database');
// Check connection
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
// Fetch ingredients from form
$ingredients = $_POST['ingredients'];
$ingredients = explode(',', $ingredients);
// Create query
$query = "SELECT * FROM recipes WHERE ingredients IN (";
for ($i=0; $i < count($ingredients); $i++) {
$query .= "?,";
}
$query = rtrim($query,",");
$query .= ");";
// Prepare statement
$stmt = $conn->prepare($query);
// Bind parameters
$types = str_repeat('s', count($ingredients));
$stmt->bind_param($types, ...$ingredients);
// Execute the query
$stmt->execute();
// Fetch the results
$result = $stmt->get_result();
// Display the results
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
echo "<p>".$row['title']."</p>";
echo "<p>".$row['ingredients']."</p>";
echo "<p>".$row['instructions']."</p>";
}
} else {
echo "No recipes found";
}
$stmt->close();
$conn->close(); |
package com.shop.dao.jedis;
/**
* <p>Description:Jedis操作接口</p>
*
* @Author 姚洪斌
* @Date 2017/8/27 16:21
*/
public interface JedisDao {
/**
* redis String型数据赋值
* @param key 键名
* @param keyValue 键值
* @return
*/
String set(String key, String keyValue);
/**
*redis 获取String型数据
* @param key 键名
* @return
*/
String get(String key);
/**
* 删除 redis String型数据
* @param key 键名
* @return
*/
Long del(String key);
/**
* redis hash型数据赋值
* @param hKey 键名
* @param key 键中的字段
* @param keyValue 字段值
* @return
*/
Long hset(String hKey, String key, String keyValue);
/**
* 获取 redis hash型数据
* @param hKey 键名
* @param key 键中的字段
* @return
*/
String hget(String hKey, String key);
/**
* 删除键中的一个字段
* @param hKey 键名
* @param key 键中的字段
* @return
*/
Long hdel(String hKey, String key);
}
|
/*
* Copyright (c) 2008-2019, Hazelcast, 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.
*/
package com.hazelcast.test.bounce;
import com.hazelcast.logging.ILogger;
import com.hazelcast.logging.Logger;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;
import static com.hazelcast.test.bounce.BounceMemberRule.STALENESS_DETECTOR_DISABLED;
import static java.util.concurrent.TimeUnit.NANOSECONDS;
import static java.util.concurrent.TimeUnit.SECONDS;
public class ProgressMonitor {
private static final long PROGRESS_LOGGING_INTERVAL_NANOS = SECONDS.toNanos(5);
private static final ILogger LOGGER = Logger.getLogger(ProgressMonitor.class);
private final long maximumStaleNanos;
private final List<BounceMemberRule.TestTaskRunnable> tasks = new ArrayList<BounceMemberRule.TestTaskRunnable>();
private long lastProgressLoggedNanos;
private long progressDelta;
public ProgressMonitor(long maximumStaleSeconds) {
this.maximumStaleNanos = maximumStaleSeconds == STALENESS_DETECTOR_DISABLED
? maximumStaleSeconds
: SECONDS.toNanos(maximumStaleSeconds);
}
public void registerTask(Runnable task) {
if (task instanceof BounceMemberRule.TestTaskRunnable) {
tasks.add((BounceMemberRule.TestTaskRunnable) task);
} else if (maximumStaleNanos != STALENESS_DETECTOR_DISABLED) {
throw new UnsupportedOperationException("Progress checking is enabled only for automatically repeated tasks");
}
}
public void checkProgress() {
long now = System.nanoTime();
long aggregatedProgress = 0;
long maxLatencyNanos = 0;
for (BounceMemberRule.TestTaskRunnable task : tasks) {
long lastIterationStartedTimestamp = task.getLastIterationStartedTimestamp();
if (lastIterationStartedTimestamp == 0) {
//the tasks haven't started yet
continue;
}
aggregatedProgress += task.getIterationCounter();
maxLatencyNanos = Math.max(maxLatencyNanos, task.getMaxLatencyNanos());
long currentStaleNanos = now - lastIterationStartedTimestamp;
if (currentStaleNanos > maximumStaleNanos) {
onStalenessDetected(task, currentStaleNanos);
}
}
logProgress(now, aggregatedProgress, maxLatencyNanos);
}
private void logProgress(long now, long aggregatedProgress, long maxLatencyNanos) {
if (now > lastProgressLoggedNanos + PROGRESS_LOGGING_INTERVAL_NANOS) {
StringBuilder sb = new StringBuilder("Aggregated progress: ")
.append(aggregatedProgress)
.append(" operations. ");
progressDelta = aggregatedProgress - progressDelta;
if (lastProgressLoggedNanos > 0) {
sb.append("Maximum latency: ")
.append(TimeUnit.NANOSECONDS.toMillis(maxLatencyNanos))
.append(" ms.");
long timeInNanos = now - lastProgressLoggedNanos;
double timeInSeconds = (double) timeInNanos / 1000000000;
double progressPerSecond = progressDelta / timeInSeconds;
sb.append("Throughput in last ")
.append((long) (timeInSeconds * 1000))
.append(" ms: ")
.append((long) progressPerSecond)
.append(" ops / second. ");
}
lastProgressLoggedNanos = now;
LOGGER.info(sb.toString());
}
}
private void onStalenessDetected(BounceMemberRule.TestTaskRunnable task, long currentStaleNanos) {
// this could seems redundant as the Hazelcast JUnit runner will also take threadumps
// however in this case we are doing the threaddump before declaring a test failure
// and stopping Hazelcast instances -> there is a higher chance we will actually
// record something useful.
long currentStaleSeconds = NANOSECONDS.toSeconds(currentStaleNanos);
long maximumStaleSeconds = NANOSECONDS.toSeconds(maximumStaleNanos);
StringBuilder sb = new StringBuilder("Stalling task detected: ")
.append(task).append('\n')
.append("Maximum staleness allowed (in seconds): ").append(maximumStaleSeconds).append('\n')
.append(", Current staleness detected (in seconds): ").append(currentStaleSeconds).append('\n');
Thread taskThread = task.getCurrentThreadOrNull();
appendStackTrace(taskThread, sb);
throw new AssertionError(sb.toString());
}
private void appendStackTrace(Thread thread, StringBuilder sb) {
if (thread == null) {
sb.append("The task has no thread currently assigned!");
return;
}
sb.append("Assigned thread: ").append(thread).append(", Stacktrace: \n");
StackTraceElement[] stackTraces = thread.getStackTrace();
for (StackTraceElement stackTraceElement : stackTraces) {
sb.append("**").append(stackTraceElement).append('\n');
}
sb.append("**********");
}
}
|
#!/bin/bash
# python whitebox4.py --cfg output/A_a1/ --results_dir whitebox_cw --attack_type cw --defense_type defense_gan --model A
python whitebox4.py --cfg output/D_a1/ --results_dir whitebox_cw --attack_type cw --defense_type defense_gan --model D
python whitebox4.py --cfg output/B_a1/ --results_dir whitebox_cw --attack_type cw --defense_type defense_gan --model B
# bash gan_new_test.sh
|
import {Component, Input, OnInit} from '@angular/core';
import {FormBuilder, FormGroup, Validators} from '@angular/forms';
import {NgbActiveModal} from '@ng-bootstrap/ng-bootstrap';
import {ToastrService} from 'ngx-toastr';
import {NgxSpinnerService} from 'ngx-spinner';
import {TranslateService} from '@ngx-translate/core';
import {ProductService} from '../../../@core/services/_service/product.service';
import {CategoriesService} from '../../../@core/services/_service/categories.service';
import {SupplierService} from '../../../@core/services/_service/supplier.service';
@Component({
selector: 'ngx-action-product',
templateUrl: './action-product.component.html',
styleUrls: ['./action-product.component.scss'],
})
export class ActionProductComponent implements OnInit {
@Input() action: any;
@Input() product: any;
isSubmitted: boolean = false;
form: FormGroup;
lstCategory: any[] = [];
lstSupplier: any[] = [
{
id: '1',
name: '<NAME>',
}, {
id: '2',
name: '<NAME>',
}, {
id: '3 ',
name: '<NAME>',
},
];
constructor(
private modal: NgbActiveModal,
private fb: FormBuilder,
private toastr: ToastrService,
private spinner: NgxSpinnerService,
private translate: TranslateService,
private service: ProductService,
private categoryService: CategoriesService,
private supplierService: SupplierService,
) {
}
ngOnInit(): void {
this.initForm();
this.getListCategory();
}
initForm() {
if (this.action) {
this.form = this.fb.group({
name: ['', Validators.required],
image: ['../../../assets/images/supplier/cty-a.jpg '],
idCategory: ['', Validators.required],
idSupplier: ['', Validators.required],
price: ['', Validators.required],
quantity: ['', Validators.required],
});
} else {
this.form = this.fb.group({
id: [this.product.id],
name: [this.product.name, Validators.required],
image: [this.product.image],
idCategory: [this.product.idCategory, Validators.required],
idSupplier: [this.product.idSupplier, Validators.required],
price: [this.product.price, Validators.required],
quantity: [this.product.quantity, Validators.required],
});
}
}
getListCategory() {
this.categoryService.getListCategory().subscribe(res => {
this.lstCategory = res.data;
});
}
// getListSupplier() {
// this.supplierService.getListSupplier().subscribe(res => {
// this.lstSupplier = res.data;
// });
// }
close() {
this.modal.close();
}
get f() {
return this.form.controls;
}
// findAll() {
// this.storeService.findAllData().subscribe(res => {
// this.lstStore = res.data;
// });
// }
processSaveOrUpdate() {
this.isSubmitted = true;
if (this.form.valid) {
this.spinner.show();
this.service.saveOrUpdateOverride(this.form.value).subscribe(res => {
this.spinner.hide();
if (res.code === 'success') {
this.modal.close('success');
this.toastr.success('success');
} else {
this.toastr.error('error');
}
});
}
}
}
|
#!/bin/sh
# Package
PACKAGE="saltpad"
DNAME="SaltPad"
# Others
INSTALL_DIR="/usr/local/${PACKAGE}"
SSS="/var/packages/${PACKAGE}/scripts/start-stop-status"
PYTHON_DIR="/usr/local/python"
PATH="${INSTALL_DIR}/bin:${INSTALL_DIR}/env/bin:${PYTHON_DIR}/bin:${PATH}"
USER="saltpad"
GROUP="nobody"
VIRTUALENV="${PYTHON_DIR}/bin/virtualenv"
TMP_DIR="${SYNOPKG_PKGDEST}/../../@tmp"
SERVICETOOL="/usr/syno/bin/servicetool"
FWPORTS="/var/packages/${PACKAGE}/scripts/${PACKAGE}.sc"
preinst ()
{
exit 0
}
postinst ()
{
# Link
ln -s ${SYNOPKG_PKGDEST} ${INSTALL_DIR}
# Create a Python virtualenv
${VIRTUALENV} --system-site-packages ${INSTALL_DIR}/env > /dev/null
# Install the wheels
${INSTALL_DIR}/env/bin/pip install --no-deps --no-index -U --force-reinstall -f ${INSTALL_DIR}/share/wheelhouse ${INSTALL_DIR}/share/wheelhouse/*.whl > /dev/null 2>&1
# Create user
adduser -h ${INSTALL_DIR}/var -g "${DNAME} User" -G ${GROUP} -s /bin/sh -S -D ${USER}
# Create configuration file
if [ "${SYNOPKG_PKG_STATUS}" == "INSTALL" ]; then
echo API_URL = \'http://localhost:8282\' > ${INSTALL_DIR}/var/settings.py
echo SECRET_KEY = \'$(python -c "import os, hashlib; print hashlib.md5(os.urandom(24)).hexdigest()")\' >> ${INSTALL_DIR}/var/settings.py
echo EAUTH = \'synology\' >> ${INSTALL_DIR}/var/settings.py
fi
# Link configuration file
ln -s ${INSTALL_DIR}/var/settings.py ${INSTALL_DIR}/share/saltpad/saltpad/local_settings.py
# Correct the files ownership
chown -R ${USER} ${SYNOPKG_PKGDEST}
# Add firewall config
${SERVICETOOL} --install-configure-file --package ${FWPORTS} >> /dev/null
exit 0
}
preuninst ()
{
# Stop the package
${SSS} stop > /dev/null
# Remove the user (if not upgrading)
if [ "${SYNOPKG_PKG_STATUS}" != "UPGRADE" ]; then
delgroup ${USER} ${GROUP}
deluser ${USER}
fi
# Remove firewall config
if [ "${SYNOPKG_PKG_STATUS}" == "UNINSTALL" ]; then
${SERVICETOOL} --remove-configure-file --package ${PACKAGE}.sc >> /dev/null
fi
exit 0
}
postuninst ()
{
# Remove link
rm -f ${INSTALL_DIR}
exit 0
}
preupgrade ()
{
# Stop the package
${SSS} stop > /dev/null
# Save some stuff
rm -fr ${TMP_DIR}/${PACKAGE}
mkdir -p ${TMP_DIR}/${PACKAGE}
mv ${INSTALL_DIR}/var ${TMP_DIR}/${PACKAGE}/
exit 0
}
postupgrade ()
{
# Restore some stuff
rm -fr ${INSTALL_DIR}/var
mv ${TMP_DIR}/${PACKAGE}/var ${INSTALL_DIR}/
rm -fr ${TMP_DIR}/${PACKAGE}
exit 0
}
|
<filename>modules/client-java/src/main/java/be/vlaanderen/awv/atom/java/FeedLinkTo.java
/*
* Dit bestand is een onderdeel van AWV DistrictCenter.
* Copyright (c) AWV Agentschap <NAME>, <NAME>
*/
package be.vlaanderen.awv.atom.java;
import be.vlaanderen.awv.atom.Link;
import be.vlaanderen.awv.atom.Url;
import lombok.Data;
/**
* Representation of a link in an atom feed.
*/
@Data
public class FeedLinkTo {
private String rel; // relation, e.g."self", "next", previous"
private String href; // link URL
/**
* Converts to an object usable by Atomium.
*
* @return atomium feed
*/
public Link toAtomium() {
return new Link(rel, new Url(href));
}
}
|
package jenkins.plugins.accurev.util;
import java.util.UUID;
import org.apache.commons.lang.StringUtils;
/** Initialized by josp on 21/09/16. */
public class UUIDUtils {
public static boolean isValid(String uuid) {
if (StringUtils.isEmpty(uuid)) {
return false;
}
try {
UUID fromStringUUID = UUID.fromString(uuid);
String toStringUUID = fromStringUUID.toString();
return toStringUUID.equals(uuid);
} catch (IllegalArgumentException e) {
return false;
}
}
public static boolean isNotValid(String uuid) {
return !isValid(uuid);
}
}
|
import { useEffect, useRef } from "react";
// Hook created by siddharthkp: https://github.com/siddharthkp/use-event-listener/blob/master/index.js
// Based on Dan Abramov implementation of useInterval: https://overreacted.io/making-setinterval-declarative-with-react-hooks/
export default function useEventListener(
eventName,
callback,
element = window
) {
const savedCallback = useRef();
useEffect(() => {
savedCallback.current = callback;
}, [callback]);
useEffect(
function() {
if (typeof element === "undefined") return;
const eventListener = event => savedCallback.current(event);
element.addEventListener(eventName, eventListener);
return function cleanup() {
return element.removeEventListener(eventName, eventListener);
};
},
[eventName]
);
}
|
#!/bin/sh
println() {
printf '%s\n' "$1">&2
}
fatal() {
println "$1"
exit 1
}
mkdirp() {
if [ -d "$1" ]; then
return 0
fi
if [ -e "$1" ]; then
return 1
fi
(
PARENT="$(dirname "$1")"
case "$PARENT" in
/|.);;
*) mkdirp "$PARENT" || return 1;;
esac
)
mkdir "$1"
}
ROOT="$(cd "$(dirname "$0")"&&pwd)"
PREFIX="${1%/}"
if [ -z "$PREFIX" ]; then
if [ "$(id -u)" -eq 0 ]; then
PREFIX=/usr/local
else
PREFIX="$HOME/.local"
fi
fi
SCIP_SRC="$ROOT/bin/scip"
LIB_SRC="$ROOT/lib/scip"
SCIP_DST_DIR="$PREFIX/bin"
LIB_DST_DIR="$PREFIX/lib"
SCIP_DST="$SCIP_DST_DIR/scip"
LIB_DST="$LIB_DST_DIR/scip"
if [ -e "$SCIP_DST" ]; then
fatal "$SCIP_DST already exists"
else
mkdirp "$SCIP_DST_DIR" || fatal "failed to create $SCIP_DST_DIR"
fi
if [ -e "$LIB_DST" ]; then
fatal "$LIB_DST already exists"
else
mkdirp "$LIB_DST_DIR" || fatal "failed to create $LIB_DST_DIR"
fi
cp -v "$SCIP_SRC" "$SCIP_DST" || fatal "failed to copy $SCIP_SRC to $SCIP_DST"
cp -rv "$LIB_SRC" "$LIB_DST" || fatal "failed to copy $LIB_SRC to $LIB_DST"
chmod +x "$SCIP_DST" || fatal "failed to add executable flag to $SCIP_DST"
println 'scip successfully installed'
|
def split_string(string, chunk_len):
'''This function takes a string as input and splits it into smaller chunks of the given length'''
return [string[i:i+chunk_len] for i in range(0, len(string), chunk_len)] |
const defaults = {
joiner: '\u00AD',
borderMarker: '.',
minWordLength: 4
};
export default defaults;
|
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT license.
import chai from "chai";
import chaiAsPromised from "chai-as-promised";
import { it } from "mocha";
import { SolutionRunningState, TeamsAppSolution } from " ../../../src/plugins/solution";
import {
AppStudioTokenProvider,
ConfigFolderName,
ConfigMap,
FxError,
ok,
PluginContext,
Result,
SolutionConfig,
SolutionContext,
Void,
Plugin,
AzureAccountProvider,
SubscriptionInfo,
IProgressHandler,
Platform,
UserInteraction,
SingleSelectConfig,
SingleSelectResult,
MultiSelectConfig,
MultiSelectResult,
InputTextConfig,
InputTextResult,
SelectFileConfig,
SelectFileResult,
SelectFilesResult,
SelectFilesConfig,
SelectFolderResult,
SelectFolderConfig,
Colors,
RunnableTask,
TaskConfig,
} from "@microsoft/teamsfx-api";
import * as sinon from "sinon";
import fs, { PathLike } from "fs-extra";
import {
DEFAULT_PERMISSION_REQUEST,
GLOBAL_CONFIG,
REMOTE_AAD_ID,
REMOTE_TEAMS_APP_ID,
SolutionError,
SOLUTION_PROVISION_SUCCEEDED,
WEB_APPLICATION_INFO_SOURCE,
} from "../../../src/plugins/solution/fx-solution/constants";
import {
FRONTEND_DOMAIN,
FRONTEND_ENDPOINT,
REMOTE_MANIFEST,
} from "../../../src/plugins/resource/appstudio/constants";
import {
HostTypeOptionAzure,
HostTypeOptionSPFx,
} from "../../../src/plugins/solution/fx-solution/question";
import { validManifest } from "./util";
import { IAppDefinition } from "../../../src/plugins/resource/appstudio/interfaces/IAppDefinition";
import _ from "lodash";
import { TokenCredential } from "@azure/core-auth";
import { TokenCredentialsBase, UserTokenCredentials } from "@azure/ms-rest-nodeauth";
import { ResourceGroups } from "@azure/arm-resources";
import { AppStudioClient } from "../../../src/plugins/resource/appstudio/appStudio";
import { AppStudioPluginImpl } from "../../../src/plugins/resource/appstudio/plugin";
import * as solutionUtil from "../../../src/plugins/solution/fx-solution/utils/util";
import * as uuid from "uuid";
import { ResourcePlugins } from "../../../src/plugins/solution/fx-solution/ResourcePluginContainer";
import { AadAppForTeamsPlugin } from "../../../src";
import Container from "typedi";
chai.use(chaiAsPromised);
const expect = chai.expect;
const aadPlugin = Container.get<Plugin>(ResourcePlugins.AadPlugin) as AadAppForTeamsPlugin;
const spfxPlugin = Container.get<Plugin>(ResourcePlugins.SpfxPlugin);
const fehostPlugin = Container.get<Plugin>(ResourcePlugins.FrontendPlugin);
const appStudioPlugin = Container.get<Plugin>(ResourcePlugins.AppStudioPlugin);
class MockUserInteraction implements UserInteraction {
selectOption(config: SingleSelectConfig): Promise<Result<SingleSelectResult, FxError>> {
throw new Error("Method not implemented.");
}
selectOptions(config: MultiSelectConfig): Promise<Result<MultiSelectResult, FxError>> {
throw new Error("Method not implemented.");
}
inputText(config: InputTextConfig): Promise<Result<InputTextResult, FxError>> {
throw new Error("Method not implemented.");
}
selectFile(config: SelectFileConfig): Promise<Result<SelectFileResult, FxError>> {
throw new Error("Method not implemented.");
}
selectFiles(config: SelectFilesConfig): Promise<Result<SelectFilesResult, FxError>> {
throw new Error("Method not implemented.");
}
selectFolder(config: SelectFolderConfig): Promise<Result<SelectFolderResult, FxError>> {
throw new Error("Method not implemented.");
}
openUrl(link: string): Promise<Result<boolean, FxError>> {
throw new Error("Method not implemented.");
}
async showMessage(
level: "info" | "warn" | "error",
message: string,
modal: boolean,
...items: string[]
): Promise<Result<string | undefined, FxError>>;
async showMessage(
level: "info" | "warn" | "error",
message: Array<{ content: string; color: Colors }>,
modal: boolean,
...items: string[]
): Promise<Result<string | undefined, FxError>>;
async showMessage(
level: "info" | "warn" | "error",
message: string | Array<{ content: string; color: Colors }>,
modal: boolean,
...items: string[]
): Promise<Result<string | undefined, FxError>> {
if (modal === true && _.isEqual(["Provision", "Pricing calculator"], items)) {
return ok("Provision");
}
throw new Error("Method not implemented.");
}
createProgressBar(title: string, totalSteps: number): IProgressHandler {
throw new Error("Method not implemented.");
}
runWithProgress<T>(
task: RunnableTask<T>,
config: TaskConfig,
...args: any
): Promise<Result<T, FxError>> {
throw new Error("Method not implemented.");
}
}
class MockedAppStudioTokenProvider implements AppStudioTokenProvider {
async getAccessToken(showDialog?: boolean): Promise<string> {
return "someFakeToken";
}
async getJsonObject(showDialog?: boolean): Promise<Record<string, unknown>> {
return {
tid: "222",
};
}
signout(): Promise<boolean> {
throw new Error("Method not implemented.");
}
setStatusChangeCallback(
statusChange: (
status: string,
token?: string,
accountInfo?: Record<string, unknown>
) => Promise<void>
): Promise<boolean> {
throw new Error("Method not implemented.");
}
setStatusChangeMap(
name: string,
statusChange: (
status: string,
token?: string,
accountInfo?: Record<string, unknown>
) => Promise<void>,
immediateCall?: boolean
): Promise<boolean> {
throw new Error("Method not implemented.");
}
removeStatusChangeMap(name: string): Promise<boolean> {
throw new Error("Method not implemented.");
}
}
const mockedSubscriptionName = "subname";
const mockedSubscriptionId = "111";
const mockedTenantId = "222";
class MockedAzureTokenProvider implements AzureAccountProvider {
getAccountCredential(showDialog?: boolean): TokenCredentialsBase {
throw new Error("Method not implemented.");
}
getIdentityCredential(showDialog?: boolean): TokenCredential {
throw new Error("Method not implemented.");
}
async getAccountCredentialAsync(
showDialog?: boolean,
tenantId?: string
): Promise<TokenCredentialsBase> {
return new UserTokenCredentials("someClientId", "some.domain", "someUserName", "somePassword");
}
getIdentityCredentialAsync(showDialog?: boolean): Promise<TokenCredential> {
throw new Error("Method not implemented.");
}
signout(): Promise<boolean> {
throw new Error("Method not implemented.");
}
setStatusChangeCallback(
statusChange: (
status: string,
token?: string,
accountInfo?: Record<string, unknown>
) => Promise<void>
): Promise<boolean> {
throw new Error("Method not implemented.");
}
setStatusChangeMap(
name: string,
statusChange: (
status: string,
token?: string,
accountInfo?: Record<string, unknown>
) => Promise<void>,
immediateCall?: boolean
): Promise<boolean> {
throw new Error("Method not implemented.");
}
removeStatusChangeMap(name: string): Promise<boolean> {
throw new Error("Method not implemented.");
}
async getJsonObject(showDialog?: boolean): Promise<Record<string, unknown>> {
return {
tid: "222",
};
}
async listSubscriptions(): Promise<SubscriptionInfo[]> {
return [
{
subscriptionName: mockedSubscriptionName,
subscriptionId: mockedSubscriptionId,
tenantId: mockedTenantId,
},
];
}
async setSubscription(subscriptionId: string): Promise<void> {
return;
}
getAccountInfo(): Record<string, string> | undefined {
return {};
}
getSelectedSubscription(): Promise<SubscriptionInfo | undefined> {
const selectedSub = {
subscriptionId: "subscriptionId",
tenantId: "tenantId",
subscriptionName: "subscriptionName",
};
return Promise.resolve(selectedSub);
}
}
function mockSolutionContext(): SolutionContext {
const config: SolutionConfig = new Map();
config.set(GLOBAL_CONFIG, new ConfigMap());
return {
root: ".",
config,
ui: new MockUserInteraction(),
answers: { platform: Platform.VSCode },
projectSettings: undefined,
appStudioToken: new MockedAppStudioTokenProvider(),
azureAccountProvider: new MockedAzureTokenProvider(),
};
}
function mockProvisionThatAlwaysSucceed(plugin: Plugin) {
plugin.preProvision = async function (_ctx: PluginContext): Promise<Result<any, FxError>> {
return ok(Void);
};
plugin.provision = async function (_ctx: PluginContext): Promise<Result<any, FxError>> {
return ok(Void);
};
plugin.postProvision = async function (_ctx: PluginContext): Promise<Result<any, FxError>> {
return ok(Void);
};
}
describe("provision() simple cases", () => {
const mocker = sinon.createSandbox();
const mockedManifest = _.cloneDeep(validManifest);
// ignore icons for simplicity
mockedManifest.icons.color = "";
mockedManifest.icons.outline = "";
const mockedAppDef: IAppDefinition = {
appName: "MyApp",
teamsAppId: "qwertasdf",
};
afterEach(() => {
mocker.restore();
});
it("should return error if solution state is not idle", async () => {
const solution = new TeamsAppSolution();
expect(solution.runningState).equal(SolutionRunningState.Idle);
const mockedCtx = mockSolutionContext();
solution.runningState = SolutionRunningState.ProvisionInProgress;
let result = await solution.provision(mockedCtx);
expect(result.isErr()).to.be.true;
expect(result._unsafeUnwrapErr().name).equals(SolutionError.ProvisionInProgress);
solution.runningState = SolutionRunningState.DeployInProgress;
result = await solution.provision(mockedCtx);
expect(result.isErr()).to.be.true;
expect(result._unsafeUnwrapErr().name).equals(SolutionError.DeploymentInProgress);
solution.runningState = SolutionRunningState.PublishInProgress;
result = await solution.provision(mockedCtx);
expect(result.isErr()).to.be.true;
expect(result._unsafeUnwrapErr().name).equals(SolutionError.PublishInProgress);
});
it("should return error if manifest file is not found", async () => {
const solution = new TeamsAppSolution();
const mockedCtx = mockSolutionContext();
mockedCtx.projectSettings = {
appName: "my app",
projectId: uuid.v4(),
solutionSettings: {
hostType: HostTypeOptionSPFx.id,
name: "azure",
version: "1.0",
activeResourcePlugins: [fehostPlugin.name],
},
};
// We leverage the fact that in testing env, this is not file at `${ctx.root}/.${ConfigFolderName}/${REMOTE_MANIFEST}`
// So we even don't need to mock fs.readJson
const result = await solution.provision(mockedCtx);
expect(result.isErr()).to.be.true;
});
it("should return false even if provisionSucceeded is true", async () => {
const solution = new TeamsAppSolution();
const mockedCtx = mockSolutionContext();
mockedCtx.config.get(GLOBAL_CONFIG)?.set(SOLUTION_PROVISION_SUCCEEDED, true);
const result = await solution.provision(mockedCtx);
expect(result.isOk()).to.be.false;
});
});
describe("provision() with permission.json file missing", () => {
const mocker = sinon.createSandbox();
const permissionsJsonPath = "./permissions.json";
const fileContent: Map<string, any> = new Map();
beforeEach(() => {
mocker.stub(fs, "writeFile").callsFake((path: number | PathLike, data: any) => {
fileContent.set(path.toString(), data);
});
mocker.stub(fs, "writeJSON").callsFake((file: string, obj: any) => {
fileContent.set(file, JSON.stringify(obj));
});
mocker.stub<any, any>(fs, "pathExists").withArgs(permissionsJsonPath).resolves(false);
});
afterEach(() => {
mocker.restore();
});
it("should return error for Azure projects", async () => {
const solution = new TeamsAppSolution();
const mockedCtx = mockSolutionContext();
mockedCtx.projectSettings = {
appName: "my app",
projectId: uuid.v4(),
solutionSettings: {
hostType: HostTypeOptionAzure.id,
name: "azure",
version: "1.0",
activeResourcePlugins: [fehostPlugin.name],
},
};
const result = await solution.provision(mockedCtx);
expect(result.isErr()).to.be.true;
expect(result._unsafeUnwrapErr().name).equals(SolutionError.MissingPermissionsJson);
});
it("should work for SPFx projects on happy path", async () => {
const solution = new TeamsAppSolution();
const mockedCtx = mockSolutionContext();
mockedCtx.projectSettings = {
appName: "my app",
projectId: uuid.v4(),
solutionSettings: {
hostType: HostTypeOptionSPFx.id,
name: "azure",
version: "1.0",
activeResourcePlugins: [spfxPlugin.name],
},
};
solution.doProvision = async function (_ctx: PluginContext): Promise<Result<any, FxError>> {
return ok(Void);
};
const result = await solution.provision(mockedCtx);
expect(result.isOk()).to.be.true;
});
});
describe("provision() happy path for SPFx projects", () => {
const mocker = sinon.createSandbox();
// const permissionsJsonPath = "./permissions.json";
const fileContent: Map<string, any> = new Map();
const mockedAppDef: IAppDefinition = {
appName: "MyApp",
teamsAppId: "qwertasdf",
};
const mockedManifest = _.cloneDeep(validManifest);
// ignore icons for simplicity
mockedManifest.icons.color = "";
mockedManifest.icons.outline = "";
beforeEach(() => {
mocker.stub(fs, "writeFile").callsFake((path: number | PathLike, data: any) => {
fileContent.set(path.toString(), data);
});
mocker.stub(fs, "writeJSON").callsFake((file: string, obj: any) => {
fileContent.set(file, JSON.stringify(obj));
});
mocker
.stub<any, any>(fs, "readJson")
.withArgs(`./.${ConfigFolderName}/${REMOTE_MANIFEST}`)
.resolves(mockedManifest);
// mocker.stub<any, any>(fs, "pathExists").withArgs(permissionsJsonPath).resolves(true);
mocker.stub(AppStudioClient, "createApp").resolves(mockedAppDef);
mocker.stub(AppStudioClient, "updateApp").resolves(mockedAppDef);
mocker
.stub(AppStudioPluginImpl.prototype, "getAppDirectory" as any)
.resolves(`./.${ConfigFolderName}`);
});
afterEach(() => {
mocker.restore();
});
it("should succeed if app studio returns successfully", async () => {
const solution = new TeamsAppSolution();
const mockedCtx = mockSolutionContext();
mockedCtx.projectSettings = {
appName: "my app",
projectId: uuid.v4(),
solutionSettings: {
hostType: HostTypeOptionSPFx.id,
name: "SPFx",
version: "1.0",
activeResourcePlugins: [spfxPlugin.name, appStudioPlugin.name],
},
};
expect(mockedCtx.config.get(GLOBAL_CONFIG)?.get(SOLUTION_PROVISION_SUCCEEDED)).to.be.undefined;
expect(mockedCtx.config.get(GLOBAL_CONFIG)?.get(REMOTE_TEAMS_APP_ID)).to.be.undefined;
const result = await solution.provision(mockedCtx);
expect(result.isOk()).to.be.true;
expect(mockedCtx.config.get(GLOBAL_CONFIG)?.get(SOLUTION_PROVISION_SUCCEEDED)).to.be.true;
expect(mockedCtx.config.get(GLOBAL_CONFIG)?.get(REMOTE_TEAMS_APP_ID)).equals(
mockedAppDef.teamsAppId
);
expect(solution.runningState).equals(SolutionRunningState.Idle);
});
});
describe("provision() happy path for Azure projects", () => {
const mocker = sinon.createSandbox();
const permissionsJsonPath = "./permissions.json";
const resourceGroupName = "test-rg";
const mockedAppDef: IAppDefinition = {
appName: "MyApp",
teamsAppId: "qwertasdf",
};
const mockedManifest = _.cloneDeep(validManifest);
// ignore icons for simplicity
mockedManifest.icons.color = "";
mockedManifest.icons.outline = "";
beforeEach(() => {
mocker.stub<any, any>(fs, "pathExists").withArgs(permissionsJsonPath).resolves(true);
mocker
.stub<any, any>(fs, "readJSON")
.withArgs(permissionsJsonPath)
.resolves(DEFAULT_PERMISSION_REQUEST);
mocker
.stub<any, any>(fs, "readJson")
.withArgs(`./.${ConfigFolderName}/${REMOTE_MANIFEST}`)
.resolves(mockedManifest);
mocker.stub(AppStudioClient, "createApp").resolves(mockedAppDef);
mocker.stub(AppStudioClient, "updateApp").resolves(mockedAppDef);
// mocker.stub(ResourceGroups.prototype, "checkExistence").resolves({body: true});
mocker.stub(ResourceGroups.prototype, "createOrUpdate").resolves({ name: resourceGroupName });
mocker.stub(solutionUtil, "getSubsriptionDisplayName").resolves(mockedSubscriptionName);
});
afterEach(() => {
mocker.restore();
});
it("should succeed if app studio returns successfully", async () => {
const solution = new TeamsAppSolution();
const mockedCtx = mockSolutionContext();
mockedCtx.projectSettings = {
appName: "my app",
projectId: uuid.v4(),
solutionSettings: {
hostType: HostTypeOptionAzure.id,
name: "azure",
version: "1.0",
activeResourcePlugins: [fehostPlugin.name, aadPlugin.name, appStudioPlugin.name],
},
};
mockProvisionThatAlwaysSucceed(fehostPlugin);
fehostPlugin.provision = async function (ctx: PluginContext): Promise<Result<any, FxError>> {
ctx.config.set(FRONTEND_ENDPOINT, "http://example.com");
ctx.config.set(FRONTEND_DOMAIN, "http://example.com");
return ok(Void);
};
mockProvisionThatAlwaysSucceed(aadPlugin);
aadPlugin.postProvision = async function (ctx: PluginContext): Promise<Result<any, FxError>> {
ctx.config.set(REMOTE_AAD_ID, "mockedRemoteAadId");
return ok(Void);
};
mockProvisionThatAlwaysSucceed(appStudioPlugin);
appStudioPlugin.postProvision = async function (
ctx: PluginContext
): Promise<Result<any, FxError>> {
return ok(mockedAppDef.teamsAppId);
};
aadPlugin.setApplicationInContext = function (
ctx: PluginContext,
_isLocalDebug?: boolean
): Result<any, FxError> {
ctx.config.set(WEB_APPLICATION_INFO_SOURCE, "mockedWebApplicationInfoResouce");
return ok(Void);
};
const spy = mocker.spy(aadPlugin, "setApplicationInContext");
expect(mockedCtx.config.get(GLOBAL_CONFIG)?.get(SOLUTION_PROVISION_SUCCEEDED)).to.be.undefined;
expect(mockedCtx.config.get(GLOBAL_CONFIG)?.get(REMOTE_TEAMS_APP_ID)).to.be.undefined;
// mockedCtx.config.get(GLOBAL_CONFIG)?.set("resourceGroupName", resourceGroupName);
mockedCtx.config.get(GLOBAL_CONFIG)?.set("subscriptionId", mockedSubscriptionId);
mockedCtx.config.get(GLOBAL_CONFIG)?.set("tenantId", mockedTenantId);
mocker.stub(AppStudioPluginImpl.prototype, "getConfigForCreatingManifest" as any).returns(
ok({
tabEndpoint: "tabEndpoint",
tabDomain: "tabDomain",
aadId: uuid.v4(),
botDomain: "botDomain",
botId: uuid.v4(),
webApplicationInfoResource: "webApplicationInfoResource",
})
);
const result = await solution.provision(mockedCtx);
expect(result.isOk()).to.be.true;
expect(spy.calledOnce).to.be.true;
expect(mockedCtx.config.get(GLOBAL_CONFIG)?.get(SOLUTION_PROVISION_SUCCEEDED)).to.be.true;
// expect(mockedCtx.config.get(GLOBAL_CONFIG)?.get(REMOTE_TEAMS_APP_ID)).equals(
// mockedAppDef.teamsAppId
// );
});
});
|
<reponame>KrazyTheFox/Cataclysm-DDA-Map-Editor
package net.krazyweb.cataclysm.mapeditor.map.data.entryeditorcontrollers;
import net.krazyweb.cataclysm.mapeditor.map.data.OvermapEntry;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
public class OvermapController {
private static final Logger log = LogManager.getLogger(OvermapController.class);
public void setOvermap(final OvermapEntry overmap) {
log.debug(overmap);
}
}
|
<reponame>DenseLance/Discord-Chatbot-AI
import json
import markovify
import discord
from discord.ext import commands
user = "scba"
TOKEN = "REDACTED" # Insert your bot token here
bot = commands.Bot(command_prefix = "")
@bot.event
async def on_ready():
global text_model
with open(f"{user}_model.json", "r", encoding = "utf8") as f:
text_model = markovify.Text.from_json(json.loads(f.read()))
f.close()
print(f"Thou hath summoned {bot.user}.")
@bot.event
async def on_message(message):
if message.author == bot.user:
return
await message.channel.send(text_model.make_sentence())
bot.run(TOKEN)
|
#!/bin/bash
./gradlew cleanJar build copyJar
|
# 英和辞書から word が含まれている語句を抽出する
def search(word):
with open(".\data\ejdict-hand-utf8.txt", "r", encoding="utf-8") as fp:
for line in fp:
# 単語が含まれていたら
if word in line:
print(line, end='')
if __name__ == '__main__':
# 英和辞書のデータを一行ずつ読む
word = "ball" # 検索単語を指定
search(word)
|
import tensorflow as tf
# define data
data = [
{'text': "I had a blast!", 'label': 'positive'},
{'text': "It's ok.", 'label': 'neutral'},
{'text': "I'm disappointed.", 'label': 'negative'},
]
# prepare data
inputs, labels = [], []
for datum in data:
inputs.append(datum['text'])
labels.append(datum['label'])
# create model
model = tf.keras.Sequential([
tf.keras.layers.Input(shape=(None, )),
tf.keras.layers.Embedding(input_dim=10000, output_dim=128),
tf.keras.layers.GlobalAveragePooling1D(),
tf.keras.layers.Dense(256, activation='relu'),
tf.keras.layers.Dense(3, activation='softmax'),
])
# compile the model
model.compile(
optimizer='adam',
loss=tf.keras.losses.SparseCategoricalCrossentropy(),
metrics=['accuracy'],
)
# train the model
model.fit(inputs, labels, epochs=10) |
<reponame>oueya1479/OpenOLAT<filename>src/main/java/org/olat/core/gui/components/form/flexible/FormUIFactory.java
/**
* OLAT - Online Learning and Training<br>
* http://www.olat.org
* <p>
* Licensed under the Apache License, Version 2.0 (the "License"); <br>
* you may not use this file except in compliance with the License.<br>
* You may obtain a copy of the License at
* <p>
* http://www.apache.org/licenses/LICENSE-2.0
* <p>
* Unless required by applicable law or agreed to in writing,<br>
* software distributed under the License is distributed on an "AS IS" BASIS, <br>
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. <br>
* See the License for the specific language governing permissions and <br>
* limitations under the License.
* <p>
* Copyright (c) since 2004 at Multimedia- & E-Learning Services (MELS),<br>
* University of Zurich, Switzerland.
* <hr>
* <a href="http://www.openolat.org">
* OpenOLAT - Online Learning and Training</a><br>
* This file has been modified by the OpenOLAT community. Changes are licensed
* under the Apache 2.0 license as the original file.
* <p>
*/
package org.olat.core.gui.components.form.flexible;
import java.io.File;
import java.lang.management.MemoryType;
import java.util.Date;
import java.util.List;
import org.olat.core.commons.controllers.linkchooser.CustomLinkTreeModel;
import org.olat.core.gui.UserRequest;
import org.olat.core.gui.components.Component;
import org.olat.core.gui.components.ComponentEventListener;
import org.olat.core.gui.components.dropdown.DropdownItem;
import org.olat.core.gui.components.form.flexible.elements.AddRemoveElement;
import org.olat.core.gui.components.form.flexible.elements.AutoCompleter;
import org.olat.core.gui.components.form.flexible.elements.AutoCompletionMultiSelection;
import org.olat.core.gui.components.form.flexible.elements.AutoCompletionMultiSelection.AutoCompletionSource;
import org.olat.core.gui.components.form.flexible.elements.DateChooser;
import org.olat.core.gui.components.form.flexible.elements.DownloadLink;
import org.olat.core.gui.components.form.flexible.elements.FileElement;
import org.olat.core.gui.components.form.flexible.elements.FlexiTableElement;
import org.olat.core.gui.components.form.flexible.elements.FormLink;
import org.olat.core.gui.components.form.flexible.elements.FormToggle;
import org.olat.core.gui.components.form.flexible.elements.IntegerElement;
import org.olat.core.gui.components.form.flexible.elements.MemoryElement;
import org.olat.core.gui.components.form.flexible.elements.MultipleSelectionElement;
import org.olat.core.gui.components.form.flexible.elements.MultipleSelectionElement.Layout;
import org.olat.core.gui.components.form.flexible.elements.RichTextElement;
import org.olat.core.gui.components.form.flexible.elements.SingleSelection;
import org.olat.core.gui.components.form.flexible.elements.SliderElement;
import org.olat.core.gui.components.form.flexible.elements.SpacerElement;
import org.olat.core.gui.components.form.flexible.elements.StaticTextElement;
import org.olat.core.gui.components.form.flexible.elements.TextAreaElement;
import org.olat.core.gui.components.form.flexible.elements.TextBoxListElement;
import org.olat.core.gui.components.form.flexible.elements.TextElement;
import org.olat.core.gui.components.form.flexible.impl.FormBasicController;
import org.olat.core.gui.components.form.flexible.impl.FormEvent;
import org.olat.core.gui.components.form.flexible.impl.FormItemImpl;
import org.olat.core.gui.components.form.flexible.impl.components.SimpleExampleText;
import org.olat.core.gui.components.form.flexible.impl.components.SimpleFormErrorText;
import org.olat.core.gui.components.form.flexible.impl.elements.AddRemoveElementImpl;
import org.olat.core.gui.components.form.flexible.impl.elements.AddRemoveElementImpl.AddRemoveMode;
import org.olat.core.gui.components.form.flexible.impl.elements.AutoCompleterImpl;
import org.olat.core.gui.components.form.flexible.impl.elements.AutoCompletionMultiSelectionImpl;
import org.olat.core.gui.components.form.flexible.impl.elements.DownloadLinkImpl;
import org.olat.core.gui.components.form.flexible.impl.elements.FileElementImpl;
import org.olat.core.gui.components.form.flexible.impl.elements.FormCancel;
import org.olat.core.gui.components.form.flexible.impl.elements.FormLinkImpl;
import org.olat.core.gui.components.form.flexible.impl.elements.FormReset;
import org.olat.core.gui.components.form.flexible.impl.elements.FormSubmit;
import org.olat.core.gui.components.form.flexible.impl.elements.FormToggleImpl;
import org.olat.core.gui.components.form.flexible.impl.elements.IntegerElementImpl;
import org.olat.core.gui.components.form.flexible.impl.elements.JSDateChooser;
import org.olat.core.gui.components.form.flexible.impl.elements.MemoryElementImpl;
import org.olat.core.gui.components.form.flexible.impl.elements.MultiSelectionTreeImpl;
import org.olat.core.gui.components.form.flexible.impl.elements.MultipleSelectionElementImpl;
import org.olat.core.gui.components.form.flexible.impl.elements.SelectboxSelectionImpl;
import org.olat.core.gui.components.form.flexible.impl.elements.SingleSelectionImpl;
import org.olat.core.gui.components.form.flexible.impl.elements.SliderElementImpl;
import org.olat.core.gui.components.form.flexible.impl.elements.SpacerElementImpl;
import org.olat.core.gui.components.form.flexible.impl.elements.StaticTextElementImpl;
import org.olat.core.gui.components.form.flexible.impl.elements.TextAreaElementImpl;
import org.olat.core.gui.components.form.flexible.impl.elements.TextBoxListElementImpl;
import org.olat.core.gui.components.form.flexible.impl.elements.TextElementImpl;
import org.olat.core.gui.components.form.flexible.impl.elements.richText.RichTextConfiguration;
import org.olat.core.gui.components.form.flexible.impl.elements.richText.RichTextElementImpl;
import org.olat.core.gui.components.form.flexible.impl.elements.table.FlexiTableDataModel;
import org.olat.core.gui.components.form.flexible.impl.elements.table.FlexiTableElementImpl;
import org.olat.core.gui.components.link.ExternalLinkItem;
import org.olat.core.gui.components.link.ExternalLinkItemImpl;
import org.olat.core.gui.components.link.Link;
import org.olat.core.gui.components.progressbar.ProgressBarItem;
import org.olat.core.gui.components.rating.RatingFormItem;
import org.olat.core.gui.components.textboxlist.TextBoxItem;
import org.olat.core.gui.components.tree.MenuTreeItem;
import org.olat.core.gui.components.tree.TreeModel;
import org.olat.core.gui.components.util.SelectionValues;
import org.olat.core.gui.control.WindowBackOffice;
import org.olat.core.gui.control.WindowControl;
import org.olat.core.gui.media.MediaResource;
import org.olat.core.gui.themes.Theme;
import org.olat.core.gui.translator.Translator;
import org.olat.core.id.Identity;
import org.olat.core.util.StringHelper;
import org.olat.core.util.UserSession;
import org.olat.core.util.ValidationStatus;
import org.olat.core.util.tree.INodeFilter;
import org.olat.core.util.vfs.VFSContainer;
import org.olat.core.util.vfs.VFSLeaf;
/**
* Factory class to create the flexible form elements.
*
* @author patrickb
*
*/
public class FormUIFactory {
// inject later via spring
private static FormUIFactory INSTANCE = new FormUIFactory();
FormUIFactory() {
// no public constructors.
}
/**
*
* @return
*/
public static FormUIFactory getInstance() {
return INSTANCE;
}
/**
* helper for all factory methods, to check if a label should be set or not.
*
* each addXXXX method in the factory should have a smallest possible one, which is using the "name" as "i18nkey" for the label. And another method
* with at least one parameter more, the "string i18nkeylabel". Furthermore the latter method should use the setLabelIfNotNull method to decide whether
* a label is set (and translated).
*
* @param i18nLabel the i18n key to set the label, or <code>null</code> to disable the label.
* @param fi
*/
static FormItem setLabelIfNotNull(String i18nLabel, FormItem fi){
if (StringHelper.containsNonWhitespace(i18nLabel)) {
fi.setLabel(i18nLabel, null);
fi.showLabel(true);
}else{
fi.showLabel(false);
}
return fi;
}
/**
* Date chooser is a text field with an icon, which on click shows a java script calendar to choose a date/time.
* This method uses the name to set the i18nkey of the label.
* <p>
* If no label is desired use the {@link FormUIFactory#addDateChooser(String, String, String, FormItemContainer)} with <code>null</code> as i18nLabel.
*
* @param name
* @param initValue
* @param formLayout
* @return
*/
public DateChooser addDateChooser(String name, Date initValue, FormItemContainer formLayout) {
return addDateChooser(name, name, initValue, formLayout);
}
/**
* Date chooser is a text field with an icon, which on click shows a java script calendar to choose a date/time.
*
* @param name
* @param initValue
* @param i18nLabel
* @param formLayout
* @return
*/
public DateChooser addDateChooser(String name, String i18nLabel, Date initValue, FormItemContainer formLayout) {
JSDateChooser tmp = new JSDateChooser(name, initValue, formLayout.getTranslator().getLocale());
setLabelIfNotNull(i18nLabel, tmp);
formLayout.add(tmp);
return tmp;
}
/**
* create an integer Element.
* This method uses the name to set the i18nkey of the label.
* <p>
* If no label is desired use the {@link FormUIFactory#addIntegerElement(String, String, int, FormItemContainer)} with <code>null</code> as i18nLabel.
*
* @param name
* @param initVal
* @param formLayout
* @return
*/
public IntegerElement addIntegerElement(String name, int initVal, FormItemContainer formLayout) {
return addIntegerElement(name, name, initVal, formLayout);
}
/**
* create an integer Element
*
* @param name
* @param initVal
* @param formLayout
* @return
*/
public IntegerElement addIntegerElement(String name, String i18nLabel, int initVal, FormItemContainer formLayout) {
IntegerElement tmp = new IntegerElementImpl(name, initVal);
setLabelIfNotNull(i18nLabel, tmp);
formLayout.add(tmp);
return tmp;
}
/**
* Create a multiple selection element with check-boxes horizontal aligned.
* This method uses the name to set the i18nkey of the label.
* <p>
* If no label is desired use the {@link FormUIFactory#addCheckboxesHorizontal(String, String, FormItemContainer, String[], String[], String[])} with <code>null</code> as i18nLabel.
* @param name
* @param layouter
* @param keys
* @param values
* @return
*/
public MultipleSelectionElement addCheckboxesHorizontal(String name, FormItemContainer formLayout, String[] keys, String[] values) {
return addCheckboxesHorizontal(name, name, formLayout, keys, values);
}
/**
* Create a multiple selection element with check-boxes horizontal aligned.
*
* @param name
* @param i18nLabel
* @param formLayout
* @param keys
* @param values
* @return
*/
public MultipleSelectionElement addCheckboxesHorizontal(String name, String i18nLabel, FormItemContainer formLayout, String[] keys, String[] values) {
MultipleSelectionElement mse = new MultipleSelectionElementImpl(name);
mse.setKeysAndValues(keys, values);
setLabelIfNotNull(i18nLabel, mse);
formLayout.add(mse);
return mse;
}
/**
* Create a multiple selection element with check-boxes that is rendered in vertical columns
* This method uses the name to set the i18nkey of the label.
* <p>
* If no label is desired use the {@link FormUIFactory#addCheckboxesVertical(String, String, FormItemContainer, String[], String[], String[], int)} with <code>null</code> as i18nLabel.
* @param name
* @param layouter
* @param keys
* @param values
* @param cssClasses
* @param columns Currently 1 and 2 columns are supported
* @return
*/
public MultipleSelectionElement addCheckboxesVertical(String name, FormItemContainer formLayout, String[] keys, String[] values, int columns) {
return addCheckboxesVertical(name, name, formLayout, keys, values, null, null, columns);
}
/**
*
* See above
* @param name
* @param formLayout
* @param keys
* @param values
* @param iconLeftCSS Icon placed with an <i> tag
* @param columns
* @return
*/
public MultipleSelectionElement addCheckboxesVertical(String name, FormItemContainer formLayout, String[] keys, String[] values, String[] iconLeftCSS, int columns) {
return addCheckboxesVertical(name, name, formLayout, keys, values, null, iconLeftCSS, columns);
}
public MultipleSelectionElement addCheckboxesVertical(String name, String i18nLabel, FormItemContainer formLayout, String[] keys, String[] values, String[] iconLeftCSS, int columns) {
return addCheckboxesVertical(name, i18nLabel, formLayout, keys, values, null, iconLeftCSS, columns);
}
public MultipleSelectionElement addCheckboxesVertical(String name, String i18nLabel, FormItemContainer formLayout, String[] keys, String[] values, int columns) {
return addCheckboxesVertical(name, i18nLabel, formLayout, keys, values, null, null, columns);
}
/**
* Create a multiple selection element with check-boxes that is rendered in vertical columns
* @param name
* @param i18nLabel
* @param formLayout
* @param keys
* @param values
* @param cssClasses
* @param columns
* @return
*/
public MultipleSelectionElement addCheckboxesVertical(String name, String i18nLabel, FormItemContainer formLayout,
String[] keys, String[] values, String[] cssClasses, String[] iconLeftCSS, int columns) {
MultipleSelectionElement mse = new MultipleSelectionElementImpl(name, Layout.vertical, columns);
mse.setKeysAndValues(keys, values, cssClasses, iconLeftCSS);
setLabelIfNotNull(i18nLabel, mse);
formLayout.add(mse);
return mse;
}
public MultipleSelectionElement addCheckboxesDropdown(String name, FormItemContainer formLayout) {
return addCheckboxesDropdown(name, name, formLayout, new String[] {}, new String[] {});
}
public MultipleSelectionElement addCheckboxesDropdown(String name, String i18nLabel, FormItemContainer formLayout,
String[] keys, String[] values) {
return addCheckboxesDropdown(name, i18nLabel, formLayout, keys, values, null, null);
}
public MultipleSelectionElement addCheckboxesDropdown(String name, String i18nLabel, FormItemContainer formLayout,
String[] keys, String[] values, String[] cssClasses, String[] iconLeftCSS) {
MultipleSelectionElement mse = new MultipleSelectionElementImpl(name, Layout.dropdown);
mse.setKeysAndValues(keys, values, cssClasses, iconLeftCSS);
setLabelIfNotNull(i18nLabel, mse);
formLayout.add(mse);
return mse;
}
public AutoCompletionMultiSelection addAutoCompletionMultiSelection(String name,
FormItemContainer formLayout, WindowControl wControl, AutoCompletionSource source) {
return addAutoCompletionMultiSelection(name, name, formLayout, wControl, source);
}
public AutoCompletionMultiSelection addAutoCompletionMultiSelection(String name, String i18nLabel,
FormItemContainer formLayout, WindowControl wControl, AutoCompletionSource source) {
AutoCompletionMultiSelectionImpl acms = new AutoCompletionMultiSelectionImpl(wControl, name, source);
setLabelIfNotNull(i18nLabel, acms);
formLayout.add(acms);
return acms;
}
/**
* Create a multiple selection element as a tree.
* @param name
* @param i18nLabel Can be null
* @param formLayout
* @param treemodel
* @param selectableFilter
* @return
*/
public MultipleSelectionElement addTreeMultiselect(String name, String i18nLabel, FormItemContainer formLayout, TreeModel treemodel, INodeFilter selectableFilter){
MultipleSelectionElement mse = new MultiSelectionTreeImpl(name, treemodel, selectableFilter);
setLabelIfNotNull(i18nLabel, mse);
formLayout.add(mse);
return mse;
}
public MenuTreeItem addTreeMultiselect(String name, String i18nLabel, FormItemContainer formLayout, TreeModel treemodel, ComponentEventListener listener){
MenuTreeItem mse = new MenuTreeItem(name, listener);
mse.setTreeModel(treemodel);
setLabelIfNotNull(i18nLabel, mse);
formLayout.add(mse);
return mse;
}
/**
* Add horizontal aligned radio buttons. <br>
* This method uses the name to set the i18nkey of the label.
* <p>
* If no label is desired use the {@link FormUIFactory#addRadiosHorizontal(String, String, FormItemContainer, String[], String[])} with <code>null</code> as i18nLabel.
*
* @param name item identifier and i18n key for the label
* @param formLayout
* @param theKeys the radio button keys
* @param theValues the radio button display values
* @return
*/
public SingleSelection addRadiosHorizontal(final String name, FormItemContainer formLayout, final String[] theKeys, final String[] theValues) {
return addRadiosHorizontal(name, name, formLayout, theKeys, theValues);
}
/**
* Add horizontal aligned radio buttons. <br>
*
* @param name
* @param i18nLabel
* @param formLayout
* @param theKeys
* @param theValues
* @return
*/
public SingleSelection addRadiosHorizontal(final String name, final String i18nLabel, FormItemContainer formLayout, final String[] theKeys, final String[] theValues) {
SingleSelection ss = new SingleSelectionImpl(name, name, SingleSelection.Layout.horizontal, formLayout.getTranslator().getLocale());
ss.setKeysAndValues(theKeys, theValues, null);
setLabelIfNotNull(i18nLabel, ss);
formLayout.add(ss);
return ss;
}
/**
* Add vertical aligned radio buttons<br>
* This method uses the name to set the i18nkey of the label.
* <p>
* If no label is desired use the {@link FormUIFactory#addRadiosVertical(String, String, FormItemContainer, String[], String[])} with <code>null</code> as i18nLabel.
*
* @param name item identifier and i18n key for the label
* @param formLayout
* @param theKeys the radio button keys
* @param theValues the radio button display values
* @return
*/
public SingleSelection addRadiosVertical(final String name, FormItemContainer formLayout, final String[] theKeys, final String[] theValues) {
return addRadiosVertical(name, name, formLayout, theKeys, theValues);
}
/**
* Add vertical aligned radio buttons<br>
*
* @param name
* @param i18nLabel
* @param formLayout
* @param theKeys
* @param theValues
* @return
*/
public SingleSelection addRadiosVertical(final String name, final String i18nLabel, FormItemContainer formLayout, final String[] theKeys, final String[] theValues) {
SingleSelection ss = new SingleSelectionImpl(name, name, SingleSelection.Layout.vertical, formLayout.getTranslator().getLocale());
ss.setKeysAndValues(theKeys, theValues, null);
setLabelIfNotNull(i18nLabel, ss);
formLayout.add(ss);
return ss;
}
/**
* A radio button group rendered horizontally as cards with a card title,
* description and icon. When there is not enough space the cards will render on
* multiple lines (fixed width). If you need custom styling, width etc, use the
* setElementCssClass on the SingleSelection.
*
* @param name The form item name and i18n key for the label
* @param formLayout The layout where the form item is added
* @param theKeys Array of keys for each card
* @param theTitles The titles of the cards
* @param theDescriptions The optional descriptions of the cards
* @param theIconCssClasses The optional icons of the cards
* @return
*/
public SingleSelection addCardSingleSelectHorizontal(final String name, FormItemContainer formLayout, final String[] theKeys, final String[] theTitles, final String[] theDescriptions, final String[] theIconCssClasses) {
SingleSelectionImpl ss = new SingleSelectionImpl(name, name, SingleSelection.Layout.horizontal, formLayout.getTranslator().getLocale());
ss.setKeysAndValuesAndEnableCardStyle(theKeys, theTitles, theDescriptions, theIconCssClasses);
setLabelIfNotNull(name, ss);
formLayout.add(ss);
return ss;
}
/**
* A radio button group rendered vertically as cards with a card title,
* description and icon. If you need custom styling, width etc, use the
* setElementCssClass on the SingleSelection.
*
* @param name The form item name and i18n key for the label
* @param formLayout The layout where the form item is added
* @param theKeys Array of keys for each card
* @param theTitles The titles of the cards
* @param theDescriptions The optional descriptions of the cards
* @param theIconCssClasses The optional icons of the cards
* @return
*/
public SingleSelection addCardSingleSelectVertical(final String name, FormItemContainer formLayout, final String[] theKeys, final String[] theTitles, final String[] theDescriptions, final String[] theIconCssClasses) {
SingleSelectionImpl ss = new SingleSelectionImpl(name, name, SingleSelection.Layout.vertical, formLayout.getTranslator().getLocale());
ss.setKeysAndValuesAndEnableCardStyle(theKeys, theTitles, theDescriptions, theIconCssClasses);
setLabelIfNotNull(name, ss);
formLayout.add(ss);
return ss;
}
public SingleSelection addButtonGroupSingleSelectVertical(final String name, FormItemContainer formLayout, SelectionValues selectionValues) {
SingleSelectionImpl ss = new SingleSelectionImpl(name, name, SingleSelection.Layout.vertical, formLayout.getTranslator().getLocale());
ss.setKeysAndValuesAndEnableButtonGroupStyle(selectionValues.keys(), selectionValues.values(), selectionValues.cssClasses(), selectionValues.enabledStates());
setLabelIfNotNull(name, ss);
formLayout.add(ss);
return ss;
}
public SingleSelection addButtonGroupSingleSelectHorizontal(final String name, FormItemContainer formLayout, SelectionValues selectionValues) {
SingleSelectionImpl ss = new SingleSelectionImpl(name, name, SingleSelection.Layout.horizontal, formLayout.getTranslator().getLocale());
ss.setKeysAndValuesAndEnableButtonGroupStyle(selectionValues.keys(), selectionValues.values(), selectionValues.cssClasses(), selectionValues.enabledStates());
setLabelIfNotNull(name, ss);
formLayout.add(ss);
return ss;
}
public SingleSelection addDropdownSingleselect(final String name, FormItemContainer formLayout, final String[] theKeys, final String[] theValues) {
return addDropdownSingleselect(name, name, name, formLayout, theKeys, theValues, null);
}
public SingleSelection addDropdownSingleselect(final String name, final String i18nLabel, FormItemContainer formLayout, final String[] theKeys, final String[] theValues) {
return addDropdownSingleselect(name, name, i18nLabel, formLayout, theKeys, theValues, null);
}
/**
* Add a drop down menu (also called pulldown menu), with a label's i18n key being the same as the <code>name<code>.
* If you do not want a label, use the {@link FormUIFactory#addDropdownSingleselect(String, String, FormItemContainer, String[], String[], String[])}
* method with the <code>i18nKey</code> and set it <code>null</code>
*
* @param name item identifier and i18n key for the label
* @param formLayout
* @param theKeys the menu selection keys
* @param theValues the menu display values
* @param theCssClasses the css classes to style the menu items or NULL to use no special styling
* @return
*/
public SingleSelection addDropdownSingleselect(final String name, FormItemContainer formLayout, final String[] theKeys, final String[] theValues, final String[] theCssClasses) {
return addDropdownSingleselect(name, name, name, formLayout, theKeys, theValues, theCssClasses);
}
/**
* Add a drop down menu (also called pulldown menu).
* @param name
* @param labelKey i18n key for the label, may be <code>null</code> indicating no label.
* @param formLayout
* @param theKeys
* @param theValues
* @param theCssClasses
* @return
*/
public SingleSelection addDropdownSingleselect(final String name, final String i18nLabel, FormItemContainer formLayout, final String[] theKeys, final String[] theValues, final String[] theCssClasses) {
return addDropdownSingleselect(name, name, i18nLabel, formLayout, theKeys, theValues, theCssClasses);
}
/**
* Add a drop down menu (also called pulldown menu).
* @param id The unique identifier of the selection box (can be null, will be auto generated)
* @param name
* @param labelKey i18n key for the label, may be <code>null</code> indicating no label.
* @param formLayout
* @param theKeys
* @param theValues
* @param theCssClasses
* @return
*/
public SingleSelection addDropdownSingleselect(final String id, final String name, final String i18nLabel, FormItemContainer formLayout, final String[] theKeys, final String[] theValues, final String[] theCssClasses) {
SingleSelection ss = new SelectboxSelectionImpl(id, name, formLayout.getTranslator().getLocale());
ss.setKeysAndValues(theKeys, theValues, theCssClasses);
setLabelIfNotNull(i18nLabel, ss);
formLayout.add(ss);
return ss;
}
/**
* Add a static text, with a label's i18n key being the same as the <code>name<code>.
* If you do not want a label, use the {@link FormUIFactory#addStaticTextElement(String, String, String, FormItemContainer)}
* method with the <code>i18nKey</code> and set it <code>null</code>
*
* @param name
* @param translatedText
* @param formLayout
* @return
*/
public StaticTextElement addStaticTextElement(String name, String translatedText, FormItemContainer formLayout) {
return addStaticTextElement(name,name,translatedText,formLayout);
}
/**
* Add a static text.
* @param name
* @param i18nLabel
* @param translatedText
* @param formLayout
* @return
*/
public StaticTextElement addStaticTextElement(String name, String i18nLabel,String translatedText, FormItemContainer formLayout) {
StaticTextElement ste = new StaticTextElementImpl(name, translatedText == null ? "" : translatedText);
setLabelIfNotNull(i18nLabel, ste);
formLayout.add(ste);
return ste;
}
public TextElement addInlineTextElement(String name, String value, FormItemContainer formLayout, FormBasicController listener) {
TextElement ie = new TextElementImpl(null, name, value, TextElementImpl.HTML_INPUT_TYPE_TEXT, true);
ie.addActionListener(FormEvent.ONCLICK);
if(listener != null){
formLayout.add(ie);
}
return ie;
}
/**
* Inserts an HTML horizontal bar (<HR>) element.
*
* @param name
* @param formLayout
* @return
*/
public SpacerElement addSpacerElement(String name, FormItemContainer formLayout, boolean onlySpaceAndNoLine) {
SpacerElement spacer = new SpacerElementImpl(name);
if (onlySpaceAndNoLine) {
spacer.setSpacerCssClass("o_spacer_noline");
}
formLayout.add(spacer);
return spacer;
}
/**
* adds a given text formatted in example style as part of the form.
* @param name
* @param text
* @param formLayout
* @return
*/
public FormItem addStaticExampleText(String name, String text, FormItemContainer formLayout){
return addStaticExampleText(name, name, text, formLayout);
}
/**
*
* @param name
* @param i18nLabel i18n key for label, null to disable
* @param text
* @param formLayout
* @return
*/
public FormItem addStaticExampleText(String name, String i18nLabel, String text, FormItemContainer formLayout){
final SimpleExampleText set = new SimpleExampleText(name, text);
//wrap the SimpleExampleText Component within a FormItem
FormItem fiWrapper = new FormItemImpl("simpleExampleTextWrapper_"+name) {
@Override
protected Component getFormItemComponent() {
return set;
}
@Override
public void validate(List<ValidationStatus> validationResults) {
//nothing to do
}
@Override
protected void rootFormAvailable() {
//nothing to do
}
@Override
public void reset() {
//nothing to do
}
@Override
public void evalFormRequest(UserRequest ureq) {
//nothing to do
}
};
setLabelIfNotNull(i18nLabel, fiWrapper);
formLayout.add(fiWrapper);
return fiWrapper;
}
public TextElement addTextElement(final String i18nLabel, final int maxLen, String initialValue,
FormItemContainer formLayout) {
return addTextElement(i18nLabel, i18nLabel, maxLen, initialValue, formLayout);
}
public TextElement addTextElement(String name, final String i18nLabel, final int maxLen, String initialValue,
FormItemContainer formLayout) {
String val = initialValue == null ? "" : initialValue;
return addTextElement(null, name, i18nLabel, maxLen, val, formLayout);
}
/**
* @param id The unique identifier of this text element (can be null)
* @param name
* @param maxLen
* @param initialValue
* @param i18nLabel
* @param formLayout
* @return
*/
public TextElement addTextElement(String id, String name, final String i18nLabel, final int maxLen, String initialValue,
FormItemContainer formLayout) {
String val = initialValue == null ? "" : initialValue;
TextElement te = new TextElementImpl(id, name, val);
te.setNotLongerThanCheck(maxLen, "text.element.error.notlongerthan");
setLabelIfNotNull(i18nLabel, te);
te.setMaxLength(maxLen);
formLayout.add(te);
return te;
}
/**
* adds a component to choose text elements with autocompletion
* see also TextBoxListComponent
* @param name
* @param i18nLabel
* @param inputHint if empty ("") a default will be used
* @param initialItems
* @param formLayout
* @param translator
* @return
*/
public TextBoxListElement addTextBoxListElement(String name, final String i18nLabel, String inputHint, List<TextBoxItem> initialItems, FormItemContainer formLayout, Translator translator){
TextBoxListElement tbe = new TextBoxListElementImpl(name, inputHint, initialItems, translator);
setLabelIfNotNull(i18nLabel, tbe);
formLayout.add(tbe);
return tbe;
}
public TextElement addPasswordElement(String name, final String i18nLabel, final int maxLen, String initialValue,
FormItemContainer formLayout) {
return addPasswordElement(null, name, i18nLabel, maxLen, initialValue, formLayout);
}
public TextElement addPasswordElement(String id, String name, final String i18nLabel, final int maxLen, String initialValue,
FormItemContainer formLayout) {
TextElement te = new TextElementImpl(id, name, initialValue, TextElementImpl.HTML_INPUT_TYPE_CREDENTIAL);
te.setNotLongerThanCheck(maxLen, "text.element.error.notlongerthan");
setLabelIfNotNull(i18nLabel, te);
te.setMaxLength(maxLen);
formLayout.add(te);
return te;
}
public AutoCompleter addTextElementWithAutoCompleter(String name, final String i18nLabel, final int maxLen, String initialValue,
FormItemContainer formLayout) {
return addTextElementWithAutoCompleter(null, name, i18nLabel, maxLen, initialValue, formLayout);
}
public AutoCompleter addTextElementWithAutoCompleter(String id, String name, final String i18nLabel, final int maxLen, String initialValue,
FormItemContainer formLayout) {
String val = initialValue == null ? "" : initialValue;
AutoCompleterImpl te = new AutoCompleterImpl(id, name);
te.setNotLongerThanCheck(maxLen, "text.element.error.notlongerthan");
setLabelIfNotNull(i18nLabel, te);
te.setMaxLength(maxLen);
te.setValue(val);
formLayout.add(te);
return te;
}
/**
* Add a multi line text element, using the provided name as i18n key for the label, no max length check set, and fits content hight at maximium (100lnes).
*
* @see FormUIFactory#addTextAreaElement(String, String, int, int, int, boolean, boolean, String, FormItemContainer)
* @param name
* @param rows
* @param cols
* @param initialValue
* @param formLayout
* @return
*/
public TextAreaElement addTextAreaElement(String name, final int rows, final int cols, String initialValue, FormItemContainer formLayout) {
return addTextAreaElement(name, name, -1, rows, cols, true, false, initialValue, formLayout);
}
/**
* Add a multi line text element
* @param name
* @param i18nLabel i18n key for the label or null to set no label at all.
* @param maxLen
* @param rows the number of lines or -1 to use default value
* @param cols the number of characters per line or -1 to use 100% of the
* available space
* @param isAutoHeightEnabled true: element expands to fit content height,
* (max 100 lines); false: specified rows used
* @param fixedFontWidth
* @param initialValue Initial value
* @param formLayout
* @return
*/
public TextAreaElement addTextAreaElement(String name, final String i18nLabel, final int maxLen, final int rows, final int cols,
boolean isAutoHeightEnabled, boolean fixedFontWidth, String initialValue, FormItemContainer formLayout) {
return addTextAreaElement(name, i18nLabel, maxLen, rows, cols, isAutoHeightEnabled, fixedFontWidth, false, initialValue, formLayout);
}
/**
* Add a multi line text element
* @param name
* @param i18nLabel i18n key for the label or null to set no label at all.
* @param maxLen
* @param rows the number of lines or -1 to use default value
* @param cols the number of characters per line or -1 to use 100% of the
* available space
* @param isAutoHeightEnabled true: element expands to fit content height,
* (max 100 lines); false: specified rows used
* @param fixedFontWidth
* @param originalLineBreaks Maintain the original line breaks and prevent the browser
* to add its own, scroll horizontally if necessary
* @param initialValue Initial value
* @param formLayout
* @return
*/
public TextAreaElement addTextAreaElement(String name, final String i18nLabel, final int maxLen, final int rows, final int cols,
boolean isAutoHeightEnabled, boolean fixedFontWidth, boolean originalLineBreaks, String initialValue, FormItemContainer formLayout) {
TextAreaElement te = new TextAreaElementImpl(name, initialValue, rows, cols, isAutoHeightEnabled, fixedFontWidth, originalLineBreaks) {
{
setNotLongerThanCheck(maxLen, "text.element.error.notlongerthan");
// the text.element.error.notlongerthan uses a variable {0} that
// contains the length maxLen
}
};
setLabelIfNotNull(i18nLabel, te);
formLayout.add(te);
return te;
}
/**
* Add a rich text formattable element that offers basic formatting
* functionality and loads the data form the given string value. Use
* item.getEditorConfiguration() to add more editor features if you need
* them
*
* @param name
* Name of the form item
* @param i18nLabel
* The i18n key of the label or NULL when no label is used
* @param initialValue
* The initial value or NULL if no initial value is available
* @param rows
* The number of lines the editor should offer. Use -1 to
* indicate no specific height
* @param cols
* The number of characters width the editor should offer. Use -1
* to indicate no specific width
* @param externalToolbar
* true: use an external toolbar that is only visible when the
* user clicks into the text area; false: use the static toolbar
* @param formLayout The form item container where to add the rich
* text element
* @param usess The user session that dispatches the images
* @param wControl the current window controller
* @param wControl
* the current window controller
* @return The rich text element instance
*/
public RichTextElement addRichTextElementForStringDataMinimalistic(String name, final String i18nLabel, String initialHTMLValue, final int rows,
final int cols, FormItemContainer formLayout, WindowControl wControl) {
// Create richt text element with bare bone configuration
RichTextElement rte = new RichTextElementImpl(name, initialHTMLValue, rows, cols, formLayout.getTranslator().getLocale());
setLabelIfNotNull(i18nLabel, rte);
// Now configure editor
rte.getEditorConfiguration().setConfigProfileFormEditorMinimalistic(wControl.getWindowBackOffice().getWindow().getGuiTheme());
rte.getEditorConfiguration().setPathInStatusBar(false);
// Add to form and finish
formLayout.add(rte);
return rte;
}
/**
* Add a rich text formattable element that offers simple formatting
* functionality and loads the data form the given string value. Use
* item.getEditorConfiguration() to add more editor features if you need
* them
*
* @param name
* Name of the form item
* @param i18nLabel
* The i18n key of the label or NULL when no label is used
* @param initialValue
* The initial value or NULL if no initial value is available
* @param rows
* The number of lines the editor should offer. Use -1 to
* indicate no specific height
* @param cols
* The number of characters width the editor should offer. Use -1
* to indicate no specific width
* @param externalToolbar
* true: use an external toolbar that is only visible when the
* user clicks into the text area; false: use the static toolbar
* @param fullProfile
* false: load only the necessary plugins; true: load all plugins
* from the full profile
* @param baseContainer
* The VFS container where to load resources from (images etc) or
* NULL to not allow embedding of media files at all
* @param formLayout
* The form item container where to add the richt text element
* @param customLinkTreeModel A custom link tree model or NULL not not use a
* custom model
* @param formLayout The form item container where to add the rich
* text element
* @param usess The user session that dispatches the images
* @param wControl the current window controller
* @return The rich text element instance
*/
public RichTextElement addRichTextElementForStringData(String name, String i18nLabel, String initialHTMLValue, int rows,
int cols, boolean fullProfile, VFSContainer baseContainer, CustomLinkTreeModel customLinkTreeModel,
FormItemContainer formLayout, UserSession usess, WindowControl wControl) {
return addRichTextElementForStringData(name, i18nLabel, initialHTMLValue, rows, cols,
fullProfile, baseContainer, null, customLinkTreeModel, formLayout, usess, wControl);
}
public RichTextElement addRichTextElementForStringData(String name, String i18nLabel, String initialHTMLValue, int rows,
int cols, boolean fullProfile, VFSContainer baseContainer, String relFilePath, CustomLinkTreeModel customLinkTreeModel,
FormItemContainer formLayout, UserSession usess, WindowControl wControl) {
// Create richt text element with bare bone configuration
WindowBackOffice backoffice = wControl.getWindowBackOffice();
RichTextElement rte = new RichTextElementImpl(name, initialHTMLValue, rows, cols, formLayout.getTranslator().getLocale());
setLabelIfNotNull(i18nLabel, rte);
// Now configure editor
Theme theme = backoffice.getWindow().getGuiTheme();
rte.getEditorConfiguration().setConfigProfileFormEditor(fullProfile, usess, theme, baseContainer, relFilePath, customLinkTreeModel);
// Add to form and finish
formLayout.add(rte);
return rte;
}
public RichTextElement addRichTextElementForStringDataCompact(String name, String i18nLabel, String initialHTMLValue, int rows,
int cols, VFSContainer baseContainer, FormItemContainer formLayout, UserSession usess, WindowControl wControl) {
// Create rich text element with bare bone configuration
RichTextElement rte = new RichTextElementImpl(name, initialHTMLValue, rows, cols, formLayout.getTranslator().getLocale());
setLabelIfNotNull(i18nLabel, rte);
// Now configure editor
Theme theme = wControl.getWindowBackOffice().getWindow().getGuiTheme();
rte.getEditorConfiguration().setConfigProfileFormCompactEditor(usess, theme, baseContainer);
// Add to form and finish
formLayout.add(rte);
return rte;
}
public RichTextElement addRichTextElementForParagraphEditor(String name, String i18nLabel, String initialHTMLValue, int rows,
int cols, FormItemContainer formLayout, WindowControl wControl) {
// Create rich text element with bare bone configuration
RichTextElement rte = new RichTextElementImpl(name, initialHTMLValue, rows, cols, formLayout.getTranslator().getLocale());
setLabelIfNotNull(i18nLabel, rte);
// Now configure editor
rte.getEditorConfiguration().setConfigProfileFormParagraphEditor(wControl.getWindowBackOffice().getWindow().getGuiTheme());
rte.getEditorConfiguration().setPathInStatusBar(false);
// Add to form and finish
formLayout.add(rte);
return rte;
}
/**
*
* This is a version with olat media only. The tiny media is disabled because we need to catch the object
* tag use by QTI and interpret it as a olat video. It enable the strict uri validation for file names.
*
* @param name
* @param i18nLabel
* @param initialHTMLValue
* @param rows
* @param cols
* @param baseContainer
* @param formLayout
* @param usess
* @param wControl
* @return
*/
public RichTextElement addRichTextElementForQTI21(String name, String i18nLabel, String initialHTMLValue, int rows,
int cols, VFSContainer baseContainer, FormItemContainer formLayout, UserSession usess, WindowControl wControl) {
// Create rich text element with bare bone configuration
RichTextElement rte = new RichTextElementImpl(name, initialHTMLValue, rows, cols, formLayout.getTranslator().getLocale());
setLabelIfNotNull(i18nLabel, rte);
// Now configure editor
Theme theme = wControl.getWindowBackOffice().getWindow().getGuiTheme();
rte.getEditorConfiguration().setConfigProfileFormCompactEditor(usess, theme, baseContainer);
rte.getEditorConfiguration().setInvalidElements(RichTextConfiguration.INVALID_ELEMENTS_FORM_FULL_VALUE_UNSAVE_WITH_SCRIPT);
rte.getEditorConfiguration().setExtendedValidElements("script[src|type|defer]");
rte.getEditorConfiguration().disableTinyMedia();
rte.getEditorConfiguration().setFilenameUriValidation(true);
rte.getEditorConfiguration().setFigCaption(false);
// Add to form and finish
formLayout.add(rte);
return rte;
}
public RichTextElement addRichTextElementVeryMinimalistic(String name, String i18nLabel, String initialHTMLValue, int rows,
int cols, boolean withLinks, VFSContainer baseContainer, FormItemContainer formLayout, UserSession usess, WindowControl wControl) {
// Create rich text element with bare bone configuration
RichTextElement rte = new RichTextElementImpl(name, initialHTMLValue, rows, cols, formLayout.getTranslator().getLocale());
setLabelIfNotNull(i18nLabel, rte);
// Now configure editor
Theme theme = wControl.getWindowBackOffice().getWindow().getGuiTheme();
rte.getEditorConfiguration().setConfigProfileFormVeryMinimalisticConfigEditor(usess, theme, baseContainer, withLinks);
rte.getEditorConfiguration().setInvalidElements(RichTextConfiguration.INVALID_ELEMENTS_FORM_FULL_VALUE_UNSAVE_WITH_SCRIPT);
rte.getEditorConfiguration().setExtendedValidElements("script[src|type|defer]");
rte.getEditorConfiguration().disableTinyMedia();
rte.getEditorConfiguration().setFilenameUriValidation(true);
rte.getEditorConfiguration().setFigCaption(false);
// Add to form and finish
formLayout.add(rte);
return rte;
}
/**
* Add a rich text formattable element that offers complex formatting
* functionality and loads the data from the given file path. Use
* item.getEditorConfiguration() to add more editor features if you need
* them
*
* @param name
* Name of the form item
* @param i18nLabel
* The i18n key of the label or NULL when no label is used
* @param initialValue
* The initial value or NULL if no initial value is available
* @param rows
* The number of lines the editor should offer. Use -1 to
* indicate no specific height
* @param cols
* The number of characters width the editor should offer. Use -1
* to indicate no specific width
* @param externalToolbar
* true: use an external toolbar that is only visible when the
* user clicks into the text area; false: use the static toolbar
* @param baseContainer
* The VFS container where to load resources from (images etc) or
* NULL to not allow embedding of media files at all
* @param relFilePath
* The path to the file relative to the baseContainer
* @param customLinkTreeModel
* A custom link tree model or NULL not not use a custom model
* @param toolLinkTreeModel
* @param formLayout
* The form item container where to add the rich text element
* @param usess
* The user session that dispatches the images
* @param wControl
* the current window controller
* @return The richt text element instance
*/
public RichTextElement addRichTextElementForFileData(String name, final String i18nLabel, String initialValue,
final int rows, int cols, VFSContainer baseContainer, String relFilePath,
CustomLinkTreeModel customLinkTreeModel, CustomLinkTreeModel toolLinkTreeModel,
FormItemContainer formLayout, UserSession usess, WindowControl wControl) {
// Create richt text element with bare bone configuration
RichTextElement rte = new RichTextElementImpl(name, initialValue, rows, cols, formLayout.getTranslator().getLocale());
setLabelIfNotNull(i18nLabel, rte);
// Now configure editor
rte.getEditorConfiguration().setConfigProfileFileEditor(usess,
wControl.getWindowBackOffice().getWindow().getGuiTheme(),
baseContainer, relFilePath, customLinkTreeModel, toolLinkTreeModel);
// Add to form and finish
formLayout.add(rte);
return rte;
}
/**
* Static text with the error look and feel.
* @param name in velocity for <code>$r.render("name")</code>
* @param translatedText already translated text that should be displayed.
* @return
*/
public FormItem createSimpleErrorText(final String name, final String translatedText) {
FormItem wrapper = new FormItemImpl(name) {
SimpleFormErrorText mySimpleErrorTextC = new SimpleFormErrorText(name, translatedText);
@Override
public void validate(List<ValidationStatus> validationResults) {
// nothing to do
}
@Override
protected void rootFormAvailable() {
// nothing to do
}
@Override
public void reset() {
// nothing to do
}
@Override
protected Component getFormItemComponent() {
return mySimpleErrorTextC;
}
@Override
public void evalFormRequest(UserRequest ureq) {
// nothing to do
}
};
return wrapper;
}
/**
*
* @param wControl
* @param name
* @param tableModel
* @param translator
* @param formLayout
* @return
*/
public FlexiTableElement addTableElement(WindowControl wControl, String name, FlexiTableDataModel<?> tableModel,
Translator translator, FormItemContainer formLayout) {
FlexiTableElementImpl fte = new FlexiTableElementImpl(wControl, name, translator, tableModel);
formLayout.add(fte);
return fte;
}
public FlexiTableElement addTableElement(WindowControl wControl, String name, FlexiTableDataModel<?> tableModel,
int pageSize, boolean loadOnInit, Translator translator, FormItemContainer formLayout) {
FlexiTableElementImpl fte = new FlexiTableElementImpl(wControl, name, translator, tableModel, pageSize, loadOnInit);
formLayout.add(fte);
return fte;
}
/**
* creates a form link with the given name which acts also as command, i18n
* and component name.
* @param name
* @param formLayout
* @return
*/
public FormLink addFormLink(String name, FormItemContainer formLayout) {
FormLinkImpl fte = new FormLinkImpl(name);
formLayout.add(fte);
return fte;
}
/**
* Add a form link with the option to choose the presentation, the <code>name</code> parameter is taken as
* to be used in <code>$r.render("<name>")</code>, as i18nkey for the link text, and also the cmd string.<p>
* If different values are needed for name, i18nkey link text, use the {@link FormUIFactory#addFormLink(String, String, String, FormItemContainer, int)}. This allows also to set
* the i18n key for label.
*
* @param name The name of the form element (identifyer), also used as i18n key
* @param formLayout
* @param presentation See Link.BUTTON etc
* @return
*/
public FormLink addFormLink(String name, FormItemContainer formLayout, int presentation) {
FormLinkImpl fte = new FormLinkImpl(name, name, name, presentation);
if(formLayout != null) {
formLayout.add(fte);
}
return fte;
}
/**
*
* @param name to be used to render in velocity <code>$r.render("name")</code>
* @param i18nLink i18n key for the link text
* @param i18nLabel i18n key for the link elements label, maybe <code>null</code>
* @param formLayout FormLink is added as element here
* @param presentation See Link.BUTTON etc.
* @return
*/
public FormLink addFormLink(String name, String i18nLink, String i18nLabel, FormItemContainer formLayout, int presentation){
FormLinkImpl fte = new FormLinkImpl(name,name,i18nLink,presentation);
fte.setI18nKey(i18nLink);
setLabelIfNotNull(i18nLabel, fte);
if(formLayout != null) {
formLayout.add(fte);
}
return fte;
}
/**
*
* @param name to be used to render in velocity <code>$r.render("name")</code>
* @param cmd The cmd to be used
* @param i18nLink i18n key for the link text
* @param i18nLabel i18n key for the link elements label, maybe <code>null</code>
* @param formLayout FormLink is added as element here
* @param presentation See Link.BUTTON etc.
* @return
*/
public FormLink addFormLink(String name, String cmd, String i18nLink, String i18nLabel, FormItemContainer formLayout, int presentation){
FormLinkImpl fte = new FormLinkImpl(name, cmd, i18nLink, presentation);
fte.setI18nKey(i18nLink);
setLabelIfNotNull(i18nLabel, fte);
if(formLayout != null) {
formLayout.add(fte);
}
return fte;
}
public FormLink addFormLink(String name, String cmd, String i18nLink, FlexiTableElement table) {
return addFormLink(name, cmd, i18nLink, table, Link.LINK);
}
public FormLink addFormLink(String name, String cmd, String i18nLink, FlexiTableElement table, int presentation) {
FormLinkImpl fte = new FormLinkImpl(name, cmd, i18nLink, presentation);
fte.setI18nKey(i18nLink);
setLabelIfNotNull(null, fte);
if(table instanceof FlexiTableElementImpl) {
((FlexiTableElementImpl)table).addFormItem(fte);
}
return fte;
}
/**
* Add a form link with a special css class
*
* @param name The name of the form element (identifyer), also used as i18n key
* @param formLayout
* @param css class
* @return
*/
public FormLink addFormLink(String name, FormItemContainer formLayout, String customEnabledLinkCSS) {
FormLinkImpl fte = new FormLinkImpl(name);
fte.setCustomEnabledLinkCSS(customEnabledLinkCSS);
if(formLayout != null) {
formLayout.add(fte);
}
return fte;
}
/**
* Add a download link
* @param name
* @param linkTitle
* @param i18nLabel
* @param file
* @param formLayout
* @return
*/
public DownloadLink addDownloadLink(String name, String linkTitle, String i18nLabel, VFSLeaf file, FormItemContainer formLayout) {
DownloadLinkImpl fte = new DownloadLinkImpl(name);
fte.setLinkText(linkTitle);
fte.setDownloadItem(file);
setLabelIfNotNull(i18nLabel, fte);
if(formLayout != null) {
formLayout.add(fte);
}
return fte;
}
/**
* Add a download link
* @param name
* @param linkTitle
* @param i18nLabel
* @param file
* @param table
* @return
*/
public DownloadLink addDownloadLink(String name, String linkTitle, String i18nLabel, VFSLeaf file, FlexiTableElement table) {
DownloadLinkImpl fte = new DownloadLinkImpl(name);
fte.setLinkText(linkTitle);
fte.setDownloadItem(file);
setLabelIfNotNull(i18nLabel, fte);
if(table instanceof FlexiTableElementImpl) {
((FlexiTableElementImpl)table).addFormItem(fte);
}
return fte;
}
public DownloadLink addDownloadLink(String name, String linkTitle, String i18nLabel, File file, FlexiTableElement table) {
DownloadLinkImpl fte = new DownloadLinkImpl(name);
fte.setLinkText(linkTitle);
fte.setDownloadItem(file);
setLabelIfNotNull(i18nLabel, fte);
if(table instanceof FlexiTableElementImpl) {
((FlexiTableElementImpl)table).addFormItem(fte);
}
return fte;
}
public DownloadLink addDownloadLink(String name, String linkTitle, String i18nLabel, MediaResource resource, FlexiTableElement table) {
DownloadLinkImpl fte = new DownloadLinkImpl(name);
fte.setLinkText(linkTitle);
fte.setDownloadMedia(resource);
setLabelIfNotNull(i18nLabel, fte);
if(table instanceof FlexiTableElementImpl) {
((FlexiTableElementImpl)table).addFormItem(fte);
}
return fte;
}
/**
* add a toggle which handles on/off state itself and can be asked for status
* with " isOn() ".
*
* @param name the name of the element (identifier), also used as i18n key
* @param toggleText null if the i18n key should be used and translated, or a text to be on the toggle
* @param formLayout
* @param toggledOnCSS a special css class for the on state, or null for default
* @param toggledOffCSS a special css class for the off state, or null for default
* @return
*/
public FormToggle addToggleButton(String name, String toggleText, FormItemContainer formLayout, String toggledOnCSS, String toggledOffCSS) {
FormToggleImpl fte;
if (StringHelper.containsNonWhitespace(toggleText)) {
fte = new FormToggleImpl(name, name, toggleText, Link.NONTRANSLATED);
} else {
fte = new FormToggleImpl(name, name, name);
}
if (toggledOnCSS != null) fte.setToggledOnCSS(toggledOnCSS);
if (toggledOffCSS != null) fte.setToggledOffCSS(toggledOffCSS);
formLayout.add(fte);
return fte;
}
/**
* Add a file upload element, with a label's i18n key being the same as the <code>name<code>.
* If you do not want a label, use the {@link FormUIFactory#addFileElement(String, Identity, String, FormItemContainer)}
* method with <code>null</code> value for the <code>i18nKey</code>.
* @param wControl
* @param savedBy
* @param name
* @param formLayout
* @return
*/
public FileElement addFileElement(WindowControl wControl, Identity savedBy, String name, FormItemContainer formLayout) {
return addFileElement(wControl, savedBy, name, name, formLayout);
}
/**
* Add a file upload element
* @param wControl
* @param savedBy
* @param name
* @param formLayout
* @param i18nKey
* @return
*/
public FileElement addFileElement(WindowControl wControl, Identity savedBy, String name, String i18nLabel, FormItemContainer formLayout) {
FileElement fileElement = new FileElementImpl(wControl, savedBy, name);
setLabelIfNotNull(i18nLabel, fileElement);
formLayout.add(fileElement);
return fileElement;
}
/**
* Add a form submit button.
*
* @param name the button name (identifyer) and at the same time the i18n key of the button
* @param formItemContiner The container where to add the button
* @return the new form button
*/
public FormSubmit addFormSubmitButton(String name, FormItemContainer formLayout) {
return addFormSubmitButton(name, name, formLayout);
}
/**
* Add a form submit button.
*
* @param name the button name (identifyer)
* @param i18nKey The display key
* @param formItemContiner The container where to add the button
* @return the new form button
*/
public FormSubmit addFormSubmitButton(String name, String i18nKey, FormItemContainer formLayout) {
return addFormSubmitButton(null, name, i18nKey, null, formLayout);
}
/**
* Add a form submit button.
*
* @param id A fix identifier for state-less behavior, must be unique or null
* @param name the button name (identifier)
* @param i18nKey The display key
* @param i18nArgs
* @param formItemContiner The container where to add the button
* @return the new form button
*/
public FormSubmit addFormSubmitButton(String id, String name, String i18nKey, String[] i18nArgs, FormItemContainer formLayout) {
FormSubmit subm = new FormSubmit(id, name, i18nKey, i18nArgs);
formLayout.add(subm);
return subm;
}
public FormReset addFormResetButton(String name, String i18nKey, FormItemContainer formLayout) {
FormReset subm = new FormReset(name, i18nKey);
formLayout.add(subm);
return subm;
}
/**
* Add a form cancel button. You must implement the formCancelled() method
* in your FormBasicController to get events fired by this button
*
* @param name
* @param formLayoutContainer
* @param ureq
* @param wControl
* @return
*/
public FormCancel addFormCancelButton(String name, FormItemContainer formLayoutContainer, UserRequest ureq, WindowControl wControl) {
FormCancel cancel = new FormCancel(name, formLayoutContainer, ureq, wControl);
formLayoutContainer.add(cancel);
return cancel;
}
public MemoryElement addMemoryView(String name, String i18nLabel, MemoryType type, FormItemContainer formLayout) {
MemoryElementImpl fte = new MemoryElementImpl(name, type);
setLabelIfNotNull(i18nLabel, fte);
formLayout.add(fte);
return fte;
}
public ProgressBarItem addProgressBar(String name, String i18nLabel, FormItemContainer formLayout) {
ProgressBarItem fte = new ProgressBarItem(name);
setLabelIfNotNull(i18nLabel, fte);
formLayout.add(fte);
return fte;
}
public ProgressBarItem addProgressBar(String name, String i18nLabel, int width, float actual, float max, String unitLabel, FormItemContainer formLayout) {
ProgressBarItem fte = new ProgressBarItem(name, width, actual, max, unitLabel);
setLabelIfNotNull(i18nLabel, fte);
formLayout.add(fte);
return fte;
}
public SliderElement addSliderElement(String name, String i18nLabel, FormItemContainer formLayout) {
SliderElementImpl slider = new SliderElementImpl(name);
setLabelIfNotNull(i18nLabel, slider);
formLayout.add(slider);
return slider;
}
public DropdownItem addDropdownMenu(String name, String i18nLabel, FormItemContainer formLayout, Translator translator) {
return addDropdownMenu(name, name, i18nLabel, formLayout, translator);
}
public DropdownItem addDropdownMenu(String name, String label, String i18nLabel, FormItemContainer formLayout, Translator translator) {
DropdownItem dropdown = new DropdownItem(name, label, translator);
dropdown.setEmbbeded(true);
dropdown.setButton(true);
setLabelIfNotNull(i18nLabel, dropdown);
if (formLayout != null) {
formLayout.add(dropdown);
}
return dropdown;
}
public RatingFormItem addRatingItem(String name, String i18nLabel, float initialRating, int maxRating, boolean allowUserInput, FormItemContainer formLayout) {
RatingFormItem ratingCmp = new RatingFormItem(name, initialRating, maxRating, allowUserInput);
setLabelIfNotNull(i18nLabel, ratingCmp);
if(i18nLabel != null) {
ratingCmp.showLabel(true);
}
if(formLayout != null) {
formLayout.add(ratingCmp);
}
return ratingCmp;
}
public AddRemoveElement addAddRemoveElement(String name, String i18nLabel, int presentation, boolean showText, FormItemContainer formLayout) {
AddRemoveElementImpl addRemove = new AddRemoveElementImpl(name, presentation);
addRemove.setShowText(showText);
setLabelIfNotNull(i18nLabel, addRemove);
if(formLayout != null) {
formLayout.add(addRemove);
}
return addRemove;
}
public AddRemoveElement addAddRemoveElement(String i18nLabel, int presentation, boolean showText, FormItemContainer formLayout) {
return addAddRemoveElement(i18nLabel, i18nLabel, presentation, showText, formLayout);
}
public AddRemoveElement addAddRemoveElement(String name, String i18nLabel, int presentation, boolean showText, AddRemoveMode displayMode, FormItemContainer formLayout) {
AddRemoveElement addRemove = addAddRemoveElement(name, i18nLabel, presentation, showText, formLayout);
addRemove.setAddRemoveMode(displayMode);
return addRemove;
}
public ExternalLinkItem addExternalLink(String name, String url, String target, FormItemContainer formLayout) {
ExternalLinkItemImpl link = new ExternalLinkItemImpl(name);
link.setTarget(target);
link.setUrl(url);
if(formLayout != null) {
formLayout.add(link);
}
return link;
}
}
|
def convert_seconds(time_in_seconds):
hours = time_in_seconds // 3600
minutes = (time_in_seconds % 3600) // 60
seconds = time_in_seconds % 60
return (hours, minutes, seconds)
time_in_seconds = 647
hours, minutes, seconds = convert_seconds(time_in_seconds)
print("{} Hours {} Minutes {} Seconds".format(hours, minutes, seconds)) |
<gh_stars>10-100
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See License.txt in the project root.
package com.microsoft.alm.plugin.idea.tfvc.extensions;
import com.google.common.collect.Maps;
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.vcs.LocalFilePath;
import com.microsoft.alm.plugin.idea.tfvc.core.tfs.TFVCUtil;
import com.microsoft.tfs.model.connector.TfsWorkspaceMapping;
import org.jetbrains.annotations.NotNull;
import java.nio.file.InvalidPathException;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
public class TfvcRootCache {
private static final Logger ourLogger = Logger.getInstance(TfvcRootCache.class);
private static void assertNoServiceDirectory(Path path) {
if (TFVCUtil.isInServiceDirectory(new LocalFilePath(path.toString(), true))) {
throw new InvalidPathException(path.toString(), "Path contains TFVC service directory name");
}
}
private final Object myLock = new Object();
private final Map<Path, CachedStatus> myData = Maps.newHashMap();
/**
* Tries to determine an item status from the cache.
*
* @param path path to determine its status.
* @return cached status or {@link CachedStatus#UNKNOWN} it no information is available in the cache.
*/
@NotNull
public CachedStatus get(@NotNull Path path) {
synchronized (myLock) {
CachedStatus result = myData.get(path); // direct cache match
if (result != null) {
ourLogger.trace(String.format("%s: %s (cache hit)", path, result));
return result;
}
for (Map.Entry<Path, CachedStatus> entry : myData.entrySet()) {
Path key = entry.getKey();
CachedStatus value = entry.getValue();
boolean isParent = path.startsWith(key);
boolean isChild = key.startsWith(path);
// If any child of an item is known to be NO_ROOT, i.e. not under any mapping, then the result is
// NO_ROOT.
if (isChild && value == CachedStatus.NO_ROOT) {
ourLogger.trace(String.format("%s: %s (derived from %s being %s)", path, value, key, value));
return value;
}
// If any child of an item is known to be IS_MAPPING_ROOT, then the result is NO_ROOT, since mapping
// roots cannot be nested.
if (isChild && value == CachedStatus.IS_MAPPING_ROOT) {
ourLogger.trace(String.format("%s: %s (derived from %s being %s)", path, CachedStatus.NO_ROOT, key, value));
return CachedStatus.NO_ROOT;
}
// If any parent of an item is known to be IS_MAPPING_ROOT, then the result is UNDER_MAPPING_ROOT.
if (isParent && value == CachedStatus.IS_MAPPING_ROOT) {
ourLogger.trace(String.format("%s: %s (derived from %s being %s)", path, CachedStatus.UNDER_MAPPING_ROOT, key, value));
return CachedStatus.UNDER_MAPPING_ROOT;
}
}
return CachedStatus.UNKNOWN;
}
}
/**
* Caches the fact that there're no workspace mappings for the path or its parents.
*/
public void putNoMappingsFor(@NotNull Path path) {
assertNoServiceDirectory(path);
ourLogger.trace(String.format("New without mapping roots: %s", path));
synchronized (myLock) {
// Destroy contradictory information: since we know the path isn't a mapping root and contains no parent
// mapping roots, and information about the parents being roots is now invalid.
ArrayList<Path> keysToRemove = new ArrayList<>();
for (Map.Entry<Path, CachedStatus> entry : myData.entrySet()) {
Path key = entry.getKey();
if (key.equals(path))
continue;
CachedStatus value = entry.getValue();
boolean isParent = path.startsWith(key);
if (isParent && value == CachedStatus.IS_MAPPING_ROOT) {
ourLogger.info(
String.format(
"Evicting information about %s being %s because %s is %s",
key,
value,
path,
CachedStatus.NO_ROOT));
keysToRemove.add(key);
}
}
for (Path key : keysToRemove) {
myData.remove(key);
}
myData.put(path, CachedStatus.NO_ROOT);
}
}
/**
* Caches the fact that the following mappings are available on disk.
*/
public void putMappings(@NotNull List<TfsWorkspaceMapping> mappings) {
synchronized (myLock) {
for (TfsWorkspaceMapping mapping : mappings) {
Path path = Paths.get(mapping.getLocalPath().getPath());
assertNoServiceDirectory(path);
ourLogger.trace(String.format("New mapping root: %s", path));
// Destroy contradictory information: since we know the path is a mapping root, then any information
// that tells us its children are roots themselves or aren't under a root, or its parents are roots is
// now invalid (mapping roots cannot be nested).
ArrayList<Path> keysToRemove = new ArrayList<>();
for (Map.Entry<Path, CachedStatus> entry : myData.entrySet()) {
Path key = entry.getKey();
if (key.equals(path))
continue;
CachedStatus value = entry.getValue();
boolean isParent = path.startsWith(key);
boolean isChild = key.startsWith(path);
boolean isEvicted = false;
if (isChild && value == CachedStatus.IS_MAPPING_ROOT || value == CachedStatus.NO_ROOT) {
keysToRemove.add(key);
isEvicted = true;
}
if (isParent && value == CachedStatus.IS_MAPPING_ROOT) {
keysToRemove.add(key);
isEvicted = true;
}
if (isEvicted) {
ourLogger.info(
String.format(
"Evicting information about %s being %s because %s is %s",
key,
value,
path,
CachedStatus.IS_MAPPING_ROOT));
}
}
for (Path key : keysToRemove) {
myData.remove(key);
}
myData.put(path, CachedStatus.IS_MAPPING_ROOT);
}
}
}
public enum CachedStatus {
/**
* Item status isn't known from the cache.
*/
UNKNOWN,
/**
* Item is known to be a TFVC workspace mapping root.
*/
IS_MAPPING_ROOT,
/**
* Item is known to be under a TFVC workspace mapping root (while not itself being a mapping).
*/
UNDER_MAPPING_ROOT,
/**
* Item is known to not be under a TFVC root.
*/
NO_ROOT
}
}
|
package eu._5gzorro.governancemanager.dto.identityPermissions;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import java.util.List;
import java.util.Objects;
import java.util.Optional;
public class CredentialPreviewDto {
private List<CredentialAttributeDto> attributes;
public CredentialPreviewDto() {
}
public List<CredentialAttributeDto> getAttributes() {
return attributes;
}
public void setAttributes(List<CredentialAttributeDto> attributes) {
this.attributes = attributes;
}
public String getDid() {
try {
Optional<CredentialAttributeDto> attr = attributes.stream().filter(a -> a.getName().equals("credentialSubject")).findFirst();
if(!attr.isPresent())
return null;
String valToDeserialise = attr.get().getValue().replace("'", "\"");
ObjectMapper mapper = new ObjectMapper().configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
CredentialSubjectDto subject = mapper.readValue(valToDeserialise, CredentialSubjectDto.class);
return subject.getId();
}
catch(Exception e)
{
return null;
}
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
CredentialPreviewDto that = (CredentialPreviewDto) o;
return Objects.equals(attributes, that.attributes);
}
@Override
public int hashCode() {
return Objects.hash(attributes);
}
@Override
public String toString() {
return "CredentialPreviewDto{" +
"attributes=" + attributes +
'}';
}
}
|
package keys
import (
"fmt"
"math/rand"
"golang.org/x/tools/container/intsets"
)
type KeyList interface {
Name() string
Desc() string
Keys() []string
Count() int
}
func NewKeyList(name string, desc string, keys []string) KeyList {
return &MemoryKeyList{name, desc, keys}
}
func SamplingKeyList(origList KeyList, sampleSize int) (KeyList, error) {
if sampleSize > origList.Count() {
return nil, fmt.Errorf("sample size %d must be <= original list count %d", sampleSize, origList.Count())
}
if sampleSize == origList.Count() {
return origList, nil
}
var origIndices intsets.Sparse
for origIndices.Len() < sampleSize {
origIndex := rand.Intn(origList.Count())
origIndices.Insert(origIndex)
}
origKeys := origList.Keys()
sampleKeys := make([]string, sampleSize)
for sampleIndex := 0; sampleIndex < sampleSize; sampleIndex++ {
var origIndex int
if origIndices.TakeMin(&origIndex) {
sampleKeys[sampleIndex] = origKeys[origIndex]
} else {
// should never happen
return nil, fmt.Errorf("unable to take key for sample index %d", sampleIndex)
}
}
return NewKeyList(
fmt.Sprintf("%d from %v", sampleSize, origList.Name()),
fmt.Sprintf("%d keys sampled from %v", sampleSize, origList.Desc()),
sampleKeys,
), nil
}
|
def find_anagrams(word):
anagrams = []
word_sorted = sorted(word)
for line in open('dictionary.txt'):
if sorted(line.strip()) == word_sorted and line.strip() != word:
anagrams.append(line.strip())
return anagrams |
#include <iostream>
using namespace std;
// A function to print all prime numbers between two given numbers
void printPrimeInRange(int a, int b)
{
for (int i=a; i<=b; i++)
{
int flag = 0;
for (int j=2; j<=i/2; j++)
{
if (i%j==0)
{
flag=1;
break;
}
}
if (flag == 0)
{
cout << i << " ";
}
}
cout << endl;
}
int main()
{
int a=3, b=10;
cout << "The prime numbers between " << a << " and " << b << " are: ";
printPrimeInRange(a, b);
return 0;
}
// Output: The prime numbers between 3 and 10 are: 3 5 7 |
// Define the GraphQL schema
const typeDefs = `
type Query {
getCurrentInventory: [Product]
getOrderItems: [OrderItem]
}
type Mutation {
addOrderItem(productID: Int!, quantity: Int): OrderItem
}
type Product {
productID: Int
productName: String
price: Float
quantity: Int
}
type OrderItem {
orderID: Int
product: Product
quantity: Int
subtotal: Float
}
`;
// Implement the GraphQL resolvers
const resolvers = {
Query: {
getCurrentInventory: (parent, args, context, info) => {
// query the database to get the list of products
// returns array of product objects
},
getOrderItems: (parent, args, context, info) => {
// query the database to get the list of order items
// returns array of order item objects
},
},
Mutation: {
addOrderItem: (parent, args, context, info) => {
// query the database to create the new order item
// takes in productID and quantity
// returns the new order item object
}
}
};
// Create a new GraphQL server instance
const server = new ApolloServer({
typeDefs,
resolvers
});
// Serve the GraphQL API endoint
server.listen().then(({url}) => console.log(`GraphQL API ready at ${url}`)); |
<reponame>mashedpotato2018/management-vue<gh_stars>0
/* eslint-disable new-cap */
import Mock from 'mockjs'
import faceList from '../face/qilin.json'
let qinlin = []
faceList.forEach(item=>{
qinlin.push(item.middleURL)
})
const count = 100
//基本信息
const List = []
for (let i = 0; i < count; i++) {
List.push(Mock.mock({
UserId: '@increment',
NickName: '@cname',
"HeadImg|1": qinlin,
Money: '@integer(60, 10000)',
KingMoney: '@integer(60, 10000)',
CardNum:'@integer(60, 100)',
LastLoginTime: '@date("yyyy-MM-dd HH:mm:ss")',
RegisterTime: '@date("yyyy-MM-dd HH:mm:ss")',
"state|1-2": true
}))
}
// 输赢统计
let statistics = []
List.forEach(item=>{
statistics.push(Mock.mock({
UserId: item.UserId,
NickName: item.NickName,
HeadImg: item.HeadImg,
Money: item.Money,
CardNum: item.CardNum,
KingMoney: item.KingMoney,
RegisterTime: item.RegisterTime,
state: item.state,
LastLoginTime: item.LastLoginTime,
YesterdayMoney:'@integer(60, 10000)'
}))
})
statistics.forEach(item=>{
item.WeekMoney = item.YesterdayMoney * 7
item.MonthMoney = item.YesterdayMoney * 30
})
// 输赢记录
let record = []
for (let i = 0; i < count; i++) {
List.forEach(item=>{
record.push(Mock.mock({
UserId: item.UserId,
NickName: item.NickName,
TotalWinLose: '@integer(60, 10000)',
startTime: '@date("yyyy-MM-dd HH:mm:ss")'
}))
})
}
let score = []
for (let i = 0; i < count; i++) {
List.forEach(item=>{
score.push(Mock.mock({
UserId: item.UserId,
NickName: item.NickName,
Money: '@integer(60, 10000)',
"Mark|1":[1,-1],
startTime: '@date("yyyy-MM-dd HH:mm:ss")',
proxyId:'@integer(60, 10000)',
proxyNickName:'@cname'
}))
})
}
export default [
{
url: '/player/statistics',
type: 'get',
response: config => {
const { keyword,state = true, page = 1, limit = 10 } = config.query
const boolType = { true:true, false: false }
const mockList = statistics.filter(item => {
if(!boolType[state]){
if(item.state === true) return false
}
if (keyword && (item.UserId !== parseInt(keyword)&&item.NickName.indexOf(keyword) < 0)) return false
return true
})
const pageList = mockList.filter((item, index) => index < limit * page && index >= limit * (page - 1))
return {
code: 20000,
data: {
total: mockList.length,
items: pageList
}
}
}
},
{
url: '/player/record',
type: 'get',
response: config => {
const { keyword, page = 1, limit = 10 } = config.query
const mockList = record.filter(item => {
if(!keyword) return false
if (item.UserId !== parseInt(keyword)&&item.NickName.indexOf(keyword) < 0) return false
return true
})
const basicList = List.filter(item => {
if(!keyword) return false
if (item.UserId !== parseInt(keyword)&&item.NickName.indexOf(keyword) < 0) return false
return true
})
const pageList = mockList.filter((item, index) => index < limit * page && index >= limit * (page - 1))
return {
code: 20000,
data: {
total: mockList.length,
items: pageList,
basic: basicList
}
}
}
},
{
url: '/player/score',
type: 'get',
response: config => {
const { keyword, page = 1, limit = 10 } = config.query
const mockList = score.filter(item => {
if(!keyword) return false
if (item.UserId !== parseInt(keyword)&&item.NickName.indexOf(keyword) < 0) return false
return true
})
const basicList = List.filter(item => {
if(!keyword) return false
if (item.UserId !== parseInt(keyword)&&item.NickName.indexOf(keyword) < 0) return false
return true
})
const pageList = mockList.filter((item, index) => index < limit * page && index >= limit * (page - 1))
return {
code: 20000,
data: {
total: mockList.length,
items: pageList,
basic: basicList
}
}
}
},
{
url: '/player/update',
type: 'post',
response: _ => {
return {
code: 20000,
data: 'success'
}
}
},
{
url: '/player/banned',
type: 'post',
response: _ => {
return {
code: 20000,
data: 'success'
}
}
},
{
url: '/player/freeze',
type: 'post',
response: _ => {
return {
code: 20000,
data: 'success'
}
}
},
{
url: '/player/deblock',
type: 'post',
response: _ => {
return {
code: 20000,
data: 'success'
}
}
}
]
|
<reponame>AtoMaso/FullLoudWhisperer<gh_stars>0
"use strict";
var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
return c > 3 && r && Object.defineProperty(target, key, r), r;
};
var __metadata = (this && this.__metadata) || function (k, v) {
if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
};
var __param = (this && this.__param) || function (paramIndex, decorator) {
return function (target, key) { decorator(target, key, paramIndex); }
};
var core_1 = require('@angular/core');
var common_1 = require('@angular/common');
var validation_service_1 = require('../../services/validation.service');
var ControlMessages = (function () {
// this is the host where this message control is used
function ControlMessages(_formDir) {
this._formDir = _formDir;
}
Object.defineProperty(ControlMessages.prototype, "errorMessage", {
get: function () {
// Find the control in the Host (Parent) form
var c = this._formDir.form.find(this.controlName);
for (var propertyName in c.errors) {
// If control has a error
if (c.errors.hasOwnProperty(propertyName) && c.touched) {
// Return the appropriate error message from the Validation Service
return validation_service_1.ValidationService.getValidatorErrorMessage(propertyName);
}
}
return null;
},
enumerable: true,
configurable: true
});
ControlMessages = __decorate([
core_1.Component({
selector: 'control-messages',
inputs: ['controlName: control'],
template: "<div *ngIf=\"errorMessage !== null\">{{errorMessage}}</div>"
}),
__param(0, core_1.Host()),
__metadata('design:paramtypes', [common_1.NgFormModel])
], ControlMessages);
return ControlMessages;
}());
exports.ControlMessages = ControlMessages;
//# sourceMappingURL=control-messages.component.js.map |
# frozen_string_literal: true
require "dat_direc/differs/registration"
require "dat_direc/differs/base"
require "dat_direc/differs/table_presence/table_diff"
module DatDirec
module Differs
module TablePresence
# Checks that databases all have the same list of tables
class Differ < Base
def self.priority
# TablePresence has a low priority because it needs to run earliest
# - no point comparing a column across the databases if it's in a
# table that's going to be removed.
0
end
def diff
@diff = table_names.map do |table|
diff_for(table)
end
remove_identical_states
@diff
end
private
def remove_identical_states
@diff.delete_if do |result|
result.states.all?(&:found?)
end
end
def diff_for(table)
TableDiff.new(table,
databases.map do |db|
state_for(db, table)
end)
end
def state_for(db, table_name)
if db.tables.key? table_name
Found.new(db, table_name)
else
NotFound.new(db, table_name)
end
end
end
# Represents the fact that a table was found on a database
Found = Struct.new(:database, :table) do
def found?
true
end
end
# Represents the fact that a table was not found on a database
NotFound = Struct.new(:database, :table) do
def found?
false
end
end
end
end
end
DatDirec::Differs.register DatDirec::Differs::TablePresence::Differ
|
import requests
import json
def retry_reservation(organization_code: str, vaccine_type: str, jar: dict) -> dict:
reservation_url = 'https://vaccine.kakao.com/api/v2/reservation/retry'
headers_vaccine = {'Content-Type': 'application/json'}
data = {"from": "List", "vaccineCode": vaccine_type,
"orgCode": organization_code, "distance": None}
response = requests.post(reservation_url, data=json.dumps(data), headers=headers_vaccine, cookies=jar, verify=False)
response_json = json.loads(response.text)
return response_json |
#!/bin/bash
#SBATCH -J Act_minsin_1
#SBATCH --mail-user=eger@ukp.informatik.tu-darmstadt.de
#SBATCH --mail-type=FAIL
#SBATCH -e /work/scratch/se55gyhe/log/output.err.%j
#SBATCH -o /work/scratch/se55gyhe/log/output.out.%j
#SBATCH -n 1 # Number of cores
#SBATCH --mem-per-cpu=2000
#SBATCH -t 23:59:00 # Hours, minutes and seconds, or '#SBATCH -t 10' -only mins
#module load intel python/3.5
python3 /home/se55gyhe/Act_func/progs/meta.py minsin 1 Adadelta 3 0.5575851307701827 451 0.8260077097118774 he_normal PE-infersent
|
const MONGO_URL = process.env.MONGO_URL || undefined
const REDIS_URL = process.env.REDIS_URL || undefined
module.exports = {
MONGO_URL,//: 'mongodb://the_username:the_password@localhost:3456/the_database',
REDIS_URL//: '//localhost:6378'
} |
<gh_stars>0
import React from 'react';
import { connect } from 'react-redux';
import { addTodo } from 'store/actions';
class TodosControlsContainer extends React.Component {
addTodo = (todo) => {
const payload = { todo: { text: 'Thing' } } || { todo };
this.props.addTodo(payload);
}
render() {
return (
<section className="fit-center">
<button onClick={ this.addTodo }>
Add Todo
</button>
</section>
);
}
};
const mapStateToProps = (state/* , ownProps */) => ({
});
const mapDispatchToProps = (dispatch/* , ownProps */) => ({
addTodo: todo => dispatch(addTodo(todo)),
});
const ConnectedTodosControls = connect(mapStateToProps, mapDispatchToProps)(TodosControlsContainer);
export default ConnectedTodosControls;
|
<gh_stars>1-10
const {app, BrowserWindow} = require('electron');
const path = require('path');
let mainWindow;
app.on('window-all-closed', function() {
app.quit();
});
app.commandLine.appendSwitch('ppapi-flash-path', path.join(__dirname, 'libpepflashplayer.so'));
app.commandLine.appendSwitch('ppapi-flash-version', '192.168.3.11');
app.on('ready', function() {
mainWindow = new BrowserWindow({width: 1024, height: 768 });
mainWindow.setMenu(null);
mainWindow.loadURL('file://' + __dirname + '/browser.html');
});
|
#!/bin/bash
echo ""
echo "Applying migration ClaimantType"
echo "Adding routes to conf/app.routes"
echo "" >> ../conf/app.routes
echo "GET /claimantType controllers.ClaimantTypeController.onPageLoad(mode: Mode = NormalMode)" >> ../conf/app.routes
echo "POST /claimantType controllers.ClaimantTypeController.onSubmit(mode: Mode = NormalMode)" >> ../conf/app.routes
echo "GET /changeClaimantType controllers.ClaimantTypeController.onPageLoad(mode: Mode = CheckMode)" >> ../conf/app.routes
echo "POST /changeClaimantType controllers.ClaimantTypeController.onSubmit(mode: Mode = CheckMode)" >> ../conf/app.routes
echo "Adding messages to conf.messages"
echo "" >> ../conf/messages.en
echo "claimantType.title = Are you the importer or their representative?" >> ../conf/messages.en
echo "claimantType.heading = Are you the importer or their representative?" >> ../conf/messages.en
echo "claimantType.importer = I am the importer" >> ../conf/messages.en
echo "claimantType.representative = I am a representative of the importer" >> ../conf/messages.en
echo "claimantType.checkYourAnswersLabel = Are you the importer or their representative?" >> ../conf/messages.en
echo "claimantType.error.required = Select claimantType" >> ../conf/messages.en
echo "Adding to UserAnswersEntryGenerators"
awk '/trait UserAnswersEntryGenerators/ {\
print;\
print "";\
print " implicit lazy val arbitraryClaimantTypeUserAnswersEntry: Arbitrary[(ClaimantTypePage.type, JsValue)] =";\
print " Arbitrary {";\
print " for {";\
print " page <- arbitrary[ClaimantTypePage.type]";\
print " value <- arbitrary[ClaimantType].map(Json.toJson(_))";\
print " } yield (page, value)";\
print " }";\
next }1' ../test/generators/UserAnswersEntryGenerators.scala > tmp && mv tmp ../test/generators/UserAnswersEntryGenerators.scala
echo "Adding to PageGenerators"
awk '/trait PageGenerators/ {\
print;\
print "";\
print " implicit lazy val arbitraryClaimantTypePage: Arbitrary[ClaimantTypePage.type] =";\
print " Arbitrary(ClaimantTypePage)";\
next }1' ../test/generators/PageGenerators.scala > tmp && mv tmp ../test/generators/PageGenerators.scala
echo "Adding to ModelGenerators"
awk '/trait ModelGenerators/ {\
print;\
print "";\
print " implicit lazy val arbitraryClaimantType: Arbitrary[ClaimantType] =";\
print " Arbitrary {";\
print " Gen.oneOf(ClaimantType.values.toSeq)";\
print " }";\
next }1' ../test/generators/ModelGenerators.scala > tmp && mv tmp ../test/generators/ModelGenerators.scala
echo "Adding to UserAnswersGenerator"
awk '/val generators/ {\
print;\
print " arbitrary[(ClaimantTypePage.type, JsValue)] ::";\
next }1' ../test/generators/UserAnswersGenerator.scala > tmp && mv tmp ../test/generators/UserAnswersGenerator.scala
echo "Adding helper method to CheckYourAnswersHelper"
awk '/class/ {\
print;\
print "";\
print " def claimantType: Option[AnswerRow] = userAnswers.get(ClaimantTypePage) map {";\
print " x =>";\
print " AnswerRow(";\
print " HtmlFormat.escape(messages(\"claimantType.checkYourAnswersLabel\")),";\
print " HtmlFormat.escape(messages(s\"claimantType.$x\")),";\
print " routes.ClaimantTypeController.onPageLoad(CheckMode).url";\
print " )"
print " }";\
next }1' ../app/utils/CheckYourAnswersHelper.scala > tmp && mv tmp ../app/utils/CheckYourAnswersHelper.scala
echo "Migration ClaimantType completed"
|
def sort(arr):
for i in range(len(arr)):
for j in range(i+1, len(arr)):
if arr[i] > arr[j]:
arr[i], arr[j] = arr[j], arr[i]
return arr
sort([2, 3, 1, 7, 5, 4])
# Output: [1, 2, 3, 4, 5, 7] |
<gh_stars>0
package com.vodafone.garage.exception;
public class GarageFullException extends RuntimeException{
public GarageFullException(String message) {
super(message);
}
}
|
import os
import shutil
def organize_files(source_dir):
extensions = {} # Dictionary to store file extensions and their corresponding paths
for root, _, files in os.walk(source_dir):
for file in files:
file_path = os.path.join(root, file)
file_ext = os.path.splitext(file)[1].lower() # Get the file extension in lowercase
if file_ext not in extensions:
extensions[file_ext] = os.path.join(source_dir, file_ext[1:] + "_files") # Create subdirectory path
os.makedirs(extensions[file_ext], exist_ok=True) # Create subdirectory if it doesn't exist
shutil.move(file_path, os.path.join(extensions[file_ext], file)) # Move the file to its corresponding subdirectory |
package org.junithelper.core.extractor;
import static org.hamcrest.CoreMatchers.*;
import static org.junit.Assert.*;
import java.util.List;
import org.junit.Test;
import org.junithelper.core.config.Configuration;
import org.junithelper.core.exception.JUnitHelperCoreException;
import org.junithelper.core.extractor.ImportedListExtractor;
public class ImportedListExtractorTest {
@Test
public void type() throws Exception {
assertNotNull(ImportedListExtractor.class);
}
@Test
public void instantiation() throws Exception {
Configuration config = null;
ImportedListExtractor target = new ImportedListExtractor(config);
assertNotNull(target);
}
@Test
public void extract_A$String() throws Exception {
Configuration config = new Configuration();
ImportedListExtractor target = new ImportedListExtractor(config);
// given
String sourceCodeString = "package foo.var; import java.util.List; import java.io.InputStream; public class Sample { }";
// when
List<String> actual = target.extract(sourceCodeString);
// then
assertEquals(2, actual.size());
}
@Test
public void extract_A$String_StringIsNull() throws Exception {
Configuration config = new Configuration();
ImportedListExtractor target = new ImportedListExtractor(config);
String sourceCodeString = null;
try {
target.extract(sourceCodeString);
fail();
} catch (JUnitHelperCoreException e) {
}
}
@Test
public void extract_A$String_StringIsEmpty() throws Exception {
Configuration config = new Configuration();
ImportedListExtractor target = new ImportedListExtractor(config);
String sourceCodeString = "";
List<String> actual = target.extract(sourceCodeString);
assertThat(actual, notNullValue());
}
}
|
#!/bin/sh
#PBS -A OPEN-12-63
#PBS -q qprod
#PBS -N FOAM_PTF
#PBS -l select=2:ncpus=24:mpiprocs=24:accelerator=false
#PBS -l x86_adapt=true
#PBS -l walltime=03:00:00
#PBS -m be
APP="simpleFoam -parallel"
THRDS=1
MPI_PROCS=24
PHASE_REG_NAME="iteration"
if [ "$PBS_ENVIRONMENT" == "PBS_BATCH" ]; then
export FM_DIR=$PBS_O_WORKDIR
else
export FM_DIR=$(pwd)
fi
export FM_DIR=$FM_DIR/..
cd $FM_DIR
source readex_env/set_env_ptf_rapl.source
source scripts_$READEX_MACHINE/environment.sh
cd $FM_DIR/OpenFOAM-v1612+/
source $FM_DIR/OpenFOAM-v1612+/etc/bashrc
cd ../../motorBike24/
export SCOREP_TOTAL_MEMORY=3G
export SCOREP_SUBSTRATE_PLUGINS=rrl
export SCOREP_RRL_PLUGINS=cpu_freq_plugin,uncore_freq_plugin
export SCOREP_RRL_VERBOSE="WARN"
export SCOREP_METRIC_PLUGINS=x86_energy_sync_plugin
export SCOREP_METRIC_PLUGINS_SEP=";"
export SCOREP_METRIC_X86_ENERGY_SYNC_PLUGIN=*/E
export SCOREP_METRIC_X86_ENERGY_SYNC_PLUGIN_CONNECTION="INBAND"
export SCOREP_METRIC_X86_ENERGY_SYNC_PLUGIN_VERBOSE="WARN"
export SCOREP_METRIC_X86_ENERGY_SYNC_PLUGIN_STATS_TIMEOUT_MS=1000
export SCOREP_ENABLE_TRACING=false
export SCOREP_ENABLE_PROFILING=true
export SCOREP_MPI_ENABLE_GROUPS=ENV
psc_frontend --apprun="$APP" --mpinumprocs=$MPI_PROCS --ompnumthreads=$THRDS --phase=$PHASE_REG_NAME --tune=readex_intraphase --config-file=readex_config_extended.xml --force-localhost --info=2 --selective-info=AutotuneAll,AutotunePlugins
|
package com.arsylk.mammonsmite.views;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import java.util.List;
public class PickWhichDialog<T> extends AlertDialog.Builder {
public static class Option<T> {
public interface OnOptionPicked<T> {
void onOptionPicked(Option<T> option);
}
private String label;
private T object;
public Option(String label, T object) {
this.label = label;
this.object = object;
}
public String getLabel() {
return label;
}
public T getObject() {
return object;
}
@Override
public String toString() {
return label;
}
}
private Context context;
private List<Option<T>> options;
private Option.OnOptionPicked<T> onOptionPicked = null;
private AlertDialog dialog = null;
public PickWhichDialog(Context context, List<Option<T>> options) {
super(context);
this.context = context;
this.options = options;
initViews();
}
public PickWhichDialog<T> setOnOptionPicked(Option.OnOptionPicked<T> onOptionPicked) {
this.onOptionPicked = onOptionPicked;
return this;
}
private void initViews() {
setTitle("Pick option");
ListView listView = new ListView(context);
listView.setAdapter(new ArrayAdapter<>(context, android.R.layout.simple_list_item_1, options));
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
if(dialog != null) dialog.dismiss();
if(onOptionPicked != null) onOptionPicked.onOptionPicked(options.get(position));
}
});
setView(listView);
setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
dialog = create();
}
@Override
public AlertDialog show() {
dialog.show();
return dialog;
}
}
|
<filename>server/state.go<gh_stars>1-10
package main
import (
"time"
)
type bet struct {
quantity int
face int
}
type state struct {
lastTimestamp time.Time
started bool
finished bool
lastBet bet
lastPlayer Entity
players []Entity
turn int
round int
numDices int
calledLiar bool // to protect multiple people call liar at the same turn
}
func (s *state) encode() *respState {
players := make([]string, 0, len(s.players))
for _, p := range s.players {
players = append(players, p.Name())
}
return &respState{
Players: players,
Turn: s.turn,
Round: s.round,
NumDices: s.numDices,
LastQuantity: s.lastBet.quantity,
LastFace: s.lastBet.face,
}
}
func (s *state) incrementTurn() {
for {
s.turn = (s.turn + 1) % len(s.players)
if len(s.players[s.turn].Dice()) != 0 {
break
}
}
}
|
<reponame>y-yao/pyscf_arrow
#!/usr/bin/env python
# Copyright 2014-2018 The PySCF Developers. 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.
def gen_grad_scanner(method):
if hasattr(method, 'nuc_grad_method'):
return method.nuc_grad_method().as_scanner()
else:
raise NotImplementedError('Nuclear gradients of %s not available' % method)
|
<reponame>xwjdsh/wxpay<filename>wxconfig.go
package wxpay
import (
"errors"
"net/url"
"github.com/xwjdsh/httphelper"
)
type WxConfig struct {
AppId string
AppKey string
MchId string
NotifyUrl string
TradeType string
//config check
checked bool
}
func (this *WxConfig) NewWxPay() (*WxPay, error) {
if this.AppId == "" || this.AppKey == "" || this.MchId == "" || this.NotifyUrl == "" || this.TradeType == "" {
return nil, errors.New("any config can't equals empty string")
}
this.checked = true
helper := &httpHelper.HttpHelper{CommonHeader: url.Values{}, Log: true}
return &WxPay{
Config: this,
http: helper,
}, nil
}
|
<gh_stars>1-10
package mezz.jei.api.gui;
import javax.annotation.Nullable;
import java.awt.Rectangle;
import java.util.List;
import net.minecraft.client.gui.inventory.GuiContainer;
import mezz.jei.api.IModRegistry;
import mezz.jei.api.ingredients.IModIngredientRegistration;
/**
* Allows plugins to change how JEI is displayed next to their mod's guis.
* Register your implementation with {@link IModRegistry#addAdvancedGuiHandlers(IAdvancedGuiHandler[])}.
*/
public interface IAdvancedGuiHandler<T extends GuiContainer> {
/**
* @return the class that this IAdvancedGuiHandler handles.
*/
Class<T> getGuiContainerClass();
/**
* Give JEI information about extra space that the GuiContainer takes up.
* Used for moving JEI out of the way of extra things like gui tabs.
*
* @return the space that the gui takes up besides the normal rectangle defined by GuiContainer.
*/
@Nullable
default List<Rectangle> getGuiExtraAreas(T guiContainer) {
return null;
}
/**
* Return anything under the mouse that JEI could not normally detect, used for JEI recipe lookups.
* <p>
* This is useful for guis that don't have normal slots (which is how JEI normally detects items under the mouse).
* <p>
* This can also be used to let JEI look up liquids in tanks directly, by returning a FluidStack.
* Works with any ingredient type that has been registered with {@link IModIngredientRegistration}.
*
* @param mouseX the current X position of the mouse in screen coordinates.
* @param mouseY the current Y position of the mouse in screen coordinates.
* @since JEI 3.13.2
*/
@Nullable
default Object getIngredientUnderMouse(T guiContainer, int mouseX, int mouseY) {
return null;
}
}
|
SELECT Name, Salary
FROM Employees
ORDER BY Salary DESC; |
echo '--- envdir requires arguments'
envdir whatever; echo $?
echo '--- envdir complains if it cannot read directory'
ln -s env1 env1
envdir env1 echo yes; echo $?
echo '--- envdir complains if it cannot read file'
rm env1
mkdir env1
ln -s Message env1/Message
envdir env1 echo yes; echo $?
echo '--- envdir adds variables'
rm env1/Message
echo This is a test. This is only a test. > env1/Message
envdir env1 sh -c 'echo $Message'; echo $?
echo '--- envdir removes variables'
mkdir env2
touch env2/Message
envdir env1 envdir env2 sh -c 'echo $Message'; echo $?
echo '--- envdir adds prefix'
envdir -p prefix_ env1 sh -c 'echo $Message; echo $prefix_Message'; echo $?
|
import sys
sys.path.append("/opt/jump-cellpainting-lambda")
import run_DCP
import create_batch_jobs
# AWS Configuration Specific to this Function
config_dict = {
"DOCKERHUB_TAG": "cellprofiler/distributed-fiji:latest",
"SCRIPT_DOWNLOAD_URL": "https://raw.githubusercontent.com/broadinstitute/AuSPICEs/main/6_CheckSegment/make_fiji_montages.py",
"TASKS_PER_MACHINE": "1",
"MACHINE_TYPE": ["m4.2xlarge"],
"MACHINE_PRICE": "0.25",
"EBS_VOL_SIZE": "40",
"DOWNLOAD_FILES": "False",
"MEMORY": "31000",
"SQS_MESSAGE_VISIBILITY": "600",
"MIN_FILE_SIZE_BYTES": "1",
"NECESSARY_STRING": "",
}
def lambda_handler(event, context):
if event["run_segment"]:
prefix = f"projects/{event['project_name']}/workspace/"
bucket = event["bucket"]
batch = event["batch"]
config_dict["APP_NAME"] = event["project_name"] + "_Montage"
project_name = event["project_name"]
# Include/Exclude Plates
exclude_plates = event["exclude_plates"]
include_plates = event["include_plates"]
platelist = []
for x in event["Output_0"]["Payload"]:
shortplate = x["plate"].split("__")[0]
platelist.append(shortplate)
if exclude_plates:
platelist = [i for i in platelist if i not in exclude_plates]
if include_plates:
platelist = include_plates
config_dict["EXPECTED_NUMBER_FILES"] = 0
run_DCP.run_setup(bucket, prefix, batch, config_dict, type="FIJI")
# make the jobs
create_batch_jobs.create_batch_jobs_6(
bucket, project_name, batch, platelist,
)
# Start a cluster
run_DCP.run_cluster(bucket, prefix, batch, len(platelist), config_dict)
run_DCP.setup_monitor(bucket, prefix, config_dict)
|
#!/usr/bin/env bash
if [ ! -d "../data" ]; then
mkdir ../data
fi
if [ ! -d "../data/raw_data" ]; then
mkdir ../data/raw_data
fi
if [ ! -f ../data/raw_data/test.csv ]; then
echo "------------------------------"
echo "retrieving raw data"
./get_data.sh
echo "finished retrieving raw data"
fi
if [ ! -d "../data/intermediate" ]; then
echo "------------------------------"
echo "combining raw_data .csv files"
mkdir ../data/intermediate
python3 combine_data.py
echo "finished combining raw_data .csv files"
fi
if [ ! -d "../data/all_data" ]; then
echo "------------------------------"
echo "converting data to .json format"
mkdir ../data/all_data
python3 data_to_json.py
echo "finished converting data to .json format"
fi
|
/**
* Class for holding and downloading glTF file data
*/
export declare class GLTFData {
/**
* Object which contains the file name as the key and its data as the value
*/
glTFFiles: {
[fileName: string]: string | Blob;
};
/**
* Initializes the glTF file object
*/
constructor();
/**
* Downloads the glTF data as files based on their names and data
*/
downloadFiles(): void;
}
|
package io.opensphere.core.util;
import java.io.IOException;
import java.nio.ByteBuffer;
/**
* An object that knows how to read its content stream into a byte buffer.
*/
public interface Reader
{
/**
* Read the stream into a new byte buffer.
*
* @return The byte buffer.
* @throws IOException If there is an exception reading the stream.
*/
ByteBuffer readStreamIntoBuffer() throws IOException;
/**
* Read the stream into an existing byte buffer if it has enough capacity.
* If the existing buffer does not have enough capacity, a new buffer will
* be created and the contents of the existing buffer will be copied to the
* new buffer, along with the contents of the stream.
*
* @param buffer The byte buffer to use if possible.
* @return The byte buffer containing the data from the stream.
* @throws IOException If there is an exception reading the stream.
*/
ByteBuffer readStreamIntoBuffer(ByteBuffer buffer) throws IOException;
}
|
#!/usr/bin/env bash
STACKNAME=python-hands-on-pipeline
TEMPLATE=ci.yml
TEMPLATE_PARAMS=ci-parameter.json
TAGKEY=Name
TAGVALUE=event
echo "**********************************"
echo STACKNAME:${STACKNAME}
echo TEMPLATE:${TEMPLATE}
echo TEMPLATE_PARAMS:${TEMPLATE_PARAMS}
echo TAGKEY:${TAGKEY}
echo TAGVALUE:${TAGVALUE}
echo "**********************************"
aws cloudformation update-stack --stack-name ${STACKNAME} \
--template-body file://${TEMPLATE} \
--parameters file://${TEMPLATE_PARAMS} \
--tags Key=${TAGKEY},Value=${TAGVALUE} \
--capabilities CAPABILITY_NAMED_IAM
|
package stepconf
import "github.com/bitrise-io/go-utils/v2/env"
// InputParser ...
type InputParser interface {
Parse(input interface{}) error
}
type inputParser struct {
envRepository env.Repository
}
// NewInputParser ...
func NewInputParser(envRepository env.Repository) InputParser {
return inputParser{
envRepository: envRepository,
}
}
// Parse ...
func (p inputParser) Parse(input interface{}) error {
return parse(input, p.envRepository)
}
|
import request from '@/utils/request'
export function login(data) {
return request({
url: '/sys/user/login', // '/vue-admin-template/user/login',
method: 'post',
data
})
}
export function getInfo(token) {
console.log(token)
return request({
url: '/sys/user/getInfo',
method: 'get',
params: { token }
})
}
export function logout() {
return request({
url: '/vue-admin-template/user/logout',
method: 'post'
})
}
export function getList(data) {
console.log('can-', data)
return request({
url: '/sys/user/findAll',
method: 'post',
data
})
}
|
package net.andreaskluth.elefantenstark.consumer;
import static net.andreaskluth.elefantenstark.PostgresSupport.withPostgresConnectionsAndSchema;
import static net.andreaskluth.elefantenstark.TestData.scheduleThreeWorkItems;
import static net.andreaskluth.elefantenstark.consumer.ConsumerTestSupport.assertNextWorkItemIsCaptured;
import static net.andreaskluth.elefantenstark.consumer.ConsumerTestSupport.capturingConsume;
import java.sql.Connection;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.atomic.AtomicReference;
import net.andreaskluth.elefantenstark.work.WorkItem;
import net.andreaskluth.elefantenstark.work.WorkItemContext;
import org.junit.jupiter.api.Test;
class MultiThreadedConsumerTest {
@Test
void fetchesAndDistributesWorkOrderedByKeyAndVersionTransactionScoped() {
validateConsumer(Consumer.transactionScoped());
}
@Test
void fetchesAndDistributesWorkOrderedByKeyAndVersionSessionScoped() {
validateConsumer(Consumer.sessionScoped());
}
private void validateConsumer(Consumer consumer) {
AtomicReference<WorkItemContext> capturedWorkA = new AtomicReference<>();
AtomicReference<WorkItemContext> capturedWorkB = new AtomicReference<>();
AtomicReference<WorkItemContext> capturedWorkC = new AtomicReference<>();
CountDownLatch blockLatch = new CountDownLatch(1);
CountDownLatch syncLatch = new CountDownLatch(1);
withPostgresConnectionsAndSchema(
connections -> {
Connection connection = connections.get();
Connection anotherConnection = connections.get();
scheduleThreeWorkItems(connection);
Thread worker =
new Thread(
() ->
consumer.next(
connection,
wic -> {
capturedWorkA.set(wic);
syncLatch.countDown();
awaitLatch(blockLatch);
return null;
}));
worker.start();
awaitLatch(syncLatch);
// Obtain the next free work item while the other thread holds the first.
capturingConsume(anotherConnection, consumer, capturedWorkB);
blockLatch.countDown();
joinThread(worker);
capturingConsume(anotherConnection, consumer, capturedWorkC);
});
assertNextWorkItemIsCaptured(WorkItem.hashedOnKey("a", "b", 23), capturedWorkA.get());
assertNextWorkItemIsCaptured(WorkItem.hashedOnKey("c", "d", 12), capturedWorkB.get());
assertNextWorkItemIsCaptured(WorkItem.hashedOnKey("a", "b", 24), capturedWorkC.get());
}
private void joinThread(final Thread worker) {
try {
worker.join();
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
throw new RuntimeException(e);
}
}
private void awaitLatch(final CountDownLatch latch) {
try {
latch.await();
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
throw new RuntimeException(e);
}
}
}
|
// axiosconfig.js
import axios from 'axios';
// configure base url
const api = axios.create({
baseURL:
process.env[
process.env.NODE_ENV === 'production'
? 'REACT_APP_API_BASE_URL_PROD'
: 'REACT_APP_API_BASE_URL_DEV'
],
timeout: 30000
});
// Export API object
export default api;
|
from django.db import models
from django.contrib.auth.models import User
from lugar.models import Pais, Departamento, Municipio, Comunidad, Microcuenca
# Create your models here.
class SubirArchivos(models.Model):
nombre_documento = models.CharField(max_length=250)
tema = models.CharField(max_length=250)
descripcion = models.TextField(null=True, blank=True)
archivo = models.FileField(upload_to='documentos/')
pais = models.ForeignKey(Pais)
user = models.ForeignKey(User)
def __unicode__(self):
return self.nombre_documento
|
#!/usr/bin/env nix-shell
#!nix-shell -i bash -p coreutils curl jq common-updater-scripts dotnet-sdk_3 git gnupg nixFlakes
set -euo pipefail
# This script uses the following env vars:
# getVersionFromTags
# refetch
pkgName=$1
depsFile=$2
customFlags=$3
: ${getVersionFromTags:=}
: ${refetch:=}
scriptDir=$(cd "${BASH_SOURCE[0]%/*}" && pwd)
nixpkgs=$(realpath "$scriptDir"/../../../../..)
evalNixpkgs() {
nix eval --impure --raw --expr "(with import \"$nixpkgs\" {}; $1)"
}
getRepo() {
url=$(evalNixpkgs $pkgName.src.meta.homepage)
echo $(basename $(dirname $url))/$(basename $url)
}
getLatestVersionTag() {
"$nixpkgs"/pkgs/common-updater/scripts/list-git-tags --url=https://github.com/$(getRepo) 2>/dev/null \
| sort -V | tail -1 | sed 's|^v||'
}
oldVersion=$(evalNixpkgs "$pkgName.version")
if [[ $getVersionFromTags ]]; then
newVersion=$(getLatestVersionTag)
else
newVersion=$(curl -s "https://api.github.com/repos/$(getRepo)/releases" | jq -r '.[0].name')
fi
if [[ $newVersion == $oldVersion && ! $refetch ]]; then
echo "nixpkgs already has the latest version $newVersion"
echo "Run this script with env var refetch=1 to re-verify the content hash via GPG"
echo "and to recreate $(basename "$depsFile"). This is useful for reviewing a version update."
exit 0
fi
# Fetch release and GPG-verify the content hash
tmpdir=$(mktemp -d /tmp/$pkgName-verify-gpg.XXX)
repo=$tmpdir/repo
trap "rm -rf $tmpdir" EXIT
git clone --depth 1 --branch v${newVersion} -c advice.detachedHead=false https://github.com/$(getRepo) $repo
export GNUPGHOME=$tmpdir
# Fetch Nicolas Dorier's key (64-bit key ID: 6618763EF09186FE)
gpg --keyserver hkps://keyserver.ubuntu.com --recv-keys AB4CFA9895ACA0DBE27F6B346618763EF09186FE 2> /dev/null
echo
echo "Verifying commit"
git -C $repo verify-commit HEAD
rm -rf $repo/.git
newHash=$(nix hash-path $repo)
rm -rf $tmpdir
echo
# Update pkg version and hash
echo "Updating $pkgName: $oldVersion -> $newVersion"
if [[ $newVersion == $oldVersion ]]; then
# Temporarily set a source version that doesn't equal $newVersion so that $newHash
# is always updated in the next call to update-source-version.
(cd "$nixpkgs" && update-source-version "$pkgName" "0" "0000000000000000000000000000000000000000000000000000")
fi
(cd "$nixpkgs" && update-source-version "$pkgName" "$newVersion" "$newHash")
echo
# Create deps file
storeSrc="$(nix-build "$nixpkgs" -A $pkgName.src --no-out-link)"
. "$scriptDir"/create-deps.sh "$storeSrc" "$depsFile" "$customFlags"
|
package com.java.study.zuo.vedio.basic.chapter7;
/**
* <Description>
*
* @author hushiye
* @since 2020-08-26 23:44
*/
public class Cow {
public static long getCow(int n) {
if (n == 1 || n == 2 || n == 3) {
return n;
}
return getCow(n - 1) + getCow(n - 3);
}
public static long getCow1(int n) {
if (n == 0) {
return 0;
}
if (n == 1 || n == 2 || n == 3) {
return n;
}
long[] arr = new long[n];
arr[0] = 1;
arr[1] = 2;
arr[2] = 3;
for (int i = 3; i < n; i++) {
arr[i] = arr[i - 1] + arr[i - 3];
}
return arr[n - 1];
}
public static void main(String[] args) {
System.out.println(getCow(55));
System.out.println(getCow1(55));
}
}
|
<reponame>lananh265/social-network
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.androidMail = void 0;
var androidMail = {
"viewBox": "0 0 512 512",
"children": [{
"name": "g",
"attribs": {
"id": "Icon_19_"
},
"children": [{
"name": "g",
"attribs": {},
"children": [{
"name": "g",
"attribs": {},
"children": [{
"name": "path",
"attribs": {
"d": "M437.332,80H74.668C51.199,80,32,99.198,32,122.667v266.666C32,412.802,51.199,432,74.668,432h362.664\r\n\t\t\tC460.801,432,480,412.802,480,389.333V122.667C480,99.198,460.801,80,437.332,80z M432,170.667L256,288L80,170.667V128\r\n\t\t\tl176,117.333L432,128V170.667z"
},
"children": [{
"name": "path",
"attribs": {
"d": "M437.332,80H74.668C51.199,80,32,99.198,32,122.667v266.666C32,412.802,51.199,432,74.668,432h362.664\r\n\t\t\tC460.801,432,480,412.802,480,389.333V122.667C480,99.198,460.801,80,437.332,80z M432,170.667L256,288L80,170.667V128\r\n\t\t\tl176,117.333L432,128V170.667z"
},
"children": []
}]
}]
}]
}]
}]
};
exports.androidMail = androidMail; |
<filename>blingfirecompile.library/inc/FAMultiMapPack_fixed.h
/**
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License.
*/
#ifndef _FA_MULTIMAPPACK_FIXED_H_
#define _FA_MULTIMAPPACK_FIXED_H_
#include "FAConfig.h"
#include "FAArray_cont_t.h"
namespace BlingFire
{
class FAMultiMapA;
class FAAllocatorA;
///
/// Builds memory dump for the given FAMultiMapA
///
class FAMultiMapPack_fixed {
public:
FAMultiMapPack_fixed (FAAllocatorA * pAlloc);
public:
// sets up input map
void SetMultiMap (const FAMultiMapA * pMMap);
// sets up min sizeof value, otherwise minimum possible is used
void SetSizeOfValue (const int SizeOfValue);
// builds dump
void Process ();
// returns bulit dump
const int GetDump (const unsigned char ** ppDump) const;
private:
const int Prepare ();
private:
// input multi-map
const FAMultiMapA * m_pMMap;
// value size
int m_ValueSize;
// min Key
int m_MinKey;
// max Key
int m_MaxKey;
// maximum amount of values associated with a Key
int m_MaxCount;
// output dump
FAArray_cont_t < unsigned char > m_dump;
unsigned char * m_pDump;
};
}
#endif
|
# Write your solution here
print('print("Hello there!")') |
#!/bin/sh
set -e
# Patch headers paths to comply paths inside frameworks
sed -i '.bak' 's|#include "td/telegram/|#include "|g' ../td/td/telegram/td_json_client.h
sed -i '.bak' 's|#include "td/telegram/|#include "|g' ../td/td/telegram/td_log.h |
import random
import string
def generate_password():
chars = string.ascii_letters + string.digits
return ''.join(random.choice(chars) for _ in range(8)) + random.choice(string.ascii_lowercase) + random.choice(string.ascii_uppercase) + random.choice(string.digits) |
import Head from 'next/head'
const IndexPage = () => (
<>
<Head>
<title>Hello Next.js</title>
<meta name='description' content='A new next.js app' />
</Head>
<h1>Hello Next.js</h1>
</>
)
export default IndexPage
|
# Copyright 2017 BBVA
#
# 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 pytest
from os.path import join
from apitest import ApitestNotFoundError
from apitest.actions.unittest.helpers import build_templates, CustomTemplate
@pytest.fixture
def test_path(tmpdir):
for x in ('xx1.jinja2.py', 'xx1.jinja2.py', 'xx1.txt'):
open(join(str(tmpdir), x), "w").write("xxx")
return str(tmpdir)
@pytest.fixture
def built_jinja_templates(tmpdir):
with open(str(tmpdir) + "/case_01.jinja2.py", "w") as c01:
c01.write("""import re
def test_sqli_case_001(make_requests):
current, good, bad = make_requests("{{ url }}")
assert bad.status_code == current.status_code
assert bad.body == current.body
""")
with open(str(tmpdir) + "/case_02.jinja2.py", "w") as c02:
c02.write("""from apitest.helpers.fuzzer import build_fuzzed_method
def test_sqli_case_001(make_requests):
current, good, bad = make_requests("{{ url }}")
assert bad.status_code == current.status_code
assert bad.body == current.body
""")
with open(str(tmpdir) + "/empty.jinja2.py", "w") as c03:
c03.write("")
return str(tmpdir)
@pytest.fixture
def fixtures_with_spaces(tmpdir):
with open(str(tmpdir) + "/case_03.jinja2.py", "w") as f:
f.write("""def test_sqli_case_001(make_requests):
current, good, bad = make_requests("{{ url }}")
assert bad.status_code == current.status_code
assert bad.body == current.body
""")
return str(tmpdir)
# --------------------------------------------------------------------------
# Constructor
# --------------------------------------------------------------------------
def test_build_templates_constructor_ok():
r = build_templates("/tmp", "blah")
assert r is not None
def test_build_templates_constructor_none_templates_dir():
with pytest.raises(AssertionError):
build_templates(None, "blah")
def test_build_templates_constructor_none_output_file_dir():
with pytest.raises(AssertionError):
build_templates("/tmp", None)
def test_build_templates_constructor_templates_dir_not_found():
with pytest.raises(ApitestNotFoundError):
build_templates("/asdfasfasdfsa", "as")
# --------------------------------------------------------------------------
# __enter__ method
# --------------------------------------------------------------------------
def test___enter___instance_ok(test_path):
with build_templates(test_path, "") as templates:
for template in templates:
assert isinstance(template, CustomTemplate)
# --------------------------------------------------------------------------
# __exit__ method
# --------------------------------------------------------------------------
def test__exit__empty_templates(tmpdir):
output_file = str(tmpdir) + "/output"
bt = build_templates(str(tmpdir), output_file)
with bt as _:
pass
assert len(bt.results) == 0
def test___exit__built_templates_oks(built_jinja_templates):
output_file = built_jinja_templates + "/output"
bt = build_templates(built_jinja_templates, output_file)
with bt as templates:
for template in templates:
template.render()
def test___exit__built_templates_template_with_non_imports(fixtures_with_spaces):
output_file = fixtures_with_spaces + "/output"
bt = build_templates(fixtures_with_spaces, output_file)
with bt as templates:
for template in templates:
template.render()
|
using System;
using System.Collections.Generic;
using System.Linq;
public class SuccessRateTracker
{
private List<PingDataPoint> dataPoints;
public SuccessRateTracker()
{
dataPoints = new List<PingDataPoint>();
}
public void AddDataPoint(PingDataPoint dataPoint)
{
dataPoints.Add(dataPoint);
}
public double CalculateSuccessRate(DateTime startTime, DateTime endTime)
{
var dataPointsWithinWindow = dataPoints.Where(p => p.Timestamp >= startTime && p.Timestamp <= endTime).ToList();
if (dataPointsWithinWindow.Count == 0)
{
return 0.0; // No data points within the specified time window
}
var successfulDataPoints = dataPointsWithinWindow.Count(p => p.Success);
return (double)successfulDataPoints / dataPointsWithinWindow.Count * 100;
}
} |
#!/usr/bin/env bash
PREFIX="${PREFIX:-/opt/postgres}"
if docker build --build-arg PREFIX="$PREFIX" -t postgres-reloc-alpine .; then
docker run --rm postgres-reloc-alpine cat /tmp/postgres.tar.xz > 'postgres.tar.xz'
fi
# vim:ts=4:sw=4:et:
|
import test from 'ava';
import double from '../../helpers/double';
import Just from '../../../src/core/just';
import Nothing from '../../../src/core/nothing';
const value = 42;
test('returns a new Just', t => {
const wrapped = Just(value);
const mapped = wrapped.map(double);
t.not(wrapped, mapped);
});
test('does not mutate the original Just', t => {
const wrapped = Just(value);
wrapped.map(double);
t.is(wrapped.value, value);
});
test('wraps the mapped value', t => {
t.is(
Just(value).map(double).value,
double(value)
);
});
test('returns Nothing when mapping to null', t => {
t.is(
Just(value).map(() => null),
Nothing()
);
});
test('returns Nothing when mapping to undefined', t => {
t.is(
Just(value).map(() => undefined),
Nothing()
);
});
|
import os
class FileLinker:
def cmd_link(self, source_dir, target_dir):
"""Link files in source_dir to corresponding files in target_dir."""
for root, _, files in os.walk(source_dir):
for file in files:
source_path = os.path.join(root, file)
target_path = os.path.join(target_dir, os.path.relpath(source_path, source_dir))
if os.path.exists(target_path):
os.remove(target_path) # Remove existing file or link
os.symlink(source_path, target_path) # Create symbolic link |
struct NilError: Error {
// NilError properties and methods can be left empty for this problem
}
extension Optional {
func unwrap() throws -> Wrapped {
guard let result = self else {
throw NilError()
}
return result
}
}
// Example usage:
let optionalValue: Int? = 42
do {
let unwrappedValue = try optionalValue.unwrap()
print("Unwrapped value:", unwrappedValue)
} catch {
print("Error:", error)
} |
package org.blankapp.flutterplugins.flutter_svprogresshud;
import android.app.Activity;
import android.os.Handler;
import android.widget.ImageView;
import com.kaopiz.kprogresshud.KProgressHUD;
import io.flutter.plugin.common.MethodCall;
import io.flutter.plugin.common.MethodChannel;
import io.flutter.plugin.common.MethodChannel.MethodCallHandler;
import io.flutter.plugin.common.MethodChannel.Result;
import io.flutter.plugin.common.PluginRegistry.Registrar;
/**
* FlutterSvprogresshudPlugin
*/
public class FlutterSvprogresshudPlugin implements MethodCallHandler {
/**
* Plugin registration.
*/
public static void registerWith(Registrar registrar) {
final MethodChannel channel = new MethodChannel(registrar.messenger(), "flutter_svprogresshud");
channel.setMethodCallHandler(new FlutterSvprogresshudPlugin(registrar.activity()));
}
private final Activity currentActivity;
private KProgressHUD hud;
public FlutterSvprogresshudPlugin(Activity activity) {
super();
this.currentActivity = activity;
}
@Override
public void onMethodCall(MethodCall call, Result result) {
double progress = 0;
String status = null;
int delay = 0;
if (call.hasArgument("progress")) progress = call.argument("progress");
if (call.hasArgument("status")) status = call.argument("status");
if (call.hasArgument("delay")) delay = call.argument("delay");
if (call.method.equals("setDefaultStyle")) {
// No-op
} else if (call.method.equals("setDefaultMaskType")) {
// No-op
} else if (call.method.equals("show")) {
this.show(status);
} else if (call.method.equals("showInfo")) {
this.showInfo(status);
} else if (call.method.equals("showSuccess")) {
this.showSuccess(status);
} else if (call.method.equals("showError")) {
this.showError(status);
} else if (call.method.equals("showProgress")) {
this.showProgress(progress, status);
} else if (call.method.equals("dismiss")) {
this.dismiss(0);
} else if (call.method.equals("dismissWithDelay")) {
this.dismiss(delay);
} else {
result.notImplemented();
return;
}
result.success(true);
}
public void show(String status) {
dismiss(0);
hud = KProgressHUD.create(currentActivity);
if (status != null && !status.isEmpty()) {
hud.setLabel(status);
}
hud.show();
}
public void showInfo(String status) {
dismiss(0);
ImageView imageView = new ImageView(currentActivity);
imageView.setBackgroundResource(R.mipmap.info);
hud = KProgressHUD.create(currentActivity)
.setCustomView(imageView)
.setLabel(status);
hud.show();
}
public void showSuccess(String status) {
dismiss(0);
ImageView imageView = new ImageView(currentActivity);
imageView.setBackgroundResource(R.mipmap.success);
hud = KProgressHUD.create(currentActivity)
.setCustomView(imageView)
.setLabel(status);
hud.show();
}
public void showError(String status) {
dismiss(0);
ImageView imageView = new ImageView(currentActivity);
imageView.setBackgroundResource(R.mipmap.error);
hud = KProgressHUD.create(currentActivity)
.setCustomView(imageView)
.setLabel(status);
hud.show();
}
public void showProgress(Double progress, String status) {
if (hud == null) {
hud = KProgressHUD.create(currentActivity)
.setStyle(KProgressHUD.Style.BAR_DETERMINATE)
.setMaxProgress(100)
.setLabel(status);
}
hud.setProgress(progress.intValue());
if (status != null && !status.isEmpty()) {
hud.setLabel(status);
}
if (!hud.isShowing()) {
hud.show();
}
}
public void dismiss(Integer delay) {
int delayMillis = delay != null ? delay.intValue() : 0;
if (delayMillis == 0) {
if (hud != null) {
hud.dismiss();
hud = null;
}
} else {
Handler handler = new Handler();
handler.postDelayed(new Runnable() {
@Override
public void run() {
if (hud != null) {
hud.dismiss();
hud = null;
}
}
}, delayMillis);
}
}
}
|
$(document).ready(function(){
//wylogowanie
$('#navLogout').click(logOut);
$('#navAddArticles').click(function(){document.location.href='../edit-article'});
//obsługa przycisków formularza usera
$('#btnChangeName').click(function(){
$(this).tooltip('hide');
$('#modalChangeName').modal();
});
$('#btnChangeMail').click(function(){
$(this).tooltip('hide');
$('#changeMailNewMail').on('input',checkEmail); //walidacja pola podczas wpisywania
$('#changeMailOldMail').on('input',checkEmail);
$('#changeMailPass').on('input',checkPass);
$('#modalChangeMail').modal();
});
$('#btnChangePass').click(function(){
$(this).tooltip('hide');
$('#changePassNewPass').on('input',checkPass);
$('#changePassNewPass2').bind('input',{idFirstPass: '#<PASSWORD>Pass',idSecondPass: '#<PASSWORD>'},checkPass2);
$('#changePassMail').on('input',checkEmail);
$('#changePassOldPass').on('input',checkPass);
$('#modalChangePass').modal();
});
//podpowiedzi dla urządzeń mobilnych
$(window).on('resize orientationchange',showPillToolTips);
showPillToolTips();
//sprawdzenie czy user jest zalogowany i wypełniamy formularz
firebase.auth().onAuthStateChanged(function(user) {
if (user) {
currUser = user;
if(currUser.isAnonymous){ //logowanie anonimowe
window.location.href='login';
}
else{
$('.mainSection').removeAttr('hidden');
$('#userNameSpan').text(currUser.displayName);
$('#profileUserName').val(currUser.displayName);
$('#profileUserEmail').val(currUser.email);
$('#profileUserPass').val('######');
//przekierowanie do konkretnej zakładki
let tab = window.location.hash;
if(tab=='#navArticles'){
$(tab).click();
}
else if (tab){
$('#navArticles').click(); //przekazany hash to id artykułu
}
}
} else {
currUser=null;
window.location.href='login';
}
});
//odczytanie artykułów usera
$('#navArticles').click(function (){
$('#cardArticles').empty(); //kasujemy wszystkie subelementy kontenera do karty artykułów.
getUserArticles(); //pobieramy artykuły
});
$('#artEra').change(function(){
$('#cardArticles').empty();
getUserArticles();
});
//ukrycie tooltipa po kliknięciu
$('[data-toggle="pill"]').each(function(){
$(this).bind('click',function(){ $(this).tooltip('hide'); });
});
});
//METODY do obsługi strony
//ARTYKUŁY-----------
function getUserArticles(){
try{
if(currUser){
if(!currUser.isAnonymous){
let c=0;
let articles = db.collection("Articles"); //odnośnik do listy artykułów
let artFiltr= articles.where("UserId","==",currUser.uid); //filtr po id usera
if($('#artEra').val()!=0){
artFiltr = artFiltr.where("Era","==",$('#artEra').val());
}
artFiltr.get() //pobieramy
.then(function(querySnapshot) {
querySnapshot.forEach(function(doc){ //pętla po wynikach
createUserCardArticle(doc);
c++;
});
$('#artCount').html("Liczba artykułów: <b>"+c+"</b>");
//przewijamy stronę do artykułu
let hashId = document.location.hash;
if(hashId){
let docHash = document.getElementById(hashId.substring(1));
if(docHash){
let y = $(docHash).offset().top - $('.navbar').outerHeight() - 10; //wyznaczamy punkt odniesienia
window.scrollTo({ top: y, behavior: 'smooth' }); //przewijamy
//delikatnie wyróżniamy kartę artykułu
let btnE = $(docHash).find('.btn-outline-primary');
$(btnE).removeClass('btn-outline-primary');
$(btnE).addClass('btn-primary');
let btnU = $(docHash).find('.btn-outline-danger');
$(btnU).removeClass('btn-outline-danger');
$(btnU).addClass('btn-danger');
$(docHash).find('.card').css('border-width','3px');
}
}
})
.catch(function(error){
showError('Błąd pobierania listy artykułów.',error);
});
}
}
}
catch(err){
showError('Error (get user articles): ',err);
}
}
function createUserCardArticle(article){
try{
//article -> obiekt otrzymany z bazy firebase
//article.id -> id obiektu (dokumentu) zapisanego w bazie
//article.data() -> treść właściwego artykułu (dokumentu)
let articleText = article.data().ArticleText;
if(articleText.length>500){ //skracamy tekst do 500 znaków
articleText = articleText.substring(0,500)+'...';
}
let title = article.data().Title;
let footer = 'Ostatnia modyfikacja: '+article.data().ModifyDate;
if(article.data().Public){
footer=footer+'</br> Opublikowano: '+article.data().PublicDate;
}
let tags = "Tagi: "+article.data().Tags;
let articleTemplate= document.createElement('div');
articleTemplate.setAttribute('class', 'col mb-4');
articleTemplate.setAttribute('id', article.id);
let cardTemplate = document.createElement('div');
cardTemplate.setAttribute('class', 'card h-100 border-info');
let cardBodyTemplate = document.createElement('div');
cardBodyTemplate.setAttribute('class','card-body');
cardBodyTemplate.innerHTML = '<h5 class="card-title">'+title+'</h5> <p class="card-text">'+articleText+'</p>';
let cardFooterTemplate = document.createElement('div');
cardFooterTemplate.setAttribute('class','card-footer bg-muted border-info');
cardFooterTemplate.innerHTML=`<div class="row justify-content-between"> <small class="col-6 text-muted">${tags}</small>
<div class="mr-2">
<button class="btn btn-outline-primary py-0" onclick="editArticle('${article.id}')">Edytuj</button>
<button class="btn btn-outline-danger py-0" onclick="deleteArticle('${article.id}','${title}')">Usuń</button>
</div>
</div>
<small class="text-muted ">${footer}</small>`;
//dodajemy do struktury strony
cardTemplate.appendChild(cardBodyTemplate);
cardTemplate.appendChild(cardFooterTemplate);
articleTemplate.appendChild(cardTemplate);
document.getElementById('cardArticles').appendChild(articleTemplate);
}
catch(err){
showError('Error (create card article): ',err);
}
}
function deleteArticle(articleId, title){
try{
$('#modalDelArticle p').html('Czy chcesz usunąć artykuł "'+title+'"?');
$('#delArtYes').click(function(){
db.collection("Articles").doc(articleId).delete().then(function() {
$('#cardArticles').empty();
getUserArticles();
}).catch(function(error) {
showError("Błąd podczas usuwania artykułu", error);
});
});
$('#modalDelArticle').modal();
}
catch(err){
showError('Error (delete article): ',err);
}
}
function editArticle(articleId){
try{
document.location.href="../edit-article/#"+articleId;
}
catch(err){
showError('Error (edit article): ',err);
}
}
//PODPOWIEDZI-----------
function showPillToolTips(){
try{
if($(window).width()<=768){
$('[data-toggle="pill"]').attr('data-html',true);
$('#navProfile').attr('title','<h6>Twój profil</h6>');
$('#navAddArticles').attr('title','<h6>Dodaj artykuł</h6>');
$('#navArticles').attr('title','<h6>Twój artykuły</h6>');
$('#navLogout').attr('title','<h6>Wyloguj...</h6>');
$('[data-toggle="pill"]').tooltip();
}
else{
$('[data-toggle="pill"]').removeAttr('data-html');
$('[data-toggle="pill"]').removeAttr('title'); //trzeba usunąć atrybut
$('[data-toggle="pill"]').tooltip('dispose'); //i wyłączyć tooltip
}
}
catch(err){
console.error('Tooltip error: '+err);
}
}
//PROFIL-----------
function changeUserName(newName){
if(newName){
try{
if(currUser){
currUser.updateProfile({
displayName: newName
})
.then(function() {
$('#profileUserName').val(currUser.displayName);
showInfo('<NAME>','Twoja imię zostało zmienione.');
})
.catch(function(error) {showError('Błąd '+error.code,error.message);});
}
}
catch(err){
showError('Change name error',err);
}
}
}
function changeUserMail(e,idNewMail,idOldMail,idPass){
try{
//weryfikacja formy
if($(idNewMail).val()=='' | !validateEmail($(idNewMail).val())){
$(idNewMail).addClass('is-invalid');
}
else{
$(idNewMail).removeClass('is-invalid');
$(idNewMail).addClass('is-valid');
}
if($(idOldMail).val()=='' | !validateEmail($(idOldMail).val())){
$(idOldMail).addClass('is-invalid');
}
else{
$(idOldMail).removeClass('is-invalid');
$(idOldMail).addClass('is-valid');
}
if($(idPass).val().length<6){
$(idPass).addClass('is-invalid');
}
else{
$(idPass).removeClass('is-invalid');
$(idPass).addClass('is-valid');
}
if($(idNewMail).hasClass('is-invalid') | $(idOldMail).hasClass('is-invalid') | $(idPass).hasClass('is-invalid')){
e.preventDefault();
e.stopPropagation();
}
else{
//ponownie uwierzytelniamy usera
let credentials = firebase.auth.EmailAuthProvider.credential($(idOldMail).val(), $(idPass).val());
currUser.reauthenticateWithCredential(credentials)
.then(function() {
//zmieniamy mail
currUser.updateEmail($(idNewMail).val())
.then(function() {
showInfo("Zmiana adresu e-mail","Twój adres e-mail został zmieniony.");
$('#profileUserEmail').val(currUser.email);
})
.catch(function(error) {
showError('Błąd podczas zmiany adresu e-mail '+error.code,error.message);
$('#modalChangeMail').modal();
});
})
.catch(function(error) {
decodeLogInError(error);
$('#modalChangeMail').modal();
});
//czyścimy formę z klas walidacji
changeModalClear(idNewMail,idOldMail,idPass);
}
}
catch(err){
showError('Change mail error',err);
}
}
function changeUserPass(e,idNewPass,idNewPass2,idMail,idOldPass){
try{
//weryfikacja formy
if($(idMail).val()=='' | !validateEmail($(idMail).val())){
$(idMail).addClass('is-invalid');
}
else{
$(idMail).removeClass('is-invalid');
$(idMail).addClass('is-valid');
}
if($(idNewPass).val().length<6){
$(idNewPass).addClass('is-invalid');
}
else{
$(idNewPass).removeClass('is-invalid');
$(idNewPass).addClass('is-valid');
}
if($(idOldPass).val().length<6){
$(idOldPass).addClass('is-invalid');
}
else{
$(idOldPass).removeClass('is-invalid');
$(idOldPass).addClass('is-valid');
}
if($(idNewPass2).val().length<6 || $(idNewPass).val()!=$(idNewPass2).val()){
$(idNewPass2).addClass('is-invalid');
}
else{
$(idNewPass2).removeClass('is-invalid');
$(idNewPass2).addClass('is-valid');
}
if($(idMail).hasClass('is-invalid') | $(idNewPass).hasClass('is-invalid') | $(idOldPass).hasClass('is-invalid') | $(idNewPass2).hasClass('is-invalid')){
e.preventDefault();
e.stopPropagation();
}
else{
//ponownie uwierzytelniamy usera
let credentials = firebase.auth.EmailAuthProvider.credential($(idMail).val(), $(idOldPass).val());
currUser.reauthenticateWithCredential(credentials)
.then(function() {
//zmieniamy mail
currUser.updatePassword($(idNewPass).val())
.then(function() { showInfo("Zmiana hasła","Twoje hasło zostało zmienione.");})
.catch(function(error) {
showError('Błąd podczas zmiany hasła '+error.code,error.message);
$('#modalChangePass').modal();
});
})
.catch(function(error) {
decodeLogInError(error);
$('#modalChangePass').modal();
});
//czyścimy formę z klas walidacji
changeModalClear(idNewPass,idNewPass2,idMail,idOldPass);
}
}
catch(err){
showError('Change password error',err);
}
}
function deleteUser(e,idMail,idPass){
try{
//walidacja podczas wpisywania
$(idMail).on('input',checkEmail);
$(idPass).on('input',checkPass);
//weryfikacja formy
if($(idMail).val()=='' | !validateEmail($(idMail).val())){
$(idMail).addClass('is-invalid');
}
else{
$(idMail).removeClass('is-invalid');
$(idMail).addClass('is-valid');
}
if($(idPass).val().length<6){
$(idPass).addClass('is-invalid');
}
else{
$(idPass).removeClass('is-invalid');
$(idPass).addClass('is-valid');
}
if($(idMail).hasClass('is-invalid') | $(idPass).hasClass('is-invalid')){
e.preventDefault();
e.stopPropagation();
}
else{
let credentials = firebase.auth.EmailAuthProvider.credential($(idMail).val(), $(idPass).val());
currUser.reauthenticateWithCredential(credentials)
.then(function() {
//zmieniamy mail
currUser.delete()
.then(function() {
showInfo("Usuwanie konta","Twoje konto zostało usunięte.");
})
.catch(function(error) {
showError('Błąd podczas usuwania konta '+error.code,error.message);
$('#modalDelUser').modal();
});
})
.catch(function(error) {
decodeLogInError(error);
$('#modalDelUser').modal();
});
changeModalClear(idMail,idPass);
}
}
catch(err){
showError('Delete user error',err);
}
}
//usunięcie klas walidujących formę
function changeModalClear(id1,id2,id3,id4){
try{
if(id1){
$(id1).removeClass('is-invalid');
$(id1).removeClass('is-valid');
}
if(id2){
$(id2).removeClass('is-invalid');
$(id2).removeClass('is-valid');
}
if(id3){
$(id3).removeClass('is-invalid');
$(id3).removeClass('is-valid');
}
if(id4){
$(id4).removeClass('is-invalid');
$(id4).removeClass('is-valid');
}
}
catch(err){
console.error('Clear modal error: '+err);
}
} |
package com.ctriposs.lcache.utils;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.ObjectOutput;
import java.io.ObjectOutputStream;
import java.io.Serializable;
import java.text.DecimalFormat;
import java.text.NumberFormat;
import java.util.Random;
public class TestUtil {
static final String AB = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";
static Random rnd = new Random();
private static final NumberFormat MEM_FMT = new DecimalFormat("##,###.##");
public static String randomString(int len )
{
StringBuilder sb = new StringBuilder( len );
for( int i = 0; i < len; i++ )
sb.append( AB.charAt( rnd.nextInt(AB.length()) ) );
return sb.toString();
}
public static void sleepQuietly(long duration) {
try {
Thread.sleep(duration);
} catch (InterruptedException e) {
// ignore
}
}
public static final String TEST_BASE_DIR = "d:/sdb_test/";
public static String kbString(long memBytes) {
return MEM_FMT.format(memBytes / 1024) + " kb";
}
public static String printMemoryFootprint() {
Runtime run = Runtime.getRuntime();
String memoryInfo = "Memory - free: " + kbString(run.freeMemory()) + " - max:" + kbString(run.maxMemory()) + "- total:" + kbString(run.totalMemory());
return memoryInfo;
}
public static byte[] getBytes(Object o) {
if (o instanceof String) {
return ((String)o).getBytes();
} else if (o instanceof byte[]) {
return (byte[])o;
} else if (o instanceof Serializable) {
ByteArrayOutputStream bos = new ByteArrayOutputStream();
ObjectOutput out = null;
try {
out = new ObjectOutputStream(bos);
out.writeObject(o);
byte[] bytes = bos.toByteArray();
return bytes;
} catch(Exception e) {
return null;
} finally {
try {
if (out != null) {
out.close();
}
} catch (IOException ex) {
// ignore close exception
}
try {
bos.close();
} catch (IOException ex) {
// ignore close exception
}
}
}
throw new RuntimeException("Fail to convert object to bytes");
}
public static String convertToString(byte[] bytes){
return new String(bytes);
}
}
|
<reponame>phosphor-icons/phosphr-webcomponents
/* GENERATED FILE */
import { html, svg, define } from "hybrids";
const PhEye = {
color: "currentColor",
size: "1em",
weight: "regular",
mirrored: false,
render: ({ color, size, weight, mirrored }) => html`
<svg
xmlns="http://www.w3.org/2000/svg"
width="${size}"
height="${size}"
fill="${color}"
viewBox="0 0 256 256"
transform=${mirrored ? "scale(-1, 1)" : null}
>
${weight === "bold" &&
svg`<path d="M128,55.99219C48,55.99219,16,128,16,128s32,71.99219,112,71.99219S240,128,240,128,208,55.99219,128,55.99219Z" fill="none" stroke="${color}" stroke-linecap="round" stroke-linejoin="round" stroke-width="24"/>
<circle cx="128" cy="128" r="32" fill="none" stroke="${color}" stroke-linecap="round" stroke-linejoin="round" stroke-width="24"/>`}
${weight === "duotone" &&
svg`<path d="M127.99414,55.99231c-80,0-112,72.00781-112,72.00781s32,71.99219,112,71.99219,112-71.99219,112-71.99219S207.99414,55.99231,127.99414,55.99231Zm0,112.0083a40,40,0,1,1,40-40A40.0001,40.0001,0,0,1,127.99414,168.00061Z" opacity="0.2"/>
<path d="M127.99414,55.99219c-80,0-112,72.00781-112,72.00781s32,71.99219,112,71.99219,112-71.99219,112-71.99219S207.99414,55.99219,127.99414,55.99219Z" fill="none" stroke="${color}" stroke-linecap="round" stroke-linejoin="round" stroke-width="16"/>
<circle cx="127.99414" cy="128.00061" r="40" fill="none" stroke="${color}" stroke-linecap="round" stroke-linejoin="round" stroke-width="16"/>`}
${weight === "fill" &&
svg`<path d="M247.31055,124.75061c-.35157-.79-8.81934-19.57617-27.65332-38.41113C194.57324,61.25256,162.87793,47.99182,128,47.99182S61.42676,61.25256,36.34277,86.33948c-18.834,18.835-27.30175,37.62109-27.65332,38.41113a8.00282,8.00282,0,0,0,0,6.49805c.35157.791,8.82032,19.57226,27.6543,38.40429C61.42773,194.734,93.12207,207.99182,128,207.99182S194.57227,194.734,219.65625,169.653c18.834-18.832,27.30273-37.61328,27.6543-38.40429A8.00282,8.00282,0,0,0,247.31055,124.75061ZM128,92.00061a36,36,0,1,1-36,36A36.04061,36.04061,0,0,1,128,92.00061Z"/>`}
${weight === "light" &&
svg`<path d="M128,55.99219C48,55.99219,16,128,16,128s32,71.99219,112,71.99219S240,128,240,128,208,55.99219,128,55.99219Z" fill="none" stroke="${color}" stroke-linecap="round" stroke-linejoin="round" stroke-width="12"/>
<circle cx="128" cy="128.00061" r="40" fill="none" stroke="${color}" stroke-linecap="round" stroke-linejoin="round" stroke-width="12"/>`}
${weight === "thin" &&
svg`<path d="M128,55.99219C48,55.99219,16,128,16,128s32,71.99219,112,71.99219S240,128,240,128,208,55.99219,128,55.99219Z" fill="none" stroke="${color}" stroke-linecap="round" stroke-linejoin="round" stroke-width="8"/>
<circle cx="128" cy="128.00061" r="40" fill="none" stroke="${color}" stroke-linecap="round" stroke-linejoin="round" stroke-width="8"/>`}
${weight === "regular" &&
svg`<path d="M128,55.99219C48,55.99219,16,128,16,128s32,71.99219,112,71.99219S240,128,240,128,208,55.99219,128,55.99219Z" fill="none" stroke="${color}" stroke-linecap="round" stroke-linejoin="round" stroke-width="16"/>
<circle cx="128" cy="128.00061" r="40" fill="none" stroke="${color}" stroke-linecap="round" stroke-linejoin="round" stroke-width="16"/>`}
</svg>
`,
};
define("ph-eye", PhEye);
export default PhEye;
|
#!/bin/bash
if [ -t 0 ]; then
DROPLET_INFO=$1
else
DROPLET_INFO=$(cat)
fi
echo $DROPLET_INFO | jq -c --raw-output ".id"
|
<filename>batching/src/main/java/com/flipkart/batching/listener/TrimPersistedBatchReadyListener.java
/*
* The MIT License (MIT)
*
* Copyright (c) 2017 Flipkart Internet Pvt. Ltd.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package com.flipkart.batching.listener;
import android.os.Handler;
import com.flipkart.batching.BatchingStrategy;
import com.flipkart.batching.core.Batch;
import com.flipkart.batching.core.Data;
import com.flipkart.batching.core.SerializationStrategy;
/**
* TrimPersistedBatchReadyListener that extends {@link PersistedBatchReadyListener}
*/
public class TrimPersistedBatchReadyListener<E extends Data, T extends Batch<E>> extends PersistedBatchReadyListener<E, T> {
public final static int MODE_TRIM_NONE = 0;
public final static int MODE_TRIM_AT_START = 1;
public final static int MODE_TRIM_ON_READY = 1 << 1;
protected final Handler handler;
private final TrimmedBatchCallback trimListener;
int mode;
private int trimSize, maxQueueSize;
public TrimPersistedBatchReadyListener(String filePath, SerializationStrategy<E, T> serializationStrategy, Handler handler, int maxQueueSize, int trimSize, int mode, PersistedBatchCallback<T> persistedBatchCallback, TrimmedBatchCallback trimmedBatchCallback) {
super(filePath, serializationStrategy, handler, persistedBatchCallback);
if (trimSize > maxQueueSize) {
throw new IllegalArgumentException("trimSize must be smaller than maxQueueSize");
}
this.trimSize = trimSize;
this.maxQueueSize = maxQueueSize;
this.handler = handler;
this.mode = mode;
this.trimListener = trimmedBatchCallback;
}
@Override
protected void onInitialized() {
super.onInitialized();
if ((mode & MODE_TRIM_AT_START) == MODE_TRIM_AT_START) {
trimQueue();
}
}
@Override
public void onReady(BatchingStrategy<E, T> causingStrategy, T batch) {
super.onReady(causingStrategy, batch);
handler.post(new Runnable() {
@Override
public void run() {
if ((mode & MODE_TRIM_ON_READY) == MODE_TRIM_ON_READY) {
trimQueue();
}
}
});
}
void trimQueue() {
int oldSize = getSize();
if (oldSize >= maxQueueSize && remove(trimSize)) {
callTrimListener(oldSize, getSize());
}
}
private void callTrimListener(int oldSize, int newSize) {
if (trimListener != null) {
trimListener.onTrimmed(oldSize, newSize);
}
}
}
|
#!/bin/bash
source ./scripts/env.sh
source ./virtuoso_scripts/virtuoso_env.sh
MAXPROCS=`echo "scale=0; $MAXPROCS / 2.5" | bc`
if [ $MAXPROCS = 0 ] ; then
MAXPROCS=1
fi
DB_NAME=prd
rm -f /tmp/prd-virtuoso-last
init=false
change=`find $RDF_PRD -name '*.rdf.gz' -mtime -4 | wc -l`
which isql &> /dev/null
if [ $? != 0 ] ; then
echo "isql: command not found..."
echo "Please install Virtuoso (https://virtuoso.openlinksw.com/)."
exit 1
fi
#./virtuoso_scripts/start_virtuoso.sh || exit 1
#sleep 30
GRAPH_URI=http://rdf.wwpdb.org/$DB_NAME
graph_exist=`./virtuoso_scripts/ask_graph_existance.sh $GRAPH_URI` || exit 1
if [ $graph_exist = 1 ] && [ $init = "false" ] ; then
if [ $change = 0 ] ; then
echo $DB_NAME is update.
fi
exit 0
fi
echo
echo "Do you want to update Virtuoso DB ($GRAPH_URI)? (y [n]) "
read ans
case $ans in
y*|Y*) ;;
*) echo skipped.
exit 1;;
esac
isql $VIRTUOSO_DB_PORT $VIRTUOSO_DB_USER $VIRTUOSO_DB_PASS exec="status();" || exit 1
rm -rf $RDF_BIRD_LINK
mkdir -p $RDF_BIRD_LINK
cd $RDF_BIRD_LINK
rdf_file_list=rdf_file_list
find ../$RDF_PRD -type f -iname "*.rdf.gz" > $rdf_file_list
while read rdf_file
do
ln -s $rdf_file .
done < $rdf_file_list
rm -f $rdf_file_list
err=$DB_NAME"_err"
if [ $graph_exist = 1 ] ; then
VIRTUOSO_EXEC_COM="log_enable(3,1); SPARQL CLEAR GRAPH <$GRAPH_URI>;"
echo $VIRTUOSO_EXEC_COM
isql $VIRTUOSO_DB_PORT $VIRTUOSO_DB_USER $VIRTUOSO_DB_PASS exec="$VIRTUOSO_EXEC_COM" 2> $err || ( cat $err && exit 1 )
VIRTUOSO_EXEC_COM="log_enable(3,1); DELETE FROM rdf_quad WHERE g = iri_to_id ('$GRAPH_URI');"
echo $VIRTUOSO_EXEC_COM
isql $VIRTUOSO_DB_PORT $VIRTUOSO_DB_USER $VIRTUOSO_DB_PASS exec="$VIRTUOSO_EXEC_COM" 2> $err || ( cat $err && exit 1 )
fi
VIRTUOSO_EXEC_COM="ld_dir('$PWD', '*.rdf.gz', '$GRAPH_URI');"
echo $VIRTUOSO_EXEC_COM
isql $VIRTUOSO_DB_PORT $VIRTUOSO_DB_USER $VIRTUOSO_DB_PASS exec="$VIRTUOSO_EXEC_COM" 2> $err || ( cat $err && exit 1 )
grep Error $err &> /dev/null || ( cat $err && exit 1 )
rm -f $err
for proc_id in `seq 1 $MAXPROCS` ; do
isql $VIRTUOSO_DB_PORT $VIRTUOSO_DB_USER $VIRTUOSO_DB_PASS exec="rdf_loader_run();" &
done
if [ $? != 0 ] ; then
exit 1
fi
wait
isql $VIRTUOSO_DB_PORT $VIRTUOSO_DB_USER $VIRTUOSO_DB_PASS exec="checkpoint;" || exit 1
date -u +"%b %d, %Y" > /tmp/prd-virtuoso-last
echo "RDF->VIRTUOSO (prefix:"$DB_NAME") is completed."
cd .. ; rm -rf $RDF_BIRD_LINK
#echo -n $"Stopping virtuoso-t daemon: "
#isql $VIRTUOSO_DB_PORT $VIRTUOSO_DB_USER $VIRTUOSO_DB_PASS -K
echo
|
<filename>meiduo_mall/meiduo_mall/apps/oauth/utils.py
from itsdangerous import TimedJSONWebSignatureSerializer as Serializer,BadData
from django.conf import settings
def generate_openid_sign(raw_openid):
"""
对openid进行加加密,并返回加密后的结果
:param raw_openid: 要加密的openid
:return: 加密后的openid
"""
# 1.创建加密/解密对象
serializer = Serializer(secret_key=settings.SECRET_KEY,expires_in=600)
# 2.包装要加密的数据为字典格式
data = {'openid':raw_openid}
# 3. 加密对象调用dumps() 进行加密,默认返回bytes
secret_openid = serializer.dumps(data)
return secret_openid.decode()
def check_out_openid(secret_openid):
"""
对openid进行解密,并返回解密后的结果
:param openid_sign: 要解密的openid
:return: 解密后的openid
"""
# 1.创建加密/解密对象
serializer = Serializer(secret_key=settings.SECRET_KEY, expires_in=600)
# 2.调用loads方法进行解密,解密成功返回原有字典
try:
data = serializer.loads(secret_openid)
raw_openid = data.get('openid')
return raw_openid
except BadData as e:
return None
|
<filename>src/main/java/org/rs2server/rs2/domain/dao/AbstractMongoDao.java
package org.rs2server.rs2.domain.dao;
import javax.annotation.Nonnull;
import javax.annotation.Nullable;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Objects;
import java.util.concurrent.atomic.AtomicBoolean;
import org.joda.time.DateTime;
import org.joda.time.DateTimeZone;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.datatype.joda.JodaModule;
import com.mongodb.BasicDBObject;
import com.mongodb.DBCollection;
import com.mongodb.DBObject;
import com.mongodb.DuplicateKeyException;
import org.mongojack.DBCursor;
import org.mongojack.DBQuery;
import org.mongojack.DBSort;
import org.mongojack.JacksonDBCollection;
import org.mongojack.WriteResult;
import org.mongojack.internal.MongoJackModule;
/**
* Abstract DAO implementation.
*/
public abstract class AbstractMongoDao<T extends MongoEntity> implements MongoDao<T> {
private static final Logger logger = LoggerFactory.getLogger(AbstractMongoDao.class);
/**
* Custom configured ObjectMapper instance to use the JodaModule in the MongoDB jackson mapper.
*/
private static final ObjectMapper OBJECT_MAPPER = new ObjectMapper();
private final MongoService mongoService;
private final String collectionName;
private final Class<T> tClass;
private JacksonDBCollection<T, String> jacksonDBCollection;
private AtomicBoolean dbReady = new AtomicBoolean(false);
protected AbstractMongoDao(final MongoService mongoService, final String collectionName, final Class<T> tClass) {
this.mongoService = mongoService;
this.collectionName = collectionName;
this.tClass = tClass;
OBJECT_MAPPER.registerModule(new JodaModule());
MongoJackModule.configure(OBJECT_MAPPER);
}
protected JacksonDBCollection<T, String> getJacksonDBCollection() {
initDB();
return jacksonDBCollection;
}
protected void ensureUniqueIndex(String idToIndex) {
BasicDBObject query = new BasicDBObject(idToIndex, 1);
getJacksonDBCollection().ensureIndex(query, idToIndex + "IndexUnique", true);
}
protected void ensureNonUniqueIndex(String idToIndex) {
BasicDBObject query = new BasicDBObject(idToIndex, 1);
getJacksonDBCollection().ensureIndex(query, idToIndex + "Index", false);
}
/**
* Implement your indices here. This method will be called only once before the first access of any DB method.
*/
protected abstract void ensureIndices();
/**
* Prepares the MongoDB if not already initialised.
* <p>
* This method is thread-safe for the rare case where the db is not yet available and
* multiple threads attempt to initialise it simultaneously.
*/
private void initDB() {
try {
if (dbReady.compareAndSet(false, true)) {
final DBCollection dbCollection = mongoService.getDatabase().getCollection(collectionName);
jacksonDBCollection = JacksonDBCollection.wrap(dbCollection, tClass, String.class, OBJECT_MAPPER);
ensureIndices();
}
} catch (Exception e) {
logger.error("Encountered MongoDB error.", e);
}
}
@Override
public T create(@Nonnull final T t) throws DuplicateKeyException {
Objects.requireNonNull(t);
updateTimestamps(t);
final WriteResult<T, String> insert = getJacksonDBCollection().insert(t);
return insert.getSavedObject();
}
@Override
public T save(@Nonnull final T t) {
Objects.requireNonNull(t);
updateTimestamps(t);
// This performs an atomic upsert in MongoDB.
final WriteResult<T, String> result = getJacksonDBCollection().save(t);
return result.getSavedObject();
}
private void updateTimestamps(@Nonnull final T t) {
final long now = DateTime.now(DateTimeZone.UTC).getMillis();
if (t.getTimestampCreated() == 0) {
t.setTimestampCreated(now);
}
t.setTimestampUpdated(now);
}
@Override
public long countAll() {
return getJacksonDBCollection().count();
}
@Override
public void deleteAll() {
getJacksonDBCollection().drop();
ensureIndices();
}
@Override
public void drop() {
getJacksonDBCollection().drop();
}
@Override
@Nonnull
public List<T> findAll() {
return toList(getJacksonDBCollection().find());
}
@Override
@Nullable
public T find(@Nonnull String id) {
Objects.requireNonNull(id, "id");
try {
return getJacksonDBCollection().findOneById(id);
} catch (IllegalArgumentException e) {
// This exception is thrown by the mongo driver if the id is an invalid ObjectId (@see ObjectId.isValid)
// although some documents use custom id's so we cannot simply verify the id ourselves
return null;
}
}
/**
* Converts the input cursor to a list.
*
* @param cursor
* if null, an empty list will be returned.
* @return the list, all elements in the cursor are added to it.
*/
protected List<T> toList(@Nullable final DBCursor<T> cursor) {
if (cursor == null) {
return new ArrayList<>();
}
final List<T> result = new ArrayList<>();
final Iterator<T> iterator = toIterator(cursor);
while (iterator.hasNext()) {
result.add(iterator.next());
}
return result;
}
protected Iterator<T> toIterator(final DBCursor<T> cursor) {
if (cursor == null || cursor.getCursor() == null) {
return new Iterator<T>() {
@Override
public boolean hasNext() {
return false;
}
@Override
public T next() {
return null;
}
@Override
public void remove() {
throw new UnsupportedOperationException();
}
};
}
return new Iterator<T>() {
@Override
public boolean hasNext() {
return cursor.hasNext();
}
@Override
public T next() {
return cursor.next();
}
@Override
public void remove() {
throw new UnsupportedOperationException();
}
};
}
/**
* Retrieves a list of documents matching field=value.
*/
@Nonnull
protected List<T> findListByField(@Nonnull String field, @Nonnull Object value) {
Objects.requireNonNull(field, "field");
Objects.requireNonNull(value, "value");
return findListByQuery(DBQuery.is(field, value));
}
protected List<T> findListByQuery(final DBQuery.Query query) {
Objects.requireNonNull(query, "query");
final DBCursor<T> cursor = getJacksonDBCollection().find(query);
return toList(cursor);
}
protected List<T> findListByQuery(final DBObject query) {
Objects.requireNonNull(query, "query");
final DBCursor<T> cursor = getJacksonDBCollection().find(query);
return toList(cursor);
}
protected List<T> findListByQuerySortedByField(final DBQuery.Query query, String sortingField) {
Objects.requireNonNull(query, "query");
Objects.requireNonNull(sortingField, "query");
final DBCursor<T> cursor = getJacksonDBCollection().find(query).sort(DBSort.asc(sortingField));
return toList(cursor);
}
protected T findSingleByQuery(DBQuery.Query query) {
return getJacksonDBCollection().findOne(query);
}
}
|
<filename>app/js/comment-timeline.js
const { gsap } = require("gsap/dist/gsap");
const { FlowComment } = require("./flow-comment");
const { FixedComment } = require("./fixed-comment");
class NicoScript {
constructor(){
const scripts = [
"[@@]デフォルト",
"@置換",
"@逆",
"@コメント禁止",
"@シーク禁止",
"@ジャンプ",
"@ピザ"
];
this._scritp_re = new RegExp(scripts.join("|"), "i");
const colors = [
"white",
"red",
"pink",
"orange",
"yellow",
"green",
"cyan",
"blue",
"purple",
"black",
];
this._color_re = new RegExp(colors.join("|"), "i");
this._fontsize_re = new RegExp("big|middle|small", "i");
}
/**
*
* @param {Array} comments
*/
getApplied(comments){
const script_comments = comments.filter(comment => {
return this._hasScript(comment.content);
});
const normal_comments = comments.filter(comment => {
return !this._hasScript(comment.content);
});
const applied_comments = this._applyDefault(script_comments, normal_comments);
return applied_comments;
}
/**
*
* @param {Array} script_comments
* @param {Array} normal_comments
*/
_applyDefault(script_comments, normal_comments){
const f = script_comments.find(comment => {
return /[@@]デフォルト/ig.test(comment.content);
});
if(f===undefined){
return normal_comments;
}
const color = this._color_re.exec(f.mail);
const font_size = this._fontsize_re.exec(f.mail);
const opt = {};
if(color){
Object.assign(opt, {color:color[0]});
}
if(font_size){
Object.assign(opt, {font_size:font_size[0]});
}
if( Object.keys(opt).length === 0){
return normal_comments;
}
return normal_comments.map(comment => {
const mail = comment.mail;
const opts = [];
if(mail){
opts.push(mail);
}
if(this._color_re.test(mail)===false && opt.color){
opts.push(opt.color);
}
if(this._fontsize_re.test(mail)===false && opt.font_size){
opts.push(opt.font_size);
}
comment.mail = opts.join(" ");
return comment;
});
}
_hasScript(text){
return this._scritp_re.test(text);
}
}
class CommentOptionParser {
constructor(){
this._default_color = "white";
this._p_color_map = new Map([
["niconicowhite", "#CCCC99"],
["white2", "#CCCC99"],
["truered", "#CC0033"],
["red2", "#CC0033"],
["pink2", "#FF33CC"],
["passionorange", "#FF6600"],
["orange2", "#FF6600"],
["madyellow", "#999900"],
["yellow2", "#999900"],
["elementalgreen", "#00CC66"],
["green2", "#00CC66"],
["cyan2", "#00CCCC"],
["marineblue", "#3399FF"],
["blue2", "#3399FF"],
["nobleviolet", "#6633CC"],
["purple2", "#6633CC"],
["black2", "#666666"]
]);
this._u_color_map = new Map([
["white", "#FFFFFF"],
["red", "#FF0000"],
["pink", "#FF8080"],
["orange", "#FFCC00"],
["yellow", "#FFFF00"],
["green", "#00FF00"],
["cyan", "#00FFFF"],
["blue", "#0000FF"],
["purple", "#C000FF"],
["black", "#000000"]
]);
this._p_color_regex = this._create(this._p_color_map);
this._u_color_regex = this._create(this._u_color_map);
}
_create(color_map){
const keys = [];
color_map.forEach((value, key)=>{
keys.push(key);
});
return new RegExp(keys.join("|"), "i");
}
_getColorCode(mail, color_map, color_regex){
const color = color_regex.exec(mail);
if(color!=null){
if(color_map.has(color[0])===true){
return color_map.get(color[0]);
}
}
return null;
}
/**
*
* @param {String} mail
*/
_getType(mail){
const type = mail.match(/^ue\s|\sue\s|\sue$|^naka\s|\snaka\s|\snaka$|^shita\s|\sshita\s|\sshita$/gi);
if(type!==null){
return type[0].trim();
}
if(mail=="ue" || mail=="naka" || mail=="shita"){
return mail;
}
return null;
}
/**
*
* @param {String} mail
*/
_getFontSize(mail){
const size = mail.match(/^big\s|\sbig\s|\sbig$|^middle\s|\smiddle\s|\smiddle$|^small\s|\ssmall\s|\ssmall$/gi);
if(size!==null){
return size[0].trim();
}
if(mail=="big" || mail=="middle" || mail=="small"){
return mail;
}
return null;
}
/**
*
* @param {String} mail
* @param {String} user_id
*/
parse(mail, user_id){
const options = {
type: "naka",
font_size:"middle",
color: this._u_color_map.get(this._default_color)
};
if(mail){
const normalized_mail = mail.replace(/\u3000/g, "\x20");
const type = this._getType(normalized_mail);
if(type!==null){
options.type = type;
}
const size = this._getFontSize(normalized_mail);
if(size!==null){
options.font_size = size;
}
if(user_id=="owner"){
const duration = /\s*@\d+\s*/.exec(normalized_mail);
if(duration){
const sec = parseInt(duration[0].replace("@", ""));
Object.assign(options, { duration:sec*1000 });
}
}
const p_color_code = this._getColorCode(
normalized_mail, this._p_color_map, this._p_color_regex);
if(p_color_code!==null){
options.color = p_color_code;
return options;
}
const u_color_code = this._getColorCode(
normalized_mail, this._u_color_map, this._u_color_regex);
if(u_color_code!==null){
options.color = u_color_code;
return options;
}
const color_code = normalized_mail.match(/#[a-f0-9]{6}/ig);
if(color_code!==null){
options.color = color_code[0];
return options;
}
}
return options;
}
}
class CommentTimeLine {
/**
*
* @param {HTMLElement} parent_elm
* @param {Number} duration_sec
* @param {Number} row_num
* @param {String} comment_font_family
*/
constructor(parent_elm, duration_sec, row_num, comment_font_family){
this.parent_elm = parent_elm;
this.duration_sec = duration_sec;
this.row_num = row_num;
this.comment_font_family = comment_font_family;
this.ctx = null;
this.area_size = {
height: parent_elm.clientHeight,
width: parent_elm.clientWidth
};
this.timeLine = null;
this.enable = true;
this._last_time_sec = 0;
this._paused = true;
this._ended = false;
this._has_comment = true;
this._on_complete = ()=>{};
}
onComplete(on_complete){
this._on_complete = on_complete;
}
get paused(){
return this._paused;
}
get ended(){
return this._ended;
}
get hasComment(){
return this._has_comment;
}
get lastTimeSec(){
return this._last_time_sec;
}
setFPS(fps){
gsap.ticker.fps(fps);
}
/**
* @param {Array} comments
*/
create(comments) {
this._has_comment = comments.length > 0;
this._ended = false;
this._createCanvas();
this.clear();
this.timeLine = gsap.timeline(
{
onComplete:()=>{
this._ended = true;
this.pause();
this._on_complete();
},
paused: true
}
);
comments.sort((a, b) => {
if (a.vpos < b.vpos) return -1;
if (a.vpos > b.vpos) return 1;
return 0;
});
this._last_time_sec = 0;
if(comments.length>0){
this._last_time_sec =
comments[comments.length-1].vpos/100 + this.duration_sec;
}
const [flow_comments,
fixed_top_comments,
fixed_bottom_comments] = this._getEachComments(comments);
this._createFlowTL(flow_comments);
this._createFixedTL(fixed_top_comments, fixed_bottom_comments);
}
/**
*
* @param {Array} comments
*/
_createFlowTL(comments){
const view_width = this.area_size.width;
const duration_msec = this.duration_sec * 1000;
const flow_cmt = new FlowComment(this.row_num, view_width, duration_msec);
const fragment = document.createDocumentFragment();
const row_h = this.area_size.height / this.row_num;
const params = this._createFlowParams(comments, flow_cmt, row_h, fragment);
this.parent_elm.appendChild(fragment);
this._createFlowTweenMax(params);
}
_createFlowTweenMax(params){
params.forEach((param)=>{
const { elm, left, delay } = param;
const id = elm.id;
this.timeLine.add(
gsap.to(`#${id}`, {
duration: this.duration_sec,
x: left,
display : "block",
ease: "none",
onComplete:()=>{
gsap.set(`#${id}`, {display : "none"});
}
}), delay);
});
}
/**
*
* @param {Array} top_comments
* @param {Array} bottom_comments
*/
_createFixedTL(top_comments, bottom_comments){
const fixed_top_cmt = new FixedComment(this.row_num);
fixed_top_cmt.createRowIndexMap(top_comments);
const fixed_bottom_cmt = new FixedComment(this.row_num);
fixed_bottom_cmt.createRowIndexMap(bottom_comments);
const row_h = this.area_size.height / this.row_num;
const fragment = document.createDocumentFragment();
const fixed_top_params = this._createFixedParams("ue", top_comments, fixed_top_cmt, row_h, fragment);
const fixed_bottom_params = this._createFixedParams("shita", bottom_comments, fixed_bottom_cmt, row_h, fragment);
const params = fixed_top_params.concat(fixed_bottom_params);
this.parent_elm.appendChild(fragment);
this._createFixedTweenMax(params);
}
_createFixedTweenMax(params){
params.forEach((param)=>{
const { elm, delay, duration } = param;
const id = elm.id;
this.timeLine.add(
gsap.to(`#${id}`, {
duration: duration,
alpha: 1,
display : "block",
onComplete:()=>{
gsap.set(`#${id}`, {display : "none"});
}
}) ,delay );
});
}
clear(){
if(this.enable!==true){
return;
}
if(!this.timeLine){
return;
}
this.timeLine.kill();
this.parent_elm.querySelectorAll(".comment").forEach(elm=>{
this.parent_elm.removeChild(elm);
});
this.timeLine = null;
this._paused = true;
}
play(){
if(this.enable!==true){
return;
}
this.timeLine.play();
this._paused = false;
}
pause(){
if(this.enable!==true){
return;
}
this.timeLine.pause();
this._paused = true;
}
seek(seek_sec){
if(seek_sec < this.lastTimeSec){
this._ended = false;
}else{
this._ended = true;
}
if(this.enable!==true){
return;
}
this.timeLine.time(seek_sec, false);
}
getCurrentTime(){
return this.timeLine.time();
}
_createCanvas(){
if(this.ctx){
return;
}
const canvas = document.createElement("canvas");
this.ctx = canvas.getContext("2d");
}
_getTextWidth(text, font_size){
this.ctx.font = `${font_size}px ${this.comment_font_family}`;
// 改行で分割して一番長いものを採用
const lens = text.split(/\r\n|\n/).map(ar=>{
return this.ctx.measureText(ar).width;
});
return Math.max(...lens);
}
_createElm(comment, fragment){
const elm = document.createElement("div");
elm.classList.add("comment");
// 半角空白が連続していたら一つにまとめられてしまうので
// 2個連続している半角空白を全角空白に置き換える
elm.innerText = comment.content.replace(/(\s)\1/g, "\u3000");
elm.style.display = "none";
elm.style.whiteSpace = "nowrap";
elm.style.position = "absolute";
fragment.appendChild(elm);
const view_height = this.area_size.height;
const view_width = this.area_size.width;
let font_size = Math.floor(view_height/20);
if(comment.font_size=="big"){
font_size = Math.floor(view_height/15);
}else if(comment.font_size=="small"){
font_size = Math.floor(view_height/25);
}
const text_width = this._getTextWidth(comment.content, font_size);
elm.style.fontSize = font_size + "px";
elm.style.left = view_width + "px";
elm.style.color = comment.color;
return {elm, text_width};
}
/**
*
* @param {Array} comments
* @param {FlowComment} flow_cmt
* @param {DocumentFragment} fragment
*/
_createFlowParams(comments, flow_cmt, row_h, fragment){
flow_cmt.createRowIndexMap(comments);
return comments.map((comment, index)=>{
const row_index = flow_cmt.getRowIndex(comment);
const { elm, text_width } =
this._createElm(comment, fragment);
const id = `flow-comment-id${index}`;
elm.id = id;
elm.classList.add("flow");
const margin = (row_h - parseInt(elm.style.fontSize)) / 2;
elm.style.top = (row_index * row_h + margin) + "px";
const left = -(this.area_size.width + text_width);
const delay = comment.vpos / 1000; //sec
return { elm, left, delay };
});
}
/**
*
* @param {String} pos_type
* @param {Array} comments
* @param {FixedComment} fixed_cmt
* @param {Number} row_h
* @param {DocumentFragment} fragment
*/
_createFixedParams(pos_type, comments, fixed_cmt, row_h, fragment){
return comments.map((comment, index)=>{
const row_index = fixed_cmt.getRowIndex(comment);
const { elm, text_width } =
this._createElm(comment, fragment);
const id = `fixed-${pos_type}-comment-id${index}`;
elm.id = id;
elm.classList.add("fixed");
const delay = comment.vpos / 1000; //sec
elm.style.left = (this.area_size.width / 2 - text_width / 2) + "px";
const duration = comment.duration / 1000; //sec
const margin = (row_h - parseInt(elm.style.fontSize)) / 2;
if(pos_type=="ue"){
elm.style.top = (row_index * row_h + margin) + "px";
}else if(pos_type=="shita"){
elm.style.top = ((this.row_num - row_index - 1) * row_h + margin) + "px";
}
return { elm, delay, duration };
});
}
/**
*
* @param {Array} comments
*/
_getEachComments(comments) {
const flow_comments = [];
const fixed_top_comments = [];
const fixed_bottom_comments = [];
// comments.sort((a, b) => {
// if (a.vpos < b.vpos) return -1;
// if (a.vpos > b.vpos) return 1;
// return 0;
// });
const cmt_opt_parser = new CommentOptionParser();
comments.forEach(comment=>{
const p = {
user_id:comment.user_id,
no:comment.no,
vpos:comment.vpos*10,
content:comment.content,
duration: this.duration_sec*1000
};
const opts = cmt_opt_parser.parse(comment.mail, comment.user_id);
Object.assign(p, opts);
if(p.type=="ue"){
fixed_top_comments.push(p);
}else if(p.type=="shita"){
fixed_bottom_comments.push(p);
}else{
flow_comments.push(p);
}
});
return [
flow_comments,
fixed_top_comments,
fixed_bottom_comments];
}
}
module.exports = {
CommentTimeLine,
CommentOptionParser,
NicoScript
}; |
<gh_stars>1-10
var _vina_like_scoring_function_8h =
[
[ "VinaLikeScoringFunction", "class_smol_dock_1_1_score_1_1_vina_like_scoring_function.html", "class_smol_dock_1_1_score_1_1_vina_like_scoring_function" ],
[ "VinaLikeIntermolecularScoringFunction", "_vina_like_scoring_function_8h.html#af7f12c4b8451b856342af3afdbcadce8", null ]
]; |
def sort_and_print_pairs(pairs):
final = {}
for pair in pairs:
final[pair[0]] = pair[1]
final = sorted(final.items())
for x in final:
print(x[0] + ',' + str(x[1]))
# Test the function with the given example
pairs = [["apple", 5], ["banana", 3], ["cherry", 7], ["date", 2]]
sort_and_print_pairs(pairs) |
package com.commerce.backend.validator;
import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class CustomEmailValidator implements ConstraintValidator<CustomEmail, String> {
private static final String EMAIL_PATTERN = "^[a-zA-Z0-9_!#$%&’*+/=?`{|}~^.-]+@[a-zA-Z0-9.-]+$";
private Pattern pattern;
private Matcher matcher;
@Override
public void initialize(CustomEmail constraintAnnotation) {
}
@Override
public boolean isValid(String email, ConstraintValidatorContext context) {
return (validateEmail(email));
}
private boolean validateEmail(String email) {
pattern = Pattern.compile(EMAIL_PATTERN);
matcher = pattern.matcher(email);
return matcher.matches();
}
} |
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = void 0;
var _zipkin = require("zipkin");
var zipkinRecordError = function zipkinRecordError(error, options) {
var instrumentation = new _zipkin.Instrumentation.HttpClient(options);
if (error.response) {
instrumentation.recordResponse(options.tracer.id, error.response.status);
} else {
instrumentation.recordError(options.tracer.id, error);
}
return Promise.reject(error);
};
var zipkinRecordRequest = function zipkinRecordRequest(config, options) {
var instrumentation = new _zipkin.Instrumentation.HttpClient(options);
return instrumentation.recordRequest(config, config.url, config.method);
};
var zipkinRecordResponse = function zipkinRecordResponse(res, options) {
var instrumentation = new _zipkin.Instrumentation.HttpClient(options);
instrumentation.recordResponse(options.tracer.id, res.status);
return res;
};
var wrapAxios = function wrapAxios(axios) {
var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
axios.interceptors.request.use(function (config) {
return zipkinRecordRequest(config, options);
}, function (err) {
return zipkinRecordError(err, options);
});
axios.interceptors.response.use(function (res) {
return zipkinRecordResponse(res, options);
}, function (err) {
return zipkinRecordError(err, options);
});
return axios;
};
var _default = wrapAxios;
exports.default = _default;
module.exports = exports.default; |
def is_anagram(str1, str2):
if sorted(str1.lower()) == sorted(str2.lower()):
return True
else:
return False
string1 = "anagram"
string2 = "nagaram"
print(is_anagram(string1, string2)) |
#!/bin/bash
# Copyright 2019 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
set -eo pipefail
shopt -s nullglob
## Get the directory of the build script
scriptDir=$(realpath $(dirname "${BASH_SOURCE[0]}"))
## cd to the parent directory, i.e. the root of the git repo
cd ${scriptDir}/..
# include common functions
source ${scriptDir}/common.sh
# Print out Java
java -version
echo $JOB_TYPE
function determineMavenOpts() {
local javaVersion=$(
# filter down to the version line, then pull out the version between quotes,
# then trim the version number down to its minimal number (removing any
# update or suffix number).
java -version 2>&1 | grep "version" \
| sed -E 's/^.*"(.*?)".*$/\1/g' \
| sed -E 's/^(1\.[0-9]\.0).*$/\1/g'
)
if [[ $javaVersion == 17* ]]
then
# MaxPermSize is no longer supported as of jdk 17
echo -n "-Xmx1024m"
else
echo -n "-Xmx1024m -XX:MaxPermSize=128m"
fi
}
export MAVEN_OPTS=$(determineMavenOpts)
# this should run maven enforcer
retry_with_backoff 3 10 \
mvn install -B -V -ntp \
-DskipTests=true \
-Dmaven.javadoc.skip=true \
-Dclirr.skip=true
mvn -B dependency:analyze -DfailOnWarning=true
echo "****************** DEPENDENCY LIST COMPLETENESS CHECK *******************"
## Run dependency list completeness check
function completenessCheck() {
# Output dep list with compile scope generated using the original pom
# Running mvn dependency:list on Java versions that support modules will also include the module of the dependency.
# This is stripped from the output as it is not present in the flattened pom.
# Only dependencies with 'compile' or 'runtime' scope are included from original dependency list.
msg "Generating dependency list using original pom..."
mvn dependency:list -f pom.xml -DexcludeArtifactIds=error_prone_annotations -DincludeScope=runtime -Dsort=true | grep '\[INFO] .*:.*:.*:.*:.*' | sed -e 's/ --.*//' >.org-list.txt
# Output dep list generated using the flattened pom (only 'compile' and 'runtime' scopes)
msg "Generating dependency list using flattened pom..."
mvn dependency:list -f .flattened-pom.xml -DexcludeArtifactIds=error_prone_annotations -DincludeScope=runtime -Dsort=true | grep '\[INFO] .*:.*:.*:.*:.*' >.new-list.txt
# Compare two dependency lists
msg "Comparing dependency lists..."
diff .org-list.txt .new-list.txt >.diff.txt
if [[ $? == 0 ]]
then
msg "Success. No diff!"
else
msg "Diff found. See below: "
msg "You can also check .diff.txt file located in $1."
cat .diff.txt
return 1
fi
}
# Allow failures to continue running the script
set +e
error_count=0
for path in **/.flattened-pom.xml
do
# Check flattened pom in each dir that contains it for completeness
dir=$(dirname "$path")
pushd "$dir"
completenessCheck "$dir"
error_count=$(($error_count + $?))
popd
done
if [[ $error_count == 0 ]]
then
msg "All checks passed."
exit 0
else
msg "Errors found. See log statements above."
exit 1
fi
|
MYSQL_VERSION="5.7.33-36"
MYSQL_SHA256SUM="964e32f4a1e235421e26be81d2d24f9e659d8ef3cbd9ae6c3e85fe545bedfd5b"
getpkg https://downloads.percona.com/downloads/Percona-Server-5.7/Percona-Server-${MYSQL_VERSION}/source/tarball/percona-server-${MYSQL_VERSION}.tar.gz $MYSQL_SHA256SUM
tar zxf percona-server-${MYSQL_VERSION}.tar.gz
LIBBOOST_VERSION="1.59.0"
LIBBOOST_SHA256SUM="47f11c8844e579d02691a607fbd32540104a9ac7a2534a8ddaef50daf502baac"
getpkg http://sourceforge.net/projects/boost/files/boost/${LIBBOOST_VERSION}/boost_${LIBBOOST_VERSION//./_}.tar.gz $LIBBOOST_SHA256SUM
tar zxf boost_${LIBBOOST_VERSION//./_}.tar.gz
mkdir -p $VENV/opt/mysql
cd percona-server-${MYSQL_VERSION}
cmake . \
-DCMAKE_INSTALL_PREFIX=$VENV/opt/mysql \
-DCMAKE_PREFIX_PATH=$VENV \
-DCMAKE_FIND_FRAMEWORK=LAST \
-DCMAKE_VERBOSE_MAKEFILE=ON \
-DMYSQL_DATADIR=$DATA_DIR/mysql \
-DWITH_SSL=system \
-DDEFAULT_CHARSET=utf8 \
-DDEFAULT_COLLATION=utf8_general_ci \
-DWITHOUT_TOKUDB=1 \
-DWITHOUT_ROCKSDB=1 \
-DWITH_UNIT_TESTS=OFF \
-DENABLED_LOCAL_INFILE=1 \
-DWITH_BOOST=$BUILD_DIR/boost_${LIBBOOST_VERSION//./_}
$PMAKE
make install
|
<reponame>smagill/opensphere-desktop
package io.opensphere.core.util.net;
import java.net.MalformedURLException;
import java.net.URL;
import org.junit.Test;
import org.junit.Assert;
/** Test for {@link URLEncodingUtilities}. */
public class URLEncodingUtilitiesTest
{
/**
* Test for {@link URLEncodingUtilities#encodeURL(URL)}.
*
* @throws MalformedURLException If the test URL cannot be encoded.
*/
@Test
public void testEncodeURL() throws MalformedURLException
{
URL input = new URL("http://www.blah.com:8080/something/getKml.pl?a=b>1&c=d#ref");
URL expected = new URL("http://www.blah.com:8080/something/getKml.pl?a=b%3E1&c=d#ref");
URL actual = URLEncodingUtilities.encodeURL(input);
Assert.assertEquals(expected.toString(), actual.toString());
}
/**
* Test for {@link URLEncodingUtilities#encodeURL(URL)}.
*
* @throws MalformedURLException If the test URL cannot be encoded.
*/
@Test
public void testEncodeURLNoQuery() throws MalformedURLException
{
URL input = new URL("http://www.blah.com:8080/something/getKml.pl#ref");
URL actual = URLEncodingUtilities.encodeURL(input);
Assert.assertEquals(input.toString(), actual.toString());
}
/** Test for {@link URLEncodingUtilities#encodeURL(URL)}. */
@Test
public void testEncodeURLNull()
{
Assert.assertNull(URLEncodingUtilities.encodeURL(null));
}
}
|
<filename>kernel/drivers/char/sunxi_g2d/g2d_driver.c
#include"g2d_driver_i.h"
#include<linux/g2d_driver.h>
#define G2D_BYTE_ALIGN(x) ( ( (x + (4*1024-1)) >> 12) << 12) /* alloc based on 4K byte */
static struct info_mem g2d_mem[MAX_G2D_MEM_INDEX];
static int g2d_mem_sel = 0;
static enum g2d_scan_order scan_order;
static struct mutex global_lock;
static struct class *g2d_class;
static struct cdev *g2d_cdev;
static dev_t devid ;
__g2d_drv_t g2d_ext_hd;
__g2d_info_t para;
#if !defined(CONFIG_OF)
static struct resource g2d_resource[2] =
{
[0] = {
.start = SUNXI_MP_PBASE,
.end = SUNXI_MP_PBASE + 0x000fffff,
.flags = IORESOURCE_MEM,
},
[1] = {
.start = INTC_IRQNO_DE_MIX,
.end = INTC_IRQNO_DE_MIX,
.flags = IORESOURCE_IRQ,
},
};
#endif
__s32 drv_g2d_init(void)
{
g2d_init_para init_para;
DBG("drv_g2d_init\n");
init_para.g2d_base = (__u32)para.io;
memset(&g2d_ext_hd, 0, sizeof(__g2d_drv_t));
init_waitqueue_head(&g2d_ext_hd.queue);
g2d_init(&init_para);
return 0;
}
void *g2d_malloc(__u32 bytes_num, __u32 *phy_addr)
{
void* address = NULL;
#if defined(CONFIG_ION_SUNXI)
u32 actual_bytes;
if (bytes_num != 0) {
actual_bytes = PAGE_ALIGN(bytes_num);
address = dma_alloc_coherent(para.dev, actual_bytes, (dma_addr_t*)phy_addr, GFP_KERNEL);
if (address) {
DBG("dma_alloc_coherent ok, address=0x%p, size=0x%x\n", (void*)(*(unsigned long*)phy_addr), bytes_num);
return address;
} else {
ERR("dma_alloc_coherent fail, size=0x%x\n", bytes_num);
return NULL;
}
} else {
ERR("%s size is zero\n", __func__);
}
#else
unsigned map_size = 0;
struct page *page;
if (bytes_num != 0) {
map_size = PAGE_ALIGN(bytes_num);
page = alloc_pages(GFP_KERNEL,get_order(map_size));
if (page != NULL) {
address = page_address(page);
if (NULL == address) {
free_pages((unsigned long)(page),get_order(map_size));
ERR("page_address fail!\n");
return NULL;
}
*phy_addr = virt_to_phys(address);
return address;
} else {
ERR("alloc_pages fail!\n");
return NULL;
}
} else {
ERR("%s size is zero\n", __func__);
}
#endif
return NULL;
}
void g2d_free(void *virt_addr, void *phy_addr, unsigned int size)
{
#if defined(CONFIG_ION_SUNXI)
u32 actual_bytes;
actual_bytes = PAGE_ALIGN(size);
if (phy_addr && virt_addr)
dma_free_coherent(para.dev, actual_bytes, virt_addr, (dma_addr_t)phy_addr);
#else
unsigned map_size = PAGE_ALIGN(size);
unsigned page_size = map_size;
if (NULL == virt_addr)
return ;
free_pages((unsigned long)virt_addr,get_order(page_size));
#endif
return ;
}
__s32 g2d_get_free_mem_index(void)
{
__u32 i = 0;
for(i=0; i<MAX_G2D_MEM_INDEX; i++)
{
if(g2d_mem[i].b_used == 0)
{
return i;
}
}
return -1;
}
int g2d_mem_request(__u32 size)
{
__s32 sel;
__u32 ret = 0;
__u32 phy_addr;
sel = g2d_get_free_mem_index();
if(sel < 0)
{
ERR("g2d_get_free_mem_index fail!\n");
return -EINVAL;
}
ret = (__u32)g2d_malloc(size,&phy_addr);
if(ret != 0)
{
g2d_mem[sel].virt_addr = (void*)ret;
memset(g2d_mem[sel].virt_addr,0,size);
g2d_mem[sel].phy_addr = phy_addr;
g2d_mem[sel].mem_len = size;
g2d_mem[sel].b_used = 1;
INFO("map_g2d_memory[%d]: pa=%08lx va=%p size:%x\n",sel,g2d_mem[sel].phy_addr, g2d_mem[sel].virt_addr, size);
return sel;
}
else
{
ERR("fail to alloc reserved memory!\n");
return -ENOMEM;
}
}
int g2d_mem_release(__u32 sel)
{
if(g2d_mem[sel].b_used == 0)
{
ERR("mem not used in g2d_mem_release,%d\n",sel);
return -EINVAL;
}
g2d_free((void *)g2d_mem[sel].virt_addr,(void *)g2d_mem[sel].phy_addr,g2d_mem[sel].mem_len);
memset(&g2d_mem[sel],0,sizeof(struct info_mem));
return 0;
}
int g2d_mmap(struct file *file, struct vm_area_struct * vma)
{
unsigned long mypfn = vma->vm_pgoff;
unsigned long vmsize = vma->vm_end-vma->vm_start;
vma->vm_pgoff = 0;
vma->vm_page_prot = pgprot_writecombine(vma->vm_page_prot);
if (remap_pfn_range(vma,vma->vm_start,mypfn,vmsize,vma->vm_page_prot))
return -EAGAIN;
return 0;
}
static int g2d_open(struct inode *inode, struct file *file)
{
mutex_lock(¶.mutex);
if (!para.opened) {
if (para.clk)
clk_prepare_enable(para.clk);
para.opened = true;
}
mutex_unlock(¶.mutex);
return 0;
}
static int g2d_release(struct inode *inode, struct file *file)
{
mutex_lock(¶.mutex);
if (para.opened) {
if (para.clk)
clk_disable(para.clk);
para.opened = false;
}
mutex_unlock(¶.mutex);
mutex_lock(&global_lock);
scan_order = G2D_SM_TDLR;
mutex_unlock(&global_lock);
return 0;
}
irqreturn_t g2d_handle_irq(int irq, void *dev_id)
{
__u32 mod_irq_flag,cmd_irq_flag;
mod_irq_flag = mixer_get_irq();
cmd_irq_flag = mixer_get_irq0();
if(mod_irq_flag & G2D_FINISH_IRQ)
{
mixer_clear_init();
g2d_ext_hd.finish_flag = 1;
wake_up(&g2d_ext_hd.queue);
}
else if(cmd_irq_flag & G2D_FINISH_IRQ)
{
mixer_clear_init0();
g2d_ext_hd.finish_flag = 1;
wake_up(&g2d_ext_hd.queue);
}
return IRQ_HANDLED;
}
int g2d_init(g2d_init_para *para)
{
mixer_set_reg_base(para->g2d_base);
return 0;
}
int g2d_exit(void)
{
__u8 err = 0;
return err;
}
int g2d_wait_cmd_finish(void)
{
long timeout = 100; /* 100ms */
timeout = wait_event_timeout(g2d_ext_hd.queue, g2d_ext_hd.finish_flag == 1, msecs_to_jiffies(timeout));
if(timeout == 0)
{
mixer_clear_init();
mixer_clear_init0();
pr_warn("wait g2d irq pending flag timeout\n");
g2d_ext_hd.finish_flag = 1;
wake_up(&g2d_ext_hd.queue);
return -1;
}
return 0;
}
int g2d_blit(g2d_blt * para)
{
__s32 err = 0;
__u32 tmp_w,tmp_h;
if ((para->flag & G2D_BLT_ROTATE90) || (para->flag & G2D_BLT_ROTATE270)){tmp_w = para->src_rect.h;tmp_h = para->src_rect.w;}
else {tmp_w = para->src_rect.w;tmp_h = para->src_rect.h;}
/* check the parameter valid */
if(((para->src_rect.x < 0)&&((-para->src_rect.x) > para->src_rect.w)) ||
((para->src_rect.y < 0)&&((-para->src_rect.y) > para->src_rect.h)) ||
((para->dst_x < 0)&&((-para->dst_x) > tmp_w)) ||
((para->dst_y < 0)&&((-para->dst_y) > tmp_h)) ||
((para->src_rect.x > 0)&&(para->src_rect.x > para->src_image.w - 1)) ||
((para->src_rect.y > 0)&&(para->src_rect.y > para->src_image.h - 1)) ||
((para->dst_x > 0)&&(para->dst_x > para->dst_image.w - 1)) ||
((para->dst_y > 0)&&(para->dst_y > para->dst_image.h - 1)))
{
printk("invalid blit parameter setting");
return -EINVAL;
}
else
{
if(((para->src_rect.x < 0)&&((-para->src_rect.x) < para->src_rect.w)))
{
para->src_rect.w = para->src_rect.w + para->src_rect.x;
para->src_rect.x = 0;
}
else if((para->src_rect.x + para->src_rect.w) > para->src_image.w)
{
para->src_rect.w = para->src_image.w - para->src_rect.x;
}
if(((para->src_rect.y < 0)&&((-para->src_rect.y) < para->src_rect.h)))
{
para->src_rect.h = para->src_rect.h + para->src_rect.y;
para->src_rect.y = 0;
}
else if((para->src_rect.y + para->src_rect.h) > para->src_image.h)
{
para->src_rect.h = para->src_image.h - para->src_rect.y;
}
if(((para->dst_x < 0)&&((-para->dst_x) < tmp_w)))
{
para->src_rect.w = tmp_w + para->dst_x;
para->src_rect.x = (-para->dst_x);
para->dst_x = 0;
}
else if((para->dst_x + tmp_w) > para->dst_image.w)
{
para->src_rect.w = para->dst_image.w - para->dst_x;
}
if(((para->dst_y < 0)&&((-para->dst_y) < tmp_h)))
{
para->src_rect.h = tmp_h + para->dst_y;
para->src_rect.y = (-para->dst_y);
para->dst_y = 0;
}
else if((para->dst_y + tmp_h) > para->dst_image.h)
{
para->src_rect.h = para->dst_image.h - para->dst_y;
}
}
g2d_ext_hd.finish_flag = 0;
/* Add support inverted order copy, however,
* hardware have a bug when reciving y coordinate,
* it use (y + height) rather than (y) on inverted
* order mode, so here adjust it before pass it to hardware.
*/
mutex_lock(&global_lock);
if (scan_order > G2D_SM_TDRL)
para->dst_y += para->src_rect.h;
mutex_unlock(&global_lock);
err = mixer_blt(para, scan_order);
return err;
}
int g2d_fill(g2d_fillrect * para)
{
__s32 err = 0;
/* check the parameter valid */
if(((para->dst_rect.x < 0)&&((-para->dst_rect.x)>para->dst_rect.w)) ||
((para->dst_rect.y < 0)&&((-para->dst_rect.y)>para->dst_rect.h)) ||
((para->dst_rect.x > 0)&&(para->dst_rect.x > para->dst_image.w - 1)) ||
((para->dst_rect.y > 0)&&(para->dst_rect.y > para->dst_image.h - 1)))
{
printk("invalid fillrect parameter setting");
return -EINVAL;
}
else
{
if(((para->dst_rect.x < 0)&&((-para->dst_rect.x) < para->dst_rect.w)))
{
para->dst_rect.w = para->dst_rect.w + para->dst_rect.x;
para->dst_rect.x = 0;
}
else if((para->dst_rect.x + para->dst_rect.w) > para->dst_image.w)
{
para->dst_rect.w = para->dst_image.w - para->dst_rect.x;
}
if(((para->dst_rect.y < 0)&&((-para->dst_rect.y) < para->dst_rect.h)))
{
para->dst_rect.h = para->dst_rect.h + para->dst_rect.y;
para->dst_rect.y = 0;
}
else if((para->dst_rect.y + para->dst_rect.h) > para->dst_image.h)
{
para->dst_rect.h = para->dst_image.h - para->dst_rect.y;
}
}
g2d_ext_hd.finish_flag = 0;
err = mixer_fillrectangle(para);
return err;
}
int g2d_stretchblit(g2d_stretchblt * para)
{
__s32 err = 0;
/* check the parameter valid */
if(((para->src_rect.x < 0)&&((-para->src_rect.x) > para->src_rect.w)) ||
((para->src_rect.y < 0)&&((-para->src_rect.y) > para->src_rect.h)) ||
((para->dst_rect.x < 0)&&((-para->dst_rect.x) > para->dst_rect.w)) ||
((para->dst_rect.y < 0)&&((-para->dst_rect.y) > para->dst_rect.h)) ||
((para->src_rect.x > 0)&&(para->src_rect.x > para->src_image.w - 1)) ||
((para->src_rect.y > 0)&&(para->src_rect.y > para->src_image.h - 1)) ||
((para->dst_rect.x > 0)&&(para->dst_rect.x > para->dst_image.w - 1)) ||
((para->dst_rect.y > 0)&&(para->dst_rect.y > para->dst_image.h - 1)))
{
printk("invalid stretchblit parameter setting");
return -EINVAL;
}
else
{
if(((para->src_rect.x < 0)&&((-para->src_rect.x) < para->src_rect.w)))
{
para->src_rect.w = para->src_rect.w + para->src_rect.x;
para->src_rect.x = 0;
}
else if((para->src_rect.x + para->src_rect.w) > para->src_image.w)
{
para->src_rect.w = para->src_image.w - para->src_rect.x;
}
if(((para->src_rect.y < 0)&&((-para->src_rect.y) < para->src_rect.h)))
{
para->src_rect.h = para->src_rect.h + para->src_rect.y;
para->src_rect.y = 0;
}
else if((para->src_rect.y + para->src_rect.h) > para->src_image.h)
{
para->src_rect.h = para->src_image.h - para->src_rect.y;
}
if(((para->dst_rect.x < 0)&&((-para->dst_rect.x) < para->dst_rect.w)))
{
para->dst_rect.w = para->dst_rect.w + para->dst_rect.x;
para->dst_rect.x = 0;
}
else if((para->dst_rect.x + para->dst_rect.w) > para->dst_image.w)
{
para->dst_rect.w = para->dst_image.w - para->dst_rect.x;
}
if(((para->dst_rect.y < 0)&&((-para->dst_rect.y) < para->dst_rect.h)))
{
para->dst_rect.h = para->dst_rect.h + para->dst_rect.y;
para->dst_rect.y = 0;
}
else if((para->dst_rect.y + para->dst_rect.h) > para->dst_image.h)
{
para->dst_rect.h = para->dst_image.h - para->dst_rect.y;
}
}
g2d_ext_hd.finish_flag = 0;
/* Add support inverted order copy, however,
* hardware have a bug when reciving y coordinate,
* it use (y + height) rather than (y) on inverted
* order mode, so here adjust it before pass it to hardware.
*/
mutex_lock(&global_lock);
if (scan_order > G2D_SM_TDRL)
para->dst_rect.y += para->src_rect.h;
mutex_unlock(&global_lock);
err = mixer_stretchblt(para, scan_order);
return err;
}
int g2d_set_palette_table(g2d_palette *para)
{
if((para->pbuffer == NULL) || (para->size < 0) || (para->size>1024))
{
printk("para invalid in mixer_set_palette\n");
return -1;
}
mixer_set_palette(para);
return 0;
}
int g2d_cmdq(unsigned int para)
{
__s32 err = 0;
g2d_ext_hd.finish_flag = 0;
err = mixer_cmdq(para);
return err;
}
long g2d_ioctl(struct file *file, unsigned int cmd, unsigned long arg)
{
__s32 ret = 0;
if(!mutex_trylock(¶.mutex)) {
mutex_lock(¶.mutex);
}
switch (cmd) {
/* Proceed to the operation */
case G2D_CMD_BITBLT:{
g2d_blt blit_para;
if(copy_from_user(&blit_para, (g2d_blt *)arg, sizeof(g2d_blt)))
{
kfree(&blit_para);
ret = -EFAULT;
goto err_noput;
}
ret = g2d_blit(&blit_para);
break;
}
case G2D_CMD_FILLRECT:{
g2d_fillrect fill_para;
if(copy_from_user(&fill_para, (g2d_fillrect *)arg, sizeof(g2d_fillrect)))
{
kfree(&fill_para);
ret = -EFAULT;
goto err_noput;
}
ret = g2d_fill(&fill_para);
break;
}
case G2D_CMD_STRETCHBLT:{
g2d_stretchblt stre_para;
if(copy_from_user(&stre_para, (g2d_stretchblt *)arg, sizeof(g2d_stretchblt)))
{
kfree(&stre_para);
ret = -EFAULT;
goto err_noput;
}
ret = g2d_stretchblit(&stre_para);
break;
}
case G2D_CMD_PALETTE_TBL:{
g2d_palette pale_para;
if(copy_from_user(&pale_para, (g2d_palette *)arg, sizeof(g2d_palette)))
{
kfree(&pale_para);
ret = -EFAULT;
goto err_noput;
}
ret = g2d_set_palette_table(&pale_para);
break;
}
case G2D_CMD_QUEUE:{
unsigned int cmdq_addr;
if(copy_from_user(&cmdq_addr, (unsigned int *)arg, sizeof(unsigned int)))
{
kfree(&cmdq_addr);
ret = -EFAULT;
goto err_noput;
}
ret = g2d_cmdq(cmdq_addr);
break;
}
/* just management memory for test */
case G2D_CMD_MEM_REQUEST:
ret = g2d_mem_request(arg);
break;
case G2D_CMD_MEM_RELEASE:
ret = g2d_mem_release(arg);
break;
case G2D_CMD_MEM_SELIDX:
g2d_mem_sel = arg;
break;
case G2D_CMD_MEM_GETADR:
if(g2d_mem[arg].b_used)
{
ret = g2d_mem[arg].phy_addr;
}
else
{
ERR("mem not used in G2D_CMD_MEM_GETADR\n");
ret = -1;
}
break;
case G2D_CMD_INVERTED_ORDER:
{
if (arg > G2D_SM_DTRL) {
ERR("scan mode is err.\n");
ret = -EINVAL;
goto err_noput;
}
mutex_lock(&global_lock);
scan_order = arg;
mutex_unlock(&global_lock);
break;
}
/* Invalid IOCTL call */
default:
return -EINVAL;
}
err_noput:
mutex_unlock(¶.mutex);
return ret;
}
static struct file_operations g2d_fops = {
.owner = THIS_MODULE,
.open = g2d_open,
.release = g2d_release,
.unlocked_ioctl = g2d_ioctl,
.mmap = g2d_mmap,
};
static int g2d_probe(struct platform_device *pdev)
{
#if !defined(CONFIG_OF)
int size;
struct resource *res;
#endif
int ret = 0;
__g2d_info_t *info = NULL;
info = ¶
info->dev = &pdev->dev;
platform_set_drvdata(pdev,info);
#if !defined(CONFIG_OF)
/* get the memory region */
res = platform_get_resource(pdev, IORESOURCE_MEM, 0);
if(res == NULL)
{
ERR("failed to get memory register\n");
ret = -ENXIO;
goto dealloc_fb;
}
size = (res->end - res->start) + 1;
/* map the memory */
info->io = ioremap(res->start, size);
if(info->io == NULL)
{
ERR("iormap() of register failed\n");
ret = -ENXIO;
goto dealloc_fb;
}
#else
info->io = of_iomap(pdev->dev.of_node, 0);
if(info->io == NULL)
{
ERR("iormap() of register failed\n");
ret = -ENXIO;
goto dealloc_fb;
}
#endif
#if !defined(CONFIG_OF)
/* get the irq */
res = platform_get_resource(pdev, IORESOURCE_IRQ, 0);
if(res == NULL)
{
ERR("failed to get irq resource\n");
ret = -ENXIO;
goto release_regs;
}
info->irq = res->start;
#else
info->irq = irq_of_parse_and_map(pdev->dev.of_node, 0);
if (!info->irq) {
ERR("irq_of_parse_and_map irq fail for transform\n");
ret = -ENXIO;
goto release_regs;
}
#endif
/* request the irq */
ret = request_irq(info->irq,g2d_handle_irq,0,dev_name(&pdev->dev),NULL);
if(ret)
{
ERR("failed to install irq resource\n");
goto release_regs;
}
#if defined(CONFIG_OF)
/* clk init */
info->clk = of_clk_get(pdev->dev.of_node, 0);
if (IS_ERR(info->clk)) {
ERR("fail to get clk\n");
}
#endif
drv_g2d_init();
mutex_init(&info->mutex);
mutex_init(&global_lock);
return 0;
release_regs:
#if !defined(CONFIG_OF)
iounmap(info->io);
#endif
dealloc_fb:
platform_set_drvdata(pdev, NULL);
return ret;
}
static int g2d_remove(struct platform_device *pdev)
{
__g2d_info_t *info = platform_get_drvdata(pdev);
free_irq(info->irq, NULL);
#if !defined(CONFIG_OF)
iounmap(info->io);
#endif
platform_set_drvdata(pdev, NULL);
INFO("Driver unloaded succesfully.\n");
return 0;
}
static int g2d_suspend(struct platform_device *pdev, pm_message_t state)
{
INFO("%s. \n", __func__);
mutex_lock(¶.mutex);
if (para.opened) {
if (para.clk)
clk_disable(para.clk);
}
mutex_unlock(¶.mutex);
INFO("g2d_suspend succesfully.\n");
return 0;
}
static int g2d_resume(struct platform_device *pdev)
{
INFO("%s. \n", __func__);
mutex_lock(¶.mutex);
if (para.opened) {
if (para.clk)
clk_prepare_enable(para.clk);
}
mutex_unlock(¶.mutex);
INFO("g2d_resume succesfully.\n");
return 0;
}
#if !defined(CONFIG_OF)
struct platform_device g2d_device =
{
.name = "g2d",
.id = -1,
.num_resources = ARRAY_SIZE(g2d_resource),
.resource = g2d_resource,
.dev =
{
},
};
#else
static const struct of_device_id sunxi_g2d_match[] = {
{ .compatible = "allwinner,sunxi-g2d", },
{},
};
#endif
static struct platform_driver g2d_driver = {
.probe = g2d_probe,
.remove = g2d_remove,
.suspend = g2d_suspend,
.resume = g2d_resume,
.suspend = NULL,
.resume = NULL,
.driver =
{
.owner = THIS_MODULE,
.name = "g2d",
.of_match_table = sunxi_g2d_match,
},
};
int __init g2d_module_init(void)
{
int ret = 0, err;
alloc_chrdev_region(&devid, 0, 1, "g2d_chrdev");
g2d_cdev = cdev_alloc();
cdev_init(g2d_cdev, &g2d_fops);
g2d_cdev->owner = THIS_MODULE;
err = cdev_add(g2d_cdev, devid, 1);
if (err)
{
ERR("I was assigned major number %d.\n", MAJOR(devid));
return -1;
}
g2d_class = class_create(THIS_MODULE, "g2d_class");
if (IS_ERR(g2d_class))
{
ERR("create class error\n");
return -1;
}
device_create(g2d_class, NULL, devid, NULL, "g2d");
#if !defined(CONFIG_OF)
ret = platform_device_register(&g2d_device);
#endif
if (ret == 0)
{
ret = platform_driver_register(&g2d_driver);
}
INFO("Module initialized.major:%d\n", MAJOR(devid));
return ret;
}
static void __exit g2d_module_exit(void)
{
INFO("g2d_module_exit\n");
kfree(g2d_ext_hd.g2d_finished_sem);
platform_driver_unregister(&g2d_driver);
#if !defined(CONFIG_OF)
platform_device_unregister(&g2d_device);
#endif
device_destroy(g2d_class, devid);
class_destroy(g2d_class);
cdev_del(g2d_cdev);
}
module_init(g2d_module_init);
module_exit(g2d_module_exit);
MODULE_AUTHOR("yupu_tang");
MODULE_AUTHOR("tyle <<EMAIL>>");
MODULE_DESCRIPTION("g2d driver");
MODULE_LICENSE("GPL");
MODULE_ALIAS("platform:g2d");
|
import CodeInput from 'components/atoms/Common/CodeInput/CodeInput'
export default {
name: 'ConfirmCode',
components: {
CodeInput
},
data () {
return {
title: 'Confirm'
}
},
methods: {
onFill (isFill) {
if (isFill) {
this.eventHub.$emit('enabledNextButton')
} else {
this.eventHub.$emit('disabledNextButton')
}
}
}
}
|
<filename>src/routes/CommunitySettings/DeleteSettingsTab/DeleteSettingsTab.test.js<gh_stars>0
import DeleteSettingsTab from './DeleteSettingsTab'
import { shallow } from 'enzyme'
import React from 'react'
it('renders correctly', () => {
const community = {
id: 1,
name: 'Hylo'
}
const wrapper = shallow(<DeleteSettingsTab
community={community}
deleteCommunity={() => {}}
/>)
expect(wrapper).toMatchSnapshot()
})
|
<reponame>Zac-Garby/Radon
package compiler
import (
"bytes"
"errors"
"fmt"
"reflect"
"github.com/Zac-Garby/radon/ast"
"github.com/Zac-Garby/radon/bytecode"
"github.com/Zac-Garby/radon/object"
)
// CompileExpression takes an AST expression and generates some bytecode
// for it.
func (c *Compiler) CompileExpression(e ast.Expression) error {
switch node := e.(type) {
case *ast.Number:
return c.compileNumber(node)
case *ast.String:
return c.compileString(node)
case *ast.Boolean:
return c.compileBoolean(node)
case *ast.Nil:
return c.compileNil(node)
case *ast.Identifier:
return c.compileIdentifier(node)
case *ast.Infix:
return c.compileInfix(node)
case *ast.Prefix:
return c.compilePrefix(node)
case *ast.If:
return c.compileIf(node)
case *ast.List:
return c.compileList(node)
case *ast.Map:
return c.compileMap(node)
case *ast.Call:
return c.compileCall(node)
case *ast.Block:
return c.compileBlock(node)
case *ast.Match:
return c.compileMatch(node)
default:
return fmt.Errorf("compiler: compilation not yet implemented for %s", reflect.TypeOf(e))
}
}
func (c *Compiler) compileNumber(node *ast.Number) error {
_, err := c.addAndLoad(&object.Number{Value: node.Value})
return err
}
func (c *Compiler) compileString(node *ast.String) error {
_, err := c.addAndLoad(&object.String{Value: node.Value})
return err
}
func (c *Compiler) compileBoolean(node *ast.Boolean) error {
_, err := c.addAndLoad(&object.Boolean{Value: node.Value})
return err
}
func (c *Compiler) compileNil(node *ast.Nil) error {
_, err := c.addAndLoad(&object.Nil{})
return err
}
func (c *Compiler) compileIdentifier(node *ast.Identifier) error {
return c.compileName(node.Value)
}
func (c *Compiler) compileInfix(node *ast.Infix) error {
left, right := node.Left, node.Right
// Some operators are handled differently
switch node.Operator {
case "=":
return c.compileAssignOrDeclare(left, right, "assign")
case ":=":
return c.compileAssignOrDeclare(left, right, "declare")
case ".":
return c.compileDot(left, right)
case ",":
return c.compileCommaInfix(left, right)
}
if err := c.CompileExpression(left); err != nil {
return err
}
if err := c.CompileExpression(right); err != nil {
return err
}
op, ok := map[string]byte{
"+": bytecode.BinaryAdd,
"-": bytecode.BinarySub,
"*": bytecode.BinaryMul,
"/": bytecode.BinaryDiv,
"^": bytecode.BinaryExp,
"//": bytecode.BinaryFloorDiv,
"%": bytecode.BinaryMod,
"||": bytecode.BinaryLogicOr,
"&&": bytecode.BinaryLogicAnd,
"|": bytecode.BinaryBitOr,
"&": bytecode.BinaryBitAnd,
"==": bytecode.BinaryEqual,
"!=": bytecode.BinaryNotEqual,
"<": bytecode.BinaryLess,
">": bytecode.BinaryMod,
"<=": bytecode.BinaryLessEq,
">=": bytecode.BinaryMoreEq,
}[node.Operator]
if !ok {
return fmt.Errorf("compiler: operator %s not yet implemented", node.Operator)
}
c.push(op)
return nil
}
func (c *Compiler) compileCommaInfix(left, right ast.Expression) error {
if left == nil || right == nil {
c.addAndLoad(&object.Tuple{})
return nil
}
if err := c.CompileExpression(left); err != nil {
return err
}
if err := c.CompileExpression(right); err != nil {
return err
}
c.push(bytecode.BinaryTuple)
return nil
}
func (c *Compiler) compileDot(left, right ast.Expression) error {
if err := c.CompileExpression(left); err != nil {
return err
}
if id, ok := right.(*ast.Identifier); ok {
index, err := c.addConst(&object.String{Value: id.Value})
if err != nil {
return err
}
c.loadConst(index)
} else {
return errors.New("compiler: expected an identifier to the right of a dot (.)")
}
c.push(bytecode.LoadSubscript)
return nil
}
func (c *Compiler) compileAssignOrDeclare(l, right ast.Expression, t string) error {
switch left := l.(type) {
case *ast.Identifier:
return c.compileAssignToIdent(left, right, t)
case *ast.Call:
if list, ok := left.Argument.(*ast.List); ok {
if len(list.Value) != 1 {
return fmt.Errorf("compiler: exactly one element should be present in an index assignment: a[b] = c")
}
return c.compileAssignToIndex(left.Function, list.Value[0], right, t)
}
return c.compileAssignToFunction(left, right, t)
}
return nil
}
func (c *Compiler) compileAssignToIdent(ident *ast.Identifier, right ast.Expression, t string) error {
if err := c.CompileExpression(right); err != nil {
return err
}
index, err := c.addName(ident.Value)
if err != nil {
return err
}
low, high := runeToBytes(rune(index))
if t == "assign" {
c.push(bytecode.StoreName, high, low)
} else {
c.push(bytecode.DeclareName, high, low)
}
return nil
}
func (c *Compiler) compileAssignToIndex(obj, idx, val ast.Expression, t string) error {
if t != "assign" {
return errors.New("compiler: cannot declare to a subscript[expression], use an assignment instead: a[b] = c")
}
if err := c.CompileExpression(val); err != nil {
return err
}
if err := c.CompileExpression(obj); err != nil {
return err
}
if err := c.CompileExpression(idx); err != nil {
return err
}
c.push(bytecode.StoreSubscript)
return nil
}
func (c *Compiler) compileAssignToFunction(function *ast.Call, body ast.Expression, t string) error {
fn := &object.Function{}
params, err := c.getParameterList(function.Argument)
if err != nil {
return err
}
fn.Parameters = params
// Compile the function body in a new Compiler instance
subCompiler := New()
subCompiler.CompileExpression(body)
code, err := bytecode.Read(bytes.NewReader(subCompiler.Bytes))
if err != nil {
return err
}
fn.Code = code
fn.Constants = subCompiler.Constants
fn.Names = subCompiler.Names
fn.Jumps = subCompiler.Jumps
c.addAndLoad(fn)
switch name := function.Function.(type) {
case *ast.Identifier:
index, err := c.addName(name.Value)
if err != nil {
return err
}
low, high := runeToBytes(rune(index))
if t == "assign" {
c.push(bytecode.StoreName, high, low)
} else {
c.push(bytecode.DeclareName, high, low)
}
case *ast.Infix:
if t != "assign" {
return errors.New("compiler: cannot declare a function to a subscript expression, use an assignment instead: a.b <params> = <body>")
}
if name.Operator != "." {
return errors.New("compiler: can only define functions as identifiers or model methods")
}
if err := c.CompileExpression(name.Left); err != nil {
return err
}
if id, ok := name.Right.(*ast.Identifier); ok {
c.addAndLoad(&object.String{Value: id.Value})
} else {
return errors.New("compiler: expected an identifier to the right of a dot (.)")
}
c.push(bytecode.StoreSubscript)
default:
return errors.New("compiler: can only define functions as identifiers or model methods")
}
return nil
}
func (c *Compiler) compilePrefix(node *ast.Prefix) error {
if err := c.CompileExpression(node.Right); err != nil {
return err
}
if node.Operator == "+" {
return nil
}
op := map[string]byte{
"-": bytecode.UnaryNegate,
"!": bytecode.UnaryInvert,
",": bytecode.UnaryTuple,
}[node.Operator]
c.push(op)
return nil
}
func (c *Compiler) compileIf(node *ast.If) error {
if err := c.CompileExpression(node.Condition); err != nil {
return err
}
// JumpIfFalse followed by two empty bytes for the argument
c.push(bytecode.JumpUnless, 0, 0)
condJump := len(c.Bytes) - 3
c.pushScope()
if err := c.CompileExpression(node.Consequence); err != nil {
return err
}
var skipJump int
if node.Alternative != nil {
// Jump past the alternative
c.push(bytecode.Jump, 0, 0)
skipJump = len(c.Bytes) - 3
}
c.popScope()
// Set the jump target after the conditional
c.setJumpArg(condJump, len(c.Bytes)+1)
if node.Alternative != nil {
c.pushScope()
if err := c.CompileExpression(node.Alternative); err != nil {
return err
}
c.popScope()
}
// Set the jump target after a dummy byte
c.push(bytecode.Nop)
c.setJumpArg(skipJump, len(c.Bytes))
return nil
}
func (c *Compiler) compileList(node *ast.List) error {
for _, elem := range node.Value {
if err := c.CompileExpression(elem); err != nil {
return err
}
}
low, high := runeToBytes(rune(len(node.Value)))
c.push(bytecode.MakeList, high, low)
return nil
}
func (c *Compiler) compileMap(node *ast.Map) error {
for key, val := range node.Value {
if err := c.CompileExpression(key); err != nil {
return err
}
if err := c.CompileExpression(val); err != nil {
return err
}
}
low, high := runeToBytes(rune(len(node.Value)))
c.push(bytecode.MakeMap, high, low)
return nil
}
func (c *Compiler) compileCall(node *ast.Call) error {
var args []ast.Expression
if tupInf, ok := node.Argument.(*ast.Infix); ok && tupInf.Operator == "," {
args = c.expandTuple(tupInf)
} else {
args = []ast.Expression{node.Argument}
}
// Iterate arguments in reverse order
for i := len(args) - 1; i >= 0; i-- {
if err := c.CompileExpression(args[i]); err != nil {
return err
}
}
if err := c.CompileExpression(node.Function); err != nil {
return err
}
low, high := runeToBytes(rune(len(args)))
c.push(bytecode.CallFunction, high, low)
return nil
}
func (c *Compiler) compileBlock(node *ast.Block) error {
c.pushScope()
defer c.popScope()
for _, stmt := range node.Value {
if err := c.CompileStatement(stmt); err != nil {
return err
}
}
return nil
}
func (c *Compiler) compileMatch(node *ast.Match) error {
c.pushScope()
defer c.popScope()
if err := c.CompileExpression(node.Input); err != nil {
return err
}
c.push(bytecode.StartMatch)
var wildcard ast.Expression
for _, branch := range node.Branches {
if id, ok := branch.Condition.(*ast.Identifier); ok && id.Value == "_" {
if wildcard != nil {
return errors.New("compiler: only one wildcard branch is permitted per match-expression")
}
wildcard = branch.Body
continue
}
if err := c.CompileExpression(branch.Condition); err != nil {
return err
}
c.push(bytecode.StartBranch)
if err := c.CompileExpression(branch.Body); err != nil {
return err
}
c.push(bytecode.EndBranch)
}
if wildcard == nil {
c.addAndLoad(&object.Nil{})
} else {
if err := c.CompileExpression(wildcard); err != nil {
return err
}
}
c.push(bytecode.EndMatch)
return nil
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.