language
stringclasses
15 values
src_encoding
stringclasses
34 values
length_bytes
int64
6
7.85M
score
float64
1.5
5.69
int_score
int64
2
5
detected_licenses
listlengths
0
160
license_type
stringclasses
2 values
text
stringlengths
9
7.85M
Shell
UTF-8
52,730
3.625
4
[]
no_license
#!/bin/bash # //////////////////////////////////////////////////////////////////////////// # # # # description : install, uninstall # # create Date : 2014/10/14 # # Author : w00241627 # # Since : Foundation PaaS V100R001C00 # # # # Copyright (c) Huawei Technologies Co., Ltd. 2013-2014. All rights reserved. # # # # //////////////////////////////////////////////////////////////////////////// # # //////////////////////////////////////////////////////////////////////////// # # # # Global Variables # # # # //////////////////////////////////////////////////////////////////////////// # USERID=`id -u` UTILITY="$0" UTILITY_NAME=${UTILITY##*/} USERNAME=`whoami` RESULT_OK=0 RESULT_ERROR=1 PARAMETER_ERROR=2 USER_REJECTED=3 BUILD_ERROR=6 DATE=$(date +%Y%m%d) ROOTPATH=$(cd "$(dirname "$0")"; pwd) LOG_FILE_PATH="$ROOTPATH/../systemlog/$DATE" LOG_FILE="$LOG_FILE_PATH/uninstall_temp.log" HOST_IP=`LANG=C ifconfig eth0 | awk '/inet addr:/{ print $2 }' | awk -F: '{print $2 }'` # The default system log for shell # //////////////////////////////////////////////////////////////////////////// # # # # Display Function # # # # //////////////////////////////////////////////////////////////////////////// # # status flags for display FTAG="\033[31;49;1mFAILURE\033[0m" STAG="\033[32;49;1mSUCCESS\033[0m" RTAG="\033[33;49;1mRunning\033[0m" sTAG="\033[36;49msuccess\033[0m" fTAG="\033[35;49mfailure\033[0m" # **************************************************************************** # # Function : print_help # Description : show the help message of this script # Parameter : none # Return : none # Since : Foundation PaaS V100R001C00 # Others : # **************************************************************************** # function print_help() { echo -e " $UTILITY_NAME is a UTILITY to install/uninstall and start/stop topus server. Usage: $UTILITY_NAME install [-v] $UTILITY_NAME uninstall [-v] $UTILITY_NAME start [-v] [-m primary/standby] $UTILITY_NAME stop [-v] $UTILITY_NAME status Common options: -m, --mode start mode -v, --verbose more verbose marginal on marginal errors. -V, --version output version information, then exit. -?, --help show this help info, then exit. " } # **************************************************************************** # # Function : print_verbose # Description : show the information if verbose is set # Parameter : $1 -- information # Return : none # Since : Foundation PaaS V100R001C00 # Others : # **************************************************************************** # function print_verbose() { information="$1" if [ -n "$information" ] && [ "$verbose" = "-v" ]; then echo -e "$information" fi } # **************************************************************************** # # Function : print_progress # Description : print progress # Parameter : $1 - current step index # $2 - total step num # Return : none # Since : Foundation PaaS V100R001C00 # Others : w00241627 # **************************************************************************** # function print_progress() { len=${#1} if [ $len -eq 1 ]; then echo -e "[\033[33;49;1m step $1 of $2 \033[0m] $3 ..." else echo -e "[\033[33;49;1m step $1 of $2 \033[0m] $3 ..." fi } # **************************************************************************** # # Function : print_log_to_screen # Description : print_log_to_screen # Parameter : $1 - detail process you want to display # $2 - status flag (can be empty) # Return : none # Since : Foundation PaaS V100R001C00 # Others : w00241627 # **************************************************************************** # function print_log_to_screen() { if [ "$2" = "" ]; then black_str=" \c" str_len=${#1} echo -e "+ $1${black_str:$str_len}" else black_str=" $2" str_len=${#1} echo -e "+ $1${black_str:$str_len}" fi } # **************************************************************************** # # Function : central_print # Description : print a string centrally in giving length # Parameter : $1 - string length # $2 - string length # Return : none # Since : Foundation PaaS V100R001C00 # Others : w00241627 # **************************************************************************** # function central_print() { local black_str=" " local str_len=${#2} local tmp_len=`expr $1 - $str_len` local pre_len=`expr $tmp_len / 2` local sub_len=`expr $str_len + $pre_len` black_str=${black_str:0:$1} echo -e "${black_str:0:$pre_len}$2${black_str:$sub_len}\c" } function print_ip() { echo -e "|\c" central_print 20 "$1" echo -e "|\c" central_print 20 "$2" echo -e "|" } # **************************************************************************** # # Function : print_title # Description : print_title # Parameter : $1 - title string you want to display # Return : none # Since : Foundation PaaS V100R001C00 # Others : w00241627 # **************************************************************************** # function print_title() { central_str=`central_print 70 "$1"` echo -e " ------------------------------------------------------------------------ |$central_str| ------------------------------------------------------------------------ " } # **************************************************************************** # # Function : check_port # Description : check_port # Parameter : $1 - appname # $2 - port # $3 - retrying in TIMER seconds # $4 - HOST # Return : none # Since : Foundation PaaS V100R001C00 # Others : # **************************************************************************** # function check_port { APP=$1 PORT=$2 TIMER=$3 HOST=$4 for i in {1..24} do echo -ne "checking whether ${APP} port ${PORT} is opened on ${HOST:-localhost}..." >> $LOG_FILE_PATH/install_temp.log netstat -anp|grep ${PORT} if [ $? -eq 0 ]; then echo "${APP} port ${PORT} is opened" >> $LOG_FILE_PATH/install_temp.log return else echo "WARNING: ${APP} port ${PORT} is closed, retrying in ${TIMER:-5} seconds ($i)" >> $LOG_FILE_PATH/install_temp.log sleep ${TIMER:-5} fi done echo "${APP} port ${PORT} is closed!" >> $LOG_FILE_PATH/install_temp.log } function install_salt() { salt_root=/var/paas/packages/package/$version/salt cd $salt_root tar -zvxf salt.tar.gz salt_packages=(dctrl-tools_2.23ubuntu1_amd64.deb libgmp10_5.0.2+dfsg-2ubuntu1_amd64.deb libpgm-5.1-0_5.1.118-1~dfsg-0.1ubuntu3_amd64.deb libzmq3_4.0.4+dfsg-2_amd64.deb python-zmq_14.0.1-1build2_amd64.deb python-crypto_2.6.1-4build1_amd64.deb python-markupsafe_0.18-1build2_amd64.deb python-m2crypto_0.21.1-3ubuntu5_amd64.deb python-msgpack_0.3.0-1ubuntu3_amd64.deb python-jinja2_2.7.2-2_all.deb python-dateutil_1.5+dfsg-1ubuntu1_all.deb python-croniter_0.3.4-0ubuntu1_all.deb libyaml-0-2_0.1.4-3ubuntu3.1_amd64.deb python-yaml_3.10-4ubuntu0.1_amd64.deb salt-common_2015.5.3+ds-1trusty1_all.deb) for i in "${!salt_packages[@]}";do if test -f salt-install/${salt_packages[$i]};then sudo dpkg -i salt-install/${salt_packages[$i]} if [ $? -ne 0 ];then exit $RESULT_ERROR fi else exit $RESULT_ERROR fi done if test -f salt-install/salt-master_2015.5.3+ds-1trusty1_all.deb;then result=$(sudo dpkg -i salt-install/salt-master_2015.5.3+ds-1trusty1_all.deb) if [ $? -ne 0 ]; then echo -e "$fTAG:$result" return $RESULT_ERROR fi fi rm -rf salt-install sleep 5 sudo service salt-master stop pkill salt-master sudo chown -R paas:paas /etc/salt if [ ! -d /var/paas/sys/cache/salt ];then mkdir -p /var/paas/sys/cache/salt fi if [ ! -d /var/paas/sys/log/salt ];then mkdir -p /var/paas/sys/log/salt fi if [ ! -d /var/paas/sys/run/salt ];then mkdir -p /var/paas/sys/run/salt fi sudo chown -R paas:paas /var/paas/sys chmod -R 750 /var/paas/sys cat > /etc/salt/master.d/master.conf << EOF file_roots: paas-iam: - /var/paas/paas-iam/saltstack/salt/states - /var/paas/paas-iam/release - /var/paas - /home/paas paas-iam-dev: - /var/paas/paas-iam/saltstack/salt/states cloudify: - /var/paas/cloudify/saltstack/salt/states - /var/paas/cloudify/release - /etc - /var/paas - /home/paas cloudify-dev: - /var/paas/cloudify/saltstack/salt/states - /var/paas/cloudify/saltstack/salt/states/paas-common cde: - /var/paas/cde/saltstack/salt/states - /var/paas/cde/release - /etc - /var/paas - /home/paas cde-dev: - /var/paas/cde/saltstack/salt/states - /var/paas/cde/saltstack/salt/states/paas-common cce: - /var/paas/cce/saltstack/salt/states - /var/paas/cce/release - /etc - /var/paas - /home/paas cce-dev: - /var/paas/cce/saltstack/salt/states - /var/paas/cce/saltstack/salt/states/paas-common cae: - /var/paas/cae/saltstack/salt/states - /var/paas/cae/release - /etc - /var/paas - /home/paas cae-dev: - /var/paas/cae/saltstack/salt/states - /var/paas/cae/saltstack/salt/states/paas-common common: - /var/paas/common/saltstack/salt/states - /var/paas/common/release - /var/paas - /home/paas common-dev: - /var/paas/common/saltstack/salt/states - /var/paas/common/saltstack/salt/states/paas-common servicemgr: - /var/paas/servicemgr/saltstack/salt/states - /var/paas/servicemgr/release - /var/paas - /home/paas servicemgr-dev: - /var/paas/servicemgr/saltstack/salt/states ops-salt: - /var/paas/ops/saltstack/salt/states - /var/paas/ops/release - /var/paas - /home/paas - /etc ops-dev: - /var/paas/ops/saltstack/salt/states/ - /var/paas/ops/saltstack/salt/states/paas-common om-salt: - /var/paas/om/saltstack/salt/states - /var/paas/om/release - /var/paas - /home/paas - /etc om-dev: - /var/paas/om/saltstack/salt/states/ - /var/paas/om/saltstack/salt/states/paas-common presetservices: - /var/paas/presetservices/saltstack/salt/states - /var/paas/presetservices/release - /var/paas presetservices-dev: - /var/paas/presetservices/saltstack/salt/states docker-hub: - /var/paas/docker-hub/saltstack/salt/states - /var/paas/docker-hub/release - /var/paas - /home/paas - /etc docker-hub-dev: - /var/paas/docker-hub/saltstack/salt/states/ - /var/paas/docker-hub/saltstack/salt/states/paas-common pillar_roots: paas-iam: - /var/paas/paas-iam/saltstack/salt/pillar paas-iam-dev: - /var/paas/paas-iam/saltstack/salt/pillar cloudify: - /var/paas/cloudify/saltstack/salt/pillar cloudify-dev: - /var/paas/cloudify/saltstack/salt/pillar cde: - /var/paas/cde/saltstack/salt/pillar cde-dev: - /var/paas/cde/saltstack/salt/pillar cce: - /var/paas/cce/saltstack/salt/pillar cce-dev: - /var/paas/cce/saltstack/salt/pillar common: - /var/paas/common/saltstack/salt/pillar common-dev: - /var/paas/common/saltstack/salt/pillar cae: - /var/paas/cae/saltstack/salt/pillar cae-dev: - /var/paas/cae/saltstack/salt/pillar servicemgr: - /var/paas/servicemgr/saltstack/salt/pillar servicemgr-dev: - /var/paas/servicemgr/saltstack/salt/pillar ops-salt: - /var/paas/ops/saltstack/salt/pillar ops-dev: - /var/paas/ops/saltstack/salt/pillar om-salt: - /var/paas/om/saltstack/salt/pillar om-dev: - /var/paas/om/saltstack/salt/pillar presetservices: - /var/paas/presetservices/saltstack/salt/pillar docker-hub: - /var/paas/docker-hub/saltstack/salt/pillar docker-hub-dev: - /var/paas/docker-hub/saltstack/salt/pillar state_events: True user: paas failhard: True auto_accept: True worker_threads: 20 publish_port: 5001 ret_port: 5002 log_file: /var/paas/sys/log/salt/master key_logfile: /var/paas/sys/log/salt/key log_level: warning log_level_logfile: warning timeout: 20 gather_job_timeout: 20 pidfile: /var/paas/sys/run/salt/master.pid sock_dir: /var/paas/sys/run/salt/master cachedir: /var/paas/sys/cache/salt/master EOF if [ -f /etc/logrotate.d/salt-common ]; then sudo sed -i "s|\/var\/log\/salt|\/var\/paas\/sys\/log\/salt|g" /etc/logrotate.d/salt-common fi sudo service salt-master start chmod g-wx,o-rwx -R /var/paas/sys/cache/salt chmod g-wx,o-rwx -R /var/paas/sys/run/salt chmod 640 /var/paas/sys/log/salt/* sudo rm -rf /var/log/salt sudo rm -rf /var/run/salt sudo rm -rf /var/cache/salt return $RESULT_OK } function uninstall_salt() { sudo service salt-master stop pkill salt-master sudo dpkg -P salt-master salt_packages=(salt-common python-croniter python-dateutil python-jinja2 python-msgpack python-m2crypto python-markupsafe python-crypto python-zmq libzmq3 libpgm-5.1-0 libgmp10 dctrl-tools) for i in ${salt_packages[@]};do sudo dpkg -P ${i} done rm -rf /etc/salt/* rm -rf /var/paas/sys/cache/salt rm -rf /var/paas/sys/run/salt rm -rf /var/paas/sys/log/salt return $RESULT_OK } function saltcloud_install() { salt_root=/var/paas/packages/package/$version/salt cd $salt_root tar zxvf salt-cloud.tar.gz cd salt-cloud sudo pip install apache-libcloud-0.14.1.tar.gz if [ $? -ne 0 ];then return $RESULT_ERROR fi sudo dpkg -i *.deb if [ $? -ne 0 ];then return $RESULT_ERROR fi rm -rf $salt_root/salt-cloud sudo chown paas:paas -R /etc/salt return $RESULT_OK } function saltcloud_uninstall() { sudo pip uninstall --yes apache-libcloud salt_packages=(salt-cloud python-libcloud python-lockfile python-netaddr python-simplejson) for i in ${salt_packages[@]};do sudo dpkg -P ${i} done return $RESULT_OK } function install_expect() { dpkg -l |grep expect >> /dev/null 2>&1 if [ $? -ne 0 ]; then cp /var/paas/packages/package/$version/common/expect.tar.gz $ROOTPATH/ cd $ROOTPATH/ tar zxvf expect.tar.gz >> /dev/null 2>&1 result=$(sudo dpkg -i tcl8.5_8.5.11-1ubuntu1_amd64.deb) if [ $? -ne 0 ]; then print_log_to_screen "install deb $line" "$fTAG: $result" return $RESULT_ERROR fi result=$(sudo dpkg -i expect_5.45-2_amd64.deb) if [ $? -ne 0 ]; then print_log_to_screen "install deb $line" "$fTAG: $result" return $RESULT_ERROR fi rm -rf $ROOTPATH/expect_5.45-2_amd64.deb rm -rf $ROOTPATH/tcl8.5_8.5.11-1ubuntu1_amd64.deb rm -rf $ROOTPATH/expect.tar.gz fi } # **************************************************************************** # # Function : create_http_service # Description : create_http_service # Parameter : $1 - title string you want to display # Return : none # Since : Foundation PaaS V100R001C00 # Others : w00241627 # **************************************************************************** # function install() { if [ ! -f $ROOTPATH/monit_done ]; then if [ "$mode" = "" ] || [ "$mode" = "monit" ]; then install_monit >>$LOG_FILE_PATH/install_temp.log 2>&1 if [ $? -ne 0 ] ; then print_log_to_screen "install monit" "$fTAG" return $RESULT_ERROR fi print_log_to_screen "install monit" "$sTAG" touch $ROOTPATH/monit_done fi fi if [ ! -f $ROOTPATH/manager_done ]; then if [ "$mode" = "" ] || [ "$mode" = "manager" ]; then install_manager >>$LOG_FILE_PATH/install_temp.log 2>&1 if [ $? -ne 0 ] ; then print_log_to_screen "install manager" "$fTAG" return $RESULT_ERROR fi print_log_to_screen "install manager" "$sTAG" touch $ROOTPATH/manager_done fi fi if [ ! -f $ROOTPATH/mysql_done ]; then if [ "$mode" = "" ] || [ "$mode" = "mysql" ]; then install_mysql >>$LOG_FILE_PATH/install_temp.log 2>&1 if [ $? -ne 0 ] ; then print_log_to_screen "install mysql" "$fTAG" return $RESULT_ERROR fi print_log_to_screen "install mysql" "$sTAG" touch $ROOTPATH/mysql_done fi fi if [ ! -f $ROOTPATH/etcd_done ]; then if [ "$mode" = "" ] || [ "$mode" = "etcd" ]; then install_etcd >>$LOG_FILE_PATH/install_temp.log 2>&1 if [ $? -ne 0 ] ; then print_log_to_screen "install etcd" "$fTAG" return $RESULT_ERROR fi print_log_to_screen "install etcd" "$sTAG" touch $ROOTPATH/etcd_done fi fi if [ ! -f $ROOTPATH/skydns_done ]; then if [ "$mode" = "" ] || [ "$mode" = "skydns" ]; then install_skydns >>$LOG_FILE_PATH/install_temp.log 2>&1 if [ $? -ne 0 ] ; then print_log_to_screen "install skydns" "$fTAG" return $RESULT_ERROR fi print_log_to_screen "install skydns" "$sTAG" touch $ROOTPATH/skydns_done fi fi if [ ! -f $ROOTPATH/deploy_rest_server_done ]; then if [ "$mode" = "" ] || [ "$mode" = "deploy_rest_server" ]; then install_deploy_rest_server >>$LOG_FILE_PATH/install_temp.log 2>&1 if [ $? -ne 0 ] ; then print_log_to_screen "install deploy_rest_server" "$fTAG" return $RESULT_ERROR fi print_log_to_screen "install deploy_rest_server" "$sTAG" touch $ROOTPATH/deploy_rest_server_done fi fi if [ ! -f $ROOTPATH/salt_done ]; then if [ "$mode" = "" ] || [ "$mode" = "salt" ]; then install_salt >>$LOG_FILE_PATH/install_temp.log 2>&1 saltcloud_install >>$LOG_FILE_PATH/install_temp.log 2>&1 if [ $? -ne 0 ] ; then print_log_to_screen "install salt" "$fTAG" return $RESULT_ERROR fi print_log_to_screen "install salt" "$sTAG" touch $ROOTPATH/salt_done fi fi if [ "`which expect`" = "" ]; then install_expect >> /dev/null 2>&1 fi conf_logrotate >> /dev/null 2>&1 modify_permission >> /dev/null 2>&1 return $RESULT_OK } function modify_permission() { sudo chmod g-wx,o-rwx -R /var/paas/cloudify/ sudo chmod g-wx,o-rwx -R /var/paas/deploy_rest_server/ sudo chmod g-wx,o-rwx -R /var/paas/scripts sudo chmod g-wx,o-rwx -R /var/paas/sys/ sudo chmod g-wx,o-rwx -R /var/paas/components/ sudo chmod g-wx,o-rwx -R $ROOTPATH/../ chmod g-wx,o-rwx -R /home/paas/bootstrap chmod g-wx,o-rwx -R /var/paas/bootstrap sudo chmod g-rwx,o-rwx /etc/ssh/sshd_config } function conf_logrotate() { #add log rotate crontab job BOOTSTRAP_ROOT=/var/paas/bootstrap mkdir -p -m 750 $BOOTSTRAP_ROOT/logrotate touch $BOOTSTRAP_ROOT/logrotate/logrotate.conf chmod 640 $BOOTSTRAP_ROOT/logrotate/logrotate.conf cat > $BOOTSTRAP_ROOT/logrotate/logrotate.conf <<EOF /var/paas/*.log /var/paas/monit/*.log /var/paas/sys/log/mysql/*.log /var/paas/sys/log/*.log /var/paas/sys/log/deploy_rest_server/*.log /var/paas/deploy_rest_server/*.log /var/paas/deploy_rest_server/policybootstrap/*.log /var/paas/sys/log/nginx/*.log /var/paas/sys/log/cloudify/*.log /var/paas/sys/log/monit/*.log /var/paas/sys/log/skydns/*.log { missingok rotate 20 compress copytruncate notifempty size 50M } EOF touch $BOOTSTRAP_ROOT/logrotate/crontab.conf chmod 640 $BOOTSTRAP_ROOT/logrotate/crontab.conf sudo crontab -u root -l > $BOOTSTRAP_ROOT/logrotate/crontab.conf if [ `cat $BOOTSTRAP_ROOT/logrotate/crontab.conf|grep -c "$BOOTSTRAP_ROOT/logrotate/logrotate.conf"` == 0 ];then cat >> $BOOTSTRAP_ROOT/logrotate/crontab.conf <<EOF 45 * * * * su paas -c "/usr/sbin/logrotate $BOOTSTRAP_ROOT/logrotate/logrotate.conf 2>/dev/null" EOF fi #start logrotate crontab job sudo crontab -u root $BOOTSTRAP_ROOT/logrotate/crontab.conf } function install_monit() { rm -rf /var/paas/monit/opsmgr-plugin rm -rf /var/paas/monit/opsmgr-plugin.zip sudo dpkg -i /var/paas/packages/spec/ops_mgr/opsmgr-plugin/unzip_6.0-9ubuntu1.3_amd64.deb mkdir -p /var/paas/monit cp /var/paas/packages/spec/ops_mgr/opsmgr-plugin/opsmgr-plugin.zip /var/paas/monit cd /var/paas/monit unzip opsmgr-plugin.zip cd /var/paas/monit/opsmgr-plugin/monit/install tar zxf monit_runit_agent.tar.gz cd /var/paas/monit/opsmgr-plugin/monit/install/monit_runit_agent/runit sudo dpkg -i runit_2.1.1-6.2ubuntu3_amd64_trusty.deb sudo mkdir -p /etc/sv/monit sudo cp /var/paas/monit/opsmgr-plugin/monit/install/monit/run /etc/sv/monit/run sudo chmod +x /etc/sv/monit/run cd /var/paas/monit/opsmgr-plugin/monit/install/monit_runit_agent/monit mkdir -p /var/paas/monit/bin cp monit /var/paas/monit/bin mkdir -p /var/paas/monit/etc sudo chmod -R 750 /var/paas/monit cp monitrc /var/paas/monit/etc sudo chmod 0700 /var/paas/monit/etc/monitrc sudo ln -s /etc/sv/monit/ /etc/service/monit rm -rf /var/paas/monit/opsmgr-plugin rm -rf /var/paas/monit/opsmgr-plugin.zip # fetch monit-related files. utils_path="/var/paas/scripts/utils" if [ ! -d ${utils_path} ]; then mkdir -p ${utils_path} cp $ROOTPATH/monitfile/utils/* ${utils_path} chmod -R 750 ${utils_path} chmod 700 ${utils_path}/* fi cd $ROOTPATH } function install_deploy_rest_server() { if [ -f $ROOTPATH/deploy_rest_server/config/deploy_rest_server.env ]; then source $ROOTPATH/deploy_rest_server/config/deploy_rest_server.env fi mysql_root=/var/paas/mysql mkdir -p /var/paas/sys/log deploy_rest_server_root=/var/paas/deploy_rest_server if [ ! -d "$deploy_rest_server_root" ]; then mkdir -p $deploy_rest_server_root fi # fetch monit-related files. utils_path="/var/paas/scripts/utils" if [ ! -d ${utils_path} ]; then mkdir -p ${utils_path} cp $ROOTPATH/monitfile/utils/* ${utils_path} chmod 750 -R ${utils_path} chmod 700 ${utils_path}/* fi deploy_rest_server_ctl_path="/var/paas/jobs/deploy_rest_server/bin" mkdir -p ${deploy_rest_server_ctl_path} cp $ROOTPATH/monitfile/deploy_rest_server/deploy_rest_server_ctl ${deploy_rest_server_ctl_path} chmod 750 -R /var/paas/jobs/deploy_rest_server chmod 700 ${deploy_rest_server_ctl_path}/* deploy_rest_server_monitrc_path="/var/paas/monit/job" if [ ! -d ${deploy_rest_server_monitrc_path} ]; then mkdir -p ${deploy_rest_server_monitrc_path} chmod 750 -R ${deploy_rest_server_monitrc_path} fi cp $ROOTPATH/monitfile/deploy_rest_server/deploy_rest_server.monitrc ${deploy_rest_server_monitrc_path} chmod 640 ${deploy_rest_server_monitrc_path}/* NIC="eth0" HOST_IP=`LANG=C ifconfig $NIC | awk '/inet addr:/{ print $2 }' | awk -F: '{print $2 }'` deploy_rest_server_monitrc=${deploy_rest_server_monitrc_path}/deploy_rest_server.monitrc mkdir -p ${deploy_rest_server_root}/conf/ cp /var/paas/packages/package/$version/deploy_mgr/deploy-rest-server.tgz $deploy_rest_server_root cd $deploy_rest_server_root tar -zxf deploy-rest-server.tgz export LD_LIBRARY_PATH=${deploy_rest_server_root}/oracle/instantclient_12_1:$LD_LIBRARY_PATH cp $ROOTPATH/deploy_rest_server/config/app.conf ${deploy_rest_server_root}/conf/ cd $deploy_rest_server_root sudo dpkg -i ${deploy_rest_server_root}/oracle/*.deb ip=$(echo "$httpservice" | awk -F ':' '{print $1}') CONF_PATH=${deploy_rest_server_root}/conf/app.conf mysqlsource="$mysql_deploymgrdb_user:$mysql_deploymgrdb_password@tcp($ip:$mysql_port)/dmdb?charset=utf8" datasource_encrypt=`/var/paas/crypto_tool -text $mysqlsource` if [ $? -ne 0 ];then exit 1 fi cf_admin_account_password_encrypt=`/var/paas/crypto_tool -text $cf_admin_account_password` if [ $? -ne 0 ];then exit 1 fi sed -i "s|{httpport}|8031|g" ${CONF_PATH} sed -i "s|{httpaddr}|$HOST_IP|g" ${CONF_PATH} sed -i "s|{httpport}|8031|g" ${deploy_rest_server_monitrc} sed -i "s|{httpaddr}|$HOST_IP|g" ${deploy_rest_server_monitrc} sed -i "s|{datasource}|$datasource_encrypt|g" ${CONF_PATH} sed -i "s|{cfy_api_endpoint}|$ip:8100|g" ${CONF_PATH} sed -i "s|{policyengine_endpoint}|$paas_om_ops_endpoint|g" ${CONF_PATH} sed -i "s|{policyengine_template_path}|${deploy_rest_server_root}|g" ${CONF_PATH} sed -i "s|{cf_admin_account_password}|$cf_admin_account_password_encrypt|g" ${CONF_PATH} sed -i "s|{ObjectClass}|PaaS_Component|g" ${deploy_rest_server_root}/conf/policytemplate.json chmod g-wx,o-rwx -R /var/paas/deploy_rest_server/ /var/paas/jobs/deploy_rest_server/bin/deploy_rest_server_ctl start sleep 1 /var/paas/monit/bin/monit reload sleep 1 #policy syn config set,when paas component deploy finish run this policybootstrap cd $deploy_rest_server_root mkdir -p ${deploy_rest_server_root}/policybootstrap mv policybootstrap.tgz ${deploy_rest_server_root}/policybootstrap cd ${deploy_rest_server_root}/policybootstrap tar -zxf policybootstrap.tgz datasource="$mysql_deploymgrdb_user:$mysql_deploymgrdb_password@tcp($ip:$mysql_port)/dmdb?charset=utf8" datasource=`/var/paas/crypto_tool -text $datasource` CONF_PATH=${deploy_rest_server_root}/policybootstrap/conf/config.json sed -i "s|{policyEngineHost}|$paas_om_ops_endpoint|g" ${CONF_PATH} sed -i "s|{datasource}|$datasource|g" ${CONF_PATH} sed -i "s|{sqldriver}|mysql|g" ${CONF_PATH} sed -i "s|{templateConfigPath}|${deploy_rest_server_root}/policybootstrap/conf|g" ${CONF_PATH} sed -i "s|{ObjectClass}|PaaS_Component|g" ${deploy_rest_server_root}/policybootstrap/conf/policytemplate.json rm policybootstrap.tgz rm -rf $deploy_rest_server_root/deploy-rest-server.tgz return $RESULT_OK } function install_mysql() { PACKAGE_DIR=/var/vcap/packages/mysql RUN_DIR=/var/vcap/sys/run/mysql LOG_DIR=/var/vcap/sys/log/mysql TMP_DIR=$PACKAGE_DIR/tmp DATA_DIR=/var/vcap/store/mysql LOG_BIN_DIR=/var/vcap/store/mysql-logs CHROOT_DIR=${mysql_chroot_dir}/mysql CHROOT_PACKAGE_DIR=${CHROOT_DIR}${PACKAGE_DIR} CHROOT_RUN_DIR=${CHROOT_DIR}${RUN_DIR} CHROOT_LOG_DIR=${CHROOT_DIR}${LOG_DIR} CHROOT_TMP_DIR=$CHROOT_PACKAGE_DIR/tmp CHROOT_DATA_DIR=${CHROOT_DIR}${DATA_DIR} CHROOT_LOG_BIN_DIR=${CHROOT_DIR}${LOG_BIN_DIR} # create dir if [ ! -d /var/vcap ]; then sudo ln -s /var/paas /var/vcap fi mkdir -p ${PACKAGE_DIR} ${PACKAGE_DIR}/config mkdir -p ${TMP_DIR} cp /var/paas/packages/package/$version/common/mysql_dependency.tgz ${PACKAGE_DIR} cp /var/paas/packages/package/$version/common/mysql.tgz ${PACKAGE_DIR} pushd ${PACKAGE_DIR} tar -xzf mysql_dependency.tgz sudo dpkg -i libaio1_0.3.109-4_amd64.deb tar -xzf mysql.tgz tar xzf mysql.tar.gz -C $PACKAGE_DIR rm mysql.tgz mysql.tar.gz mysql_dependency.tgz libaio1_0.3.109-4_amd64.deb mv audit_log.so $PACKAGE_DIR/lib/plugin popd cp $ROOTPATH/mysql/config/* ${PACKAGE_DIR}/config sed -i "s|{mysql_port}|$mysql_port|g" ${PACKAGE_DIR}/config/my-default.cnf sed -i "s|<%= mysql.chroot_dir %>|${mysql_chroot_dir}|g" ${PACKAGE_DIR}/config/my-default.cnf NIC="eth0" HOST_IP=`LANG=C ifconfig $NIC | awk '/inet addr:/{ print $2 }' | awk -F: '{print $2 }'` sudo sed -i "s|<%= bindaddress %>|$HOST_IP|g" ${PACKAGE_DIR}/config/my-default.cnf sudo sed -i "s/^user =.*/user=${mysql_user}/g" ${PACKAGE_DIR}/config/my-default.cnf sed -i 's|umask 007|umask 077 \nexport UMASK=0600 \nexport UMASK_DIR=0700|g' ${PACKAGE_DIR}/bin/mysqld_safe # interactive and wait timeout sed -i "s|<%= mysql_wait_timeout %>|$mysql_wait_timeout|g" ${PACKAGE_DIR}/config/my-default.cnf sed -i "s|<%= mysql_interactive_timeout %>|$mysql_interactive_timeout|g" ${PACKAGE_DIR}/config/my-default.cnf # Innodb log file sed -i "s|<%= innodb_log_file_size %>|$innodb_log_file_size|g" ${PACKAGE_DIR}/config/my-default.cnf sed -i "s|<%= expire_logs_days %>|$expire_logs_days|g" ${PACKAGE_DIR}/config/my-default.cnf # Audit_Log Configuration sed -i "s|<%= audit_log_policy %>|$audit_log_policy|g" ${PACKAGE_DIR}/config/my-default.cnf sed -i "s|<%= audit_log_format %>|$audit_log_format|g" ${PACKAGE_DIR}/config/my-default.cnf sed -i "s|<%= audit_log_file %>|$audit_log_file|g" ${PACKAGE_DIR}/config/my-default.cnf sed -i "s|<%= audit_log_rotate_on_size %>|$audit_log_rotate_on_size|g" ${PACKAGE_DIR}/config/my-default.cnf sed -i "s|<%= audit_log_rotations %>|$audit_log_rotations|g" ${PACKAGE_DIR}/config/my-default.cnf cp -f ${PACKAGE_DIR}/config/my-default.cnf ${PACKAGE_DIR}/support-files cp -f ${PACKAGE_DIR}/config/my-default.cnf ${PACKAGE_DIR}/my.cnf chmod 600 $PACKAGE_DIR/my.cnf #update mysql_init sed -i "s|<%= mysql_max_queries_per_hour %>|$mysql_max_queries_per_hour|g" ${PACKAGE_DIR}/config/mysql_init sed -i "s|<%= mysql_max_updates_per_hour %>|$mysql_max_updates_per_hour|g" ${PACKAGE_DIR}/config/mysql_init sed -i "s|<%= mysql_max_connections_per_hour %>|$mysql_max_connections_per_hour|g" ${PACKAGE_DIR}/config/mysql_init sed -i "s|<%= mysql_max_user_connections %>|$mysql_max_user_connections|g" ${PACKAGE_DIR}/config/mysql_init sed -i "s|<%= mysql_admin_username %>|$mysql_admin_username|g" ${PACKAGE_DIR}/config/mysql_init sed -i "s|<%= mysql_admin_password %>|$mysql_admin_password|g" ${PACKAGE_DIR}/config/mysql_init sed -i "s|<%= mysql_deploymgrdb_user %>|$mysql_deploymgrdb_user|g" ${PACKAGE_DIR}/config/mysql_init sed -i "s|<%= mysql_deploymgrdb_name %>|$mysql_deploymgrdb_name|g" ${PACKAGE_DIR}/config/mysql_init sed -i "s|<%= mysql_deploymgrdb_password %>|$mysql_deploymgrdb_password|g" ${PACKAGE_DIR}/config/mysql_init sed -i "s|<%= mysql_eventbusdb_user %>|$mysql_eventbusdb_user|g" ${PACKAGE_DIR}/config/mysql_init sed -i "s|<%= mysql_eventbusdb_name %>|$mysql_eventbusdb_name|g" ${PACKAGE_DIR}/config/mysql_init sed -i "s|<%= mysql_eventbusdb_password %>|$mysql_eventbusdb_password|g" ${PACKAGE_DIR}/config/mysql_init sed -i "s|<%= mysql_ip %>|$HOST_IP|g" ${PACKAGE_DIR}/config/mysql_init sed -i "s|<%= om_ops_ip %>|$paas_om_ops_endpoint|g" ${PACKAGE_DIR}/config/mysql_init sudo rm -rf /etc/mysql/ mysql_ctl_path="/var/paas/jobs/mysql/bin" mkdir -p ${mysql_ctl_path} cp $ROOTPATH/monitfile/mysql/mysql_ctl ${mysql_ctl_path} chmod -R 750 ${mysql_ctl_path} chmod -R 750 ${mysql_ctl_path}/../ if [ "${mysql_user}" != "paas" ]; then sudo useradd -r -g paas -m -s /usr/sbin/nologin ${mysql_user} -p $(echo "${mysql_user_passwd}" | openssl passwd -1 -stdin) fi sudo sed -i "s/^mysql_user=.*/mysql_user=${mysql_user}/g" /var/paas/jobs/mysql/bin/mysql_ctl sudo sed -i "s|^CHROOT_DIR=.*|CHROOT_DIR=${mysql_chroot_dir}/mysql|g" /var/paas/jobs/mysql/bin/mysql_ctl mysql_monitrc_path="/var/paas/monit/job" if [ ! -d ${mysql_monitrc_path} ]; then mkdir -p ${mysql_monitrc_path} chmod -R 750 ${mysql_monitrc_path} fi cp $ROOTPATH/monitfile/mysql/mysql.monitrc ${mysql_monitrc_path} sed -i "s|<%= mysql.chroot_dir %>|${mysql_chroot_dir}|g" ${mysql_monitrc_path}/mysql.monitrc chmod 640 ${mysql_monitrc_path}/* # setup chroot environment sudo mkdir -p $CHROOT_DIR sudo chown -R paas:paas ${mysql_chroot_dir} pushd ${CHROOT_DIR} > /dev/null mkdir -p etc mkdir -p $CHROOT_PACKAGE_DIR $CHROOT_RUN_DIR $CHROOT_LOG_DIR $CHROOT_DATA_DIR $CHROOT_TMP_DIR $CHROOT_LOG_BIN_DIR cp /etc/localtime etc echo "127.0.0.1 localhost" > etc/hosts grep "^${mysql_user}:" /etc/passwd > etc/passwd # for reading etc/passwd and etc/hosts mkdir -p lib sudo cp `sudo find /lib/ -name libnss_compat.so.2` lib/ sudo cp `sudo find /lib/ -name libnss_files.so.2` lib/ sudo chown -R paas:paas lib sudo mv $PACKAGE_DIR/* $CHROOT_PACKAGE_DIR popd > /dev/null rm -rf $PACKAGE_DIR ${CHROOT_PACKAGE_DIR}/scripts/mysql_install_db --user=${mysql_user} --tmpdir=${CHROOT_TMP_DIR} --basedir=${CHROOT_PACKAGE_DIR} --datadir=${CHROOT_DATA_DIR} chmod g-rwx,o-rwx -R ${CHROOT_DIR}/var/vcap/* sleep 2 # sudo sed -i "s|/var/vcap/packages|/var/paas/mysql|g" $CHROOT_PACKAGE_DIR/support-files/mysql.server # sed -i 's|\[mysqld\]|[mysqld]\nsecure_auth=1\nskip-symbolic-links=1\nlocal-infile = 0\nsafe-user-create = 1\n|g' $PACKAGE_DIR/my.cnf # update file permissions chmod -R o-rwx,g-rwx ${CHROOT_DATA_DIR} echo "export PATH=\$PATH:${CHROOT_PACKAGE_DIR}/bin" >> ~/.profile sudo chown -R ${mysql_user}:paas ${mysql_chroot_dir} sudo chmod 750 ${mysql_chroot_dir} sudo chmod 0750 ${CHROOT_DIR}/var/vcap/store sudo chmod 700 $CHROOT_DATA_DIR sudo chmod 700 $CHROOT_LOG_BIN_DIR sudo chmod -R 700 $CHROOT_PACKAGE_DIR sudo chmod 0750 ${CHROOT_DIR} sudo chmod 0750 ${CHROOT_DIR}/var sudo chmod 0750 ${CHROOT_DIR}/var/vcap sudo chmod 0750 ${CHROOT_DIR}/var/vcap/packages sudo chmod 0750 ${CHROOT_DIR}/var/vcap/packages/mysql sudo chmod -R 0750 ${CHROOT_DIR}/var/vcap/sys if [ "x$MYSQL_HISTFILE" == "x" ];then sudo sh -c " echo 'export MYSQL_HISTFILE=/dev/null'>>/etc/profile" sudo sh -c " source /etc/profile" fi bash /var/paas/jobs/mysql/bin/mysql_ctl start sleep 10 /var/paas/monit/bin/monit reload APP="mysql" PORT=$mysql_port TIMER=10 for i in {1..24} do echo -ne "checking whether ${APP} port ${PORT} is opened on ${HOST_IP:-localhost}..." >> $LOG_FILE_PATH/install_temp.log netstat -anp |grep ${PORT} >/dev/null if [ $? -eq 0 ]; then echo "${APP} port ${PORT} is opened" >> $LOG_FILE_PATH/install_temp.log break else echo "WARNING: ${APP} port ${PORT} is closed, retrying in ${TIMER:-5} seconds ($i)" >> $LOG_FILE_PATH/install_temp.log sleep ${TIMER:-5} fi done netstat -anp |grep $mysql_port if [ $? -eq 0 ]; then sudo sed -i '1,$d' ${CHROOT_PACKAGE_DIR}/config/mysql_init sudo sed -i '1,$d' ${CHROOT_PACKAGE_DIR}/bin/mysqlaccess.conf else echo "mysql start up failed" >> $LOG_FILE_PATH/install_temp.log sudo sed -i '1,$d' ${CHROOT_PACKAGE_DIR}/config/mysql_init sudo sed -i '1,$d' ${CHROOT_PACKAGE_DIR}/bin/mysqlaccess.conf exit fi #chmod 700 $CHROOT_PACKAGE_DIR/mysqld.sock return $RESULT_OK } function install_etcd() { PACKAGE_DIR=/var/paas/etcd mkdir -p ${PACKAGE_DIR} cp /var/paas/packages/package/$version/common/etcd.tgz ${PACKAGE_DIR} cd ${PACKAGE_DIR} tar xzf etcd.tgz -C $PACKAGE_DIR tar zxf package.tgz -C $PACKAGE_DIR rm *.tgz ETCD_CTL_DIR=/var/paas/jobs/etcd/bin mkdir -p ${ETCD_CTL_DIR} cp $ROOTPATH/monitfile/etcd/etcd_ctl ${ETCD_CTL_DIR} sed -i "s|<%= SINGLE_ETCD_IP %>|$HOST_IP|g" ${ETCD_CTL_DIR}/etcd_ctl chmod -R 750 ${ETCD_CTL_DIR} chmod 700 ${ETCD_CTL_DIR}/* etcd_monitrc_path="/var/paas/monit/job" mkdir -p ${etcd_monitrc_path} chmod -R 750 ${etcd_monitrc_path} cp $ROOTPATH/monitfile/etcd/etcd.monitrc ${etcd_monitrc_path} chmod 640 ${etcd_monitrc_path}/* export UMASK=0600 export UMASK_DIR=0700 bash /var/paas/jobs/etcd/bin/etcd_ctl start sleep 1 /var/paas/monit/bin/monit reload netstat -anp |grep 5678 if [ $? != 0 ]; then echo "etcd start up failed" >> $LOG_FILE_PATH/install_temp.log exit fi return $RESULT_OK } # skydns depends on etcd function install_skydns() { PACKAGE_DIR=/var/paas/skydns/bin mkdir -p ${PACKAGE_DIR} cp /var/paas/packages/package/$version/common/skydns.tar.gz ${PACKAGE_DIR} cd ${PACKAGE_DIR} tar xzf skydns.tar.gz -C $PACKAGE_DIR rm skydns.tar.gz skydns_ctl_dir=/var/paas/jobs/skydns/bin mkdir -p ${skydns_ctl_dir} cp $ROOTPATH/monitfile/skydns/skydns_ctl ${skydns_ctl_dir} cp $ROOTPATH/monitfile/skydns/init.sh ${skydns_ctl_dir} sed -i "s|<%= SINGLE_ETCD_IP %>|$HOST_IP|g" ${skydns_ctl_dir}/skydns_ctl sed -i "s|<%= SINGLE_ETCD_IP %>|$HOST_IP|g" ${skydns_ctl_dir}/init.sh sed -i "s|<%= SKYDNS_IP %>|$HOST_IP|g" ${skydns_ctl_dir}/init.sh sed -i "s|<%= NAMESERVER_IP %>|$nameserver_ip|g" ${skydns_ctl_dir}/init.sh chmod -R 750 ${skydns_ctl_dir} chmod 700 ${skydns_ctl_dir}/* skydns_monitrc_path="/var/paas/monit/job" mkdir -p ${skydns_monitrc_path} chmod -R 750 ${skydns_monitrc_path} cp $ROOTPATH/monitfile/skydns/skydns.monitrc ${skydns_monitrc_path} sed -i "s|<%= SKYDNS_IP %>|$HOST_IP|g" ${skydns_monitrc_path}/skydns.monitrc chmod 640 ${skydns_monitrc_path}/* export UMASK=0600 export UMASK_DIR=0700 bash /var/paas/jobs/skydns/bin/init.sh bash /var/paas/jobs/skydns/bin/skydns_ctl start sleep 1 /var/paas/monit/bin/monit reload netstat -anp |grep 53 if [ $? != 0 ]; then echo "skydns start up failed" >> $LOG_FILE_PATH/install_temp.log exit fi return $RESULT_OK } function start_monit_celery() { celery_ctl_path=/var/paas/jobs/celery/cloudify.management__worker/env/bin if [ ! -d ${celery_ctl_path} ]; then mkdir -p ${celery_ctl_path} chmod -R 750 ${celery_ctl_path} fi cp $ROOTPATH/monitfile/celery/celery_ctl ${celery_ctl_path} chmod -R 750 ${celery_ctl_path} chmod 700 ${celery_ctl_path}/* celery_monitrc_path="/var/paas/monit/job" if [ ! -d ${celery_monitrc_path} ]; then mkdir -p ${celery_monitrc_path} chmod -R 750 ${celery_monitrc_path} fi cp $ROOTPATH/monitfile/celery/celery.monitrc ${celery_monitrc_path} chmod 640 ${celery_monitrc_path}/* /var/paas/jobs/celery/cloudify.management__worker/env/bin/celery_ctl stop sleep 1 /var/paas/jobs/celery/cloudify.management__worker/env/bin/celery_ctl start sleep 1 /var/paas/monit/bin/monit reload } function install_nginx() { echo -ne "install nginx..." sudo mkdir -p /var/log/nginx sudo mkdir -p /var/cache/nginx sudo mkdir -p /var/paas/jobs/nginx/ sudo mkdir -p /var/paas/sys/run/nginx sudo mkdir -p /var/paas/sys/log/nginx result=$(sudo dpkg -i /var/paas/packages/package/$version/cloudify/nginx.deb) if [ $? -ne 0 ]; then print_log_to_screen "install components" "$fTAG:$result" return $RESULT_ERROR fi HOST_IP=`LANG=C ifconfig eth0 | awk '/inet addr:/{ print $2 }' | awk -F: '{print $2 }'` echo -e "applying nginx config..." sudo cp $ROOTPATH/nginx/config/nginx.conf /etc/nginx/nginx.conf sudo cp $ROOTPATH/nginx/config/default.conf /etc/nginx/conf.d sudo sed -i "s/*:7777/$HOST_IP:7777/g" /etc/nginx/conf.d/default.conf sudo cp /etc/init.d/nginx /var/paas/jobs/nginx/nginx_server sudo sed -i "s|/var/run|/var/paas/sys/run/nginx|" /var/paas/jobs/nginx/nginx_server sudo update-rc.d -f nginx remove sudo /etc/init.d/nginx stop rm -rf /etc/init/nginx.conf rm -rf /etc/init.d/nginx echo -e "starting nginx..." sudo chown paas:paas -R /var/cache/nginx sudo chown paas:paas -R /var/log/nginx/ sudo chown paas:paas -R /var/paas/sys/log/nginx sudo chown paas:paas -R /var/paas/jobs/nginx sudo chown paas:paas -R /var/paas/sys/run/nginx sudo chmod g-w,o-rwx -R /var/cache/nginx sudo chmod g-wx,o-rwx -R /var/paas/sys/log/nginx sudo chmod g-w,o-rwx -R /var/paas/jobs/nginx sudo chmod g-wx,o-rwx -R /var/paas/sys/run/nginx sudo su paas -c "bash /var/paas/jobs/nginx/nginx_server start" nginx_ctl_path=/var/paas/jobs/nginx/bin if [ ! -d ${nginx_ctl_path} ]; then mkdir -p ${nginx_ctl_path} chmod -R 750 ${nginx_ctl_path} fi cp $ROOTPATH/monitfile/nginx/nginx_ctl ${nginx_ctl_path} chmod -R 750 ${nginx_ctl_path} chmod 700 ${nginx_ctl_path}/* nginx_monitrc_path="/var/paas/monit/job" if [ ! -d ${nginx_monitrc_path} ]; then mkdir -p ${nginx_monitrc_path} chmod -R 750 ${nginx_monitrc_path} fi cp $ROOTPATH/monitfile/nginx/nginx.monitrc ${nginx_monitrc_path} chmod 640 ${nginx_monitrc_path}/* /var/paas/jobs/nginx/bin/nginx_ctl start sleep 1 /var/paas/monit/bin/monit reload } function install_manager() { tar zxf /var/paas/packages/package/$version/common/crypto.tgz -C /var/paas mv /var/paas/output/crypto_tool /var/paas/ sudo cp -pr /var/paas/output/* /usr/lib/ cp -r $ROOTPATH/code/celery /var/paas/ install_nginx HOST_IP=`LANG=C ifconfig eth0 | awk '/inet addr:/{ print $2 }' | awk -F: '{print $2 }'` echo "{\"username\": \"iaas_keystone_username\", \"tenant_name\": \"iaas_keystone_tenant_name\", \"region\": \"iaas_region\", \"nova_url\": \"\", \"auth_url\": \"iaas_keystone_url\", \"password\": \"iaas_keystone_password\", \"neutron_url\": \"\"}" > /home/paas/${iaasname}_config.json sed -i "s|iaas_keystone_username|$iaas_keystone_username|g" /home/paas/${iaasname}_config.json >> /dev/null 2>&1 sed -i "s|iaas_keystone_tenant_name|$iaas_keystone_tenant_name|g" /home/paas/${iaasname}_config.json >> /dev/null 2>&1 sed -i "s|iaas_region|$iaas_region|g" /home/paas/${iaasname}_config.json >> /dev/null 2>&1 sed -i "s|iaas_keystone_url|$iaas_keystone_url|g" /home/paas/${iaasname}_config.json >> /dev/null 2>&1 iaas_keystone_password_crypto=`/var/paas/crypto_tool -text ${iaas_keystone_password}` sed -i "s|iaas_keystone_password|$iaas_keystone_password_crypto|g" /home/paas/${iaasname}_config.json >> /dev/null 2>&1 chown paas:paas /home/paas/${iaasname}_config.json cd /var/paas chmod 600 *.txt *.log celery chmod 700 crypto_tool tar zcf keystore.tgz primary_keystore.txt standby_keystore.txt crypto_tool celery cd /var/paas/output tar zcf libs.tgz * mkdir -p /var/paas/crypto_libs cp -r /var/paas/output/libs.tgz /var/paas/crypto_libs/ cp -r /var/paas/keystore.tgz /var/paas/crypto_libs/ sudo chown paas:paas /var/paas/*.log sudo chown paas:paas /var/paas/*.txt rm -rf /var/paas/output rm -rf /var/paas/keystore.tgz rm -rf /var/paas/celery sudo chmod g-w,o-rwx -R /var/paas/crypto_libs/ return $RESULT_OK } function uninstall_monit() { rm -rf /var/paas/monit/ rm -rf /var/paas/scripts/utils } # **************************************************************************** # # Function : create_http_service # Description : create_http_service # Parameter : $1 - title string you want to display # Return : none # Since : Foundation PaaS V100R001C00 # Others : w00241627 # **************************************************************************** # function uninstall() { if [ "$mode" = "" ] || [ "$mode" = "manager" ]; then uninstall_manager >>$LOG_FILE_PATH/uninstall_temp.log 2>&1 if [ $? -ne 0 ] ; then print_log_to_screen "uninstall manager" "$fTAG" return $RESULT_ERROR fi print_log_to_screen "uninstall manager" "$sTAG" rm -rf $ROOTPATH/manager_done fi if [ "$mode" = "" ] || [ "$mode" = "deploy_rest_server" ]; then uninstall_deploy_rest_server >>$LOG_FILE_PATH/uninstall_temp.log 2>&1 if [ $? -ne 0 ] ; then print_log_to_screen "uninstall deploy_rest_server" "$fTAG" return $RESULT_ERROR fi print_log_to_screen "uninstall deploy_rest_server" "$sTAG" rm -rf $ROOTPATH/deploy_rest_server_done fi if [ "$mode" = "" ] || [ "$mode" = "mysql" ]; then uninstall_mysql >>$LOG_FILE_PATH/uninstall_temp.log 2>&1 if [ $? -ne 0 ] ; then print_log_to_screen "uninstall mysql" "$fTAG" return $RESULT_ERROR fi print_log_to_screen "uninstall mysql" "$sTAG" rm -rf $ROOTPATH/mysql_done fi if [ "$mode" = "" ] || [ "$mode" = "etcd" ]; then uninstall_etcd >>$LOG_FILE_PATH/uninstall_temp.log 2>&1 if [ $? -ne 0 ] ; then print_log_to_screen "uninstall etcd" "$fTAG" return $RESULT_ERROR fi print_log_to_screen "uninstall etcd" "$sTAG" rm -rf $ROOTPATH/etcd_done fi if [ "$mode" = "" ] || [ "$mode" = "skydns" ]; then uninstall_skydns >>$LOG_FILE_PATH/uninstall_temp.log 2>&1 if [ $? -ne 0 ] ; then print_log_to_screen "uninstall skydns" "$fTAG" return $RESULT_ERROR fi print_log_to_screen "uninstall skydns" "$sTAG" rm -rf $ROOTPATH/skydns_done fi if [ "$mode" = "" ] || [ "$mode" = "monit" ]; then uninstall_monit >>$LOG_FILE_PATH/uninstall_temp.log 2>&1 if [ $? -ne 0 ] ; then print_log_to_screen "uninstall monit" "$fTAG" return $RESULT_ERROR fi print_log_to_screen "uninstall monit" "$sTAG" rm -rf $ROOTPATH/monit_done fi if [ "$mode" = "" ] || [ "$mode" = "salt" ]; then saltcloud_uninstall >>$LOG_FILE_PATH/uninstall_temp.log 2>&1 uninstall_salt >>$LOG_FILE_PATH/uninstall_temp.log 2>&1 if [ $? -ne 0 ] ; then print_log_to_screen "uninstall salt" "$fTAG" return $RESULT_ERROR fi print_log_to_screen "uninstall salt" "$sTAG" rm -rf $ROOTPATH/salt_done fi return $RESULT_OK } function uninstall_package() { if (command -v dpkg); then sudo dpkg -r $1 sudo dpkg --purge $1 fi if (command -v rpm); then sudo rpm -e $1 fi } function uninstall_manager() { bash /var/paas/jobs/manager/manager.conf stop sudo rm -rf /var/paas/jobs/manager sudo stop celeryd-cloudify-management sudo rm -rf /var/paas/jobs/celery sudo pip uninstall -q -y virtualenv /var/paas/jobs/nginx/nginx_server stop uninstall_package nginx rm -rf /var/paas/jobs/nginx mv /var/paas/jobs/rabbitmq/bin/rabbitmq_ctl /var/paas/jobs/rabbitmq/bin/rabbitmq_ctl_bak /var/paas/jobs/rabbitmq/bin/rabbitmq_ctl_bak stop rm -rf /var/paas/jobs/rabbitmq/ sudo stop elasticsearch uninstall_package elasticsearch mv /var/paas/jobs/elasticsearch_cloudify/bin/elasticsearch_cloudify_ctl /var/paas/jobs/elasticsearch_cloudify/bin/elasticsearch_cloudify_ctl_bak /var/paas/jobs/elasticsearch_cloudify/bin/elasticsearch_cloudify_ctl_bak stop sudo rm -rf /var/paas/jobs/elasticsearch* uninstall_package logstash sudo rm -rf /var/paas/jobs/logstash* sudo kill `lsof -t -i:9999` sudo rm -rf /var/paas/jobs/logstash sudo rm -rf /var/paas/aes_crypto.py* sudo rm -rf /var/paas/logstash_dec.py sudo kill `sudo lsof -t -i:9200` sudo rm -rf /var/paas/elasticsearch sudo rm -rf /etc/init.d/elasticsearch sudo update-rc.d -f elasticsearch remove rm -rf /agents rm -rf /cloudify-core rm -rf /cloudify-components sudo rm -rf /etc/default/celeryd* sudo rm -rf /etc/init.d/celeryd* sudo rm -rf /home/paas/*_config.json sudo rm -rf /home/paas/cloudify* sed -i "s/management=$management/management=/g" $ROOTPATH/../config/ipinfo return $RESULT_OK } function uninstall_deploy_rest_server() { deploy_rest_server_root=/var/paas/deploy_rest_server deploy_rest_server_ctl_path=/var/paas/jobs/deploy_rest_server/bin RUN_DIR=/var/paas/sys/run/deploy_rest_server LOG_DIR=/var/paas/sys/log/deploy_rest_server /var/paas/jobs/deploy_rest_server/bin/deploy_rest_server_ctl stop sudo rm -rf ${deploy_rest_server_ctl_path} sudo rm -rf ${deploy_rest_server_root} sudo rm -rf ${RUN_DIR} sudo rm -rf ${LOG_DIR} return $RESULT_OK } function uninstall_mysql() { PACKAGE_DIR=/var/vcap/packages/mysql TMP_DIR=$PACKAGE_DIR/tmp DATA_DIR=/var/vcap/store/mysql LOG_BIN_DIR=/var/vcap/store/mysql-logs RUN_DIR=/var/vcap/sys/run/mysql LOG_DIR=/var/vcap/sys/log/mysql monitrc_path=/var/paas/monit/job mysql_ctl_path=/var/paas/jobs/mysql/bin sudo bash -x /var/paas/jobs/mysql/bin/mysql_ctl stop sudo rm -rf ${PACKAGE_DIR} sudo rm -rf ${TMP_DIR} sudo rm -rf ${DATA_DIR} sudo rm -rf ${LOG_BIN_DIR} sudo rm -rf ${RUN_DIR} sudo rm -rf ${LOG_DIR} sudo rm -rf ${monitrc_path} sudo rm -rf ${mysql_ctl_path} sudo rm -rf ${mysql_chroot_dir} if [ "${mysql_user}" != "paas" ]; then sudo userdel -r -f ${mysql_user} fi return $RESULT_OK } function uninstall_etcd() { PACKAGE_DIR=/var/paas/etcd DATA_DIR=/var/paas/store/etcd RUN_DIR=/var/paas/sys/run/etcd LOG_DIR=/var/paas/sys/log/etcd monitrc_path=/var/paas/monit/job etcd_ctl_path=/var/paas/jobs/etcd/bin /var/paas/jobs/etcd/bin/etcd_ctl stop rm -rf ${PACKAGE_DIR} rm -rf ${DATA_DIR} rm -rf ${RUN_DIR} rm -rf ${LOG_DIR} rm -rf ${monitrc_path}/etcd.monitrc rm -rf ${etcd_ctl_path} return $RESULT_OK } function uninstall_skydns() { PACKAGE_DIR=/var/paas/skydns RUN_DIR=/var/paas/sys/run/skydns LOG_DIR=/var/paas/sys/log/skydns monitrc_path=/var/paas/monit/job skydns_ctl_path=/var/paas/jobs/skydns/bin /var/paas/jobs/skydns/bin/skydns_ctl stop rm -rf ${PACKAGE_DIR} rm -rf ${RUN_DIR} rm -rf ${LOG_DIR} rm -rf ${monitrc_path}/skydns.monitrc rm -rf ${skydns_ctl_path} return $RESULT_OK } source $ROOTPATH/../config/commoninfo.ini if [ ! -f $ROOTPATH/../config/config.ini ]; then echo -e "config/config.ini is missing \033[31;49;1m[FATAL]\033[0m" exit $RESULT_ERROR fi source $ROOTPATH/../config/config.ini while [ "$1" != "" ]; do case "$1" in "install" | "uninstall" | "status" ) operate="$1" if [ "$2" != "" ]; then mode="$2" shift 1 fi ;; "-?" | "--help" ) print_help exit $RESULT_OK ;; * ) echo -e "parameter " $1 " invalid. use patameter --help to get help." exit $PARAMETER_ERROR ;; esac shift done if [ -z "$operate" ]; then echo -e "parameter error. use patameter --help to get help." exit $PARAMETER_ERROR fi case "$operate" in "install" ) install if [ $? -ne 0 ]; then exit $RESULT_ERROR fi ;; "uninstall" ) uninstall if [ $? -ne 0 ]; then exit $RESULT_ERROR fi ;; * ) echo -e "parameter invalid. use parameter --help to get help." exit $PARAMETER_ERROR ;; esac
C++
UTF-8
1,171
2.875
3
[]
no_license
#include <stdio.h> int Q[100000]; int visit[10000] = { 0, }; int front = 0, rear = 0; bool isPrime(int value) { if (value % 2 == 0 && value != 2) return false; for (int i = 3; i*i <= value; i += 2) { if (value%i == 0) return false; } return true; } int changeNum(int value,int disit,int change) { int arr[4] = { 0, }; arr[0] = value / 1000; arr[1] = value / 100 - arr[0] * 10; arr[2] = value / 10 - arr[1] * 10 - arr[0] * 100; arr[3] = value % 10; if ((arr[disit] != change)&&!(disit==0&&change==0)) arr[disit] = change; return arr[0] * 1000 + arr[1] * 100 + arr[2] * 10 + arr[3]; } void bfs(int value) { for (int i = 0; i < 4; i++) { for (int j = 0; j < 10; j++) { int ret = changeNum(value, i, j); if (isPrime(ret) && visit[ret] == 0&&ret!=value) { Q[rear++] = ret; visit[ret] = visit[value] + 1; } } } } int main() { int src, dst, cnt = 0;; scanf("%d %d",&src,&dst); Q[rear++] = src; while (front<rear) { int pop = Q[front++]; if (pop == dst) break; bfs(pop); } printf("%d\n", visit[dst]); return 0; }
TypeScript
UTF-8
3,811
2.71875
3
[]
no_license
import { Consumer, HighLevelProducer, KafkaClient, Message, ProduceRequest, } from "kafka-node"; import redisClient from "./db"; import { Ticket, TicketState } from "./data"; const kafkaClient = new KafkaClient(); const consumer = new Consumer( kafkaClient, [ { topic: "payment_successful" }, { topic: "list_tickets" }, { topic: "order_ticket" }, ], { autoCommit: false, } ); consumer.on("error", error => { console.error("Consumer error:", error); }) const producer = new HighLevelProducer(kafkaClient); consumer.on("message", (message: Message) => { if (typeof message.value !== "string") { throw new Error("Message type should be 'string'"); } console.log(message); try { switch (message.topic) { case "order_ticket": return orderTicket(JSON.parse(message.value)); case "payment_succesful": return paymentSuccesful(JSON.parse(message.value)); case "list_tickets": return listTickets(); default: console.error(`Unexpected topic: ${message.topic}`); } } catch (e) { console.error(e); } }); function sendPayloads(payloads: ProduceRequest[]): void { // producer.on("ready", () => { producer.send(payloads, (err, data) => { console.log(err ? err : data); }); // }); } function getTickets(): Promise<Ticket[]> { return new Promise((resolve, reject) => redisClient.get("tickets", (err, reply) => err ? reject(err) : resolve(JSON.parse(reply)) ) ); } // If ticket can be found and is ordered, set its state to purchased async function paymentSuccesful(message: { user_id: number; ticket_id: number }) { const tickets: Ticket[] = await getTickets(); const ticket = tickets.find((i) => i.id === message.ticket_id); if ( typeof ticket !== "undefined" && ticket.state === TicketState.Ordered && ticket.user_id === message.user_id ) { sendPayloads([ { topic: "validate_payment", messages: JSON.stringify({ user_id: message.user_id, ticket_id: message.ticket_id }), }, ]); ticket.state = TicketState.Purchased; redisClient.set("tickets", JSON.stringify(tickets)); } } // Send array of tickets async function listTickets() { console.log("list"); const tickets: Ticket[] = await getTickets(); console.log(tickets); sendPayloads([{ topic: "ticket", messages: JSON.stringify(tickets) }]); } // Send message with ticket_id if ticket can be found or null async function orderTicket(message: { user_id: number; ticket_id: number }) { const tickets: Ticket[] = await getTickets(); const ticket = tickets.find((i) => i.id === message.ticket_id); const timeBeforeExpiry = 1000 * 20; if (typeof ticket === "undefined") { sendPayloads([ { topic: "order", messages: JSON.stringify({ user_id: message.user_id, ticket_id: null }), }, ]); } else { ticket.state = TicketState.Ordered; ticket.user_id = message.user_id; redisClient.set("tickets", JSON.stringify(tickets)); sendPayloads([ { topic: "new_order", messages: JSON.stringify({ user_id: message.user_id, ticket_id: ticket.id, expiry: new Date().setMilliseconds(new Date().getMilliseconds() + timeBeforeExpiry) }), }, ]); setTimeout(async () => { const tickets: Ticket[] = await getTickets(); const ticket = tickets.find((i) => i.id === message.ticket_id); // Set ticket state back to "in stock" if the ticket was not purchased within 20s if ( typeof ticket !== "undefined" && ticket.state === TicketState.Ordered ) { ticket.state = TicketState.InStock; redisClient.set("tickets", JSON.stringify(tickets)); } }, timeBeforeExpiry); } }
Ruby
UTF-8
1,093
4.8125
5
[]
no_license
# Write a method that searches for all multiples of 3 or 5 that lie between 1 and some other number, and then computes the sum of those multiples. For instance, if the supplied number is 20, the result should be 98 (3 + 5 + 6 + 9 + 10 + 12 + 15 + 18 + 20). # You may assume that the number passed in is an integer greater than 1. # problem: # identify all multiples of 3 or 5 from 1 to integer argument # sum the multiples # input: integer # output: integer # algorithim: # - initialise `multiples` empty array # - find multiples of 3 or 5 and add to `multiples` # - sum `multiples` and return # Examples def multisum(integer) multiples = [] 1.upto(integer) do |index| multiples << index if index % 3 == 0 || index % 5 == 0 end multiples.sum end def multiple?(number, divisor) number % divisor == 0 end def multisum(integer) (1..integer).reduce(0) do |sum, index| if multiple?(index, 3) || multiple?(index, 5) sum + index else sum end end end puts multisum(3) == 3 puts multisum(5) == 8 puts multisum(10) == 33 puts multisum(1000) == 234168
Markdown
UTF-8
19,720
3.234375
3
[]
no_license
## Introduction Arrays are the simplest and oldest data structures in programming languages. They go back to Fortran I, which was released in 1957 and provided simple one- and two-dimensional arrays of integer or floating-point values as its only data structures. Arrays have been supplemented by many other data structures and have grown in complexity since then, but the core ideas are the same. This guide is partly a tutorial introduction to the SRFI, but also contains some less-technical reference material that may be more accessible to programmers who are not mathematicians. It is intended to be correct but definitely not complete; in particular, only a few of the procedures on intervals and the reflective procedures on arrays are even mentioned in passing. In case of discrepancies between this guide and the SRFI, the SRFI prevails. Arrays as defined in the SRFI are generalizations of ordinary Scheme vectors in two different ways. Whereas a vector is indexed by a single exact integer, arrays are indexed by multiple exact integers, one for each dimension of the array. Thus a 1-dimensional array, like a vector, is indexed by a single number, and a 2-dimensional array (a matrix) is indexed by two numbers representing the row and column. To avoid confusion, this guide uses the term "vector" to refer only to Scheme vectors, never to 1-dimensional arrays. The number of dimensions available is unlimited, although the reference implementation is most efficient when handling arrays with 4 dimensions or less. In addition, whereas the smallest index of a Scheme vector is always 0, the smallest index of each dimension of an array can be any exact integer. For example, a matrix may have 100 rows numbered from 1 to 100 and 11 columns numbered from -5 to +5. It is possible to simulate arrays with vectors of vectors (of vectors ...), but at considerable cost in efficiency. By intention, the SRFI describes many array operations that can be made especially efficient in both space and time. The SRFI does not support *degenerate arrays*. These come in two kinds. An array with zero dimensions contains by convention a single element, whereas an array where the lower bound of any dimension is greater than or equal to the upper bound contains no elements at all. When this guide refers to a 3 x 4 array (or similar), that is shorthand for a 2-dimensional array with 3 rows and 4 columns, with both lower bounds equal to 0. The term *lexicographic order* represents a particular order of traversing the elements of an array in which the first dimension varies most slowly and the last dimension varies most quickly. This is also known as *row-major order*, because if a matrix is stored in memory with the elements of the first row first, followed by the elements of the other rows in order, then lexicographic order is equivalent to the order in memory. For example, lexicographic order over a 2 x 3 matrix with both lower bounds 0 is as follows: (0,0), (0,1), (0,2), (1,0), (1,1), (1, 2). By the same token, *column-major order* varies the first dimension most quickly and the last dimension most slowly. Most programming languages use row-major order, with the significant exceptions of Fortran (for historical reasons) and languages oriented towards mathematical and scientific work such as Matlab, Octave, S-Plus, R, Julia, and Scilab (for compatibility with Fortran). ## Specialized and generalized arrays The SRFI provides two (or three) kinds of arrays, specialized and generalized, where generalized arrays can be immutable or mutable, but it attempts to hide the differences between them as much as is practical. A specialized array corresponds to arrays in other programming languages: it is mutable and maintains a *storage object* which holds the values of the array. A storage object is one-dimensional, and maps an exact integer from 0 (inclusive) to the number of elements in its array (exclusive) to the value. The mapping between the multiple indices of the array and the single index of the storage object is managed by the implementation. Specialized arrays guarantee that retrieving the value of a given array element specified by its indices always retrieves the same value unless a mutation is performed, in which case retrieval of an element returns the value of the latest mutation of that element. More than one specialized array may in certain circumstances share the same storage object. In this case, a mutation performed on an element of one array is typically (but not always) visible in all other arrays that share its storage object. Generalized arrays do not have storage objects maintained by the implementation. Instead they are constructed using a getter procedure that computes and returns the value of a specified array element. This procedure may or may not return the same value over time in the way that specialized arrays do. For example, a getter that fetches the value of a particular row and column of a relational database table will produce different results if the table is mutated through some other process. This sort of immutable array is not truly immutable; it is simply that it cannot be mutated through the SRFI's procedures. Another example is an array whose elements are generated by an algorithm. If this algorithm is pure and functional, the array is truly immutable. It is also possible to create a generalized array with both a getter and a setter procedure, in which case it is considered mutable. Because of the ability to do arbitrary mutations, it must be backed by mutable storage of some sort, though it need not be as stereotyped as a storage object. It is an error if a mutable generalized array does not provide the same guarantees as a specialized array. It is also an error if the setter procedure mutates any other elements of the array than the one specified by its caller. ## Intervals, storage classes, and array constructors In order to construct an array, the lower and upper bounds of all its dimensions must be provided. In the SRFI, these are represented using an immutable object called a (multi-dimensional) *interval*, which can be constructed using the following procedure: `(make-interval `*lower-bounds upper-bounds*`)` Returns an interval whose lower bounds are specified by the vector *lower-bounds* and whose corresponding upper bounds are specified by the vector *upper-bounds*. For example, the interval for a two-dimensional array whose first dimension (rows) ranges from 0 to 9 and whose second dimension ranges from -5 to +5, inclusive, is created with `(make-interval #(0 -5) #(10 6))`. Note that an interval can be used to construct more than one array. In order to construct a specialized array, however, it is also necessary to specify the *storage class*, which represents the type of the storage object for an array. The following standard storage classes are provided: `generic-storage-class` A storage class that allows any value to be stored, as a Scheme vector does. However, a storage object belonging to this class is not necessarily a Scheme vector. `@-storage-class` Storage classes that allow particular sets of numbers to be stored The character `@` is shorthand for one of `u8`, `s8`, ... `c128`, the twelve homogeneous-vector datatypes of [SRFI 160](https://srfi.schemers.org/srfi-160/srfi-160.html). However, a storage object belonging to one of these classes is not necessarily a SRFI 160 @vector. The procedure `make-storage-class` can be used to create a specialized kind of backing store. For example, a hash table along with a default value such as 0 can provide a compact backing store for sparse arrays. With intervals and storage classes available, we can construct arrays: `(make-specialized-array `*interval* [ *storage-class* [ *safe?* ] ]`)` Returns a specialized array whose dimensions are specified by *interval* using as its backing store an object of the class specified by *storage-class* (`generic-storage-class` by default). If the *safe?* argument is true, operations on the returned array will be checked for being within *interval* in the sense of `interval-contains-multi-index`. If it is false, operations are not checked. If *safe* is omitted, a program-wide value may have been set by `specialized-array-default-safe?`, but if not, the safety is implementation-defined. `(make-array `*interval getter* [ *setter* ]`)` Returns a generalized array whose dimensions are specified by *interval*. The *getter* procedure accepts array indices as multiple arguments and computes and returns the value of an array element specified by those indices The *setter* procedure accepts a new value followed by array indices as multiple arguments and changes the array element specified by those indices to the new value, returning an unspecified value. If *setter* is not provided, the generalized array is immutable. ## Predicates The following predicates are useful for type dispatch: `(interval? `*object*`)` Return `#t` if *object* is an interval and `#f` otherwise. `(array? `*object*`)` Return `#t` if *object* is an array and `#f` otherwise. `(specialized-array? `*object*`)` Returns `#t` if *object* is a specialized array and `#f` otherwise. `(mutable-array? `*object*`)` Returns `#t` if *object* is a mutable array, either generalized or specialized, and `#f` otherwise. The following special-purpose predicate allows a program to check in advance whether a particular sequence of indices is usable with a particular array: `(interval-contains-multi-index? `*interval index0 index1* ...`)` Returns `#t` if the element specified by the *indexes* is included in *interval*, and `#f` otherwise. The interval associated with an array can be obtained using the `array-domain` accessor. ## Individual array elements There are no generic `array-ref` or `array-set!` procedures provided. Instead, individual array elements can be retrieved or changed using the `array-getter` and `array-setter` procedures, as follows: `((array-getter `*array*`)` *index0 index1* ...`)` Returns the value of *array* specified by the *indexes*. `((array-setter `*array*`)` *newvalue index1 index2* ...`)` Changes the value of array specified by the *indexes* to *newvalue*. Note that specialized arrays have getters and setters just like generalized arrays, although they are provided by the implementation rather than the user. ## Array transformations An array transformation is a procedure that takes an array and returns another array, perhaps with a different interval but the same array elements (though some of them may not be visible in the new array). Any mutation of one array is also a mutation of the other. The SRFI provides a set of *affine* transformations, meaning that the value of each upper bound in the new array is equal to the sum of a subset of the upper bounds of the old array plus a constant value, and likewise for the lower bounds. Because the composition of two affine transformations is itself affine, extracting or mutating element values is just as efficient on an array with no transformations applied as an array with five or fifty transformations applied. Except as noted, these transformation procedures accept any kind of array (specialized, generalized immutable, or generalized mutable) and return an array of the same kind. `(array-extract `*array interval*`)` Returns an array that is a rectangular subset of *array* whose bounds are specified by *interval*, like a rectangular sub-part of a spreadsheet. It is an error unless *interval* is a subset of the interval of *array*. `(array-translate `*array translation*`)` Returns an array with the same number of elements as *array*, but with the bounds of each dimension shifted upward or downward. The amount of shift for each dimension is given by the corresponding element of *translation*, a vector of exact integers. The `translation?` predicate can be used to verify that *translation* represents a meaningful translation of array indices (that is, if it is a vector where every element is an exact integer). `(array-permute `*array permutation*`)` Returns an array which has the same dimensions, bounds, and elements as *array*, but with the dimensions in a different order specified by *permutation*. The `permutation?` predicate can be used to verify that *permutation* represents a meaningful permutation of array indices (that is, if each element is a distinct exact integer in the range 0 (inclusive) to the length of *permutation* (exclusive)). `(array-curry `*array dimension*`)` Returns an array of arrays. Each of the inner arrays has the last *dimension* dimensions of *array*, whereas the outer array has the earlier dimensions of *array*. Thus currying a three-dimensional array specifying *dimension* as 1 gives a two-dimensional array made up of one-dimensional arrays with identical structure. `(array-tile `*array tile-sizes*`)` Returns an array of arrays. Both the outer array and the inner arrays (the tiles) have the same number of dimensions as *array*, but the elements are distributed in the tiles in such a way that the difference between the upper and the lower bound of each dimension is equal to the corresponding element of the vector *tile-sizes* (except near the upper bounds of the original array, where there aren't enough elements). The bounds of the inner arrays preserve the original indices of each element in *array*. The outer array has all lower bounds 0 and has the necessary upper bounds to represent the total number of tiles required for each dimension. For example, a 5 x 3 array tiled using an *tile-sizes* array of `#(2 1)` will produce a 3 x 3 outer array containing six 2 x 1 arrays and three 1 x 1 arrays. The nine inner arrays will tile the plane represented by the original array, with each element in exactly one inner array. The first two rows will contain three 2 x 1 arrays; the last row will contain three 1 x 1 arrays. It is an error unless the *tile-siezes* argument has the same length as the number of dimensions of *array*. Note: The routines `array-tile` and `array-curr`y both decompose an array into subarrays, but in different ways. For example, if `A` is a 10 x 10 array, then `(array-tile A '#(1 10))` returns an 10 x 1 array each element of which is a 1 x 10 array, whereas `(array-curry A 1)` returns a 1-dimensional array of size 10 each element of which is likewise a 1-dimensional array of size 10. `(array-reverse `*array flip?*`)` Returns an array with the same dimensions, bounds, and elements as *array*, except that a subset of the dimensions are reversed. The `flip?` argument is a vector of booleans: a dimension is reversed if the corresponding boolean is true, and unreversed otherwise. `(array-sample `*array scales*`)` Returns an array which contains only every *k*th element along each of its *n* dimensions, where *k* is equal to the *n*th element of *scales*. It is an error unless *scales* is a vector of size *n* containing positive exact integers. For example, a 6 x 6 array scaled using `#(2 3)` will be a 3 x 2 array that provides the first, third, and fifth rows and the first and fourth columns of the original array. `(specialized-array-share `*array interval interval-mapping*`)` Constructs a new specialized array that shares the body of the specialized array *array*. It is an error to apply this procedure to a generalized array. Returns a specialized array whose elements are retrieved as if by the following algorithm: Pass the indices of the desired element to the procedure *interval-mapping*, which accepts them and returns the same number of values as the number of dimensions in *array*. Then use the returned values to specify the element of *array* to be retrieved. It is an error if *interval-mapping* is not affine and one-to-one, which means that it is possible to precompute the possible results of the transformation when the new array is created; after that, *interval-mapping* is not invoked. For example, the interval mapping specified by `(lambda (i) (values i i))` will transform a square matrix into a 1-dimensional array accessing the diagonal elements. ## The whole array The following procedures accept a predicate and some arrays and apply the predicate to each corresponding element of the arrays: `(array-any `*pred array1 array2* ...`)` Invokes *pred* on the corresponding elements of the *arrays* in lexicographic order. As soon as a call to *pred* returns a true value, that value is returned by `array-any`. If all calls return false, `array-any` returns false. `(array-every `*pred array1 array2* ...`)` Invokes *pred* on the corresponding elements of the *arrays* in lexicographic order. As soon as a call to *pred* returns false, `array-any` returns false. If all calls return a true value, the value of the last call is returned by `array-any`. If no calls were made, `#t` is returned. ## Mapping and folding `(array-map `*proc array1 array2* ...`)` Returns an immutable generalized array whose elements are the result of applying *proc* to all the *arrays*, which must all have equivalent intervals. Rather than doing the mapping all at once, as `map` and `vector-map` do, elements are mapped each time they are retrieved. `(array-outer-product `*proc array1 array2*`)` Returns an immutable generalized array whose values are the result of applying *proc* to each element of *array1* and each element of *array2*. The interval of the new array is the interval of *array1* concatenated with *array2*. Like `array-map`, `array-outer-product` computes elements each time they are retrieved. For example, if *proc* is `+` and the *arrays* are both matrices, then the sum of the (1,2) element of *array1* and the (3,5) element of *array2* is placed in the (1,2,3,5) element of the result. For another example, if *proc* is `*` and both *array1* and *array2* contain 10 elements indexed from 1 to 10 and containing values from 1 to 10, then `outer-product` will return a multiplication table. `(array-for-each `*proc array1 array2* ...`)` Invokes `proc` for its side effects on the elements of *arrays* in lexicographic order and returns an unspecified value. `(array-fold `*kons knil array*`)` `(array-fold-right `*kons knil array*`)` Performs a [SRFI 1](https://srfi.schemers.org/srfi-1/srfi-1.html) `fold` or `right-fold` on the elements of *array* taken in lexicographic order. ## Mutators These procedures allow bulk mutation of arrays. The arrays must have equivalent intervals. `(array-assign! `*dst src*`)` Copies the elements of the array *src* into the corresponding locations of the array *dst*, which must be mutable. It is an error if the arrays do not have the same interval. `(array-swap! `*array1 array2*`)` Swaps the corresponding elements of *array1* and *array2*, which must both be mutable. It is an error if the arrays do not have the same interval. ## Conversions `(list->specialized-array `*interval storage-class safe?*`)` Copies the elements of *list* into the positions of a newly created specialized array in lexicographic order. The arguments *interval*, *storage-class*, and *safe?* have the same meaning as in `make-specialized-array`. Returns the newly created array. `(array->specialized-array `*array storage-class safe?*`)` Copies the elements of *array* into the corresponding positions of a newly created specialized array of the same dimensions in lexicographic order. The arguments *storage-class* and *safe?* have the same meaning as in `make-specialized-array`. Returns the newly created array. `(array->list `*array*`)` Returns a list containing the elements of *array* in lexicographic order. `
Java
UTF-8
281
3.078125
3
[]
no_license
package OneToFourteen; public class Division { public static void main(String[] args) { int a =5; int b =5; int c = a/b; /*float f = a/b; System.out.println(c); System.out.println(f); System.out.println(a*1.0f/b); System.out.println((float)(a)/b);*/ } }
Shell
UTF-8
578
3.4375
3
[]
no_license
#!/bin/bash set -eu logfile=/var/vcap/sys/log/etcd/drain.log exec 3>&1 exec 1>> $logfile exec 2>> $logfile output_for_bosh() { exit_code=$? if [ $exit_code -eq 0 ]; then echo "$(date): etcd exited" else echo "$(date): drain failed" fi echo $exit_code >&3 } trap output_for_bosh EXIT if echo $BOSH_JOB_NEXT_STATE | grep "\"persistent_disk\":0"; then NAME="<%= spec.address.split(".").first %>" MEMBER_ID="$(/var/vcap/jobs/etcd/bin/etcdctl member list | grep ${NAME} | cut -d':' -f1)" /var/vcap/jobs/etcd/bin/etcdctl member remove ${MEMBER_ID} fi
Python
UTF-8
878
3.140625
3
[]
no_license
class Solution: def findKthBit(self, n: int, k: int) -> str: length = 2 ** n - 1 j = n reverse = False while j != 1: if k == length // 2 + 1: return "1" if not reverse else '0' elif k <= length // 2: length = length // 2 else: k = length - k + 1 length = length // 2 reverse = reverse ^ True j -= 1 # print("k="+str(k)) # print(length) return "1" if reverse else '0' class Solution2: def findKthBit(self, n: int, k: int) -> str: s = '0' i = 1 while i < n: cur = s + '1' + ''.join(['0' if c == '1' else '1' for c in s[::-1]]) s = cur i += 1 return s[k - 1] k = Solution() print(k.findKthBit(n = 4, k = 15))
Markdown
UTF-8
8,906
3.34375
3
[]
no_license
# 023-链表中环的入口结点 tags: 两指针 --- ## 题目原文 [牛客网链接](https://www.nowcoder.com/practice/253d2c59ec3e4bc68da16833f79a38e4?tpId=13&tqId=11208&tPage=3&rp=1&ru=%2Fta%2Fcoding-interviews&qru=%2Fta%2Fcoding-interviews%2Fquestion-ranking) 给一个链表,若其中包含环,请找出该链表的环的入口结点,否则,输出null。 ## 解题思路 ### 剑指offer 假设链表长度为N, 那么第N链接到了第k个节点形成了环,即我们需要查找到倒数第N-K+1个节点, 那么环中就有N-K+1个节点,这时候我们定义两个指针$P_1$和$P_2$指向链表的头部, 指针$P_1$先在链表中向前移动n-k+1步,到达第n-k+2个节点, 然后两个指针同步向前移动, 当$P_2$走了K-1步到达环的入口的时候, 指针$P_1$正好走了N+1步, 到达了环的入口, 即两个指针会相遇在环的入口处 以下图为例,指针P1和P2在初始化时都指向链表的头结点。由于环中有4个结点,指针P1先在链表上向前移动4步。接下来两个指针以相同的速度在链表上向前移动,直到它们相遇。它们相遇的结点正好是环的入口结点。 ![剑指Offer(五十五):链表中环的入口结点](img/readme.assets/basis_55_1.png) 那么我们剩下的问题就是如何得到环中节点的数目? 我们可以使用一快一慢两个指针(比如慢指针一次走一步, 慢指针一次走两步),如果走的过程中发现快指针追上了慢指针, 说明遇见了环,而且相遇的位置一定在环内, 考虑一下环内, 从任何一个节点出现再回到这个节点的距离就是环的长度, 于是我们可以进一步移动慢指针,快指针原地不动, 当慢指针再次回到相遇位置时, 正好在环内走了一圈, 从而我们通过计数就可以获取到环的长度 - 第一步,找环中相汇点。分别用p1,p2指向链表头部,p1每次走一步,p2每次走二步,直到p1==p2找到在环中的相汇点。 - 第二步,找环的长度。从环中的相汇点开始, p2不动, p1前移, 当再次相遇时,p1刚好绕环一周, 其移动即为环的长度K - 第三步, 求换的起点, 转换为求环的倒数第N-K个节点,则两指针left和right均指向起始, right先走K步, 然后两个指针开始同步移动, 当两个指针再次相遇时, right刚好绕环一周回到起点, left则刚好走到了起点位置 ![微信图片_20190702172216](img/readme.assets/微信图片_20190702172216.jpg) ```c++ /* struct ListNode { int val; struct ListNode *next; ListNode(int x) : val(x), next(NULL) { } }; */ class Solution { public: ListNode* EntryNodeOfLoop(ListNode* pHead) { if(pHead==nullptr) return nullptr; ListNode* meetingNode=FindMeetingNode(pHead); if(meetingNode==nullptr) return nullptr; ListNode* p1=meetingNode->next; int num=1; while(p1!=meetingNode){ p1=p1->next; num++; } ListNode* p2=pHead; while(num>0){ p2=p2->next; num--; } p1=pHead; while(p1!=p2){ p1=p1->next; p2=p2->next; } return p1; } ListNode* FindMeetingNode(ListNode* pHead){ if(pHead==nullptr||pHead->next==nullptr) return nullptr; ListNode* slow=pHead; ListNode* fast=slow->next; while(slow!=nullptr&&fast!=nullptr){ if(slow==fast) return slow; slow=slow->next; fast=fast->next; if(fast!=nullptr) fast=fast->next; } return nullptr; } }; ``` ### 稍微简单一些的办法 [参考](https://www.acwing.com/solution/acwing/content/741/) [参考](https://www.e-learn.cn/content/qita/780537) 两个结论: ​ **1、设置快慢指针,假如有环,他们最后一定相遇。** ​ **2、两个指针分别从链表头和相遇点继续出发,每次走一步,最后一定相遇与环入口。** ​ **证明1**:设置快慢指针fast和low,fast每次走两步,low每次走一步。假如有环,两者一定会相遇(因为low一旦进环,可看作fast在后面追赶low的过程,每次两者都接近一步,最后一定能追上)。 ​ **证明2:** ​ 设: ​ 链表头到环入口长度为--**a** ​ 环入口到相遇点长度为--**b** ​ 相遇点到环入口长度为--**c** ![img](img/readme.assets/4240377_1529033184336_9A253E69EDBB4FD57BB16FC3A32C2756.jpg) 则:相遇时 ​ **快指针路程=a+(b+c)k+b** ,k>=1 其中b+c为环的长度,k为绕环的圈数(k>=1,即最少一圈,不能是0圈,不然和慢指针走的一样长,矛盾)。 ​ **慢指针路程=a+b** ​ 快指针走的路程是慢指针的两倍,所以: ​ **(a+b)\*2=a+(b+c)k+b** ​ 化简可得: ​ **a=(k-1)(b+c)+c** 这个式子的意思是: **链表头到环入口的距离=相遇点到环入口的距离+(k-1)圈环长度**。其中k>=1,所以**k-1>=0**圈。所以两个指针分别从链表头和相遇点出发,最后一定相遇于环入口。 ```c++ /** * Definition for singly-linked list. * struct ListNode { * int val; * ListNode *next; * ListNode(int x) : val(x), next(NULL) {} * }; */ class Solution { public: ListNode *entryNodeOfLoop(ListNode *head) { if (!head || !head->next) return 0; ListNode *first = head, *second = head; while (first && second) { first = first->next; second = second->next; if (second) second = second->next; else return 0; if (first == second) { first = head; while (first != second) { first = first->next; second = second->next; } return first; } } return 0; } }; ``` ### 断链法 [参考]([https://github.com/gatieme/CodingInterviews/tree/master/056-%E9%93%BE%E8%A1%A8%E4%B8%AD%E7%8E%AF%E7%9A%84%E5%85%A5%E5%8F%A3%E7%BB%93%E7%82%B9](https://github.com/gatieme/CodingInterviews/tree/master/056-链表中环的入口结点)) 时间复杂度为O(n),两个指针,一个在前面,另一个紧邻着这个指针,在后面。 两个指针同时向前移动,每移动一次,前面的指针的next指向NULL。 也就是说:访问过的节点都断开,最后到达的那个节点一定是尾节点的下一个, 也就是循环的第一个。 这时候已经是第二次访问循环的第一节点了,第一次访问的时候我们已经让它指向了NULL, 所以到这结束。 但是这种方法修改了链表的指向 ```c++ class Solution { public: ListNode* EntryNodeOfLoop(ListNode* pHead) { if (pHead == NULL || pHead->next == NULL) { return NULL; } ListNode* previous = pHead; ListNode* current = pHead->next; while (current != NULL) { previous->next = NULL; previous = current; current = current->next; } return previous; } }; ``` ## 代码 ### [c++代码](./src/cpp/023-链表中环的入口结点.cpp) ```c++ /* struct ListNode { int val; struct ListNode *next; ListNode(int x) : val(x), next(NULL) { } }; */ class Solution { public: ListNode* EntryNodeOfLoop(ListNode* pHead) { if(pHead==nullptr) return nullptr; ListNode* meetingNode=FindMeetingNode(pHead); if(meetingNode==nullptr) return nullptr; ListNode* p1=meetingNode->next; int num=1; while(p1!=meetingNode){ p1=p1->next; num++; } ListNode* p2=pHead; while(num>0){ p2=p2->next; num--; } p1=pHead; while(p1!=p2){ p1=p1->next; p2=p2->next; } return p1; } ListNode* FindMeetingNode(ListNode* pHead){ if(pHead==nullptr||pHead->next==nullptr) return nullptr; ListNode* slow=pHead; ListNode* fast=slow->next; while(slow!=nullptr&&fast!=nullptr){ if(slow==fast) return slow; slow=slow->next; fast=fast->next; if(fast!=nullptr) fast=fast->next; } return nullptr; } }; ``` ### [python代码](./src/python/023-链表中环的入口结点.py) ```python ```
Java
UTF-8
223
1.882813
2
[]
no_license
package com.sparta.sdets.model; import java.util.ArrayList; public interface TrainingCentreDTO { int getCapacity(); int getRemainingSpace(); ArrayList getTraineesList(); void addToQueue(Trainee trainee); }
Java
UTF-8
849
2.453125
2
[]
no_license
package learn.aop; import org.aspectj.lang.ProceedingJoinPoint; import org.aspectj.lang.annotation.*; import org.springframework.stereotype.Component; @Aspect @Component public class AopByAnnotation { //指定切点切面 @Pointcut(value = "execution(* learn.*.Foo.*sayHelloFoo(..))") public void point() { } @Before(value = "point()") public void before() { System.out.println("========>before sayHelloFoo"); } @AfterReturning(value = "point()") public void after() { System.out.println("========>after sayHelloFoo"); } @Around("point()") public void around(ProceedingJoinPoint joinPoint) throws Throwable { System.out.println("========>before sayHelloFoo around"); joinPoint.proceed(); System.out.println("========>after sayHelloFoo around"); } }
Java
UTF-8
327
2.5625
3
[]
no_license
package com.Marian.Exercicis.Refactoritzar.RemoveAndReplace; public class Plane extends TipusVheicles{ public Plane(int vehicleType, int speed, int acceleration){ super(vehicleType, speed, acceleration); } public int move () { int result = 0; return result = acceleration * 2; } }
TypeScript
UTF-8
1,943
2.59375
3
[]
no_license
import { getDatabase } from './database'; import { Item, User } from './data-types'; import { ObjectId } from 'mongodb'; export async function getAllItems(): Promise<Item[]> { const db = await getDatabase(); const collection = db.collection('items'); return await collection.find().sort({ _id: -1 }).toArray(); } export async function getVotesForUser(userId: string): Promise<Item[]> { const db = await getDatabase(); const collection = db.collection('items'); return await collection .find({ 'votes.userId': new ObjectId(userId) }) .sort({ _id: -1 }) .toArray(); } export async function addVoteToItem({ itemId: itemIdString, user, }: { itemId: string; user: User; }) { const db = await getDatabase(); const collection = db.collection('items'); const itemObjectId = new ObjectId(itemIdString); const userObjectId = new ObjectId(user._id); const existingVote = await collection .find({ _id: itemObjectId, 'votes.userId': userObjectId, }) .count(); if (existingVote) { throw new Error('Already voted'); } return collection.updateOne( { _id: itemObjectId }, { $push: { votes: { userId: userObjectId, created: new Date(), }, }, } ); } export async function removeVoteFromItem({ itemId: itemIdString, user, }: { itemId: string; user: User; }) { const db = await getDatabase(); const collection = db.collection('items'); const itemObjectId = new ObjectId(itemIdString); const userObjectId = new ObjectId(user._id); const existingVote = await collection .find({ _id: itemObjectId, 'votes.userId': userObjectId, }) .count(); if (!existingVote) { throw new Error('No vote found'); } return await collection.updateOne( { _id: itemObjectId }, { $pull: { votes: { userId: userObjectId, }, }, } ); }
Python
UTF-8
565
3.296875
3
[]
no_license
import csv results_file = 'file.csv' # list of lists column_headers = ['col 1', 'col 2', 'col 3'] all_data = [column_headers] all_data.append(['row 1, col 1', 'row 1, col 2', 'row 1, col 3']) with open(results_file, 'w', newline='') as f: writer = csv.writer(f) for r in all_data: writer.writerow(r) # dict of lists example_dict = {'a': [1, 2, 3], 'b': [4, 5, 6], 'c': [7, 8, 9]} with open(results_file, 'w', newline='') as f: writer = csv.writer(f) writer.writerow(example_dict.keys()) writer.writerows(zip(*example_dict.values()))
Markdown
UTF-8
1,866
2.515625
3
[]
no_license
# Мадридский "Реал" **«Реал Мадрид»**(*исп. Real Madrid Club de Fútbol*) — испанский профессиональный футбольный клуб из города Мадрида. Признан ФИФА лучшим футбольным клубом XX века. «Реал Мадрид» — один из трёх клубов, которые ни разу не покидали высший испанский дивизион, ~~двумя другими являются «Барселона» и «Атлетик Бильбао»~~. Является одним из самых титулованных клубов в испанском футболе. На его счету 62 национальных титула: рекордные 33 титула чемпиона Ла Лиги, 19 Кубков Испании и 10 Суперкубков Испании. Является рекордсменом по количеству побед и голов в Лиге чемпионов (13 раз, единственная команда, выигрывавшая этот турнир — тогда ещё Кубок Европейских чемпионов — 5 раз подряд). ![](https://s5o.ru/storage/simple/ru/edt/f9/8c/39/70/ruef0395595a8.jpg) ## Состав 2019/2020 ## 1. Альфонс Ареоля 2. Даниэль Карвахаль 3. Эдер Милитао 4. Серхио Рамос 5. Рафаэль Варан 6. Начо Фернандес 7. Эден Азар 8. Тони Кроос 9. Карим Бензема 10. Лука Модрич 11. Гарет Бэйл 12. Марсело 13. Тибо Куртуа 14. Каземиро 15. Федерико Вальверде 16. Хамес Родригес 17. Лукас Васкес 18. Лука Йович 19. Альваро Одриосола 20. Марко Асенсио 21. Браим Диас 22. Иско 23. Ферлан Менди 24. Мариано Диас 25. Винисиус Жуниор 26. Диего Альтубе 27. Родриго ## Прогноз на сезон ## <https://www.youtube.com/watch?v=FtBjoJD45KE>
Python
UTF-8
1,202
2.984375
3
[]
no_license
def maxCalc(S,N,a,b):#해당 행, 열 순회 maxCnt = 0 acnt = 1 for i in range(N-1): if S[i][b] == S[i+1][b]: acnt += 1 else: acnt = 1 maxCnt = max(acnt, maxCnt) bcnt = 1 for i in range(N-1): if S[a][i] == S[a][i+1]: bcnt += 1 else: bcnt = 1 maxCnt = max(bcnt, maxCnt) return maxCnt def one(S,N,a,b):#a행b열 하나의 칸에 대해 오른쪽, 아래쪽이랑 바꿔 본 후 최대값 반환 maxCnt = 0 if a+1 < N: S[a][b], S[a+1][b] = S[a+1][b], S[a][b] maxCnt = max(maxCnt,maxCalc(S,N,a,b)) maxCnt = max(maxCnt,maxCalc(S,N,a+1,b)) S[a][b], S[a+1][b] = S[a+1][b], S[a][b] if b+1 < N: S[a][b], S[a][b+1] = S[a][b+1], S[a][b] maxCnt = max(maxCnt,maxCalc(S,N,a,b)) maxCnt = max(maxCnt,maxCalc(S,N,a,b+1)) S[a][b], S[a][b+1] = S[a][b+1], S[a][b] return maxCnt if __name__ == '__main__': N = int(input()) S=[list(input()) for _ in range(N)] result = 0 for i in range(N): for j in range(N): result = max(result, one(S,N,i,j)) print(result)
JavaScript
UTF-8
1,585
3
3
[ "MIT" ]
permissive
import test from 'ava' import { isValidNumericInput } from '../../src/number' test('string - empty', async function (t) { t.plan(1) t.true(isValidNumericInput('', true)) }) test('string - space', async function (t) { t.plan(1) t.false(isValidNumericInput(' ', true)) }) test('string - alphabetic', async function (t) { t.plan(2) t.false(isValidNumericInput('x', true)) t.false(isValidNumericInput('foo', true)) }) test('number - valid, positive', async function (t) { t.plan(1) t.true(isValidNumericInput('3', true)) }) test('number - valid, negative', async function (t) { t.plan(2) t.true(isValidNumericInput('-', true)) t.true(isValidNumericInput('-3', true)) }) test('number - invalid', async function (t) { t.plan(8) t.false(isValidNumericInput('3.', true)) t.false(isValidNumericInput('3.142', true)) t.false(isValidNumericInput('.', true)) t.false(isValidNumericInput('.142', true)) t.false(isValidNumericInput('-3.', true)) t.false(isValidNumericInput('-3.142', true)) t.false(isValidNumericInput('-.', true)) t.false(isValidNumericInput('-.142', true)) }) test('mathematical expression - valid', async function (t) { t.plan(2) t.true(isValidNumericInput('3+', true)) t.true(isValidNumericInput('1+2-3*4/5', true)) }) test('mathematical expression - invalid', async function (t) { t.plan(5) t.false(isValidNumericInput('-3+.', true)) t.false(isValidNumericInput('-3+.142', true)) t.false(isValidNumericInput('3++', true)) t.false(isValidNumericInput('--3', true)) t.false(isValidNumericInput('.3.', true)) })
C#
UTF-8
606
2.9375
3
[]
no_license
/** * QuickRound : a Round of type Quick * * */ using System.Collections.Generic; public class QuickRound : Round { private static List<int> _accLevel = new List<int>() {4,2,1}; //Accuracy values for level (one-side threshold, i.e. +-threshold) private int Acc; //Accuracy : precision threshold level (0-2) public QuickRound(int index, int difficulty) : base (index) { Acc = _accLevel[difficulty]; } protected override bool IsValueCorrect(int playerValue) { int lowerGoal = Goal - Acc; int upperGoal = Goal + Acc; return playerValue >= lowerGoal && playerValue <= upperGoal; } }
JavaScript
UTF-8
4,500
2.625
3
[]
no_license
var postGameScene; function postGameLoop(){ postGameCamera.position.set(0,15,45); postGameCamera.lookAt(0,0,0); if(controllersConnected){ checkAllButtons(); } if(inPostGame){ requestAnimationFrame(postGameLoop); renderer.render(postGameScene, postGameCamera); } } function buildPostGame(){ inPostGame = true; gameStarted = false; postGameScene = new THREE.Scene(); player1Info.damageReceived = player2Info.damageDealt; player2Info.damageReceived = player1Info.damageDealt; var playerInfos = [player1Info, player2Info]; console.log(player1Info); console.log(player2Info); noonLights(postGameScene); for(var i = 0; i < stage.players.length; i++){ var playerStandMesh = createBasicBoxMesh(1+Math.random()*3); postGameScene.add(playerStandMesh); playerStandMesh.position.x = -25 + i*45; playerStandMesh.position.y = 0; playerStandMesh.position.z = 0; postGameScene.add(stage.players[i].model); stage.players[i].model.position.set(-25+i*45, 10, 0); } renderer.render(postGameScene, postGameCamera); postGameCamera.position.set(0,0,10); postGameCamera.lookAt(0,0,0); var container = document.getElementById("container"); var statsCont = document.createElement("div"); statsCont.id = "statsContainer"; container.appendChild(statsCont); for(var i = 0; i < numPlayers; i++){ var statsDiv = document.createElement("div"); statsDiv.id = "p"+(i+1)+"Stats"; var pMessage = ""; // if(i == 0){ // for(var j = 0; j < ) // } statsDiv.innerHTML = "<br style = 'position:relative;left:40%;font-size:1.0em;'>Stats:" +"<br style = 'font-size:1.0em;'>Damage Dealt: "+playerInfos[i].damageDealt+" %" +"<br style = 'font-size:1.0em;'>Damage Recieved: "+playerInfos[i].damageReceived+" %" +"<br style = 'font-size:1.0em;'>Total Attacks: "+playerInfos[i].totalAttacksCast+"" +"<br style = 'font-size:1.0em;'>Total Attacks Hit: "+playerInfos[i].totalAttacksHit+"" +"<br style = 'font-size:1.0em;'>Hit Percentage: "+Math.round(100*(playerInfos[i].totalAttacksHit/playerInfos[i].totalAttacksCast))+" %" statsCont.appendChild(statsDiv); } var lockInDiv = document.createElement("div"); lockInDiv.id = "lockInReady"; if(controllersConnected){ lockInDiv.innerHTML = "Press B to Play Again!" } else{ lockInDiv.innerHTML = "Press Space to Play Again!" } lockInDiv.style.width = "25%"; lockInDiv.style.left = "35%"; container.appendChild(lockInDiv); var charSelBan = document.createElement("div"); charSelBan.id = "characterSelectBanner"; charSelBan.innerHTML = "Game! Duration: "+Math.round(stage.timer/60); container.appendChild(charSelBan) var p1WinMessage = document.createElement("div"); p1WinMessage.id = "p1WinMessage"; if(winner == 1){ p1WinMessage.innerHTML = "Winner!"; } else{ p1WinMessage.innerHTML = "2nd Place!"; } container.appendChild(p1WinMessage); var p2WinMessage = document.createElement("div"); p2WinMessage.id = "p2WinMessage"; if(winner == 2){ p2WinMessage.innerHTML = "Winner!"; } else{ p2WinMessage.innerHTML = "2nd Place!"; } container.appendChild(p2WinMessage); postGameLoop(); } function playAgain(){ //RESET ALL VARIABLES boxVar = document.getElementById("lockInReady"); if(boxVar != undefined){ boxVar.parentNode.removeChild(boxVar); } boxVar = document.getElementById("characterSelectBanner"); if(boxVar != undefined){ boxVar.parentNode.removeChild(boxVar); } boxVar = document.getElementById("statsContainer"); if(boxVar != undefined){ boxVar.parentNode.removeChild(boxVar); } boxVar = document.getElementById("p1WinMessage"); if(boxVar != undefined){ boxVar.parentNode.removeChild(boxVar); } boxVar = document.getElementById("p2WinMessage"); if(boxVar != undefined){ boxVar.parentNode.removeChild(boxVar); } p1WinMessage for(var i = 0; i < numPlayers; i++){ boxVar = document.getElementById("p"+(i+1)+"Stats"); if(boxVar != undefined){ boxVar.parentNode.removeChild(boxVar); } } inPostGame = false; buildCharacterSelect(); } function checkAllButtons(){ }
Java
UTF-8
940
3.3125
3
[]
no_license
package com.geekbrains; public class ArrMethods { public static int[] arrAfterLastFour (int[] arr) { int i=arr.length-1; while (i>=0 && arr[i]!=4) { i--; } if (arr[i]==4) { int[] arr2 = new int[arr.length-1-i]; System.arraycopy(arr,i+1,arr2,0,arr.length-1-i); return arr2; } else { throw new RuntimeException(); } } public static boolean isArrFromOneFour(int[] arr) { boolean isContainsOne=false; boolean isContainsFour=false; for (int i : arr) { switch (i) { case 1: isContainsOne=true; break; case 4: isContainsFour=true; break; default: return false; } } return isContainsFour && isContainsOne; } }
Python
UTF-8
215
3.09375
3
[]
no_license
from sys import stdin for _ in range(int(stdin.readline())): t = int(stdin.readline()) cur = 1 idx = 3 res = 1 while cur < t: cur += idx idx += 2 res += 1 print(res)
Java
UTF-8
1,133
2.515625
3
[]
no_license
package design.hustlelikeaboss.customr.models; import javax.persistence.*; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.JoinColumn; import javax.persistence.OneToMany; import javax.validation.constraints.NotNull; import java.util.ArrayList; import java.util.List; /** * Created by quanjin on 6/23/17. */ @Entity public class ProjectType { @Id @GeneratedValue private int id; private String name; @OneToMany private List<Project> projects = new ArrayList<>(); // constructor public ProjectType(String name) { this.name = name; } public ProjectType() { } // setters & getters public int getId() { return id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public List<Project> getProjects() { return projects; } public void addProject(Project project) { this.projects.add(project); } public void setProjects(List<Project> projects) { this.projects = projects; } }
JavaScript
UTF-8
5,050
3.453125
3
[]
no_license
const cardsFlippedArr = []; const matchedCardsArr = []; let cardsFlipped = 0; let totalSeconds = 0; let matches = 0; let gameRunning = true; let preventFlip = false; let previousCardFlipped; //declare DOM elements const gameContainer = document.getElementById("game"); const minutesLabel = document.querySelector("#minutes"); const secondsLabel = document.querySelector("#seconds"); const resetButton = document.querySelector("#reset-button"); const topContainerText = document.querySelector(".top-container-text-before-completion"); let highScore = document.querySelector("#high-score"); //set interval for game timer let intervalId = setInterval(updateGameTime, 1000); //check for previous high score from local storage highScore.append(` ${checkLocalStorage()}`); const COLORS = [ "red", "blue", "green", "orange", "purple", "red", "blue", "green", "orange", "purple" ]; function shuffle(array) { let counter = array.length; while (counter > 0) { let index = Math.floor(Math.random() * counter); counter--; let temp = array[counter]; array[counter] = array[index]; array[index] = temp; } return array; } let shuffledColors = shuffle(COLORS); function createDivsForColors(colorArray) { for (let color of colorArray) { const newDiv = document.createElement("div"); newDiv.classList.add(color); newDiv.addEventListener("click", handleCardClick); newDiv.setAttribute("boardDiv", true); gameContainer.append(newDiv); } } function handleCardClick(event) { if(cardsFlipped<2 && !preventFlip && matches<5 && !(matchedCardsArr.includes(event.target)) && ((event.target.style.backgroundColor==="")|| (event.target.style.backgroundColor==="white")) ) { previousCardFlipped = event.target; event.target.style.backgroundColor = event.target.className; cardsFlipped = addCardToArr(cardsFlipped, event.target, cardsFlippedArr); if(checkForMatch(cardsFlippedArr)){ matches++; matchedCardsArr.push(event.target, previousCardFlipped); cardsFlipped = 0; cardsFlippedArr.length = 0; if(matches===5){ wonGame(); if((totalSeconds<parseInt(checkLocalStorage()))|| (checkLocalStorage()==="") ){ addToLocalStorage(totalSeconds); highScore.innerText = ` ${totalSeconds}`; } } } else if(cardsFlipped===2 && (cardsFlippedArr[0].style.backgroundColor!=cardsFlippedArr[1].style.backgroundColor) && (!matchedCardsArr.includes(event.target)) ) { preventFlip = true; setTimeout(flipCards, 1000, preventFlip); cardsFlipped = 0; } } } createDivsForColors(shuffledColors); function checkForMatch(cardsFlippedArr) { if(cardsFlipped===2) { if(cardsFlippedArr[0].style.backgroundColor===cardsFlippedArr[1].style.backgroundColor) return true; } else return false; } function addCardToArr(cardsFlipped, card, cardsFlippedArr){ if(cardsFlipped<=1) { cardsFlippedArr.push(card); cardsFlipped++; } else if (cardsFlippedArr[0].offsetHeight!=card.offsetHeight || cardsFlippedArr[0].offsetWidth!=card.offsetWidth || cardsFlippedArr[0].offsetLeft!=card.offsetLeft || cardsFlippedArr[0].offsetTop!=card.offsetTop ) { cardsFlippedArr.push(card); cardsFlipped++; } return cardsFlipped; } function flipCards() { cardsFlippedArr[0].style.backgroundColor = 'white'; cardsFlippedArr[1].style.backgroundColor = 'white'; cardsFlippedArr.length = 0; return cardsFlippedArr, preventFlip=false; } function updateGameTime(){ ++totalSeconds; secondsLabel.innerHTML = pad(totalSeconds % 60); minutesLabel.innerHTML = pad(parseInt(totalSeconds / 60)); } function pad(val) { let valString = val + ""; if (valString.length < 2) { return "0" + valString; } else { return valString; } } const resetFunc = function resetGame() { matchedCardsArr.length = 0; preventFlip = false; matches = 0; cardsFlipped = 0 totalSeconds = 0; cardsFlippedArr.length = 0; removeCurrentDivs(); let shuffledColors = shuffle(COLORS); createDivsForColors(shuffledColors); if(!gameRunning) { topContainerText.classList.toggle("top-container-text"); }; clearInterval(intervalId); intervalId = setInterval(updateGameTime, 1000); gameRunning = true; } resetButton.addEventListener('click', resetFunc); function removeCurrentDivs() { const allColorDivs = document.querySelectorAll('div'); for(let div of allColorDivs) { if(div.getAttribute("boardDiv")){ div.remove(); } } } function checkLocalStorage() { if(localStorage.highScore != undefined) { return localStorage.highScore; } return ""; } function addToLocalStorage(highScore) { return localStorage.setItem("highScore", highScore); } function wonGame() { gameRunning = false; clearInterval(intervalId); topContainerText.classList.remove(".top-container-text-before-completion"); topContainerText.classList.add("top-container-text"); }
Markdown
UTF-8
2,423
2.96875
3
[]
no_license
[![Known Vulnerabilities](https://snyk.io/test/github/adankot/todolist/badge.svg)](https://snyk.io/test/github/adankot/todolist) # To do list This is a test project. A basic to do list, where you can register an account and create tasks for yourself. User actions: - Register yourself with username and password - Login with username and password - List your tasks - Create task - Update task - Update the status of a task - Delete a task - Delete all tasks - Delete all completed tasks For an easy deploy, currently it uses Docker, but it is not required. You just need to install Node.js v6.10.0 (LTS), Redis 3.2.8 and MongoDB 3.4.2 manually on your server. ## Installation ### Clone the server ``` sudo apt-get install git git clone << repository url >> ``` *If you are not using docker, then you should run: `npm i`* ### Install or upgrade Docker and Docker-compose To install or upgrade Docker and Docker-compose build applications use the command line and type: ```bash sudo apt-get update wget -qO- https://get.docker.com/ | sudo sh sudo curl -L https://github.com/docker/compose/releases/download/1.7.1/docker-compose-`uname -s`-`uname -m` > sudo /usr/local/bin/docker-compose sudo chmod +x /usr/local/bin/docker-compose ``` *note: Make sure you've always got the correct version of docker and docker-compose:* ```bash sudo docker --version #requires at least version 1.8.1 sudo docker-compose --version #requires at least version 1.7.1 ``` ### Start the server If you are using docker, then there is a predefined .env.docker file, which is set to the docker compose file, and you don't have to define a new one. ***ELSE**:If you are not using docker, you should set environment variables in `.env` file (if needed, define new one):* ```bash cp .env.example .env nano .env ``` Before start, build the application: ```bash sudo docker-compose build ``` Start the application ```bash sudo docker-compose up ``` ## Usage By default the server is listening on `http://localhost:3000`. - `/` the index and login screen - `/tasks` is where you can find your tasks (Only for authenticated users) ## Future of the project ### Planned features - Tests for easier development and deployment - Advanced authentication - Better registration flow - Email verification - Login through Facebook, Google and Twitter - Optimalization - Redis cache for user's task list - Pagination for user's task list
Shell
UTF-8
1,145
2.53125
3
[]
no_license
#!/usr/bin/env zsh export DOTS_DIR=~/.dots # fallback locale (( $+LC_ALL )) || export LC_ALL=en_US.UTF-8 (( $+LANG )) || export LANG=en_US.UTF-8 # defines MACHINE_OS and MACHINE_NAME [[ -e ~/.machine ]] && source ~/.machine # exclude some aliases from alias-tips export ZSH_PLUGINS_ALIAS_TIPS_EXCLUDES='_ - 1 g' # don't highlight comments in line-buffer typeset -gA ZSH_HIGHLIGHT_STYLES export ZSH_HIGHLIGHT_STYLES[comment]='none' # Make `npm install -g` install packages into ~/.node_modules export npm_config_prefix=~/.node_modules # fix pinentry-curses export GPG_TTY=$(tty) # Make lastpass-cli (lpass) use pinentry-curses export LPASS_PINENTRY=$(which pinentry-curses) # fzf and fd export FZF_DEFAULT_COMMAND="fd -H -E .git . ." export FZF_CTRL_T_COMMAND="${FZF_DEFAULT_COMMAND}" export FZF_ALT_C_COMMAND="fd -H -E .git -t d . ." # wayland compatibility fixes export QT_QPA_PLATFORM=wayland-egl # requires qt5-wayland export QT_WAYLAND_DISABLE_WINDOWDECORATION="1" export CLUTTER_BACKEND=wayland export SDL_VIDEODRIVER=wayland export _JAVA_AWT_WM_NONREPARENTING=1 export ECORE_EVAS_ENGINE=wayland_egl export ELM_ENGINE=wayland_egl
C++
UTF-8
13,340
2.625
3
[]
no_license
#ifndef _VISUALIZER_H #define _VISUALIZER_H // includes from this package #include "ColorRamp.hpp" #include "DrawableColor.hpp" #include "DrawablePoint.hpp" #include "DrawableBox.hpp" #include "OwnedPoint.hpp" #include "OwnedColor.hpp" // includes from c++ lib #include <iostream> #include <vector> #include <string> #include <memory> #include <algorithm> // includes from c lib #include <stdio.h> #include <stdlib.h> // incudes from GLEW #include <GL/glew.h> // includes from GLFW3 #include <GLFW/glfw3.h> // includes from GLM #define GLM_FORCE_RADIANS #include <glm/glm.hpp> #include <glm/gtc/matrix_transform.hpp> #include <glm/gtc/type_ptr.hpp> #include <glm/gtc/constants.hpp> #include <glm/gtx/fast_trigonometry.hpp> #include <glm/gtx/fast_exponential.hpp> #include <glm/gtx/rotate_vector.hpp> //#include <glm/transform.hpp> #define DEFAULT_WIDTH 800 #define DEFAULT_HEIGHT 600 #define DEFAULT_CENTER_X 0 #define DEFAULT_CENTER_Y 0 #define VX_PI 3.14159265358979323846264338327950288 // this contains definitions for the openGL visualizer widget // // the visualizer should be able to: // - visualize flow in 2d and 3d and move around in it // - visualize the geometry in 2d and 3d and move around in it // - visualize parametric or mesh CAD models and move around // - visualize and interact with point clouds namespace LookingGlass{ //************** base visualizer class ********************* class Visualizer{ public: Visualizer(); virtual ~Visualizer(); // getters and setters virtual std::string get_window_name() {return m_window_name;}; virtual void set_window_name(std::string w_name); // vertices (XYZRGBA) void set_num_vertices(unsigned int nverts) {m_vertices.assign(nverts*7, 1.0);}; void set_vertex_point(unsigned int i, const DrawablePoint & pt){ m_vertices[7*i] = pt.x(); m_vertices[7*i+1] = pt.y(); m_vertices[7*i+2] = pt.z(); } void set_vertex_color(unsigned int i, const DrawableColor & c){ m_vertices[7*i+3] = c.r(); m_vertices[7*i+4] = c.g(); m_vertices[7*i+5] = c.b(); m_vertices[7*i+6] = c.a(); } // elements // add a point (adds both a vertex and a point element) void add_point(const DrawablePoint & pt){ unsigned int nv = m_vertices.size()/7; m_vertices.push_back(pt.x()); m_vertices.push_back(pt.y()); m_vertices.push_back(pt.z()); m_vertices.push_back(1.0); m_vertices.push_back(1.0); m_vertices.push_back(1.0); m_vertices.push_back(1.0); m_point_elems.push_back(nv); } // add an edge (adds 2 vertices and an edge element) void add_edge(const DrawablePoint & p1, const DrawablePoint & p2, const DrawableColor & c = OwnedColor()){ unsigned int nv = m_vertices.size()/7; m_vertices.push_back(p1.x()); m_vertices.push_back(p1.y()); m_vertices.push_back(p1.z()); m_vertices.push_back(c.r()); m_vertices.push_back(c.g()); m_vertices.push_back(c.b()); m_vertices.push_back(c.a()); m_edge_elems.push_back(nv); m_vertices.push_back(p2.x()); m_vertices.push_back(p2.y()); m_vertices.push_back(p2.z()); m_vertices.push_back(c.r()); m_vertices.push_back(c.g()); m_vertices.push_back(c.b()); m_vertices.push_back(c.a()); m_edge_elems.push_back(nv+1); } // add a triangle (adds 3 vertices and a triangle element) void add_triangle(const DrawablePoint & p1, const DrawablePoint & p2, const DrawablePoint & p3, const DrawableColor & c = OwnedColor()){ unsigned int nv = m_vertices.size()/7; m_vertices.push_back(p1.x()); m_vertices.push_back(p1.y()); m_vertices.push_back(p1.z()); m_vertices.push_back(c.r()); m_vertices.push_back(c.g()); m_vertices.push_back(c.b()); m_vertices.push_back(c.a()); m_triangle_elems.push_back(nv); m_vertices.push_back(p2.x()); m_vertices.push_back(p2.y()); m_vertices.push_back(p2.z()); m_vertices.push_back(c.r()); m_vertices.push_back(c.g()); m_vertices.push_back(c.b()); m_vertices.push_back(c.a()); m_triangle_elems.push_back(nv+1); m_vertices.push_back(p3.x()); m_vertices.push_back(p3.y()); m_vertices.push_back(p3.z()); m_vertices.push_back(c.r()); m_vertices.push_back(c.g()); m_vertices.push_back(c.b()); m_vertices.push_back(c.a()); m_triangle_elems.push_back(nv+2); } // creates a point element associated to an existing vertex void set_point_element(unsigned int i){ m_point_elems.push_back(i); } // create an edge element associated with an existing 2 vertices void set_edge_element(unsigned int i1, unsigned int i2){ m_edge_elems.push_back(i1); m_edge_elems.push_back(i2); } // create a triangle element associated with an existing 3 vertices void set_triangle_element(unsigned int i1, unsigned int i2, unsigned int i3){ m_triangle_elems.push_back(i1); m_triangle_elems.push_back(i2); m_triangle_elems.push_back(i3); } void set_color_ramp(CRamp ramp_name); void set_color_interpolation(bool interp) {m_color_ramp.set_interpolation(interp);}; // //template <class T> void set_colorby(const T * color_by); // template <class T> // void set_colorby(T const * color_by, bool recalcminmax=true){ // if (color_by == nullptr){ // //std::cout << "SHIT THE COLORBY INPUT IS NULL" << std::endl; // return; // } // if (_colorby == nullptr) _colorby = new double[num_vertices]; // for (unsigned int i=0; i<num_vertices; i++) _colorby[i] = double(color_by[i]); // //std::cout << "converted all to double" << std::endl; // // find the min of the incoming values // if (recalcminmax){ // //std::cout << "readjusted the colorby" << std::endl; // _colorby_max = _colorby[0]; // for (auto i=1; i<num_vertices; i++){ // if (_colorby[i] > _colorby_max) _colorby_max = _colorby[i]; // } // _colorby_min = _colorby[0]; // for (auto i=1; i<num_vertices; i++){ // if (_colorby[i] < _colorby_min) _colorby_min = _colorby[i]; // } // //std::cout << "found the min and max" << std::endl; // } // // subtract out the min value // // normalize the colorby array from 0.0 to 1.0 // // with 0 input locked at 0.5 // //for (auto i=0; i<num_vertices; i++) _colorby[i] = (_colorby[i] - _colorby_min)/(_colorby_max - _colorby_min); // float fsmax, fsmin, fsscale, xscale; // xscale = std::max(std::abs(_colorby_max), std::abs(_colorby_min)); // for (auto i=0; i<num_vertices; i++) _colorby[i] = (_colorby[i])/(xscale)*0.49 + 0.51; // //std::cout << "subtracted out the min value and normalized" << std::endl; // return; // } // template <class T> // void set_color_alpha(T const * alpha, bool recalcminmax=true){ // if (alpha == nullptr){ // //std::cout << "SHIT THE ALPHA INPUT IS NULL" << std::endl; // return; // } // if (_color_alpha == nullptr) _color_alpha = new double[num_vertices]; // for (unsigned int i=0; i<num_vertices; i++) _color_alpha[i] = double(alpha[i]); // if (recalcminmax){ // //std::cout << "readjusted the alpha" << std::endl; // _alpha_max = _color_alpha[0]; _alpha_min = _color_alpha[0]; // for (auto i=1; i<num_vertices; i++){ // if (_color_alpha[i] > _alpha_max) _alpha_max = _color_alpha[i]; // if (_color_alpha[i] < _alpha_min) _alpha_min = _color_alpha[i]; // } // // normalize the values from 0.1 to 1.0 // if (_alpha_max == _alpha_min){ // for (auto i=0; i<num_vertices; i++) _color_alpha[i] = 1.0; // } // else { // for (auto i=0; i<num_vertices; i++) _color_alpha[i] = (_color_alpha[i] - _alpha_min)/(_alpha_max-_alpha_min)*0.3 + 0.7; // } // } // } //virtual void set_custom_colors(rgb * colors); //void set_lock_rotation(bool lock_mode); virtual void set_test_case(); void calculate_bounds(){ double npts = m_vertices.size()/7; double xcen=0, ycen=0, zcen=0; for (auto i=0; i<m_vertices.size()/7; i++){ xcen += m_vertices[7*i]/npts; ycen += m_vertices[7*i+1]/npts; zcen += m_vertices[7*i+2]/npts; } m_centroid = OwnedPoint(xcen,ycen,zcen); double xmin=m_vertices[0], ymin=m_vertices[1], zmin=m_vertices[2]; double xmax=m_vertices[0], ymax=m_vertices[1], zmax=m_vertices[2]; for (auto i=0; i<m_vertices.size()/7; i++){ if (m_vertices[7*i] < xmin) xmin = m_vertices[7*i]; if (m_vertices[7*i+1] < ymin) ymin = m_vertices[7*i+1]; if (m_vertices[7*i+2] < zmin) zmin = m_vertices[7*i+2]; if (m_vertices[7*i] > xmax) xmax = m_vertices[7*i]; if (m_vertices[7*i+1] > ymax) ymax = m_vertices[7*i+1]; if (m_vertices[7*i+2] > zmax) zmax = m_vertices[7*i+2]; } std::cout << "xmin: " << xmin << " xmax: " << xmax << std::endl; std::cout << "ymin: " << ymin << " ymax: " << ymax << std::endl; std::cout << "zmin: " << zmin << " zmax: " << zmax << std::endl; std::cout << "centroid: " << xcen << ", " << ycen << ", " << zcen << std::endl; m_bounding_box = DrawableBox(std::shared_ptr<DrawablePoint>(new OwnedPoint(xmin,ymin,zmin)), std::shared_ptr<DrawablePoint>(new OwnedPoint(xmax,ymax,zmax))); } // running the Visualizer virtual void run(); protected: // context data GLFWwindow * m_window_ptr; std::string m_window_name; // model related data std::vector<GLfloat> m_vertices; // holds the vertex data (XYZRGBA) std::vector<GLuint> m_point_elems; // element with 1 point std::vector<GLuint> m_edge_elems; // element of 2 points std::vector<GLuint> m_triangle_elems; // element of 3 points OwnedPoint m_centroid; DrawableBox m_bounding_box; // colors ... so pretty std::vector<double> m_colorby; std::vector<double> m_color_alpha; double m_colorby_min, m_colorby_max; double m_alpha_min, m_alpha_max; // virtual void draw_model(); bool m_display_triangles = true; bool m_display_edges = true; bool m_display_points = true; void draw_points(); void draw_edges(); void draw_triangles(); // color bar display ColorRamp m_color_ramp; bool m_display_colorbar; // std::vector<GLfloat> m_colorbar_vertices; // std::vector<GLuint> m_colorbar_elements; // std::vector<GLfloat> m_colorbar_colors; // GLuint m_vao_colorbar, m_vbo_colorbar_vertices, m_vbo_colorbar_colors, m_ebo_colorbar; // GLuint m_colorbar_vertex_shader, m_colorbar_fragment_shader, m_colorbar_shader_program; // GLint m_colorbar_pos_attrib, m_colorbar_color_attrib; // virtual const GLchar * ColorBar_v_glsl(); // virtual const GLchar * ColorBar_f_glsl(); // virtual void update_colorbar(); // virtual void compile_colorbar(); // virtual void draw_colorbar(); // virtual void free_colorbar(); // compass data and display // model shaders and buffer objects GLuint m_vbo, m_vao; GLuint m_ebo_points, m_ebo_edges, m_ebo_triangles; GLuint m_vertexShader, m_fragmentShader, m_shaderProgram; GLint m_uniModel, m_uniView, m_uniProj; // visualizer user viewing data glm::mat4 m_model, m_view, m_proj; glm::vec3 m_eye_vec, m_focus_vec, m_up_vec; glm::vec3 m_new_eye, m_new_focus; glm::vec3 m_camera_side, m_camera_up; float m_rotdeg, m_zoom_level, m_zoom_scale, m_eyez_init; // status data bool m_left_mouse_engaged; // is the left mouse button clicked? bool m_middle_mouse_engaged; // is the middle mouse button clicked? bool m_right_mouse_engaged; // is the right mouse button clicked? double m_x_upon_click, m_y_upon_click; // x and y positions of mouse upon click bool m_visualizer_active; // is the window currently drawn? bool m_rotation_lock; // lock mouse rotations? bool m_pan_lock; // lock mouse panning bool m_zoom_lock; // lock mouse zooming // base callbacks to interface with GLFW virtual void onMouseClick(int button, int action, int modifiers); virtual void onMouseWheel(double xoffset, double yoffset); virtual void onKeyboard(int key, int scancode, int action, int modifiers); virtual void onCursorPosition(double xpos, double ypos); // derived callbacks defined by me virtual void onMouseLeftDrag(double xpos, double ypos); virtual void onMouseRightDrag(double xpos, double ypos); virtual void onMouseMiddleDrag(double xpos, double ypos); /* virtual void onKeyDown(unsigned char key, int x, int y); virtual void onKeyUp(unsigned char key, int x, int y); virtual void onKeySpace(); virtual void onKeyC(); virtual void onKeyF(); virtual void onReshape(int new_width, int new_height); virtual void SetFullscreen(bool bFullscreen); virtual void cycleColorRamp(); */ virtual void recalcCamera(); // functions related to the context creation and main loop rendering virtual const GLchar * VertexShaderSource(); virtual const GLchar * FragmentShaderSource(); virtual void onInit(); virtual void onPrepareData(); virtual void onColors(); virtual void onAlpha(); virtual void onRender(); virtual void onShaders(); virtual void PreLoopTasks(); virtual bool MainLoop(); virtual void LoopTasks(); virtual void onExit(); virtual void onRefresh(); // everything is already prepared, just refresh the screen private: // base callbacks for GLFW functions static void sMouseClick(GLFWwindow * window, int button, int action, int modifiers); static void sMouseWheel(GLFWwindow * window, double xoffset, double yoffset); static void sKeyboard(GLFWwindow * window, int key, int scancode, int action, int modifiers); static void sCursorPosition(GLFWwindow * window, double xpos, double ypos); }; } #endif
Java
UTF-8
154
2.65625
3
[]
no_license
package blast; public class BornFactory implements BlastFactory { @Override public Blast add(int x, int y) { return new Born(x, y); } }
C#
UTF-8
4,499
2.75
3
[]
no_license
using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.Events; public class SH_ColliderDelegate : MonoBehaviour { public enum InteractionType { Script, Collider, Trigger, } public enum ColliderCondition { None, Name, Tag, } #region How will events be called [Tooltip("How will the events be called?" + "\n<b>Script:</b> Events will be called by external script." + "\nCollider: Events will be called when this objects collides." + "\nTrigger: Events will be called when something enters the trigger collider on this object.")] #endregion [Header("Interaction Type")] public InteractionType interactionType; [Tooltip("A tag for the collider on this object. Useful for extra check when calling events via external script.")] public string colliderTag; [Header("Collider Conditions")] [Tooltip("A condition that the other colliding object should meet before events are called." + "\nNone: No condition must be met." + "\nName: Other Collider must have specified name." + "\nTag: Other Collider must have specified tag.")] public ColliderCondition colliderCondition; public string condition; [Header("Other Proporties")] public float invokeDelay; [Header("Events")] [SerializeField] private UnityEvent onEnter; [SerializeField] private UnityEvent onExit; public delegate void Delegate(); public Delegate toCall; #region Script Callable public void GotCollision() { onEnter.Invoke(); } public void GotCollision(Delegate toCall, bool callEvent = true) { toCall.Invoke(); if (callEvent) onEnter.Invoke(); } #endregion #region Triggers private void OnTriggerEnter(Collider other) { if (interactionType == InteractionType.Trigger) { if (ConditionCheck(other)) StartCoroutine(InvokeDelay(onEnter, invokeDelay)); } } private void OnTriggerExit(Collider other) { if (interactionType == InteractionType.Trigger) { if (ConditionCheck(other)) StartCoroutine(InvokeDelay(onExit, invokeDelay)); } } #endregion #region Collisions private void OnCollisionEnter(Collision collision) { if (interactionType == InteractionType.Collider) { if (ConditionCheck(collision)) StartCoroutine(InvokeDelay(onEnter, invokeDelay)); } } private void OnCollisionExit(Collision collision) { if (interactionType == InteractionType.Collider) { if (ConditionCheck(collision)) StartCoroutine(InvokeDelay(onExit, invokeDelay)); } } #endregion private bool ConditionCheck(Collision collision) { bool toReturn = false; switch (colliderCondition) { case ColliderCondition.None: toReturn = true; break; case ColliderCondition.Name: if (collision.gameObject.name == condition) toReturn = true; break; case ColliderCondition.Tag: if (collision.gameObject.tag == condition) toReturn = true; break; } return toReturn; } private bool ConditionCheck(Collider collider) { bool toReturn = false; switch (colliderCondition) { case ColliderCondition.None: toReturn = true; break; case ColliderCondition.Name: if (collider.gameObject.name == condition) toReturn = true; break; case ColliderCondition.Tag: if (collider.gameObject.tag == condition) toReturn = true; break; } return toReturn; } private IEnumerator InvokeDelay(UnityEvent toCall, float waitTime) { yield return new WaitForSeconds(waitTime); toCall.Invoke(); } #region Context Menu [ContextMenu("Call OnEnter")] public void CallOnEnter() { onEnter.Invoke(); } [ContextMenu("Call OnExit")] public void CallOnExit() { onExit.Invoke(); } #endregion }
Java
UTF-8
2,420
3.1875
3
[]
no_license
package com.ATemplates_DataStructures.DFS_LeetCode.Tree_DFS; import com.LeetCode.TreeNode; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.LinkedList; import java.util.Queue; public class No101_SymmetricTree { private final static Logger logger = LoggerFactory.getLogger(No101_SymmetricTree.class); public static void main(String[] args) { testNo101_SymmetricTree(); } private static void testNo101_SymmetricTree() { No101_SymmetricTree No101_SymmetricTree = new No101_SymmetricTree(); // MyLogger.info("result 2 v.s. " + No101_SymmetricTree.isSymmetric("12")); // MyLogger.info("result 1 v.s. " + No101_SymmetricTree.isSymmetric("10")); } /** * @param root * @return */ public boolean isSymmetric(TreeNode root) { if (root == null) { return true; } // core logic if (root.left == null) { return root.right == null; } else if (root.right == null) { return false; } Queue<TreeNode> queueLeft = new LinkedList<>(); Queue<TreeNode> queueRight = new LinkedList<>(); queueLeft.add(root.left); queueRight.add(root.right); while (!queueLeft.isEmpty()) { if (queueRight.isEmpty()) { return false; } TreeNode currentLeft = queueLeft.poll(); TreeNode currentRight = queueRight.poll(); if (currentLeft != null || currentRight != null) { if ((currentLeft == null) || (currentRight == null) || (currentLeft.val != currentRight.val)) { return false; } queueLeft.add(currentLeft.left); queueLeft.add(currentLeft.right); queueRight.add(currentRight.right); queueRight.add(currentRight.left); } } return true; } private static class MyLogger { static boolean isDebugging = false; static boolean isInfoing = true; static void debug(Object message) { if (isDebugging) { System.out.println("MyLogger.Debugging = " + message); } } static void info(Object message) { if (isInfoing) { System.out.println("MyLogger.Debugging = " + message); } } } }
Python
UTF-8
5,419
2.75
3
[]
no_license
#!/usr/bin/env python3 import json import os import threading from dicttoxml import dicttoxml from httpserver.argparser.ArgParser import ArgParser from httpserver.http.HttpRequest import HttpRequest from httpserver.http.HttpResponse import HttpResponse from httpserver.http.HttpServer import HttpServer from httpserver.io.Directory import Directory from httpserver.io.File import File from httpserver.util.parser import parse_request from receiver.receiver import Receiver def get_directory_contents(args, path, depth=0): """ Get a generator containing a directory's contents. :param path: absolute path of directory the contents of which we want to view :return: generator containing files first and then directories (in that order), in the directory """ files, directories = [], [] for file in os.listdir(path): file_path = os.path.join(path, file) if os.path.isdir(file_path): directories.append(file_path) else: files.append(file_path) for file in files: if args.verbose: print(f"Yielding file: {file}") yield File(file) for directory in directories: if args.verbose: print(f"Yielding directory: {directory}") yield Directory(directory, get_directory_contents(args, directory, depth + 1), depth + 1) def get_json_representation(args, path): return json.dumps([x.__repr__() for x in get_directory_contents(args, path)]) def get_xml_representation(args, path): return dicttoxml([x.__repr__() for x in get_directory_contents(args, path)], custom_root="structure", attr_type=False).decode("utf-8") def get_html_representation(args, path): return ''.join([x.get_html() for x in get_directory_contents(args, path)]) def get_plain_text_representation(args, path): return ''.join([x.get_plain_text() for x in get_directory_contents(args, path)]) content_types = { "application/json": get_json_representation, "application/xml": get_xml_representation, "text/html": get_html_representation, "text/plain": get_plain_text_representation, "*/*": get_json_representation } def response(code, status, content, content_type="text/plain"): return HttpResponse("HTTP/1.0", code, status, {"Content-Length": len(content), "Content-Type": content_type}, content) def list_directory(args, path, content_type): try: if args.verbose: print(f"Listing directory at {path}") content = content_types[content_type](args, path) return response(200, "OK", content, content_type) except FileNotFoundError as e: if args.verbose: print(f"Directory {path} does not exist.") return response(404, "Not Found", str(e), "text/plain") except NotADirectoryError as e: if args.verbose: print(f"{path} is not a directory.") return response(400, "Bad Request", str(e), "text/plain") except KeyError: content = "Cannot figure out how you want to see the data." if args.verbose: print(f"Valid Accept header not specified. Must be one of: [{', '.join(content_types.keys())}]") return response(400, "Bad Request", content, "text/plain") def get_file_contents(args, path): content, code, status = File(path).get_contents() if args.verbose: print(f"{code} {status}: {content if code is not 200 else f'Read file at {path}'}") return response(code, status, content, "text/plain") def get(args, request: HttpRequest): if request.path == '/': content_type = request.headers["Accept"].split(',')[0] if "Accept" in request.headers else "application/json" return list_directory(args, args.directory, content_type) else: res = get_file_contents(args, os.path.join(args.directory, request.path[1:])) if 'download' in request.qparams: split_path = request.path.split("/") filename = split_path[len(split_path) - 1] res.headers['Content-Disposition'] = 'attachment; filename="' + filename + '"' return res def post(args, request: HttpRequest): path = os.path.join(args.directory, request.path[1:]) content, code, status = File(path).write(request.content, 'overwrite' in request.qparams) if args.verbose: print(f"{code} {status}: {content}") return response(code, status, content, "text/plain") def listen_to_client(client, address): print('Connected', address) data = client.recv(1024).decode('utf-8') request = parse_request(data) if request.verb == 'GET': response = get(args, request) client.sendall(bytes(response.__repr__(), "utf-8")) elif request.verb == 'POST': response = post(args, request) client.sendall(bytes(response.__repr__(), "utf-8")) client.close() if __name__ == '__main__': parser = ArgParser() args = parser.parse_args() args.directory = os.path.abspath(os.path.join(os.getcwd(), args.directory)) print(args) port = args.port http_server = Receiver(8007) try: print(f'Listening on port {port}') http_server.listen() while True: client, address = http_server.accept() threading.Thread(target=listen_to_client, args=(client, address)).start() except KeyboardInterrupt: http_server.kill() print('\nTerminated')
TypeScript
UTF-8
4,756
2.578125
3
[]
no_license
import * as path from "path"; import * as fs from "fs"; import * as child_process from "child_process"; import * as readline from "readline"; let protoClientDir = path.join(__dirname, "../../../protoClient"); // 客户端协议目录(服务器没有客户端svn权限,故将协议生成到公用目录,由客户端自己拉取) console.time("cmd build ok "); routeBuild(() => { console.timeEnd("cmd build ok "); console.time("proto build ok "); let fileArr = fs.readdirSync(path.join(__dirname, "../protoSrc")); fileArr.forEach((file) => { if (!file.endsWith(".proto")) { return; } let basename = path.basename(file, ".proto"); let proto_file = path.join(__dirname, "../protoSrc", file); let dist_js = path.join(__dirname, "../proto", basename + ".js"); let dist_dts = path.join(__dirname, "../proto", basename + ".d.ts"); // 服务器使用 let cmd1 = `pbjs -t static-module -w commonjs -o ${dist_js} ${proto_file}`; let cmd2 = `pbts -o ${dist_dts} ${dist_js}`; execSync(cmd1); execSync(cmd2); // 客户端协议目录。 注: creator 使用需要将文件中 require("protobufjs/minimal") 替换为 protobuf let text = fs.readFileSync(dist_js).toString(); text = text.replace(`require("protobufjs/minimal")`, `protobuf`); fs.writeFileSync(path.join(protoClientDir, path.basename(dist_js)), text); fs.copyFileSync(dist_dts, path.join(protoClientDir, path.basename(dist_dts))); }); console.timeEnd("proto build ok "); }); function execSync(cmd: string) { child_process.execSync(cmd); } function routeBuild(cb: Function) { let routePath = "../config/sys/route.ts"; let serverPath = "../config/cmd.ts"; let filepath = path.join(__dirname, routePath); if (!fs.existsSync(filepath)) { console.log(" -> Not find the script: " + filepath); process.exit(); } let readStream = fs.createReadStream(filepath); let read_l = readline.createInterface({ "input": readStream }); let hasStart = false; let cmdObjArr: { "cmd": string, "note": string }[] = []; read_l.on("line", function (line) { line = line.trim(); if (line === "") { return; } if (!hasStart) { if (line.indexOf("export") === 0) hasStart = true; return; } if (line.indexOf("]") === 0) { serverCmd(); clientCmd(); read_l.close(); return; } if (line.indexOf('"') !== 0) { return; } line = line.substring(1); let index = line.indexOf('"'); if (index === -1) { return; } let cmd = line.substring(0, index); let note = ""; index = line.indexOf("//"); if (index !== -1) { note = line.substring(index + 2).trim(); } cmdObjArr.push({ "cmd": cmd, "note": note }); }); read_l.on("close", function () { cb && cb(); }); function serverCmd() { let endStr = `export const enum cmd {\n` let index = 0; for (let one of cmdObjArr) { if (one.note) { endStr += `\t/**\n\t * ${one.note}\n\t */\n`; } let oneStr = one.cmd; if (one.cmd.indexOf('.') !== -1) { let tmpArr = one.cmd.split('.'); oneStr = tmpArr[0] + '_' + tmpArr[1] + '_' + tmpArr[2]; } endStr += `\t${oneStr} = ${index},\n`; index++; } endStr += '}'; fs.writeFileSync(path.join(__dirname, serverPath), endStr); } function clientCmd() { let endStrCs = 'public class Cmd\n{\n' let endStrTs = 'export const enum cmd {\n' for (let one of cmdObjArr) { if (one.note) { endStrCs += `\t/// <summary>\n\t/// ${one.note}\n\t/// </summary>\n`; endStrTs += `\t/**\n\t * ${one.note}\n\t */\n`; } let oneStr = one.cmd; if (one.cmd.indexOf('.') !== -1) { let tmpArr = one.cmd.split('.'); oneStr = tmpArr[0] + '_' + tmpArr[1] + '_' + tmpArr[2]; } endStrCs += `\tpublic const string ${oneStr} = "${one.cmd}";\n`; endStrTs += `\t${oneStr} = "${one.cmd}",\n`; } endStrCs += '}'; endStrTs += '}'; fs.writeFileSync(path.join(protoClientDir, "cmdClient.ts"), endStrTs); } }
Java
UTF-8
3,335
3.03125
3
[]
no_license
package com.barfly.hobservable.collectionsexample; import com.barfly.hobservable.collections.ListObservable; import java.util.ArrayList; /** * * @author jonathanodgis */ public class ContactsList { private final String userID; private final ArrayList<Contact> contacts; private final ListObservable mainObservable; private final ListObservable addObservable; private final ListObservable removeObservable; private final ListObservable editObservable; public ContactsList(String userID, ListObservable parent) { this.userID = userID; contacts = new ArrayList<>(); mainObservable = new ListObservable<>("Main ListObservable", parent, contacts); addObservable = new ListObservable<>("Add ListObservable", mainObservable, contacts); removeObservable = new ListObservable<>("Remove ListObservable", mainObservable, contacts); editObservable = new ListObservable<>("Edit ListObservable", mainObservable, contacts); } public ContactsList(String userID) { this.userID = userID; contacts = new ArrayList<>(); mainObservable = new ListObservable<>("Main ListObservable", null, contacts); addObservable = new ListObservable<>("Add ListObservable", mainObservable, contacts); removeObservable = new ListObservable<>("Remove ListObservable", mainObservable, contacts); editObservable = new ListObservable<>("Edit ListObservable", mainObservable, contacts); } public void addContact(Contact contact) { Object event = contact + " was added to the list"; contacts.add(contact); addObservable.notifyObservers(event); } public void removeContact(Contact contact) { Object event = contact + " was removed from the list"; contacts.remove(contact); removeObservable.notifyObservers(event); } /* public void editContact(Contact contact, String name, String number) { Contact originalContact = new Contact(contact.getID(), contact.getNumber()); ListObservable parent = (ListObservable) editObservable.getParentObservable(); contact.setID(name); contact.setNumber(number); Object event = contact + " was edited in the list" + " (Originally " + originalContact + ")"; //editObservable.add(event); //parent.add(event); editObservable.notifyObservers(editObservable.get(editObservable.size()-1)); } */ public String getUserID() { return this.userID; } @Override public String toString() { return this.userID + "'s contacts" + " | " + size() + " contacts"; } public ArrayList<Contact> getContacts() { return this.contacts; } public int size() { return contacts.size(); } public ListObservable getMainObservable() { return this.mainObservable; } public ListObservable getAddObservable() { return this.addObservable; } public ListObservable getRemoveObservable() { return this.removeObservable; } public ListObservable getEditObservable() { return this.editObservable; } }
Java
UTF-8
588
2.65625
3
[]
no_license
package no.hiof.larseknu.studentprosjekt; import java.util.ArrayList; public class Main { public static void main(String[] args) { // Oppretter to kursobjekter Kurs androidProgrammering = new Kurs("Android-Programmering", "ITF1337", 10); Kurs kvanteFysikk = new Kurs("Kvantefysikk", "ITF9999", 20); // Skriver ut litt kursinformasjon System.out.println(androidProgrammering.getNavn() + " har " + androidProgrammering.getStudiePoeng() + " studiepoeng."); System.out.println(kvanteFysikk.getNavn() + " har emnekode: " + kvanteFysikk.getKode()); } }
Java
UTF-8
9,858
2.421875
2
[]
no_license
package com.wangrui027.javafx.weather; import com.google.gson.JsonObject; import com.google.gson.JsonParser; import com.wangrui027.javafx.weather.model.City; import com.wangrui027.javafx.weather.model.County; import com.wangrui027.javafx.weather.model.Province; import com.wangrui027.javafx.weather.model.WeatherDataModel; import com.wangrui027.javafx.weather.util.UnirestUtils; import com.wangrui027.javafx.weather.util.WeatherDataModelBuildUtils; import com.wangrui027.javafx.weather.util.WeatherDataUtils; import javafx.event.ActionEvent; import javafx.fxml.FXML; import javafx.fxml.Initializable; import javafx.geometry.Insets; import javafx.geometry.Pos; import javafx.scene.control.ChoiceBox; import javafx.scene.control.Label; import javafx.scene.control.Tooltip; import javafx.scene.layout.HBox; import javafx.scene.layout.VBox; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.jsoup.Jsoup; import org.jsoup.nodes.Document; import org.jsoup.nodes.Element; import org.jsoup.select.Elements; import java.net.URL; import java.util.List; import java.util.ResourceBundle; public class WeatherAppController implements Initializable { private static final Logger logger = LogManager.getLogger(WeatherAppController.class); private static final UnirestUtils restUtils = UnirestUtils.builder().build(); /** * 省份选择框 */ @FXML private ChoiceBox<String> provinceChoiceBox; /** * 城市选择框 */ @FXML private ChoiceBox<String> cityChoiceBox; /** * 区县选择框 */ @FXML private ChoiceBox<String> countryChoiceBox; @FXML private Label dataUpdateTimeLabel; @FXML private HBox weatherInfoBox; /** * 视图是否被打开 */ private boolean viewOpened = false; @Override public void initialize(URL location, ResourceBundle resources) { List<Province> provinceList = WeatherDataUtils.getProvinceList(); List<City> cityList = provinceList.get(0).getCityList(); List<County> countyList = cityList.get(0).getCountyList(); String provinceName = null; String cityName = null; // String regionJson = restUtils.get("http://ipw.cn/api/ip/region"); // JsonObject jsonObject = JsonParser.parseString(regionJson).getAsJsonObject(); // if (jsonObject.has("Address")) { // jsonObject = jsonObject.getAsJsonObject("Address"); // provinceName = jsonObject.get("Province").getAsString(); // cityName = jsonObject.get("City").getAsString(); // } if (provinceName != null) { for (Province province : provinceList) { if (provinceName.startsWith(province.getName())) { cityList = province.getCityList(); provinceName = province.getName(); break; } } } if (cityName != null) { for (City city : cityList) { if (cityName.startsWith(city.getName())) { countyList = city.getCountyList(); cityName = city.getName(); break; } } } for (Province province : provinceList) { provinceChoiceBox.getItems().add(province.getName()); } for (City city : cityList) { cityChoiceBox.getItems().add(city.getName()); } for (County county : countyList) { countryChoiceBox.getItems().add(county.getName()); } if (provinceName != null && cityName != null) { provinceChoiceBox.getSelectionModel().select(provinceName); cityChoiceBox.getSelectionModel().select(cityName); } else { provinceChoiceBox.getSelectionModel().selectFirst(); } queryWeather(); } /** * 省份选择框被选中事件 * * @param event */ public void provinceChoiceBoxAction(ActionEvent event) { cityChoiceBox.getItems().removeAll(cityChoiceBox.getItems()); String provinceName = provinceChoiceBox.getValue(); List<City> cityList = WeatherDataUtils.getCityListByProvince(provinceName); for (City city : cityList) { cityChoiceBox.getItems().add(city.getName()); } cityChoiceBox.getSelectionModel().selectFirst(); } /** * 城市选择框被选中事件 * * @param event */ public void cityChoiceBoxAction(ActionEvent event) { countryChoiceBox.getItems().removeAll(countryChoiceBox.getItems()); String cityName = cityChoiceBox.getValue(); List<County> countyList = WeatherDataUtils.getCountryListByCity(cityName); for (County county : countyList) { countryChoiceBox.getItems().add(county.getName()); } countryChoiceBox.getSelectionModel().selectFirst(); } /** * 确定按钮响应事件 * * @param event */ public void countryConfirmAction(ActionEvent event) { queryWeather(); } private void queryWeather() { String provinceName = provinceChoiceBox.getValue(); String cityName = cityChoiceBox.getValue(); String countryName = countryChoiceBox.getValue(); if (viewOpened) { County county = getCountryByName(provinceName, cityName, countryName); if (county != null) { logger.info(String.format("当前选中区域【%s - %s - %s】,areaId【%s】", provinceName, cityName, county.getName(), county.getAreaId())); String url = String.format("http://www.weather.com.cn/weather/%s.shtml", county.getAreaId()); String html = restUtils.get(url); Document doc = Jsoup.parse(html); String dataUpdateTime = doc.select("#update_time").val(); dataUpdateTimeLabel.setText(dataUpdateTime); weatherInfoBox.getChildren().removeAll(weatherInfoBox.getChildren()); Elements elements = doc.select("#7d>ul>li"); for (int i = 0; i < elements.size(); i++) { Element element = elements.get(i); WeatherDataModel model = WeatherDataModelBuildUtils.build(element); weatherInfoBox.getChildren().add(getWeatherVBox(model, i)); } } else { dataUpdateTimeLabel.setText("数据异常,请检查【city.json】配置文件"); logger.error(String.format("当前选中区域【%s - %s - %s】在【city.json】配置文件中未匹配到数据!", provinceName, cityName, countryName)); } } else { viewOpened = true; } } private VBox getWeatherVBox(WeatherDataModel model, int index) { VBox vBox = new VBox(); vBox.getStyleClass().add("weatherVBox"); vBox.getStyleClass().add(model.getBackgroundCssClass()); vBox.setAlignment(Pos.CENTER); vBox.setMinWidth(100); vBox.setPadding(new Insets(10, 5, 10, 5)); Label dateLabel = new Label(model.getDate()); Label icon1Label = new Label(); icon1Label.setMinWidth(30); icon1Label.setMinHeight(30); icon1Label.getStyleClass().add("wea_icon"); icon1Label.getStyleClass().add(model.getIcon1CssClass()); Label icon2Label = new Label(); icon2Label.setMinWidth(30); icon2Label.setMinHeight(30); icon2Label.getStyleClass().add("wea_icon"); icon2Label.getStyleClass().add(model.getIcon2CssClass()); Label titleLabel = new Label(model.getTitle()); Label temperatureLabel = new Label(model.getTemperature()); HBox winIconBox = new HBox(); winIconBox.setAlignment(Pos.CENTER); Label winIcon1Label = new Label(); winIcon1Label.setTooltip(new Tooltip(model.getWind1())); winIcon1Label.setMinWidth(24); winIcon1Label.setMinHeight(24); winIcon1Label.getStyleClass().add("win_icon"); winIcon1Label.getStyleClass().add(model.getWind1CssClass()); Label winIcon2Label = new Label(); winIcon2Label.setTooltip(new Tooltip(model.getWind2())); winIcon2Label.setMinWidth(24); winIcon2Label.setMinHeight(24); winIcon2Label.getStyleClass().add("win_icon"); winIcon2Label.getStyleClass().add(model.getWind2CssClass()); winIconBox.getChildren().add(winIcon1Label); winIconBox.getChildren().add(winIcon2Label); Label windLevelLabel = new Label(model.getWindLevel()); vBox.getChildren().add(dateLabel); vBox.getChildren().add(icon1Label); vBox.getChildren().add(icon2Label); vBox.getChildren().add(titleLabel); vBox.getChildren().add(temperatureLabel); vBox.getChildren().add(winIconBox); vBox.getChildren().add(windLevelLabel); return vBox; } private County getCountryByName(String provinceName, String cityName, String countryName) { List<Province> provinceList = WeatherDataUtils.getProvinceList(); for (Province province : provinceList) { if (province.getName().equals(provinceName)) { List<City> cityList = province.getCityList(); for (City city : cityList) { if (city.getName().equals(cityName)) { List<County> countyList = city.getCountyList(); for (County county : countyList) { if (county.getName().equals(countryName)) { return county; } } } } } } return null; } }
Java
UTF-8
540
3.484375
3
[]
no_license
package com.sherkhancrs; import java.util.Scanner; public class FizzBuzz { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); System.out.print("Number: "); int number = scanner.nextInt(); String result = ""; if (number%3==0) { result += "Fizz"; } if (number%5==0) { result += "Buzz"; } if (number%5!=0 && number%3!=0) { result += number; } System.out.println(result); } }
Python
UTF-8
2,473
2.859375
3
[ "MIT" ]
permissive
"""Class for writing C-code to create a vxTableLookupNode object. Done by parsing the graph parameters of the xml description of the node. parsed_string contains the C code to be written to file """ from base_node import BaseNode # Valid values for the vx_lut parameter, i.e. implemented default LUTs # TODO: Actually implement the default LUTs DEFAULT_LUTs = {'LUT_DUMMY': 'vxCreateLUT(graphmanager_get_context(graph_manager), VX_TYPE_UINT8, 256)', 'LUT_ZERO': 'graphmanager_utils_create_lut_zero()', 'LUT_IDENTITY': 'graphmanager_utils_create_lut_unity()'} class TableLookup(BaseNode): """Class for parsing node with the given class name.""" def __init__(self): """Initialization of Class object""" BaseNode.__init__(self) self.table_lookup_count = 0 def parse(self, graphparser, current_node, assignment_string, dry_run = False): """Parsing of xml and C code for creation of the function node.""" self.reset_parameters(graphparser, current_node, dry_run) parsed_string = "" #=============== # ERROR CHECKING #=============== self.require_nbr_input_edges(graphparser, current_node, 1) self.require_nbr_output_edges(graphparser, current_node, 1) #================= # PARSE PARAMETERS #================= if not self.node_has_errors: if self.table_lookup_count == 0 and not dry_run: self.table_lookup_count += 1 parsed_string += " vx_lut lut;\n" lut_type = self.parse_single_parameter(graphparser, "vx_lut", current_node) if lut_type not in DEFAULT_LUTs: err_string = "ERROR: LUT implementation for {} not found\n".format(lut_type) self.set_graph_has_errors(graphparser, current_node, err_string) else: parsed_string += " lut = " + DEFAULT_LUTs[lut_type] + ";\n" parsed_string += " " + assignment_string + "vxTableLookupNode(graph_skeleton" parsed_string += self.parse_input_parameters(graphparser, current_node) parsed_string += ", lut" parsed_string += self.parse_output_parameters(graphparser, current_node) parsed_string += ");\n" parsed_string += " vxReleaseLUT(&lut);\n" parsed_string += self.append_to_io_arrays(graphparser, current_node) return parsed_string
Markdown
UTF-8
14,282
3.234375
3
[ "MulanPSL-2.0", "LicenseRef-scancode-mulanpsl-2.0-en", "LicenseRef-scancode-unknown-license-reference" ]
permissive
--- --- --- title: 第十九章 求情告饶 --- “在此期间,我们干了些什么呢?我们干了我们所能干的最糟糕的事,我们所干的事真该使我们更受人鄙视——我们背叛了阿玛丽亚,我们摆脱了她那无声的命令,我们不能这样生活下去,没有丝毫希望,我们就不能活,于是我们开始各用各的方式去请求或缠磨城堡宽恕我们。虽然我们知道,我们没有能力进行补救,我们也知道,我们和城堡惟一很有希望的联系就是通过索提尼,他是父亲的顶头上司,对父亲也有好感,但是由于已发生的事使我们无法再去找他,尽管如此,我们还是这样去做。父亲开了个头儿,他开始向村长、秘书、律师、文书等求情,但毫无作用,人家通常都不见他,如果由于用计谋或碰巧使得他被接见——听到这种消息,我们是多么欢欣鼓舞、额手称庆呀——他们也是极快地把他打发走,再也不接见他了。而且,要答复他也太容易了,城堡总是很好办。他究竟想要什么?他出了什么事?他想请求宽恕什么?城堡里什么时候有谁哪怕对他动过一个指头?不错,他变穷了,主顾都跑了,等等,但这些都是日常生活中常有的事,是手艺人和市场的事情,难道城堡什么事情都得管吗?事实上城堡什么都管,但是它不能单单为了一个人的利益而去粗暴地干预事态的发展。难道要城堡比方说派出官员去把父亲的主顾都追回来,强令他们再去照顾他的生意?可是,这时父亲提出异议——我们事前事后都在家里躲在角落里仔仔细细地讨论这些事情,好像避开阿玛丽亚似的,她虽然都看在眼里,却听之任之——可是,这时父亲提出异议说,他并不是在抱怨自己变穷,他在这儿所失去的一切,都能轻而易举地重新找回来,只要他得到宽恕,这一切都是次要的。可是究竟要宽恕他什么呢?人家答复他,至今并没有人告他。至少在记录簿上还没有记载,起码在律师能看到的记录簿上没有这样的记录,因此,就调查的结果而言,也没有人对他采取什么行动或准备采取什么行动。也许他能指出官方发布过什么针对他的指令?父亲指不出来。或者是否有某个官方机构进行过干预?对此父亲也一无所知。那么好吧,既然他什么都不知道,又没有发生过什么事情,那他想要什么呢?有什么可以宽恕他的呢?最多是他现在毫无目的地纠缠官府,这倒是一条不可宽恕的罪状。父亲没有罢休,那时他身体还很强壮,他被迫无所事事,因此有的是时间。‘我要恢复阿玛丽亚的名誉,现在不会再要很久了,’他每天都要对巴纳巴斯和我说上好几遍,不过说话声音很低,因为他不想让阿玛丽亚听见,虽然如此,但他也只是为了阿玛丽亚才这样说的,因为他事实上并不是想恢复名誉,而是希望得到宽恕。可是要得到宽恕,他就必须先证明自己有罪,而官府又都否认他有罪。他突然想起——这说明他的智力已减退了——人家不肯告诉他有什么罪过,是因为他钱缴得不够;直到那时为止,他总是只缴纳规定的费用,这些费用,至少就我们的经济情况来说已经是够高的了。可是现在他认为还得再多缴,这当然是不正确的,因为我们的官府虽然为省事起见,不必多费口舌而接受贿赂,但是这不会起任何作用。不过,既然父亲寄希望于此,我们也就不愿意使他失望。我们变卖了我们仅有的东西——几乎都是不可或缺的东西——,凑起钱来让父亲去奔走,有很长一段时间,每天早晨我们欣慰地看到父亲出门时口袋里至少都有几枚钱币在丁当作响。我们当然整天挨饿,而我们用那钱真正做到的惟一的一点便是使父亲保持一定的希望。可是这很难说是什么好事,他东奔西走,弄得精疲力竭;如果没有钱的话,这事本来很快就会得到应有的结局。这样一来就一天一天地拖下去。事实上人家不可能因为他多付了钱就额外开恩,因此有时某个文书至少假装去办,答应去查问,暗示已经找到一些线索,正在追查,这样做并不是他们的职责,仅仅是为了使父亲高兴;父亲听了这些话不但不怀疑,反而越来越相信。他把这种显然毫无意义的诺言带回来,好像已经重又把天大的幸福带回家来。他总是站在阿玛丽亚的背后,笑着脸,睁大眼睛,手指着阿玛丽亚向我们暗示,由于他的努力,阿玛丽亚得救的日子就要来临,没有人会比她本人更感到惊喜,可是现在一切还是秘密,我们都要严格保密。他的样子让人看了十分难受。要不是我们最后完全无能为力再把钱给父亲,这种情形一定还会继续很长时间。在这期间,经过多次恳求,巴纳巴斯被布龙斯维克收为助手,不过只允许他在黄昏时分天黑以后去领活,再在天黑的时候把做好的活送回去。必须承认,布龙斯维克为了我们,在生意上冒着一定的风险,不过他给巴纳巴斯的工钱很少,而巴纳巴斯的手艺是无懈可击的。巴纳巴斯的工钱勉强能使我们不至于完全饿死。我们经过精心准备,考虑周到后告诉父亲,我们再也没有钱给他了,他听了以后倒十分平静。他的理智已不再能理解他的意图是毫无希望的,可是他对接连不断的失望已感到厌烦了。他说——他说话已不如从前清楚了,以前他说话几乎过于清楚——他只还需要一点点钱,明天或者当天就可以打听到一切,现在一切都前功尽弃了,只因为没有钱,等等,可是他说话的语气表明他并不相信这一切。他又马上突然提出了新的计划。由于他无法证明自己有罪,因此继续通过官方途径也不会有什么结果,于是他就只好转而采取恳求的办法,去求助于官员们个人。他们中间肯定会有心慈手软的好心人,虽然在办公时不能大发慈悲,但是在公余之暇,在适当的时刻出其不意地找到他们,他们一定会大发慈悲的。” K一直全神贯注地听奥尔加叙述,听到这里便打断她的话,问道:“你认为这样做对吗?”虽然奥尔加继续说下去这个问题一定会有答案的,但是K却想马上就知道。 “不,”奥尔加说,“根本就谈不上什么同情或这一类东西。我们虽然少不更事,但是也明白这一点,父亲当然也明白,可是他已忘掉了这一点,就像他把绝大多数事情都忘记了一样。他想出来的计划是:站在靠近城堡官员们车辆来往的大路上,只要有机会,就向他们恳求宽恕。老实说,这个计划完全是想入非非,即使这种不可能的事发生了,他的请求真的让某位官员听到了,那又有什么用呢?难道单是一个官员就能宽恕吗?充其量也只有整个当局才能处理这种事情,而且连当局大概也只能给人定罪,不能给人宽恕。再说,即使有一个官员愿意下车过问此事,难道听了父亲这个可怜而又疲乏的老头子对他嘀咕的话就能弄清楚是怎么一回事?官员们都是受过很好教育的,但只限于某一方面,在他的业务范围内,他只要听一句话便能领悟掌握要领,可是把另一个部门的事向他讲上几个钟头,也许他会有礼貌地点点头,其实却一句也没有听懂。这都是很自然的;即使是涉及一个人自己的小小公事,一个官员耸耸肩膀就能处理的鸡毛蒜皮的事情,如果你想追根究底,那你一辈子也不会有个水落石出的。即使父亲凑巧碰上一个主管的官员,他没有有关的档案就什么也解决不了,尤其是不会在大路上解决,他不能宽恕,只能公事公办,为此又只能叫人履行正式手续,可是父亲早就那么做过而一事无成。父亲想不管用什么方式去实行这个新计划,他一定是已经到了山穷水尽的地步了。如果这种做法即使有一丝成功的希望,那么那条大路上就一定会挤满了请愿的人,可是这是不可能的事,连小学生也都明白,所以那条路上一个人影儿也没有。也许这也增强了父亲的希望。他从任何一件事情上都能找到理由来支持自己的希望。他也非常需要这样做;一个头脑正常的人根本就不必这样煞费苦心,光从表面的迹象就一定会清楚地看到这是不可能的。官员们进村来或回城堡去,并不是观光游览,村里和城堡里有公事等他们去办,因此他们来去都行色匆匆。他们也不会想到向车窗外张望,在外面寻找请愿人,因为车上装满了让他们看的文件。” “可是我看到过一辆官员雪橇的车厢内部,”K说,“那里面没有什么文件。”奥尔加的叙述给他打开了一个这样广阔而几乎不可信的天地,使得他忍不住想把自己的小小经历与它联系在一起,以便使自己更加确信它确实存在,自己所经历的事情也确实存在。 “那有可能,”奥尔加说,“不过,如果是那样的话,那就更糟糕。这说明那位官员有如此重要的公务在身,有关文件太珍贵或数量太多,不能随身携带,这样的官员都是马不停蹄、飞驰而过的。总而言之,没有一个会抽出时间见父亲的。况且,通向城堡的路有好几条。有时一条路成了热门,大多数车辆就都走这一条路,有时另外一条路成了热门,于是大家又都挤到那儿去。这种变化究竟有什么规律,还没有找出来。有时早上八点钟,大家都走一条路,半小时后又都走另一条路,十分钟以后又改走第三条路,半小时以后也许又回到第一条路上去,然后就会一整天都走这一条路,但是随时都有改变的可能。虽然所有大路都在村子附近汇合,但是到了那儿所有的车辆都跑得飞快,而在接近城堡时速度才会有所放慢。车辆来往的数量也和出行时选择道路一样没有规律,难以看清。有时一连好几天看不见一辆马车,有时又成群结队,蜂拥而来。面对这一切,你想一想我们的父亲吧。他穿上最好的一套衣服,不久那就成了他惟一的一套衣服了,每天早晨带着我们良好的祝愿离家而去。他把消防队的一枚小徽章带在身边,其实他是不该保留那枚徽章的,一走出村子就把它别上,在村子里他不敢戴,怕被人看见,虽然徽章小得两步以外就几乎看不见,可是父亲认为它甚至能引起过往官员对他的注意。离城堡入口不远的地方有一个菜园子,业主名叫贝尔图赫,他专门向城堡供应蔬菜。父亲就在菜园栅栏的狭长石座上选择了一个位置。贝尔图赫容忍了,因为他以前和父亲关系很好,也是父亲最忠实的主顾之一,由于他一只脚有点畸形,认为只有父亲才能给他做合适的靴子。如今父亲就一天又一天地坐在那儿,那年秋天天气阴凉多雨,但是父亲毫不在乎天气好坏,每天早晨到了一定的时间便打开门,和我们挥手道别,晚上回来时浑身淋得湿透,倒身躺在一个角落里,背也似乎一天比一天更驼了。最初他还把这一天遇到的小事情讲给我们听,诸如贝尔图赫出于怜悯和往日的交情,从栅栏上给他扔过来一条毯子啦,或是他在路过的马车中认出了这个或那个官员啦,或是这个或那个车夫认出他是谁,开玩笑地用马鞭轻轻碰他一下啦,等等。后来他就不说这些事情了,显然他已经放弃了在那儿能有任何收获的希望,他把到那儿去呆上一天仅仅看做是他应尽的义务,一件枯燥无味的差使。他的风湿痛就是打那时开始的,冬天快到了,雪下得比往年早,我们这儿冬天开始得很早;嗯,他就这样坐在那儿,有时坐在被雨淋湿的石头上,有时坐在雪地里。夜里他痛得呻吟不止,早晨他有时拿不定主意去还是不去,但结果总是横下一条心去了。母亲拖住他,不肯放他走,他很可能因为手脚不听使唤而变得胆小,便允许母亲一起去,这样母亲也患上风湿痛了。我们常常到他们那儿去,给他们送饭,或者只是去看看他们,或者想劝说他们回家,我们有多少次看见他们缩成一团,相互偎依着,坐在他们那个狭小的座位上,身上蒙着一条勉强能裹住身体的薄毛毯,周围除了白茫茫的雪和灰蒙蒙的雾以外什么都没有,一连好几天,远近看不见一个人影儿或一辆马车,那真是惨不忍睹,K,惨不忍睹!一直到有一天早晨,父亲那双僵硬的腿不能下床了;那样子真惨,他发着高烧,神志有一点不清,他觉得自己看见这时正有一辆马车停在上面贝尔图赫的菜园旁边,有一个官员下了车,沿着栅栏在找他,之后摇了摇头,悻然又回到马车上。这时父亲高声大叫起来,好像是想使山上的那个官员能注意到自己并向他解释,他没有去,并不能怪他。从此他就长期缺席了,再也不能回到那里去了,一连好几个星期卧病在床。阿玛丽亚便把侍候、护理和治疗统统包了下来,样样都干,除了偶尔中断过几次以外,一直保持到今天。她知道什么药草可以止痛,她几乎不需要睡觉,她从来不会惊慌失措,什么都不怕,从来不急不躁,尽心尽力侍奉父母;我们却急得团团转,什么忙也帮不上,而她不论发生什么事情,都能保持冷静,不声不响。后来等到最严重的时期过去,父亲在我们一左一右搀扶下小心翼翼地挣扎着又能下床了,阿玛丽亚就撒手不管了,让我们来照顾他。”
Java
WINDOWS-1252
1,998
2.546875
3
[]
no_license
package com.pc.pconsumption.framework; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.util.Enumeration; import java.util.HashMap; import java.util.Map; import java.util.Properties; import java.util.logging.Logger; import org.codehaus.jackson.map.ObjectMapper; import com.pc.pconsumption.util.SystemUtils; public class SystemGlobal { private static transient Logger log = Logger.getLogger(""); public static Map<String,String> defaults = null; // Json Container private static ObjectMapper mapper = null; public static ObjectMapper getObjectMapper(){ if(SystemUtils.isNotNull(mapper)){ return mapper; } return new ObjectMapper(); } public static String getValue(String variable){ return defaults.get(variable); } @SuppressWarnings("unchecked") public static void getSystemGlobalSql() throws Exception{ Properties props = new Properties(); String sqlScript = SystemGlobal.class.getResource("/SystemGlobal.properties").getPath(); log.info("ű "+sqlScript); InputStream is = new FileInputStream(sqlScript); try { props.load(is); is.close(); } catch (IOException e) { System.out.println("The file SystemGlobal.properties not found!"); e.printStackTrace(); throw new IOException(e.getMessage()); } defaults = new HashMap<String,String>(); Enumeration<String> en = (Enumeration<String>) props.propertyNames(); while(en.hasMoreElements()){ String key = en.nextElement(); String value = (String) props.get(key); defaults.put(key, value); } } public static void main(String[] args) { // try { // getSystemGlobalSql(); // } catch (Exception e) { // // TODO Auto-generated catch block // e.printStackTrace(); // } // Map<String,String> map = defaults; // for (Map.Entry entry : map.entrySet()) { // System.out.println(entry.getKey()+" "+entry.getValue()); // } // System.out.println(SystemGlobal.class.getResource(".").getPath()); } }
C#
UTF-8
2,993
2.796875
3
[]
no_license
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Threading; using System.Threading.Tasks; using System.Windows.Forms; namespace DemoAsync { public partial class Form1 : Form { CancellationTokenSource cts; public Form1() { InitializeComponent(); InitMyComponents(); } private void InitMyComponents() { // this.button1.Click += ClickSincrono; // Se ejecuta en otro hilo this.button1.Click += ClickAsincrono; } private void ClickSincrono(object sender, EventArgs e) { try { UseWaitCursor = true; label1.Text = "Ejecutando Operacion..."; var progreso = new Progress<int>(pct => progressBar1.Value = pct); int par = 50; float result = 0; try { result = OperacionLarga(par, progreso, cts.Token); label1.Text = "Finalizado " + result.ToString(); } catch (Exception ex) { label1.Text = "Error " + ex.Message; } UseWaitCursor = false; } catch (Exception ex) { MessageBox.Show (ex.Message); } } private async void ClickAsincrono(object sender, EventArgs e) { UseWaitCursor = true; label1.Text = "Ejecutando Operacion..."; var progreso = new Progress<int>(pct => progressBar1.Value = pct); cts = new CancellationTokenSource(); cts.CancelAfter(50000); int par = 50; float result = 0; try { result = await Task.Run<float>(() => { return OperacionLarga(par, progreso, cts.Token); }); label1.Text = "Finalizado " + result.ToString(); } catch (Exception ex) { label1.Text = "Error " + ex.Message; } UseWaitCursor = false; } float OperacionLarga(int parametro, IProgress<int> progreso, CancellationToken cToken ) { for (int i = 0; i <= 100; i+=10) { System.Threading.Thread.Sleep( 1000); if (progreso != null) { progreso.Report(i); } if (cToken != null) { cToken.ThrowIfCancellationRequested(); } } return 25 + parametro; } private void buttCancel_Click(object sender, EventArgs e) { if (cts != null) { cts.Cancel(); } } } }
C#
UTF-8
715
2.609375
3
[]
no_license
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace KeyKeeper { public class StoredPasswordClass { public int _id; public string _service; public string _url; public string _password; public string _username; public string _email; public StoredPasswordClass() { } public StoredPasswordClass(int id, string service, string url, string password, string username, string email) { _id = id; _service = service; _url = url;_password = password; _username = username; _email = email; } } }
Markdown
UTF-8
3,488
2.6875
3
[ "CC-BY-3.0", "CC-BY-3.0-US", "LicenseRef-scancode-generic-cla" ]
permissive
## Empfangen von Nachrichten auf dem simulierten Gerät In diesem Abschnitt ändern Sie die simulierte Geräteanwendung, die Sie in [Erste Schritte mit IoT Hub] erstellt haben, um Cloud-zu-Gerät-Nachrichten von IoT Hub zu empfangen. 1. Fügen Sie in Visual Studio im **SimulatedDevice**-Projekt der **Program**-Klasse folgende Methode hinzu. private static async void ReceiveC2dAsync() { Console.WriteLine("\nReceiving cloud to device messages from service"); while (true) { Message receivedMessage = await deviceClient.ReceiveAsync(); if (receivedMessage == null) continue; Console.ForegroundColor = ConsoleColor.Yellow; Console.WriteLine("Received message: {0}", Encoding.ASCII.GetString(receivedMessage.GetBytes())); Console.ResetColor(); await deviceClient.CompleteAsync(receivedMessage); } } Die `ReceiveAsync`-Methode gibt die empfangene Nachricht asynchron zurück, sobald sie vom Gerät empfangen wird. Nach Ablauf eines festlegbaren Timeoutzeitraums (hier wird der Standardwert 1 Minute verwendet) gibt sie *NULL* zurück. Falls dies geschieht, soll der Code weiter auf neue Nachrichten warten, was durch die Zeile `if (receivedMessage == null) continue` gewährleistet ist. Durch den Aufruf von `CompleteAsync()` wird IoT Hub benachrichtigt, dass die Nachricht erfolgreich verarbeitet wurde und sicher aus der Gerätewarteschlange entfernt werden kann. Falls die Nachricht von der Geräte-App nicht vollständig verarbeitet werden kann, wird sie von IoT Hub erneut übermittelt. Dabei ist es wichtig, dass die Nachrichtenverarbeitungslogik in der Geräte-App *idempotent* ist, d. h., dass der mehrfache Empfang derselben Nachricht immer dasselbe Resultat ergeben muss. Eine Anwendung kann eine Nachricht auch vorübergehend verwerfen (`Abandon`), wodurch die Nachricht von IoT Hub zur zukünftigen Nutzung in der Warteschlange beibehalten werden muss, oder eine Nachricht ablehnen (`Reject`), wodurch sie dauerhaft aus der Warteschlange entfernt wird. Weitere Informationen zum Lebenszyklus von Cloud-zu-Gerät-Nachrichten finden Sie im [Entwicklungsleitfaden für IoT Hub][IoT Hub Developer Guide - C2D]. > [AZURE.NOTE]Wird HTTP/1 anstelle von AMQP als Transport verwendet, wird `ReceiveAsync` sofort zurückgegeben. Das unterstützte Muster für Cloud-zu-Gerät-Nachrichten mit HTTP/1 entspricht Geräten, die nicht permanent verbunden sind und weniger häufig Nachrichten abrufen (d. h. seltener als alle 25 Minuten). Die Ausgabe von mehr HTTP/1-Empfangsvorgängen führt dazu, dass die Anforderungen von IoT Hub gedrosselt werden. Weitere Informationen zu den Unterschieden zwischen der AMQP- und HTTP/1-Unterstützung sowie zur IoT Hub-Drosselung finden Sie im [Entwicklungsleitfaden für IoT Hub][IoT Hub Developer Guide - C2D]. 2. Fügen Sie in der **Main**-Methode unmittelbar vor der Zeile `Console.ReadLine()` folgende Methode hinzu: ReceiveC2dAsync(); > [AZURE.NOTE]Der Einfachheit halber wird in diesem Lernprogramm keine Wiederholungsrichtlinie implementiert. Es wird empfohlen, im Produktionscode Wiederholungsrichtlinien zu implementieren (z. B. einen exponentiellen Backoff), wie im MSDN-Artikel zum [Behandeln vorübergehender Fehler] beschrieben. <!-- Links --> [IoT Hub Developer Guide - C2D]: iot-hub-devguide.md#c2d <!-- Images --> <!---HONumber=Nov15_HO2-->
PHP
UTF-8
1,590
2.53125
3
[]
no_license
<?php require_once dirname(dirname(__FILE__)).'/models/db_model.php'; class settings{ function __construct() { $this->db_model= new db_model; } function settings(){ $search=$_POST['search']; return json_encode($this->db_model->getSettings($search)); } function nameSettings(){ return json_encode($this->db_model->getNameSettings()); } function editSetting(){ $id=$_POST['id']; //$name=$_POST['Name']; $key=$_POST['Key']; $value=$_POST['Value']; $description=$_POST['description']; return $this->db_model->editSetting($id,$key,$value,$description); } function save(){ //$id=$_POST['id']; $name=$_POST['Name']; $key=$_POST['Key']; $value=$_POST['Value']; $description=$_POST['des']; return $this->db_model->saveNewSetting($name,$key,$value,$description); } function editLogo(){ //extract($_POST); $image = $_FILES['file']; $id=$_POST['id']; $ext = pathinfo($image['name'], PATHINFO_EXTENSION); $image_name = "logo_" . date("Ymdhis") . "." . $ext; $target_file=dirname(dirname(__DIR__))."/style/images/".$image_name; $name_store='style/images/'.$image_name; $valid_exts = array('jpeg', 'jpg', 'png', 'gif','ico'); if (!in_array($ext, $valid_exts)) { return false; }else{ move_uploaded_file($image["tmp_name"], $target_file); return $this->db_model->editLogo($id,$name_store); } } } ?>
JavaScript
UTF-8
1,989
2.703125
3
[]
no_license
/* * Made By (c) ZizoNaser * 12/18/17 9:38 PM * Twitter: @ZizoNaser * GitHub: github.com/ZizoNaser */ $(document).on("click", ".sus", function () { var formId = $(this).parent().parent().attr('id'); $.ajax({ url: '/SuspendFormCtl', data: { formId: formId }, success: function (responseText) { refresh(); $(this).removeClass("sus"); $(this).removeClass("btn-info"); $(this).html(">"); $(this).attr("title", "Resume"); $(this).addClass("resume"); $(this).addClass("btn-success"); $(this).parent().parent().addClass("bg-info"); } }); }); $(document).on("click", ".resume", function () { var formId = $(this).parent().parent().attr('id'); $.ajax({ url: '/UnSuspendForm', data: { formId: formId }, success: function (responseText) { $(this).removeClass("resume"); $(this).removeClass("btn-success"); $(this).parent().parent().removeClass("bg-info"); $(this).html("||"); $(this).attr("title", "Suspend"); $(this).addClass("sus"); $(this).addClass("btn-info"); refresh(); } }); }); function refresh() { console.log("refresh"); $.ajax({ url: '/GetFormsCtl', data: { // @TODO }, success: function (responseText) { $('#forms').html(responseText); } }); } $(document).on("click", ".remove", function () { var formId = $(this).parent().parent().attr('id'); $.ajax({ url: '/RemoveFormCtl', data: { formId: formId }, success: function (responseText) { refresh(); } }); $(this).parent().parent().remove(); }); $(document).ready(function () { refresh(); var int1 = setInterval("refresh()", 5000); });
Ruby
UTF-8
238
3.390625
3
[]
no_license
class Bob def hey(said) if said.split("").last == '?' 'Sure.' elsif said == said.upcase && said != '' 'Woah, chill out!' elsif said == '' 'Fine. Be that way.' else 'Whatever.' end end end
JavaScript
UTF-8
5,783
2.671875
3
[ "MIT" ]
permissive
const { Container, Text, Shape } = require('@createjs/easeljs'); const { Tween, Ease } = require('@createjs/tweenjs'); const { HashNode } = require('./hash-node'); const { tweenPromise, getHashCode, MD5 } = require('../utils'); export class ConsistentHash { constructor(player, options) { this.stage = player.getStage(); this.options = options || {}; this.log = player.log.bind(player); this.speedFn = player.getSpeed.bind(player); this.config = { maxSlots: 1000, nodeReplicationFactor: this.options.nodeReplicationFactor || 16, }; this._initVisual(); } _initVisual() { const margin = this.stage.canvas.width / 10; this.stage.canvas.height = this.stage.canvas.width; const ringRadius = (this.stage.canvas.width / 2) - margin; const ringX = margin + ringRadius; const ringY = margin + ringRadius; this.visualConfig = { ringX: ringX, ringY: ringY, ringRadius: ringRadius } this.nodeReplicas = []; this.container = new Container(); const ring = new Shape(); ring.graphics.setStrokeStyle(4).beginStroke("#66a841").drawCircle(ringX, ringY, ringRadius); this.container.addChild(ring); this.stage.addChild(this.container); } async addNode(nodeName, options) { this.log(`Adding node: ${nodeName}`) const drawPromises = []; for (let replicaNum = 1; replicaNum <= this.config.nodeReplicationFactor; replicaNum++) { const replicaName = `${nodeName}-${replicaNum}` const position = this._getPosition(replicaName); const point = this._getCircumferencePointAtPosition(position); const nodeReplica = new HashNode(nodeName, position, { x: point.x, y: point.y, radius: this.visualConfig.ringRadius / 10, speedFn: this.speedFn }); this.nodeReplicas.push(nodeReplica); drawPromises.push(nodeReplica.draw(this.container, options)); } this.nodeReplicas.sort((n1, n2) => n1.position - n2.position); await Promise.all(drawPromises); } async removeNode(nodeName) { this.log(`Removing node: ${nodeName}`); const nodeReplicasOfNode = this.nodeReplicas.filter(nodeReplica => nodeReplica.node === nodeName); const undrawPromises = []; for (const nodeReplica of nodeReplicasOfNode) { this._bringNodeReplicaToFront(nodeReplica); undrawPromises.push(nodeReplica.undraw(this.container)); this.nodeReplicas.splice(this.nodeReplicas.indexOf(nodeReplica), 1); } await Promise.all(undrawPromises); } _getPosition(key) { const position = getHashCode(MD5(key)) % this.config.maxSlots; return position; } _getNodeReplicaNextTo(position) { // TODO: Use binary search for log-n search for (const nodeReplica of this.nodeReplicas) { if (nodeReplica.position >= position) { return nodeReplica; } } return this.nodeReplicas[0]; } async getNodeForKey(key) { this.log(`Routing key: ${key}`); const position = this._getPosition(key); const nodeReplica = this._getNodeReplicaNextTo(position); await this._visualiseNodeForKey(key, position, nodeReplica); return nodeReplica.node; } _bringNodeReplicaToFront(nodeReplica) { this.container.setChildIndex(nodeReplica.container, this.container.numChildren - 1); } async _visualiseNodeForKey(key, position, nodeReplica) { const { ringRadius } = this.visualConfig; this._bringNodeReplicaToFront(nodeReplica); const textPoint = this._getCircumferencePointAtPosition(position); const pointsInBetween = this.__getCircumferencePointsBetweenPositions(4, position, nodeReplica.position); const text = new Text(key, `${ringRadius / 10}px Arial`); this.container.addChild(text); await Promise.all([ tweenPromise(Tween.get(text) .to({ x: textPoint.x, y: textPoint.y }, 500 / this.speedFn(), Ease.linear) .to({ x: pointsInBetween[0].x, y: pointsInBetween[0].y }, 100 / this.speedFn(), Ease.circIn) .to({ x: pointsInBetween[1].x, y: pointsInBetween[1].y }, 100 / this.speedFn(), Ease.circIn) .to({ x: pointsInBetween[2].x, y: pointsInBetween[2].y }, 100 / this.speedFn(), Ease.circIn) .to({ x: pointsInBetween[3].x, y: pointsInBetween[3].y }, 100 / this.speedFn(), Ease.circIn) .to({ x: nodeReplica.visualConfig.x, y: nodeReplica.visualConfig.y }, 100 / this.speedFn(), Ease.circIn)), nodeReplica.highlight() ]) this.container.removeChild(text); } _getCircumferencePointAtPosition(position) { const { ringX, ringY, ringRadius } = this.visualConfig; const angleRadian = (position / this.config.maxSlots) * (2 * Math.PI); const x = ringX + ringRadius * Math.cos(angleRadian); const y = ringY + ringRadius * Math.sin(angleRadian); return { x, y }; } __getCircumferencePointsBetweenPositions(n, pos1, pos2) { // debugger; const diff = ((pos2 - pos1) + this.config.maxSlots) % this.config.maxSlots; const step = diff / (n + 1); const points = []; for (let i = 1; i <= n; i++) { points.push(this._getCircumferencePointAtPosition(pos1 + (i * step))); } return points; } reset() { this.stage.removeChild(this.container); this._initVisual(); } }
C++
UTF-8
4,168
2.984375
3
[]
no_license
#include <iostream> using namespace std; struct node { int d; int v1; int v2; }; void swap(node &a,node &b) { node t; t=a; a=b; b=t; } void minheap(node arr[],int ind,node minH[],int &smin) { for (int j = 0; j < ind; j++) { minH[smin]=arr[j]; int x=smin; while(x>0 && minH[(x-1)/2].d>minH[x].d) { swap(minH[(x-1)/2],minH[x]); x=(x-1)/2; } smin++; } } int find(int set[],int x) { if (set[x]==-1) { return x; } else { return find(set,set[x]); } } void uni(int set[],int x,int y) { if (set[y]==-1) { set[y]=x; } else if (set[x]==-1) { set[x]=y; } else { uni(set,find(set,set[x]),find(set,set[y])); } } node deleteheaproot(node minH[],int &smin) { node t=minH[0]; minH[0]=minH[smin-1]; smin--; int x=0; while(((2*x)+2)<smin && (minH[x].d>minH[(2*x)+1].d || minH[x].d>minH[(2*x)+2].d)) { if(minH[x].d>minH[(2*x)+1].d && minH[x].d>minH[(2*x)+2].d) { if(minH[(2*x)+2].d<minH[(2*x)+1].d) { swap(minH[x],minH[(2*x)+2]); x=(2*x)+2; } else { swap(minH[x],minH[(2*x)+1]); x=(2*x)+1; } } else if(minH[x].d>minH[(2*x)+1].d) { swap(minH[x],minH[(2*x)+1]); x=(2*x)+1; } else { swap(minH[x],minH[(2*x)+2]); x=(2*x)+2; } } return t; } void minimun_spaning_tree(node minH[],int smin,int set[]) { while(smin>=0) { node t=deleteheaproot(minH,smin); //cout<<t.d<<endl; //cout<<t.v1<<" "<<t.v2<<endl; int a=t.v1,b=t.v2; /*for(int i=0;i<7;i++) { cout<<set[i]<<" "; } cout<<endl;*/ if (find(set,t.v1)!=find(set,t.v2)) { uni(set,a,b); cout<<t.v1<<" "<<t.v2<<endl; } } } int main() { int v; int e; v=7; e=12; int **G; G=new int *[v+1]; for(int i=0;i<v+1;i++) { G[i]=new int [v+1]; } for (int i = 0; i < v+1; i++) { for (int j = 0 ;j < v+1; j++) { G[i][j]=0; } } int set[v+1]; for(int i=0;i<v+1;i++) { set[i]=-1; } node arr[e+1]; int ind=0; G[1][2]=2; arr[ind].d=2; arr[ind].v1=1; arr[ind].v2=2; ind++; G[1][3]=4; arr[ind].d=4; arr[ind].v1=1; arr[ind].v2=3; ind++; G[1][4]=1; arr[ind].d=1; arr[ind].v1=1; arr[ind].v2=4; ind++; /*G[2][1]=2; arr[ind].d=2; arr[ind].v1=2; arr[ind].v2=1; ind++;*/ G[2][4]=3; arr[ind].d=3; arr[ind].v1=2; arr[ind].v2=4; ind++; G[2][5]=10; arr[ind].d=10; arr[ind].v1=2; arr[ind].v2=5; ind++; /*G[3][1]=4; arr[ind].d=4; arr[ind].v1=3; arr[ind].v2=1; ind++;*/ G[3][4]=2; arr[ind].d=2; arr[ind].v1=3; arr[ind].v2=4; ind++; G[3][6]=5; arr[ind].d=5; arr[ind].v1=3; arr[ind].v2=6; ind++; /*G[4][1]=1; arr[ind].d=1; arr[ind].v1=4; arr[ind].v2=1; ind++; G[4][2]=3; arr[ind].d=3; arr[ind].v1=4; arr[ind].v2=2; ind++; G[4][3]=2; arr[ind].d=2; arr[ind].v1=4; arr[ind].v2=3; ind++;*/ G[4][5]=7; arr[ind].d=7; arr[ind].v1=4; arr[ind].v2=5; ind++; G[4][6]=8; arr[ind].d=8; arr[ind].v1=4; arr[ind].v2=6; ind++; G[4][7]=4; arr[ind].d=4; arr[ind].v1=4; arr[ind].v2=7; ind++; /*G[5][2]=10; arr[ind].d=10; arr[ind].v1=5; arr[ind].v2=2; ind++; G[5][4]=7; arr[ind].d=7; arr[ind].v1=5; arr[ind].v2=4; ind++;*/ G[5][7]=6; arr[ind].d=6; arr[ind].v1=5; arr[ind].v2=7; ind++; /*G[6][3]=5; arr[ind].d=5; arr[ind].v1=6; arr[ind].v2=3; ind++; G[6][4]=8; arr[ind].d=8; arr[ind].v1=6; arr[ind].v2=4; ind++;*/ G[6][7]=1; arr[ind].d=1; arr[ind].v1=6; arr[ind].v2=7; ind++; /*G[7][6]=1; arr[ind].d=1; arr[ind].v1=7; arr[ind].v2=6; ind++; G[7][4]=4; arr[ind].d=4; arr[ind].v1=7; arr[ind].v2=4; ind++; G[7][5]=6; arr[ind].d=6; arr[ind].v1=7; arr[ind].v2=5; ind++;*/ node minH[50]; int smin=0; minheap(arr,ind,minH,smin); for(int i=0;i<7;i++) { set[i]=-1; } /* for(int i=0;i<smin;i++) { if(arr[i].d==1) { cout<<arr[i].v1<<" "<<arr[i].v2<<endl; } } cout<<"x\n"; cout<<smin<<endl;*/ minimun_spaning_tree(minH,smin,set); }
Java
UTF-8
14,603
1.8125
2
[]
no_license
package upsc.motivational.quotesforu; import android.annotation.SuppressLint; import android.app.Activity; import android.app.AlertDialog; import android.app.ProgressDialog; import android.content.Intent; import android.content.pm.ActivityInfo; import android.net.Uri; import android.support.annotation.NonNull; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.support.v7.widget.GridLayoutManager; import android.support.v7.widget.RecyclerView; import android.support.v7.widget.Toolbar; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.Button; import android.widget.ImageView; import android.widget.TextView; import android.widget.Toast; import com.bumptech.glide.Glide; import com.google.android.gms.ads.AdListener; import com.google.android.gms.ads.AdRequest; import com.google.android.gms.ads.AdSize; import com.google.android.gms.ads.AdView; import com.google.android.gms.ads.InterstitialAd; import com.google.android.gms.ads.MobileAds; import com.google.android.gms.ads.reward.RewardItem; import com.google.android.gms.ads.reward.RewardedVideoAd; import com.google.android.gms.ads.reward.RewardedVideoAdListener; import com.google.firebase.database.DataSnapshot; import com.google.firebase.database.DatabaseError; import com.google.firebase.database.DatabaseReference; import com.google.firebase.database.FirebaseDatabase; import com.google.firebase.database.ValueEventListener; import java.util.ArrayList; import java.util.List; public class OwnQuotes extends AppCompatActivity { RecyclerView recyclerView; GridLayoutManager gridLayoutManager; Toolbar toolbar; Button send; ProgressDialog pd; DatabaseReference databaseReference; String show="blank",sendStatus="blank"; static List<String> quotes = new ArrayList<>(); static List<String> names = new ArrayList<>(); public static final int ITEM_PER_AD = 6; private List<Object> recycleItems = new ArrayList<>(); @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_own_quotes); setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT); toolbar = findViewById(R.id.toolbar); setSupportActionBar(toolbar); send = findViewById(R.id.button); pd = new ProgressDialog(OwnQuotes.this); pd.setMessage("Loading..."); pd.show(); pd.setCancelable(false); toolbar.setTitle("Quotes List"); recyclerView = findViewById(R.id.recycle); gridLayoutManager = new GridLayoutManager(getApplicationContext(), 1); recyclerView.setLayoutManager(gridLayoutManager); send.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if (sendStatus.equals("OFF") || sendStatus.equals("blank")) { alertfun("mail"); } else { pd.dismiss(); Intent in = new Intent(Intent.ACTION_SENDTO, Uri.fromParts("mailto", "userquotes@gmail.com", null)); in.putExtra(Intent.EXTRA_SUBJECT, "My Quotation is here."); in.putExtra(Intent.EXTRA_TEXT, "Name: " + "\n\n" + "My Quote:"); startActivity(Intent.createChooser(in, "use service")); } } }); databaseReference = FirebaseDatabase.getInstance().getReference().child("OwnQuotes"); databaseReference.addValueEventListener(new ValueEventListener() { @Override public void onDataChange(@NonNull DataSnapshot dataSnapshot) { show = dataSnapshot.child("Opt").getValue(String.class); sendStatus = dataSnapshot.child("Mail").getValue(String.class); next(); } @Override public void onCancelled(@NonNull DatabaseError databaseError) { Toast.makeText(getApplicationContext(),databaseError.getMessage(),Toast.LENGTH_SHORT).show(); } }); } public void next() { if(show.equals("OFF") || show.equals("blank")) { alertfun("opt"); } else { //Toast.makeText(getApplicationContext(),show,Toast.LENGTH_SHORT).show() databaseReference.child("ON").addValueEventListener(new ValueEventListener() { @Override public void onDataChange(@NonNull DataSnapshot dataSnapshot) { recycleItems.clear(); names.clear(); for(DataSnapshot shot : dataSnapshot.getChildren()) { //show = dataSnapshot.getValue().toString(); recycleItems.add(shot.child("Quote").getValue().toString()); names.add(shot.child("Name").getValue().toString()); } show(); } @Override public void onCancelled(@NonNull DatabaseError databaseError) { Toast.makeText(getApplicationContext(),databaseError.getMessage(),Toast.LENGTH_SHORT).show(); } }); } } public void alertfun(final String temp) { pd.dismiss(); //Toast.makeText(getApplicationContext(),show,Toast.LENGTH_SHORT).show(); AlertDialog.Builder alertdialog = new AlertDialog.Builder(OwnQuotes.this); LayoutInflater inflater = OwnQuotes.this.getLayoutInflater(); View view = inflater.inflate(R.layout.alert_dialog,null,true); alertdialog.setView(view); TextView title = view.findViewById(R.id.errorTitle); TextView message = view.findViewById(R.id.errorMessage); Button positive = view.findViewById(R.id.positive); title.setText("Welcome"); message.setText("Maintenance is going on try after some time."); positive.setText("Ok"); final AlertDialog alert = alertdialog.create(); alert.setCancelable(false); alert.show(); positive.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if(temp.equals("opt")) finish(); else alert.dismiss(); } }); } public void show () { if (!recycleItems.isEmpty()) { quotes.addAll((ArrayList)recycleItems); getBannerAds(); loadBannerAd(); pd.dismiss(); recyclerView.setAdapter(new MyAdapterOwnQuotes(OwnQuotes.this, recycleItems,quotes, names)); } else { pd.setTitle("Error Loading... "); pd.setMessage("Try Again Later"); } } public void getBannerAds() { for(int i=0;i<recycleItems.size();i+=ITEM_PER_AD) { final AdView adView = new AdView(OwnQuotes.this); adView.setAdSize(AdSize.BANNER); adView.setAdUnitId(getResources().getString(R.string.banner)); recycleItems.add(i,adView); } } public void loadBannerAd() { for(int i=0;i<recycleItems.size();i++) { Object item = recycleItems.get(i); if(item instanceof AdView) { final AdView adView= (AdView)item; adView.loadAd(new AdRequest.Builder().build()); } } } class MyAdapterOwnQuotes extends RecyclerView.Adapter implements RewardedVideoAdListener { private Activity activity; List<Object> quotes ; List<String> names; List<String> quotesList; List<Integer> quotePos = new ArrayList<>(); String opt; private RewardedVideoAd rewardedVideoAd; private InterstitialAd interstitialAd; private String inter ="ca-app-pub-1621029291855475/6738710731"; private String video ="ca-app-pub-1621029291855475/7862415678"; //private String inter ="ca-app-pub-3940256099942544/1033173712"; //private String video ="ca-app-pub-3940256099942544/5224354917"; private ConnectionDetector cd; private static final int ITEM_QUOTE=0; private static final int ITEM_BANNER_AD=1; AdView adView; AdRequest adRequest; MyAdapterOwnQuotes(Activity activity,List<Object> quotes,List<String> quotesList,List<String> names) { this.activity = activity; this.quotes = quotes; this.names = names; this.quotesList = quotesList; //quotesList = (List)quotes; } @Override public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { switch (viewType) { case ITEM_QUOTE: View quote; quote = LayoutInflater.from(parent.getContext()).inflate(R.layout.frag_ownquotes_list, parent, false); return new QuotesHolder(quote); case ITEM_BANNER_AD: default: View v; v = LayoutInflater.from(parent.getContext()).inflate(R.layout.activity_recycle_ads, parent, false); return new BannerViewHolder(v); } } @Override public void onBindViewHolder(RecyclerView.ViewHolder holder, @SuppressLint("RecyclerView") final int position) { final int viewType = getItemViewType(position); switch (viewType) { case ITEM_QUOTE: QuotesHolder quotesHolder = (QuotesHolder)holder; quotesHolder.quote.setText(quotes.get(position).toString()); quotePos.add(position); break; case ITEM_BANNER_AD: default: BannerViewHolder bannerViewHolder = (BannerViewHolder) holder; AdView adView = (AdView) quotes.get(position); ViewGroup adCardView =(ViewGroup) bannerViewHolder.itemView; if(adCardView.getChildCount()>0) { adCardView.removeAllViews(); } if(adView.getParent()!=null) { ((ViewGroup) adView.getParent()).removeView(adView); } adCardView.addView(adView); } cd = new ConnectionDetector(activity); rewardedVideoAd = MobileAds.getRewardedVideoAdInstance(activity); rewardedVideoAd.setRewardedVideoAdListener(this); interstitialAd = new InterstitialAd(activity); interstitialAd.setAdUnitId(inter); holder.itemView.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { if (viewType == ITEM_QUOTE) { int pos = quotePos.indexOf(position); if (cd.isConnected()) { //Toast.makeText(activity, optName + " " + key.get(position), Toast.LENGTH_SHORT).show(); if (pos == 11 || pos == 35 || pos == 65 ||pos==105) loadRewardedVideo(); else if (pos == 4 || pos == 14 || pos == 29 || pos == 44 || pos == 54 ||pos==72 ||pos==88|| pos==100) { interstitialAd.loadAd(new AdRequest.Builder().build()); showAd(); } Intent in = new Intent(activity, OwnQuotesLast.class); in.putStringArrayListExtra("quotes", (ArrayList<String>) quotesList); in.putStringArrayListExtra("names", (ArrayList<String>) names); in.putExtra("pos", pos); activity.startActivity(in); } else { Toast.makeText(activity, "Network Connection Error.", Toast.LENGTH_SHORT).show(); } } } }); } @Override public int getItemCount() { return quotes.size(); } @Override public int getItemViewType(int position) { if(position%OwnQuotes.ITEM_PER_AD==0) return ITEM_BANNER_AD; else return ITEM_QUOTE; } class QuotesHolder extends RecyclerView.ViewHolder { TextView quote; QuotesHolder(View itemView) { super(itemView); quote = itemView.findViewById(R.id.quote); } } class BannerViewHolder extends RecyclerView.ViewHolder { BannerViewHolder(View itemView) { super(itemView); } } public void loadRewardedVideo() { rewardedVideoAd.loadAd(video,new AdRequest.Builder().build()); } public void showAd() { interstitialAd.setAdListener(new AdListener(){ @Override public void onAdLoaded() { if(interstitialAd.isLoaded()) interstitialAd.show(); } }); } @Override public void onRewardedVideoAdLoaded() { if(rewardedVideoAd.isLoaded()) rewardedVideoAd.show(); } @Override public void onRewardedVideoAdOpened() { } @Override public void onRewardedVideoStarted() { } @Override public void onRewardedVideoAdClosed() { } @Override public void onRewarded(RewardItem rewardItem) { } @Override public void onRewardedVideoAdLeftApplication() { } @Override public void onRewardedVideoAdFailedToLoad(int i) { } @Override public void onRewardedVideoCompleted() { } } @Override public void onBackPressed() { startActivity(new Intent(this,MainActivity.class).putExtra("noti",1)); finish(); } }
C++
UTF-8
41,650
2.5625
3
[ "MIT" ]
permissive
// Lexer.hpp --- CodeReverse lexical analysis // Copyright (C) 2017 Katayama Hirofumi MZ. License: MIT License #ifndef CODEREVERSE_LEXER_HPP #define CODEREVERSE_LEXER_HPP #include "TextScanner.hpp" #include <set> // for std::set #include <map> // for std::multimap #include <stack> // for std::stack #ifndef NDEBUG #include <iostream> #endif ///////////////////////////////////////////////////////////////////////// namespace CodeReverse { ///////////////////////////////////////////////////////////////////////// // TokenType and Token enum TokenType { TK_EOF = 0, TK_SYMBOL, TK_KEYWORD, TK_IDENTIFIER, TK_CHARACTER_LITERAL, TK_INTEGER_LITERAL, TK_STRING_LITERAL, TK_FLOATING_LITERAL, }; struct Token { std::string m_str; Position m_pos; TokenType m_type; std::string m_fix; // prefix or suffix Token(const Position& pos, TokenType type) : m_pos(pos), m_type(type) { } }; typedef std::vector<Token> TokensType; template <class CharT, class Traits> inline std::basic_ostream<CharT,Traits>& operator<<(std::basic_ostream<CharT,Traits>& os, const Token& tok) { os << tok.m_pos << ": " << tok.m_str << " (" << tok.m_type << ")\n"; return os; } ///////////////////////////////////////////////////////////////////////// // Lexer class Lexer { public: Lexer(TextScanner& scanner, AuxInfo& aux); Lexer(TextScanner& scanner, const TokensType& tokens, AuxInfo& aux); bool do_lex(); void fixup(); bool empty() const; size_t size() const; Token& operator[](size_t i); const Token& operator[](size_t i) const; void push_back(const Token& t); void clear(); Token& token(); const Token& token() const; void next(); void prev(); bool eof() const; TokenType type() const; string_type str() const; string_type fix() const; size_t index() const; void index(size_t pos); Position pos() const; void pos(const Position& pos_); bool scan_number(); bool scan_string_or_character(); bool scan_identifier(); bool scan_symbol(); bool do_floating_exponent(Token& token); bool do_floating_suffix(Token& token); bool do_integer_suffix(Token& token); bool do_directive(const string_type& str); bool do_line(const TokensType& tokens); bool do_pragma(const TokensType& tokens); size_t paren_close(size_t i) const; size_t brace_close(size_t i) const; protected: TextScanner& m_text; AuxInfo& m_aux; size_t m_index; int m_pack; size_t m_pragma_begin; size_t m_pragma_paren; TokensType m_tokens; typedef std::multimap<char_type, string_type> symbol_map_type; symbol_map_type m_symbol_map; typedef std::set<string_type> keyword_set_type; keyword_set_type m_keywords; typedef std::stack<int> pack_stack_type; pack_stack_type m_pack_stack; friend class CParser; char_type getch(); char_type peekch() const; void skip(size_t count); void ungetch(); void nextch(); bool match_peek(const char_type *psz) const; bool match_peek(const char_type *psz, string_type& str) const; bool match_get(const char_type *psz); bool match_get(const char_type *psz, string_type& str); void push_pack(int pack); void pop_pack(); void fixup_gnu_extensions(); }; template <class CharT, class Traits> inline std::basic_ostream<CharT,Traits>& operator<<(std::basic_ostream<CharT,Traits>& os, const Lexer& lexer) { for (size_t i = 0; i < lexer.size(); ++i) { os << lexer[i]; } return os; } ///////////////////////////////////////////////////////////////////////// // escape/unescape std::string str_quote(const std::string& str, char quote); std::string wstr_quote(const std::wstring& str, wchar_t quote); std::string str_unquote(const std::string& str, char quote); std::wstring wstr_unquote(const std::string& str, char quote); void str_trim(std::string& str, const char *spaces = " \t\r\n"); void str_trim(std::wstring& str, const wchar_t *spaces = L" \t\r\n"); template <typename T_STR> bool str_replace_all(T_STR& str, const T_STR& from, const T_STR& to); template <typename T_STR> bool str_replace_all(T_STR& str, const typename T_STR::value_type *from, const typename T_STR::value_type *to); ///////////////////////////////////////////////////////////////////////// inline const char **get_keywords(size_t& count) { static const char *s_keywords[] = { "_Alignas", "_Alignof", "_Atomic", "_Bool", "_Complex", "_Generic", "_Imaginary", "_Noreturn", "_Static_assert", "_Thread_local", "__asm", "__asm__", "__attribute__", "__cdecl", "__declspec", "__fastcall", "__float128", "__float80", "__forceinline", "__inline", "__inline__", "__int128", "__int64", "__pragma", "__ptr64", "__restrict__", "__stdcall", "__volatile__", "auto", "break", "case", "char", "const", "continue", "default", "do", "double", "else", "enum", "extern", "float", "for", "goto", "if", "inline", "int", "long", "register", "restrict", "return", "short ", "signed", "sizeof", "static", "struct", "switch", "typedef", "union", "unsigned", "void", "volatile", "while", }; count = _countof(s_keywords); return s_keywords; } ///////////////////////////////////////////////////////////////////////// inline const char **get_symbols(size_t& count) { static const char *s_symbols[] = { "!", "!=", "#", "##", "%", "%=", "&", "&&", "&=", "(", ")", "*", "*=", "+", "++", "+=", ",", "-", "--", "-=", "->", ".", "...", "/", "/=", ":", ";", "<", "<<", "<<=", "<=", "=", "==", ">", ">=", ">>", ">>=", "?", "[", "]", "^", "^=", "{", "|", "|=", "||", "}", "~", }; count = _countof(s_symbols); return s_symbols; } ///////////////////////////////////////////////////////////////////////// // Lexer inlines inline Lexer::Lexer(TextScanner& text, AuxInfo& aux) : m_text(text), m_aux(aux), m_index(0), m_pack(1), m_pragma_begin(-1), m_pragma_paren(0) { size_t count; const char **symbols = get_symbols(count); for (size_t i = 0; i < count; ++i) { m_symbol_map.insert(std::make_pair(*symbols[i], symbols[i])); } const char **keywords = get_keywords(count); for (size_t i = 0; i < count; ++i) { m_keywords.insert(keywords[i]); } } inline Lexer::Lexer(TextScanner& scanner, const TokensType& tokens, AuxInfo& aux) : m_text(scanner), m_aux(aux), m_index(0), m_pack(1), m_pragma_begin(-1), m_pragma_paren(0), m_tokens(tokens) { } inline Token& Lexer::token() { return m_tokens[m_index]; } inline const Token& Lexer::token() const { return m_tokens[m_index]; } inline void Lexer::next() { if (m_index + 1 <= size()) ++m_index; } inline void Lexer::prev() { if (m_index > 0) --m_index; } inline bool Lexer::eof() const { return type() == TK_EOF; } inline TokenType Lexer::type() const { return token().m_type; } inline string_type Lexer::str() const { return token().m_str; } inline string_type Lexer::fix() const { return token().m_fix; } inline size_t Lexer::index() const { return m_index; } inline void Lexer::index(size_t pos) { m_index = pos; } inline Position Lexer::pos() const { return m_text.pos(); } inline void Lexer::pos(const Position& pos_) { m_text.pos(pos_); } inline bool Lexer::empty() const { return size() == 0; } inline size_t Lexer::size() const { return m_tokens.size(); } inline Token& Lexer::operator[](size_t i) { return m_tokens[i]; } inline const Token& Lexer::operator[](size_t i) const { return m_tokens[i]; } inline void Lexer::push_back(const Token& t) { m_tokens.push_back(t); } inline void Lexer::clear() { m_tokens.clear(); m_index = 0; } inline char_type Lexer::getch() { return m_text.getch(); } inline char_type Lexer::peekch() const { return m_text.peekch(); } inline void Lexer::skip(size_t count) { m_text.skip(count); } inline void Lexer::ungetch() { m_text.ungetch(); } inline void Lexer::nextch() { m_text.nextch(); } inline bool Lexer::match_peek(const char_type *psz) const { return m_text.match_peek(psz); } inline bool Lexer::match_peek(const char_type *psz, string_type& str) const { return m_text.match_peek(psz, str); } inline bool Lexer::match_get(const char_type *psz) { return m_text.match_get(psz); } inline bool Lexer::match_get(const char_type *psz, string_type& str) { return m_text.match_get(psz, str); } inline void Lexer::push_pack(int pack) { m_pack_stack.push(pack); m_pack = pack; } inline void Lexer::pop_pack() { if (!m_pack_stack.empty()) { m_pack = m_pack_stack.top(); m_pack_stack.pop(); } } inline bool Lexer::do_lex() { char_type ch; m_pragma_paren = 0; m_pragma_begin = size_t(-1); for (;;) { for (;;) { ch = peekch(); if (!is_space(ch)) break; nextch(); } if (match_get("/*")) // */ { do { if (peekch() == 0) { m_aux.add_error(pos(), "comment not terminated"); return false; } nextch(); } while (!match_get("*/")); continue; } if (match_get("//")) { nextch(); for (;;) { nextch(); ch = peekch(); if (ch == 0 || ch == '\n') break; } continue; } if (ch == '#') { string_type str; for (;;) { nextch(); ch = peekch(); if (ch == 0 || ch == '\n') break; str += ch; } str_trim(str); do_directive(str); continue; } if (is_digit(ch)) { if (scan_number()) continue; m_aux.add_error(pos(), "invalid number"); return false; } if (match_peek("L'") || match_peek("L\"")) { Position p = pos(); if (scan_string_or_character()) continue; m_aux.add_error(p, "invalid escape sequence"); return false; } if (is_alpha(ch) || ch == '_') { if (scan_identifier()) continue; m_aux.add_error(pos(), "invalid identifier"); return false; } if (ch == '"' || ch == '\'') { Position p = pos(); if (scan_string_or_character()) continue; m_aux.add_error(p, "invalid escape sequence"); return false; } if (ch == 0) { break; } if (scan_symbol()) continue; m_aux.add_error(pos(), "invalid character"); return false; } Token token(pos(), TK_EOF); push_back(token); return true; } inline bool Lexer::scan_number() { char_type ch; Token token(pos(), TK_INTEGER_LITERAL); if (match_get("0x", token.m_str) || match_get("0X", token.m_str)) { for (;;) { ch = peekch(); if (!is_xdigit(ch)) break; token.m_str += ch; nextch(); } if (!do_integer_suffix(token)) { return false; } push_back(token); return true; } for (;;) { ch = peekch(); if (!is_digit(ch)) break; token.m_str += ch; nextch(); } ch = peekch(); if (ch == '.') { token.m_str += ch; token.m_type = TK_FLOATING_LITERAL; nextch(); for (;;) { ch = peekch(); if (!is_digit(ch)) break; token.m_str += ch; nextch(); } if (!do_floating_exponent(token) || !do_floating_suffix(token)) { return false; } push_back(token); return true; } if (ch == 'e' || ch == 'E') { if (!do_floating_exponent(token) || !do_floating_suffix(token)) { return false; } push_back(token); return true; } if (!do_integer_suffix(token)) return false; if (token.m_str[0] == '0' && (token.m_str.find('8') != string_type::npos || token.m_str.find('9') != string_type::npos)) { return false; } push_back(token); return true; } inline bool Lexer::do_floating_exponent(Token& token) { char_type ch = peekch(); if (ch == 'e' || ch == 'E') { token.m_str += ch; nextch(); ch = peekch(); if (ch == '+' || ch == '-') { token.m_str += ch; nextch(); } bool has_exp = false; for (;;) { ch = peekch(); if (!is_digit(ch)) break; has_exp = true; token.m_str += ch; nextch(); } return has_exp; } return true; } inline bool Lexer::do_floating_suffix(Token& token) { for (;;) { char_type ch = peekch(); switch (ch) { case 'l': case 'f': case 'L': case 'F': token.m_fix += ch; break; default: return true; } nextch(); } } inline bool Lexer::do_integer_suffix(Token& token) { for (;;) { char_type ch = peekch(); switch (ch) { case 'u': case 'l': case 'U': case 'L': token.m_fix += ch; break; default: return true; } nextch(); } } inline bool Lexer::do_pragma(const TokensType& tokens) { if (tokens[0].m_str == "pack") { if (tokens[1].m_str == "(") { if (tokens[2].m_str == ")") { m_pack = 8; return true; } else if (tokens[2].m_str == "show") { m_aux.add_warning(pos(), "packing is %d", m_pack); return true; } else if (tokens[2].m_str == "push") { if (tokens[3].m_str == ",") { if (tokens[4].m_str == "_CRT_PACKING") { push_pack(8); return true; } else { int i = atoi(tokens[2].m_str.c_str()); if (i == 0) i = 1; push_pack(i); return true; } } else { push_pack(8); return true; } } else if (tokens[2].m_str == "pop") { pop_pack(); return true; } else if (tokens[2].m_str == "_CRT_PACKING") { m_pack = 8; return true; } else if (tokens[2].m_type == TK_INTEGER_LITERAL) { int i = atoi(tokens[2].m_str.c_str()); if (i == 0) i = 1; m_pack = i; return true; } } } return false; } inline bool Lexer::do_line(const TokensType& tokens) { size_t i = 0; if (tokens[0].m_str == "line") i = 1; size_t line = std::stoi(tokens[i++].m_str); std::string file; if (tokens[i].m_type == TK_STRING_LITERAL) file = str_unquote(tokens[i].m_str, '"'); pos(Position(file.c_str(), line - 1)); return true; } inline bool Lexer::do_directive(const string_type& str) { TextScanner text(str); Lexer lexer(text, m_aux); lexer.do_lex(); auto& tokens = lexer.m_tokens; if (tokens[0].m_str == "pragma") { tokens.erase(tokens.begin()); return do_pragma(tokens); } if (tokens[0].m_type == TK_INTEGER_LITERAL || tokens[0].m_str == "line") { return do_line(tokens); } return false; } inline bool Lexer::scan_string_or_character() { Token token(pos(), TK_STRING_LITERAL); char_type ch = peekch(); if (ch == 'L') { token.m_fix += ch; nextch(); } char_type ch0 = ch = peekch(); if (ch == '\'') token.m_type = TK_CHARACTER_LITERAL; else if (ch == '"') token.m_type = TK_STRING_LITERAL; else return false; token.m_str += ch; nextch(); for (;;) { ch = peekch(); switch (ch) { case 0: return false; case '\\': token.m_str += ch; nextch(); ch = peekch(); break; default: if (ch == ch0) { token.m_str += ch; nextch(); ch = peekch(); if (ch != ch0) { push_back(token); return true; } } break; } token.m_str += ch; nextch(); } } inline bool Lexer::scan_identifier() { Token token(pos(), TK_IDENTIFIER); char_type ch = peekch(); if (!is_alpha(ch) && ch != '_') return false; token.m_str += ch; nextch(); for (;;) { ch = peekch(); if (!is_alnum(ch) && ch != '_') break; token.m_str += ch; nextch(); } if (m_keywords.count(token.m_str) > 0) { token.m_type = TK_KEYWORD; if (token.m_str == "__pragma") { m_pragma_begin = m_tokens.size(); m_pragma_paren = 0; } } push_back(token); return true; } inline bool Lexer::scan_symbol() { Token token(pos(), TK_SYMBOL); char_type ch = peekch(); string_type str; typedef symbol_map_type::iterator IT; std::pair<IT, IT> p = m_symbol_map.equal_range(ch); for (IT it = p.first; it != p.second; ++it) { if (match_peek(it->second.c_str(), str)) { if (token.m_str.size() < str.size()) { token.m_str = str; } } } if (token.m_str.size()) { skip(token.m_str.size()); push_back(token); if (m_pragma_begin != size_t(-1)) { if (token.m_str == "(") { ++m_pragma_paren; } else if (token.m_str == ")") { --m_pragma_paren; if (m_pragma_paren == 0) { TokensType tokens(m_tokens.begin() + m_pragma_begin, m_tokens.end()); m_tokens.erase(m_tokens.begin() + m_pragma_begin, m_tokens.end()); tokens.erase(tokens.begin() + tokens.size() - 1); tokens.erase(tokens.begin()); tokens.erase(tokens.begin()); do_pragma(tokens); m_pragma_begin = -1; } } } return true; } return false; } inline void Lexer::fixup() { fixup_gnu_extensions(); } inline void Lexer::fixup_gnu_extensions() { for (size_t i = 0; i < size(); ++i) { if (m_tokens[i].m_str == "__extension__") { m_tokens.erase(m_tokens.begin() + i); --i; } } } inline size_t Lexer::paren_close(size_t i) const { int nest = 0; for (; i < m_tokens.size(); ++i) { const string_type& str = m_tokens[i].m_str; if (str == "(") { ++nest; } else if (str == ")") { --nest; if (nest == 0) return i; } } return m_tokens.size(); } inline size_t Lexer::brace_close(size_t i) const { int nest = 0; for (; i < m_tokens.size(); ++i) { const string_type& str = m_tokens[i].m_str; if (str == "{") { ++nest; } else if (str == "}") { --nest; if (nest == 0) return i; } } return m_tokens.size(); } ///////////////////////////////////////////////////////////////////////// // string inlines template <typename T_STR> inline bool str_replace_all(T_STR& str, const T_STR& from, const T_STR& to) { bool ret = false; size_t i = 0; for (;;) { i = str.find(from, i); if (i == T_STR::npos) break; ret = true; str.replace(i, from.size(), to); i += to.size(); } return ret; } template <typename T_STR> inline bool str_replace_all(T_STR& str, const typename T_STR::value_type *from, const typename T_STR::value_type *to) { return str_replace_all(str, T_STR(from), T_STR(to)); } inline void str_trim(std::string& str, const char *spaces) { size_t i = str.find_first_not_of(spaces); size_t j = str.find_last_not_of(spaces); if ((i == std::string::npos) || (j == std::string::npos)) { str.clear(); } else { str = str.substr(i, j - i + 1); } } inline void str_trim(std::wstring& str, const wchar_t *spaces) { size_t i = str.find_first_not_of(spaces); size_t j = str.find_last_not_of(spaces); if ((i == std::wstring::npos) || (j == std::wstring::npos)) { str.clear(); } else { str = str.substr(i, j - i + 1); } } inline std::string str_quote(const std::string& str, char quote) { std::string ret; ret += quote; for (size_t i = 0; i < str.size(); ++i) { char ch = str[i]; switch (ch) { case '\'': if (quote == ch) ret += "\\'"; else ret += ch; break; case '\"': if (quote == ch) ret += "\\\""; else ret += ch; break; case '\\': ret += "\\\\"; break; case '\0': ret += "\\0"; break; case '\a': ret += "\\a"; break; case '\b': ret += "\\b"; break; case '\f': ret += "\\f"; break; case '\n': ret += "\\n"; break; case '\r': ret += "\\r"; break; case '\t': ret += "\\t"; break; case '\v': ret += "\\v"; break; default: if ((signed char)ch < 0x20) { // hex char buf[8]; std::sprintf(buf, "\\x%02X", (unsigned char)ch); ret += buf; } else { ret += ch; } break; } } ret += quote; return ret; } inline std::string str_unquote(const std::string& str, char quote) { static const char hex[] = "0123456789ABCDEF"; std::string str0 = str; str_trim(str0); std::string ret; if (str0.empty()) return ret; if (str0[0] == quote && str0[str0.size() - 1] == quote) str0 = str0.substr(1, str.size() - 2); int n; for (size_t i = 0; i < str0.size(); ++i) { if (str0[i] == '\\') { ++i; switch (str0[i]) { case '\'': ret += "'"; break; case '\"': ret += "\""; break; case '\\': ret += "\\"; break; case 'a': ret += "\a"; break; case 'b': ret += "\b"; break; case 'f': ret += "\f"; break; case 'n': ret += "\n"; break; case 'r': ret += "\r"; break; case 't': ret += "\t"; break; case 'v': ret += "\v"; break; case 'x': // hex n = 0; ++i; if (is_xdigit(str0[i])) { n *= 16; n += strchr(hex, str0[i]) - hex; ++i; if (is_xdigit(str0[i])) { n *= 16; n += strchr(hex, str0[i]) - hex; ++i; } } --i; ret += (char)n; break; default: n = 0; if (is_digit(str0[i])) { // octal n *= 8; n += strchr(hex, str0[i]) - hex; ++i; if (is_digit(str0[i])) { n *= 8; n += strchr(hex, str0[i]) - hex; ++i; if (is_digit(str0[i])) { n *= 8; n += strchr(hex, str0[i]) - hex; ++i; } } --i; ret += (char)n; } else { ret += str0[i]; } break; } } else if (str0[i] == quote) { ++i; if (str0[i] == quote && quote == '"') { ret += "\""; } else { return ret; } } else { ret += str0[i]; } } return ret; } inline std::string wstr_quote(const std::wstring& str, wchar_t quote) { std::string ret; ret += char(quote); for (size_t i = 0; i < str.size(); ++i) { wchar_t wch = str[i]; switch (wch) { case L'\'': if (quote == wch) ret += "\\'"; else ret += (char)wch; break; case '\"': if (quote == wch) ret += "\\\""; else ret += (char)wch; break; case L'\\': ret += "\\\\"; break; case L'\0': ret += "\\0"; break; case L'\a': ret += "\\a"; break; case L'\b': ret += "\\b"; break; case L'\f': ret += "\\f"; break; case L'\n': ret += "\\n"; break; case L'\r': ret += "\\r"; break; case L'\t': ret += "\\t"; break; case L'\v': ret += "\\v"; break; default: if (wch < 0x20 || 0x7F < wch) { // hex char buf[32]; if (wch <= 0xFF) { std::sprintf(buf, "\\x%02X", (char)wch); } else if (wch <= 0xFFFF) { std::sprintf(buf, "\\u%04X", wch); } else { std::sprintf(buf, "\\U%08X", wch); } ret += buf; } else { ret += (char)wch; } break; } } ret += char(quote); return ret; } inline std::wstring wstr_unquote(const std::string& str, char quote) { static const char hex[] = "0123456789ABCDEF"; std::wstring ret; std::string str0 = str; str_trim(str0); if (str.empty()) return ret; if (str0[0] == quote && str0[str0.size() - 1] == quote) str0 = str0.substr(1, str0.size() - 2); int n; for (size_t i = 0; i < str0.size(); ++i) { if (str0[i] == '\\') { ++i; switch (str0[i]) { case '\'': ret += L"'"; break; case '\"': ret += L"\""; break; case '\\': ret += L"\\"; break; case 'a': ret += L"\a"; break; case 'b': ret += L"\b"; break; case 'f': ret += L"\f"; break; case 'n': ret += L"\n"; break; case 'r': ret += L"\r"; break; case 't': ret += L"\t"; break; case 'v': ret += L"\v"; break; case 'x': n = 0; ++i; if (is_xdigit(str0[i])) { n *= 16; n += strchr(hex, str0[i]) - hex; ++i; if (is_xdigit(str0[i])) { n *= 16; n += strchr(hex, str0[i]) - hex; ++i; } } --i; ret += (wchar_t)n; break; case 'u': n = 0; ++i; if (is_xdigit(str0[i])) { n *= 16; n += strchr(hex, str0[i]) - hex; ++i; if (is_xdigit(str0[i])) { n *= 16; n += strchr(hex, str0[i]) - hex; ++i; if (is_xdigit(str0[i])) { n *= 16; n += strchr(hex, str0[i]) - hex; ++i; if (is_xdigit(str0[i])) { n *= 16; n += strchr(hex, str0[i]) - hex; ++i; } } } } --i; ret += (wchar_t)n; break; case 'U': n = 0; ++i; if (is_xdigit(str0[i])) { n *= 16; n += strchr(hex, str0[i]) - hex; ++i; if (is_xdigit(str0[i])) { n *= 16; n += strchr(hex, str0[i]) - hex; ++i; if (is_xdigit(str0[i])) { n *= 16; n += strchr(hex, str0[i]) - hex; ++i; if (is_xdigit(str0[i])) { n *= 16; n += strchr(hex, str0[i]) - hex; ++i; if (is_xdigit(str0[i])) { n *= 16; n += strchr(hex, str0[i]) - hex; ++i; if (is_xdigit(str0[i])) { n *= 16; n += strchr(hex, str0[i]) - hex; ++i; if (is_xdigit(str0[i])) { n *= 16; n += strchr(hex, str0[i]) - hex; ++i; if (is_xdigit(str0[i])) { n *= 16; n += strchr(hex, str0[i]) - hex; ++i; } } } } } } } } --i; ret += (wchar_t)n; break; default: n = 0; if (is_digit(str0[i])) { // octal n *= 8; n += strchr(hex, str0[i]) - hex; ++i; if (is_digit(str0[i])) { n *= 8; n += strchr(hex, str0[i]) - hex; ++i; if (is_digit(str0[i])) { n *= 8; n += strchr(hex, str0[i]) - hex; ++i; } } --i; ret += (wchar_t)n; } else { ret += (wchar_t)str0[i]; } break; } } else if (str0[i] == quote) { ++i; if (str0[i] == quote && quote == '"') { ret += L"\""; } else { return ret; } } else { wchar_t wch; int code = mbtowc(&wch, &str0[i], str0.size() - i); if (code < 0) { ret += L'?'; } else if (code == 0) { ret += L'\0'; } else { ret += wch; i += code - 1; } } } return ret; } } // namespace CodeReverse ///////////////////////////////////////////////////////////////////////// #endif // ndef CODEREVERSE_LEXER_HPP
Python
UTF-8
1,963
3.578125
4
[]
no_license
# Recurrent Neural Network # Part 1 - Data Preprocessing # Importing the libraries import numpy as np import matplotlib.pyplot as plt import pandas as pd # Importing the training set dataset_train = pd.read_csv('Google_Stock_Price_Train.csv') training_set = dataset_train.iloc[:, 1:2].values # Feature Scaling from sklearn.preprocessing import MinMaxScaler sc = MinMaxScaler(feature_range = (0, 1)) training_set_scaled = sc.fit_transform(training_set) # Creating a data structure with 60 timesteps and 1 output X_train = [] y_train = [] for i in range(60, 1258): X_train.append(training_set_scaled[i-60:i, 0]) y_train.append(training_set_scaled[i, 0]) X_train, y_train = np.array(X_train), np.array(y_train) # Reshaping X_train = np.reshape(X_train, (X_train.shape[0], X_train.shape[1], 1)) # Part 2 - Building the RNN # Importing the Keras libraries and packages from keras.models import Sequential from keras.layers import Dense from keras.layers import LSTM from keras.layers import Dropout # Initialising the RNN regressor = Sequential() # Adding the first LSTM layer and some Dropout regularisation regressor.add(LSTM(units = 50, return_sequences = True, input_shape = (X_train.shape[1], 1))) regressor.add(Dropout(0.2)) # Adding the second LSTM Layer and some dropout regularization regressor.add(LSTM(units = 50, return_sequences = True)) regressor.add(Dropout(0.2)) # Adding the third LSTM layer with some dropout regularization regressor.add(LSTM(units = 50, return_sequences = True)) regressor.add(Dropout(0.2)) # Adding the fourth LSTM Layer with some Dropout regularization regressor.add(LSTM(units = 50)) regressor.add(Dropout(0.2)) # Adding the output layer regressor.add(Dense(units = 1)) # Compiling the RNN regressor.compile(optimizer = 'adam', loss = 'mean_squared_error') # Fitting the RNN to the training data regressor.fit(X_train, y_train, epochs = 100, batch_size = 32) # Predicting and visualizing the results
JavaScript
UTF-8
3,602
2.609375
3
[]
no_license
//Mongo Connection const mongoose = require("mongoose"); //====models========== mongoose.connect(process.env.MONGODB_URI || "mongodb://localhost/workout", { useNewUrlParser: true, useUnifiedTopology: true }); const Schema = mongoose.Schema; const workOutSchema = new Schema({ type: String, name: String, duration: Number, weight: Number, reps: Number, sets: Number, distance: Number, date: { type: Date, default: Date.now }, completed: { type: Boolean, default: false }, updated_at: { type: Date, default: Date.now } }) const WorkOut = mongoose.model("WorkOut", workOutSchema); const workOutDaySchema = new Schema({ date: { type: Date, default: Date.now }, workouts: [{ type: Schema.Types.ObjectId, ref: "WorkOut" }] }) const WorkOutDay = mongoose.model("WorkOutDay", workOutDaySchema); //====== async function createWorkout( myPost ){ let workOutDay; const currentDay = new Date(); // workOutDay = await WorkOutDay.create( { date: currentDay} ); // const workOutDayId = workOutDay._id; let workoutType = myPost.type; if (workoutType === "resistance"){ const myResult = await WorkOut.create( { type: myPost.type, name: myPost.name, duration: myPost.duration, weight: myPost.weight, reps: myPost.reps, sets: myPost.sets } ); console.log( 'in orm created workout is ', myResult) // const wrkOutId = myResult._id; // dbResult = await WorkOutDay.update({ date: currentDay}, { $push: { workouts: wrkOutId } }); // dbResult = await WorkOutDay.find({ date: currentDay}); // console.log(`current day data is :`, dbResult) return myResult; } else if (workoutType === "cardio") { const myResult = await WorkOut.create( { type: myPost.type, name: myPost.name, distance: myPost.distance, duration: myPost.duration } ); console.log( 'in orm created workout is ', myResult) return myResult; } } async function listWorkOuts(){ const myList = await WorkOut.find({ completed: false}) console.log('my list in orm is : ', myList); return myList; } async function listCompletedWorkOuts(){ const myList = await WorkOut.find({ completed: true}) console.log('my completed last workout in orm is : ', myList); return myList; } async function listNonCompletedWorkOuts(){ const myNotCompletedList = await WorkOut.find({ completed: false}) // console.log('my not completed last workout in orm is : ', myNotCompletedList); return myNotCompletedList; } async function lastWorkOut(){ const myLastWrkOutDay = await WorkOut.find({ completed: true, }).sort({ _id: -1 }).limit(1) const lastDate= myLastWrkOutDay[0].date console.log('my last workout date in orm is : ', lastDate); // console.log('my completed last workout in orm is : ', myLastWrkOut); const myLastWrkOuts = await WorkOut.find({ date: lastDate}); return myLastWrkOuts; } // completeWorkout async function completeWorkout( workOtId, date ){ const myResult = await WorkOut.update({_id: workOtId}, { $set:{ completed: true, date: date } }) console.log(myResult); return myResult; } module.exports = { createWorkout, listWorkOuts, completeWorkout, listCompletedWorkOuts, lastWorkOut, listNonCompletedWorkOuts }
Markdown
UTF-8
1,400
3.25
3
[]
no_license
# lmia assembler ## How to use Give the path to the file that sould be assembled and it outputs the assembled instructions. ```bash python3 assembler.py input_file_name ``` <br/> ## Examples ### Example 1 Input: ``` asm main: ; add value from address 0xAB to register 2 add r2, 0xAB ``` Output: ``` 00: 28AB ``` <br/> ### Example 2 Input: ``` asm ; define constants! $address1 = 0xA3 $address2 = 0xA4 main: ldr r0, $address1 ; load data from $address1 to register 0 str r0, $address2 ; write data from register 0 to $address2 ``` Output: ``` 00: 00A3 01: 10A4 ``` <br/> ### Example 3 Input: ``` assembly $result = 0xE0 $value1 = 0xE1 $value2 = 0xE2 ; copy the largest of $value1 and $value2 to $result start: ldr r0, $value1 ; load value from address $value1 sub r0, $value2 ; subtract with value at address $value2 bge load1 ; jump to load1 if $value1 was greater or equal to $value2 ; if no jump was made, fall through to load2 load2: ldr r1, $value2 ; load value from address $value2 bra save ; jump to save load1: ldr r1, $value1 ; load value from address $value2 ; fall through to save save: str r1, $result ; store the value at address $result halt ``` Output: ``` 00: 00E1 01: 30E2 02: A002 03: 04E2 04: 6001 05: 04E1 06: 14E0 07: 8000 ```
C++
UTF-8
10,672
2.625
3
[ "MIT" ]
permissive
/************************************************* * Slicer.cpp * * Release: July 2011 * Update: April 2015 * * University of North Carolina at Chapel Hill * Department of Computer Science * * Ilwoo Lyu, ilwoolyu@cs.unc.edu *************************************************/ #include <algorithm> #include <cstring> #include "Slicer.h" using namespace std; Slicer::Point::Point(void) { this->pos = 0.0f; next = NULL; prev = NULL; trace = false; } Slicer::Point::Point(MathVector pos) { this->pos = pos; next = NULL; prev = NULL; trace = false; } bool Slicer::Point::operator <(const Point &p) const { return this->ID < p.ID; } bool Slicer::Point::operator >(const Point &p) const { return this->ID > p.ID; } bool Slicer::Point::operator ==(const Point &p) const { return this->ID == p.ID; } bool Slicer::Point::operator <(const MathVector &v) const { return this->ID < v; } bool Slicer::Point::operator >(const MathVector &v) const { return this->ID > v; } bool Slicer::Point::operator ==(const MathVector &v) const { return this->ID == v; } Slicer::Slicer(void) { m_mesh = NULL; m_slice.clear(); } Slicer::Slicer(const Mesh *mesh) { m_mesh = mesh; // printf("AABB Tree Construction.. "); initTree(); update(); // printf("Done\n"); } Slicer::~Slicer(void) { m_slice.clear(); } int Slicer::slicing(const float a, const float b, const float c, const float d) { vector<int> cand; searchTree(m_tree, &cand, a, b, c, d); sort(cand.begin(), cand.end()); cand.erase(unique(cand.begin(), cand.end()), cand.end()); m_slice.clear(); m_group.clear(); for (int i = 0; i < cand.size(); i++) { const float *t0 = m_mesh->face(cand[i])->vertex(0)->fv(); const float *t1 = m_mesh->face(cand[i])->vertex(1)->fv(); const float *t2 = m_mesh->face(cand[i])->vertex(2)->fv(); float p0[3], p1[3]; int nv = Coordinate::intersection(t0, t1, t2, a, b, c, d, p0, p1); if (nv == 2) { // consistent direction MathVector N = m_mesh->face(cand[i])->faceNormal().fv(); MathVector P0 = p0; MathVector P1 = p1; MathVector P = P0 + N; float p[3]; Coordinate::proj2plane(a, b, c, d, P(), p); P = p; // edge id float it0 = a * t0[0] + b * t0[1] + c * t0[2] + d; float it1 = a * t1[0] + b * t1[1] + c * t1[2] + d; float it2 = a * t2[0] + b * t2[1] + c * t2[2] + d; /*float eps = 1e-8; if (fabs(it0) < eps) it0 = 0; if (fabs(it1) < eps) it1 = 0; if (fabs(it2) < eps) it2 = 0;*/ if (MathVector(t0) == MathVector(p0) || MathVector(t0) == MathVector(p1)) it0 = 0; if (MathVector(t1) == MathVector(p0) || MathVector(t1) == MathVector(p1)) it1 = 0; if (MathVector(t2) == MathVector(p0) || MathVector(t2) == MathVector(p1)) it2 = 0; int id0[3] = {0, 0, 0}, id1[3] = {0, 0, 0}; //if (fabs(it1) < eps && fabs(it2) < eps) if (fabs(it1) == 0 && fabs(it2) == 0) { id0[0] = id0[1] = m_mesh->face(cand[i])->vertex(1)->id(); id1[0] = id1[1] = m_mesh->face(cand[i])->vertex(2)->id(); } //else if (fabs(it2) < eps && fabs(it0) < eps) else if (fabs(it2) == 0 && fabs(it0) == 0) { id0[0] = id0[1] = m_mesh->face(cand[i])->vertex(2)->id(); id1[0] = id1[1] = m_mesh->face(cand[i])->vertex(0)->id(); } //else if (fabs(it0) < eps && fabs(it1) < eps) else if (fabs(it0) == 0 && fabs(it1) == 0) { id0[0] = id0[1] = m_mesh->face(cand[i])->vertex(0)->id(); id1[0] = id1[1] = m_mesh->face(cand[i])->vertex(1)->id(); } else if (it1 * it2 >= 0) { //if (fabs(it1) < eps) if (fabs(it1) == 0) id0[0] = m_mesh->face(cand[i])->vertex(1)->id(); else id0[0] = m_mesh->face(cand[i])->vertex(0)->id(); //if (fabs(it2) < eps) if (fabs(it2) == 0) id1[0] = m_mesh->face(cand[i])->vertex(2)->id(); else id1[0] = m_mesh->face(cand[i])->vertex(0)->id(); id0[1] = m_mesh->face(cand[i])->vertex(1)->id(); id1[1] = m_mesh->face(cand[i])->vertex(2)->id(); } else if (it2 * it0 >= 0) { //if (fabs(it2) < eps) if (fabs(it2) == 0) id0[0] = m_mesh->face(cand[i])->vertex(2)->id(); else id0[0] = m_mesh->face(cand[i])->vertex(1)->id(); //if (fabs(it0) < eps) if (fabs(it0) == 0) id1[0] = m_mesh->face(cand[i])->vertex(0)->id(); else id1[0] = m_mesh->face(cand[i])->vertex(1)->id(); id0[1] = m_mesh->face(cand[i])->vertex(2)->id(); id1[1] = m_mesh->face(cand[i])->vertex(0)->id(); } else if (it0 * it1 >= 0) { //if (fabs(it0) < eps) if (fabs(it0) == 0) id0[0] = m_mesh->face(cand[i])->vertex(0)->id(); else id0[0] = m_mesh->face(cand[i])->vertex(2)->id(); //if (fabs(it1) < eps) if (fabs(it1) == 0) id1[0] = m_mesh->face(cand[i])->vertex(1)->id(); else id1[0] = m_mesh->face(cand[i])->vertex(2)->id(); id0[1] = m_mesh->face(cand[i])->vertex(0)->id(); id1[1] = m_mesh->face(cand[i])->vertex(1)->id(); } if (id0[0] > id0[1]) swap(id0[0], id0[1]); if (id1[0] > id1[1]) swap(id1[0], id1[1]); MathVector PP0 = P0 - P, PP1 = P1 - P; MathVector PCP = PP0.cross(PP1); if (PCP * MathVector(a, b, c) > 0) { swap(p0, p1); swap(id0, id1); } // new item Point item; item.pos = p0; item.ID = id0; item.faceID = cand[i]; item.nextID = id1; m_slice.push_back(item); } } sort(m_slice.begin(), m_slice.end()); return contour(); } void Slicer::getSlice(float *plist, int group) { Point *iter = m_group[group].begin; for (int i = 0; i < m_group[group].size; i++) { memcpy(&plist[i * 3], iter->pos.fv(), sizeof(float) * 3); iter = iter->next; } } void Slicer::getSliceFaceIdx(int *plist, int group) { Point *iter = m_group[group].begin; for (int i = 0; i < m_group[group].size; i++) { plist[i] = iter->faceID; iter = iter->next; } } const float * Slicer::getEdgeID(int id, int group) { Point *iter = m_group[group].begin; for (int i = 0; i < m_group[group].size; i++) { if (i == id) return iter->ID.fv(); iter = iter->next; } return NULL; } int Slicer::size(int group) { return m_group[group].size; } void Slicer::searchTree(node *root, vector<int> *cand, const float a, const float b, const float c, const float d) { if (root->left != NULL && boxIntersection(a, b, c, d, root->left->x0, root->left->x1, root->left->y0, root->left->y1, root->left->z0, root->left->z1)) searchTree(root->left, cand, a, b, c, d); if (root->right != NULL && boxIntersection(a, b, c, d, root->right->x0, root->right->x1, root->right->y0, root->right->y1, root->right->z0, root->right->z1)) searchTree(root->right, cand, a, b, c, d); if (root->left == NULL && root->right == NULL) for (int i = 0; i < root->cand.size(); i++) cand->push_back(root->cand[i]); } bool Slicer::boxIntersection(const float a, const float b, const float c, const float d, const float x0, const float x1, const float y0, const float y1, const float z0, const float z1) { float i1 = (a * x0 + b * y0 + c * z0 + d); float i2 = (a * x1 + b * y0 + c * z0 + d); float i3 = (a * x0 + b * y1 + c * z0 + d); float i4 = (a * x1 + b * y1 + c * z0 + d); float i5 = (a * x0 + b * y0 + c * z1 + d); float i6 = (a * x1 + b * y0 + c * z1 + d); float i7 = (a * x0 + b * y1 + c * z1 + d); float i8 = (a * x1 + b * y1 + c * z1 + d); if ((i1 > 0 && i2 > 0 && i3 > 0 && i4 > 0 && i5 > 0 && i6 > 0 && i7 > 0 && i8 > 0) || (i1 < 0 && i2 < 0 && i3 < 0 && i4 < 0 && i5 < 0 && i6 < 0 && i7 < 0 && i8 < 0)) return false; else return true; } int Slicer::contour(void) { bool closed = false; for (int i = 0; i < m_slice.size(); i++) //for (int i = m_slice.size() - 1; i >= 0; i--) { if (!m_slice[i].trace) { int n = tracePList(i, i); if (n > 0) { ContourHead ch; ch.begin = &m_slice[i]; ch.size = n; ch.closed = (ch.begin == ch.begin->prev->next); if (!ch.closed) { // partial loop bool inside = false; Point *part = ch.begin->prev->next; Point *iter = ch.begin; // check if the next candidate is inside the current loop for (int j = 0; j < ch.size; j++, iter = iter->next) { if (iter == part) { inside = true; break; } } if (inside) { ContourHead chLoop; swap(ch.begin->prev, part->prev); // previous group for (n = 0, iter = ch.begin; iter != part; iter = iter->next, n++); ch.size = n; // new group chLoop.begin = part; chLoop.closed = true; for (n = 1, iter = chLoop.begin; iter != chLoop.begin->prev; iter = iter->next, n++); chLoop.size = n; m_group.push_back(chLoop); } } closed = closed || !ch.closed; m_group.push_back(ch); } } } // connected components int gSize = m_group.size(); while (closed) { int i = 0; while (i < m_group.size()) { //cout << "Group " << i << ": " << m_group[i].closed << endl; if (!m_group[i].closed) { for (int c = 0; c < m_group.size(); c++) { if (m_group[c].closed) continue; Point *tail = m_group[i].begin->prev->next; Point *head = m_group[c].begin; if (tail == head) { swap(m_group[i].begin->prev, m_group[c].begin->prev); m_group[i].size += m_group[c].size; m_group.erase(m_group.begin() + c); break; } } } i++; } closed = (gSize != m_group.size()); gSize = m_group.size(); } return m_group.size(); } int Slicer::tracePList(int headID, int id) { // next target int nextID = lower_bound(m_slice.begin(), m_slice.end(), m_slice[id].nextID) - m_slice.begin(); /*int nextID; for (int i = 0; i < m_slice.size(); i++) { if (m_slice[i].ID == m_slice[id].nextID && i != id) { nextID = i; break; } }*/ m_slice[id].trace = true; m_slice[id].next = &m_slice[nextID]; if (!m_slice[nextID].trace) { m_slice[nextID].prev = &m_slice[id]; return tracePList(headID, nextID) + 1; } /*else if (m_slice[nextID].faceID != headFaceID) { cout << m_slice[nextID].trace << endl; int newNextID = m_slice.size(); Point *iter; int n = 0; for (iter = &m_slice[nextID]; iter->trace; iter = iter->prev, n++) { Point item = m_slice[nextID]; item.trace = false; item.next = &item; m_slice.push_back(item); } m_slice[nextID].prev = &m_slice[id]; m_slice[id].next = &m_slice[newNextID]; sort(m_slice.begin(), m_slice.end()); int nextID = lower_bound(m_slice.begin(), m_slice.end(), iter->nextID) - m_slice.begin(); return tracePList(headFaceID, nextID) + n; }*/ else { m_slice[headID].prev = &m_slice[id]; int nextID = -1; for (int i = 0; i < m_slice.size(); i++) { if (m_slice[i].ID == m_slice[id].nextID && i != id) { nextID = i; break; } } return 1; } }
C#
UTF-8
13,070
2.734375
3
[]
no_license
using DAL; using System; using System.Collections.Generic; using System.Data; using System.Data.SQLite; using System.Linq; using System.Text; using System.Web; namespace DAL { /// <summary> /// 数据访问类:Article /// </summary> public partial class Article { public Article() { } #region BasicMethod /// <summary> /// 是否存在该记录 /// </summary> public bool Exists(int ID) { StringBuilder strSql = new StringBuilder(); strSql.Append("select count(1) from Article"); strSql.Append(" where ID=@ID"); SQLiteParameter[] parameters = { new SQLiteParameter("@ID", DbType.Int32,4) }; parameters[0].Value = ID; return DbHelperSQLite.Exists(strSql.ToString(), parameters); } /// <summary> /// 增加一条数据 /// </summary> public int Add(Model.Article model) { StringBuilder strSql = new StringBuilder(); strSql.Append("insert into Article("); strSql.Append("Title,Detail,Summary,Author,SubmitTime,UpdateTime,Type,Click,[Order])"); strSql.Append(" values ("); strSql.Append("@Title,@Detail,@Summary,@Author,@SubmitTime,@UpdateTime,@Type,@Click,@Order)"); strSql.Append(";select LAST_INSERT_ROWID()"); SQLiteParameter[] parameters = { new SQLiteParameter("@Title", DbType.String), new SQLiteParameter("@Detail", DbType.String), new SQLiteParameter("@Summary", DbType.String), new SQLiteParameter("@Author", DbType.String), new SQLiteParameter("@SubmitTime", DbType.String), new SQLiteParameter("@UpdateTime", DbType.String), new SQLiteParameter("@Type", DbType.String), new SQLiteParameter("@Click", DbType.String), new SQLiteParameter("@Order", DbType.Int32,8)}; parameters[0].Value = model.Title; parameters[1].Value = model.Detail; parameters[2].Value = model.Summary; parameters[3].Value = model.Author; parameters[4].Value = model.SubmitTime; parameters[5].Value = model.UpdateTime; parameters[6].Value = model.Type; parameters[7].Value = model.Click; parameters[8].Value = model.Order; object obj = DbHelperSQLite.GetSingle(strSql.ToString(), parameters); if (obj == null) { return 0; } else { return Convert.ToInt32(obj); } } /// <summary> /// 更新一条数据 /// </summary> public bool Update(Model.Article model) { StringBuilder strSql = new StringBuilder(); strSql.Append("update Article set "); strSql.Append("Title=@Title,"); strSql.Append("Detail=@Detail,"); strSql.Append("Summary=@Summary,"); strSql.Append("Author=@Author,"); strSql.Append("SubmitTime=@SubmitTime,"); strSql.Append("UpdateTime=@UpdateTime,"); strSql.Append("Type=@Type,"); strSql.Append("Click=@Click,"); strSql.Append("[Order]=@Order"); strSql.Append(" where ID=@ID"); SQLiteParameter[] parameters = { new SQLiteParameter("@Title", DbType.String), new SQLiteParameter("@Detail", DbType.String), new SQLiteParameter("@Summary", DbType.String), new SQLiteParameter("@Author", DbType.String), new SQLiteParameter("@SubmitTime", DbType.String), new SQLiteParameter("@UpdateTime", DbType.String), new SQLiteParameter("@Type", DbType.String), new SQLiteParameter("@Click", DbType.String), new SQLiteParameter("@Order", DbType.Int32,8), new SQLiteParameter("@ID", DbType.Int32,8)}; parameters[0].Value = model.Title; parameters[1].Value = model.Detail; parameters[2].Value = model.Summary; parameters[3].Value = model.Author; parameters[4].Value = model.SubmitTime; parameters[5].Value = model.UpdateTime; parameters[6].Value = model.Type; parameters[7].Value = model.Click; parameters[8].Value = model.Order; parameters[9].Value = model.ID; int rows = DbHelperSQLite.ExecuteSql(strSql.ToString(), parameters); if (rows > 0) { return true; } else { return false; } } /// <summary> /// 删除一条数据 /// </summary> public bool Delete(int ID) { StringBuilder strSql = new StringBuilder(); strSql.Append("delete from Article "); strSql.Append(" where ID=@ID"); SQLiteParameter[] parameters = { new SQLiteParameter("@ID", DbType.Int32,4) }; parameters[0].Value = ID; int rows = DbHelperSQLite.ExecuteSql(strSql.ToString(), parameters); if (rows > 0) { return true; } else { return false; } } /// <summary> /// 批量删除数据 /// </summary> public bool DeleteList(string IDlist) { StringBuilder strSql = new StringBuilder(); strSql.Append("delete from Article "); strSql.Append(" where ID in (" + IDlist + ") "); int rows = DbHelperSQLite.ExecuteSql(strSql.ToString()); if (rows > 0) { return true; } else { return false; } } /// <summary> /// 得到一个对象实体 /// </summary> public Model.Article GetModel(int ID) { StringBuilder strSql = new StringBuilder(); strSql.Append("select * from Article "); strSql.Append(" where ID=@ID"); SQLiteParameter[] parameters = { new SQLiteParameter("@ID", DbType.Int32,4) }; parameters[0].Value = ID; Model.Article model = new Model.Article(); DataSet ds = DbHelperSQLite.Query(strSql.ToString(), parameters); if (ds.Tables[0].Rows.Count > 0) { return DataRowToModel(ds.Tables[0].Rows[0]); } else { return null; } } /// <summary> /// 得到一个对象实体 /// </summary> public Model.Article DataRowToModel(DataRow row) { Model.Article model = new Model.Article(); if (row != null) { if (row["ID"] != null && row["ID"].ToString() != "") { model.ID = int.Parse(row["ID"].ToString()); } if (row["Title"] != null) { model.Title = row["Title"].ToString(); } if (row["Detail"] != null) { model.Detail = row["Detail"].ToString(); } if (row["Summary"] != null) { model.Summary = row["Summary"].ToString(); } if (row["Author"] != null) { model.Author = row["Author"].ToString(); } if (row["SubmitTime"] != null) { model.SubmitTime = row["SubmitTime"].ToString(); } if (row["UpdateTime"] != null) { model.UpdateTime = row["UpdateTime"].ToString(); } if (row["Type"] != null) { model.Type = row["Type"].ToString(); } if (row["Click"] != null) { model.Click = row["Click"].ToString(); } if (row["Order"] != null && row["Order"].ToString() != "") { model.Order = int.Parse(row["Order"].ToString()); } } return model; } /// <summary> /// 获得数据列表 /// </summary> public DataSet GetList(string strWhere) { StringBuilder strSql = new StringBuilder(); strSql.Append("select * "); strSql.Append(" FROM Article "); if (strWhere.Trim() != "") { strSql.Append(" where " + strWhere); } return DbHelperSQLite.Query(strSql.ToString()); } /// <summary> /// 获取记录总数 /// </summary> public int GetRecordCount(string strWhere) { StringBuilder strSql = new StringBuilder(); strSql.Append("select count(1) FROM Article "); if (strWhere.Trim() != "") { strSql.Append(" where " + strWhere); } object obj = DbHelperSQLite.GetSingle(strSql.ToString()); if (obj == null) { return 0; } else { return Convert.ToInt32(obj); } } /// <summary> /// 分页获取数据列表 /// </summary> public DataSet GetListByPage(string strWhere, string orderby, int startIndex, int count) { StringBuilder strSql = new StringBuilder(); strSql.Append("Select * from Article"); if (strWhere != "") strSql.Append(" where " + strWhere); if (orderby != "") strSql.Append(" order by " + orderby); else strSql.Append(" order by id desc"); strSql.Append(" Limit @index,@count"); SQLiteParameter[] parameters = { new SQLiteParameter("@index",DbType.Int32), new SQLiteParameter("@count", DbType.Int32) }; parameters[0].Value = startIndex; parameters[1].Value = count; return DbHelperSQLite.Query(strSql.ToString(), parameters); } #endregion BasicMethod #region ExtensionMethod /// <summary> /// 分页获取数据 /// </summary> /// <param name="where">条件</param> /// <param name="orderby">排序</param> /// <param name="pageIndex">显示第几页</param> /// <param name="pageSize">页面条数</param> /// <param name="RowCount">返回条数</param> /// <param name="PageCount">返回页数</param> /// <returns></returns> public DataTable GetListByPage(string where, string orderby, int pageIndex, int pageSize, ref int RowCount, ref int PageCount) { int startIndex = (pageIndex - 1) * pageSize; RowCount = GetRecordCount(where); if (RowCount == 0) { PageCount = 1; return new DataTable(); } PageCount = (RowCount - 1) / pageSize + 1; return GetListByPage(where, orderby, startIndex, pageSize).Tables[0]; } /// <summary> /// 获得数据列表 /// </summary> public List<Model.Article> GetModelList(string strWhere) { DataSet ds = GetList(strWhere); return DataTableToList(ds.Tables[0]); } /// <summary> /// 获得数据列表 /// </summary> public List<Model.Article> DataTableToList(DataTable dt) { List<Model.Article> modelList = new List<Model.Article>(); int rowsCount = dt.Rows.Count; if (rowsCount > 0) { Model.Article model; for (int n = 0; n < rowsCount; n++) { model = DataRowToModel(dt.Rows[n]); if (model != null) { modelList.Add(model); } } } return modelList; } public List<Model.Article> GetModelListByPage(string where, string orderby, int pageIndex, int pageSize, ref int RowCount, ref int PageCount) { DataTable ds = GetListByPage(where, orderby, pageIndex, pageSize, ref RowCount, ref PageCount); return DataTableToList(ds); } #endregion ExtensionMethod } }
Java
UTF-8
4,751
1.890625
2
[ "Apache-2.0", "EPL-2.0" ]
permissive
/* * DBeaver - Universal Database Manager * Copyright (C) 2010-2017 Serge Rider (serge@jkiss.org) * * 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 org.jkiss.dbeaver.runtime.qm; import org.jkiss.dbeaver.Log; import org.jkiss.dbeaver.model.qm.*; import java.lang.reflect.InvocationHandler; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.lang.reflect.Proxy; import java.util.ArrayList; import java.util.List; /** * QMController default implementation */ public class QMControllerImpl implements QMController { private static final Log log = Log.getLog(QMControllerImpl.class); private QMExecutionHandler defaultHandler; private QMMCollectorImpl metaHandler; private final List<QMExecutionHandler> handlers = new ArrayList<>(); public QMControllerImpl() { defaultHandler = (QMExecutionHandler) Proxy.newProxyInstance( getClass().getClassLoader(), new Class[]{ QMExecutionHandler.class }, new NotifyInvocationHandler()); metaHandler = new QMMCollectorImpl(); registerHandler(metaHandler); } public void dispose() { if (metaHandler != null) { unregisterHandler(metaHandler); metaHandler.dispose(); metaHandler = null; } synchronized (handlers) { if (!handlers.isEmpty()) { log.warn("Some QM handlers are still registered: " + handlers); handlers.clear(); } } defaultHandler = null; } @Override public QMMCollector getMetaCollector() { return metaHandler; } @Override public QMExecutionHandler getDefaultHandler() { return defaultHandler; } @Override public void registerHandler(QMExecutionHandler handler) { synchronized (handlers) { handlers.add(handler); } } @Override public void unregisterHandler(QMExecutionHandler handler) { synchronized (handlers) { if (!handlers.remove(handler)) { log.warn("QM handler '" + handler + "' isn't registered within QM controller"); } } } @Override public void registerMetaListener(QMMetaListener metaListener) { metaHandler.addListener(metaListener); } @Override public void unregisterMetaListener(QMMetaListener metaListener) { metaHandler.removeListener(metaListener); } @Override public List<QMMetaEvent> getPastMetaEvents() { return metaHandler.getPastEvents(); } List<QMExecutionHandler> getHandlers() { synchronized (handlers) { return handlers; } } private class NotifyInvocationHandler implements InvocationHandler { @Override public Object invoke(Object proxy, Method method, Object[] args) { try { if (method.getReturnType() == Void.TYPE && method.getName().startsWith("handle")) { QMExecutionHandler[] handlersCopy; synchronized (handlers) { handlersCopy = handlers.toArray(new QMExecutionHandler[handlers.size()]); } for (QMExecutionHandler handler : handlersCopy) { try { method.invoke(handler, args); } catch (InvocationTargetException e) { log.debug("Error notifying QM handler '" + handler.getHandlerName() + "'", e.getTargetException()); } } return null; } else if (method.getName().equals("getHandlerName")) { return "Default"; } else { return method.invoke(this, args); } } catch (Throwable e) { // just ignore it log.debug("Error executing QM method " + method, e); return null; } } } }
Java
UTF-8
8,926
2.84375
3
[ "MIT" ]
permissive
package com.embroidermodder.embroideryviewer; import java.io.DataInputStream; import java.io.IOException; public class FormatPec implements IFormatReader { public boolean hasColor() { return true; } public boolean hasStitches() { return true; } public Pattern read(DataInputStream stream) { Pattern p = new Pattern(); try{ stream.skip(0x38); int colorChanges = stream.readByte(); for(int i = 0; i <= colorChanges; i++) { int index = stream.readByte(); p.addThread(getThreadByIndex(index % 65)); } stream.skip(0x221 - (0x38 + 1 + colorChanges)); readPecStitches(p, stream); } catch (IOException ex) { } return p; } public static void readPecStitches(Pattern pattern, DataInputStream stream) { try { while (stream.available() > 0) { int val1 = (stream.readByte() & 0xFF); int val2 = (stream.readByte() & 0xFF); int stitchType = StitchType.NORMAL; if (val1 == 0xFF && val2 == 0x00) { pattern.addStitchRel(0.0, 0.0, StitchType.END, true); break; } if (val1 == 0xFE && val2 == 0xB0) { stream.readByte(); pattern.addStitchRel(0.0, 0.0, StitchType.STOP, true); continue; } /* High bit set means 12-bit offset, otherwise 7-bit signed delta */ if ((val1 & 0x80) > 0) { if ((val1 & 0x20) > 0) { stitchType = StitchType.TRIM; } if ((val1 & 0x10) > 0) { stitchType = StitchType.JUMP; } val1 = ((val1 & 0x0F) << 8) + val2; /* Signed 12-bit arithmetic */ if ((val1 & 0x800) > 0) { val1 -= 0x1000; } val2 = stream.readByte() & 0xFF; } else if (val1 >= 0x40) { val1 -= 0x80; } if ((val2 & 0x80) > 0) { if ((val2 & 0x20) > 0) { stitchType = StitchType.TRIM; } if ((val2 & 0x10) > 0) { stitchType = StitchType.JUMP; } val2 = ((val2 & 0x0F) << 8) + (stream.readByte() & 0xFF); /* Signed 12-bit arithmetic */ if ((val2 & 0x800) > 0) { val2 -= 0x1000; } } else if (val2 >= 0x40) { val2 -= 0x80; } pattern.addStitchRel(val1 / 10.0, val2 / 10.0, stitchType, true); } } catch (IOException ex) { } } public static EmbThread getThreadByIndex(int index) { switch (index) { case 0: return new EmbThread(0, 0, 0, "Unknown", ""); case 1: return new EmbThread(14, 31, 124, "Prussian Blue", ""); case 2: return new EmbThread(10, 85, 163, "Blue", ""); case 3: return new EmbThread(0, 135, 119, "Teal Green", ""); case 4: return new EmbThread(75, 107, 175, "Cornflower Blue", ""); case 5: return new EmbThread(237, 23, 31, "Red", ""); case 6: return new EmbThread(209, 92, 0, "Reddish Brown", ""); case 7: return new EmbThread(145, 54, 151, "Magenta", ""); case 8: return new EmbThread(228, 154, 203, "Light Lilac", ""); case 9: return new EmbThread(145, 95, 172, "Lilac", ""); case 10: return new EmbThread(158, 214, 125, "Mint Green", ""); case 11: return new EmbThread(232, 169, 0, "Deep Gold", ""); case 12: return new EmbThread(254, 186, 53, "Orange", ""); case 13: return new EmbThread(255, 255, 0, "Yellow", ""); case 14: return new EmbThread(112, 188, 31, "Lime Green", ""); case 15: return new EmbThread(186, 152, 0, "Brass", ""); case 16: return new EmbThread(168, 168, 168, "Silver", ""); case 17: return new EmbThread(125, 111, 0, "Russet Brown", ""); case 18: return new EmbThread(255, 255, 179, "Cream Brown", ""); case 19: return new EmbThread(79, 85, 86, "Pewter", ""); case 20: return new EmbThread(0, 0, 0, "Black", ""); case 21: return new EmbThread(11, 61, 145, "Ultramarine", ""); case 22: return new EmbThread(119, 1, 118, "Royal Purple", ""); case 23: return new EmbThread(41, 49, 51, "Dark Gray", ""); case 24: return new EmbThread(42, 19, 1, "Dark Brown", ""); case 25: return new EmbThread(246, 74, 138, "Deep Rose", ""); case 26: return new EmbThread(178, 118, 36, "Light Brown", ""); case 27: return new EmbThread(252, 187, 197, "Salmon Pink", ""); case 28: return new EmbThread(254, 55, 15, "Vermillion", ""); case 29: return new EmbThread(240, 240, 240, "White", ""); case 30: return new EmbThread(106, 28, 138, "Violet", ""); case 31: return new EmbThread(168, 221, 196, "Seacrest", ""); case 32: return new EmbThread(37, 132, 187, "Sky Blue", ""); case 33: return new EmbThread(254, 179, 67, "Pumpkin", ""); case 34: return new EmbThread(255, 243, 107, "Cream Yellow", ""); case 35: return new EmbThread(208, 166, 96, "Khaki", ""); case 36: return new EmbThread(209, 84, 0, "Clay Brown", ""); case 37: return new EmbThread(102, 186, 73, "Leaf Green", ""); case 38: return new EmbThread(19, 74, 70, "Peacock Blue", ""); case 39: return new EmbThread(135, 135, 135, "Gray", ""); case 40: return new EmbThread(216, 204, 198, "Warm Gray", ""); case 41: return new EmbThread(67, 86, 7, "Dark Olive", ""); case 42: return new EmbThread(253, 217, 222, "Flesh Pink", ""); case 43: return new EmbThread(249, 147, 188, "Pink", ""); case 44: return new EmbThread(0, 56, 34, "Deep Green", ""); case 45: return new EmbThread(178, 175, 212, "Lavender", ""); case 46: return new EmbThread(104, 106, 176, "Wisteria Violet", ""); case 47: return new EmbThread(239, 227, 185, "Beige", ""); case 48: return new EmbThread(247, 56, 102, "Carmine", ""); case 49: return new EmbThread(181, 75, 100, "Amber Red", ""); case 50: return new EmbThread(19, 43, 26, "Olive Green", ""); case 51: return new EmbThread(199, 1, 86, "Dark Fuschia", ""); case 52: return new EmbThread(254, 158, 50, "Tangerine", ""); case 53: return new EmbThread(168, 222, 235, "Light Blue", ""); case 54: return new EmbThread(0, 103, 62, "Emerald Green", ""); case 55: return new EmbThread(78, 41, 144, "Purple", ""); case 56: return new EmbThread(47, 126, 32, "Moss Green", ""); case 57: return new EmbThread(255, 204, 204, "Flesh Pink", ""); case 58: return new EmbThread(255, 217, 17, "Harvest Gold", ""); case 59: return new EmbThread(9, 91, 166, "Electric Blue", ""); case 60: return new EmbThread(240, 249, 112, "Lemon Yellow", ""); case 61: return new EmbThread(227, 243, 91, "Fresh Green", ""); case 62: return new EmbThread(255, 153, 0, "Orange", ""); case 63: return new EmbThread(255, 240, 141, "Cream Yellow", ""); case 64: return new EmbThread(255, 200, 200, "Applique", ""); } return null; } }
Java
UTF-8
993
2.1875
2
[]
no_license
package bcp.limitsservice; import org.springframework.boot.context.properties.ConfigurationProperties; import org.springframework.stereotype.Component; @Component @ConfigurationProperties("limits-service") public class Configuration { private int minimum; private int maximum; private String myprofile; protected Configuration() { } public int getMinimum() { return this.minimum; } public void setMinimum(int minimum) { this.minimum = minimum; } public int getMaximum() { return this.maximum; } public void setMaximum(int maximum) { this.maximum = maximum; } public String getMyprofile() { return myprofile; } public void setMyprofile(String myprofile) { this.myprofile = myprofile; } @Override public String toString() { return "Configuration [maximum=" + maximum + ", minimum=" + minimum + ", myprofile=" + myprofile + "]"; } }
JavaScript
UTF-8
871
2.625
3
[]
no_license
'use strict' const path = require('path') const fs = require('fs') const logger = require('./logger.js') function hasFile(filepath) { let stat try { stat = fs.statSync(filepath) } catch (e) { return false } return stat.isFile() } function ensureAndResolveFile(filepath) { filepath = path.resolve(filepath) if (!hasFile(filepath)) { logger.fatal(`${filepath} does not exist or is not a file.`) } return filepath } function getConfigFile(filepath) { let config = {} const resolvedFilepath = ensureAndResolveFile(filepath) try { config = require(resolvedFilepath) // eslint-disable-line } catch (e) { logger.error(e) logger.fatal(`${resolvedFilepath} failed to load.`) } return config } module.exports = { getConfigFile, ensureAndResolveFile }
TypeScript
UTF-8
737
2.875
3
[]
no_license
import { TabStateManager } from './tab-state.manager'; export class TabStateValueAccessor<T> { private _tabStateManager: TabStateManager; private _key: string; constructor(tabStateManager: TabStateManager, key: string) { this._tabStateManager = tabStateManager; this._key = key; } public getValue(): T { return this._tabStateManager.getKeyedValue(this._key); } public setValue(value: T): void { this._tabStateManager.setKeyedValue(this._key, value); } public deleteValue(): boolean { return this._tabStateManager.deleteKeyedValue(this._key); } public hasValue(): boolean { return this._tabStateManager.isKeyValueSet(this._key); } }
PHP
UTF-8
1,294
2.515625
3
[]
no_license
<?php namespace App\Transformers; use App\UserLog; use League\Fractal\TransformerAbstract; class UserLogTransformer extends TransformerAbstract { /** * List of resources possible to include. * * @var array */ protected $availableIncludes = [ 'user', ]; /** * List of default includes. * * @var array */ protected $defaultIncludes = [ 'user', ]; /** * Transform a UserLog * * @param UserLog $action * * @return array */ public function transform(UserLog $action) { return [ 'id' => $action->id, 'action_id' => $action->action_id, 'action_type' => class_basename($action->action_type), 'action' => $action->action, 'changes' => $action->changes, 'created_at' => $action->created_at->toIso8601String(), 'updated_at' => $action->updated_at->toIso8601String(), ]; } /** * Include user. * * @param UserLog $action * * @return \League\Fractal\Resource\Item|null */ public function includeUser(UserLog $action) { if($action->user) { return $this->item($action->user, new UserTransformer); } } }
Python
UTF-8
958
4.65625
5
[]
no_license
''' Write a program with use of inheritance: Define a class publisher that stores the name of the title. Derive two classes book and tape, which inherit publisher. Book class contains member data called page no and tape class contain time for playing. Define functions in the appropriate classes to get and print the details. ''' class Publisher: title_name ="John Carter" def display(self): print("Name : ",self.title_name) class book(Publisher): no_pages = 200 def display(self): print("Name : ",self.title_name) print('Pages:',self.no_pages) class tape(book): time = 3 def display(self): print("Name : ",self.title_name) print('Pages:',self.no_pages) print('time :{} hrs'.format(self.time)) obj1 = Publisher() obj2 = book() obj3 = tape() print("----Publisher display()----") obj1.display() print("----Book display()----") obj2.display() print("----Tape display()----") obj3.display()
Python
UTF-8
2,017
2.609375
3
[]
no_license
# # _*_coding:UTF-8 _*_ # # 采集代理 # import re # from urllib import request # from lxml import etree # # test_url = "http://www.httpbin.org/ip" # local_ip = request.urlopen(test_url).read().decode() # # url = "https://ip.jiangxianli.com/blog.html" # res = request.urlopen(url).read().decode('utf-8') # # with open('ip.html','w',encoding='utf-8') as w: # # w.write(res) # ele = etree.HTML(res) # char_url_list = ele.xpath('//h3/a/@href') # for char_url in char_url_list: # res1 = request.urlopen(char_url).read().decode('utf-8') # rule = '<p>(.*?)</p>' # ip_port_list = re.findall(rule, res) # for i in ip_port_list[1:]: # ip_port = i.split('@HTTP')[0] # ip_port1 = ip_port.lstrip() # # print(ip_port1) # # 拼接对应的代理格式 # dict1 = {} # dict1['http'] = ip_port1 # print("开始测试代理{}".format(dict1)) # # 构建代理handler # proxy_handler = request.ProxyHandler(dict1) # opener = request.build_opener(proxy_handler) # try: # now_ip = opener.open(test_url, timeout=4).read().decode() # if now_ip != local_ip: # print("代理可以用:{}".format(dict1)) # with open("ip.txt", "a") as w: # w.write(str(dict1) + "\n") # print("写入ip{}".format(dict1)) # except: # pass # # 测试代理 # from urllib import request # # test_url = "http://www.httpbin.org/ip" # local_ip = request.urlopen(test_url).read().decode() # with open('ip.txt', 'r') as r: # ips = r.readlines() # for ip in ips: # proxy_handler = request.ProxyHandler(eval(ip)) # opener = request.build_opener(proxy_handler) # try: # now_ip = opener.open(test_url, timeout=4).read().decode() # if now_ip != local_ip: # print("代理可以用{}".format(ip)) # with open('ip1.txt', 'a') as w: # w.write(str(ip)) # except: # pass
Markdown
UTF-8
2,501
3.28125
3
[]
no_license
--- title: JavaScript and Node.js layout: default --- ## JavaScript and NodeJS ### Installing Node.js Maintaining your locally installed Node.js versions using the [Node Version Manager (nvm)](https://github.com/nvm-sh/nvm) is recommended. The linked GitHub project page shows instructions to install nvm. Further details on using nvm are documented in section [nvm Commands](#nvm-commands) below. On Windows you can install `nvm` using [Chocolatey](https://community.chocolatey.org/packages/nvm). The normal Node.js release cycle is 6 months. Even though the release cycle of the long term stable version of Node.js (LTS) is 30 months, I recommend keeping your projects compatible with a recent version of Node.js. Otherwise you may run into larger work when you want to upgrade from the old to the new LTS version. ### Configuring Node Projects ```sh npm init ``` - [Creating a package.json file](https://docs.npmjs.com/creating-a-package-json-file) - [package.json](https://docs.npmjs.com/cli/v8/configuring-npm/package-json) - Specifics of npm's package.json handling. ### nvm Commands Usage examples and basic instructions are given on the [Github: nvm](https://github.com/nvm-sh/nvm) page. #### Upgrade nvm ```sh curl -o- https://raw.githubusercontent.com/nvm-sh/nvm/v0.39.1/install.sh | bash ```` #### Upgrade Your Node.js Version(s) ```sh # show currently available versions and installed versions in parentheses. nvm ls # show all versions available on the remote (many!) nvm ls-remote # show the version you are currently using nvm current # install a newer version nvm install NEW_VERSION --reinstall-packages-from=OLD_VERSION # e.g. to upgrade your LATEST version nvm install node --reinstall-packages-from=$(nvm current) # e.g. to upgrade your LTS version nvm install 'lts/*' --reinstall-packages-from="$(nvm current)" # remove the old version nvm uninstall OLD_VERSION ``` ### Links - [Node.js Releases](https://nodejs.org/en/about/releases/) - shows the release cycle of Node.js. - [Node Version Manager](https://github.com/nvm-sh/nvm) - facilitates installing multiple versions of Node.js in parallel. - GitHub: [wonderbird / nodejs-starter](https://github.com/wonderbird/nodejs-starter) - Template repository you can fork to start new projects. - GitHub: [hojak / js-kata-base](https://github.com/hojak/js-kata-base) - Another template repository you can fork to start new projects. - [Linting your TypeScript Codebase](https://typescript-eslint.io/docs/linting/)
Python
UTF-8
4,050
2.953125
3
[]
no_license
#!/usr/bin/env python """ Usage: EdgeClusterFromCopathOutput.py [OPTION] INPUTFILE OUTPUTFILE Option: Examples: EdgeClusterFromCopathOutput.py Fsc54_5G1E6D40Q40S200C50H4J40W40Z0010 Fsc54_5G1E6D40Q40S200C50H4J40W40Z0010E Description: This program restores the edge clusters(2nd-order cluster) from copath's 1st-order cluster output. The result is got by running copath with min_graph_size = 1. So no connected component is lost. The program doesn't restore the graph between the edges. """ import sys, os, getopt, csv, re from codense.codense2db import cluster_dstructure class EdgeClusterFromCopathOutput: """ 04-12-05 """ def __init__(self, infname, outfname): self.infname = infname self.outfname = outfname #the main data repositary self.cooccurrent_cluster_id2cluster = {} #used to find the cooccurrent_cluster_id, like '6.6.9', cooccurrent_cluster_id is '6.6' self.p_cooccurrent_cluster_id = re.compile(r'\d+\.\d+') def copath_parser(self, row, argument=None, argument2=None): """ 04-12-05 copied from codense2db.py, changed a lot """ cooccurrent_cluster_id = self.p_cooccurrent_cluster_id.match(row[0]).group() vertex_set = row[2][1:-2].split(';') vertex_set = map(int, vertex_set) edge_list = row[3][2:-4].split(' );(') edge_set = [] for edge in edge_list: edge = edge.split(',') edge = map(int, edge) #in ascending order edge.sort() edge_set.append(edge) if cooccurrent_cluster_id not in self.cooccurrent_cluster_id2cluster: cluster = cluster_dstructure() cluster.cooccurrent_cluster_id = cooccurrent_cluster_id #it's not used in the output() #initialize two sets cluster.vertex_set = [] cluster.edge_set = [] self.cooccurrent_cluster_id2cluster[cooccurrent_cluster_id] = cluster #pass it to ease programming cluster = self.cooccurrent_cluster_id2cluster[cooccurrent_cluster_id] cluster.vertex_set += vertex_set cluster.edge_set += edge_set def output(self, outfname, cooccurrent_cluster_id2cluster): """ 04-12-05 output the cooccurrent_cluster_id2cluster in the same format as the INPUTFILE. --return_vertex_set_string --return_edge_set_string """ outf = open(outfname, 'w') writer = csv.writer(outf, delimiter='\t') sys.stderr.write("Outputting the edge clusters...") for cooccurrent_cluster_id,cluster in cooccurrent_cluster_id2cluster.iteritems(): #ascending order cluster.vertex_set.sort() cluster.edge_set.sort() no_of_nodes = len(cluster.vertex_set) cluster.splat_connectivity = 2.0*len(cluster.edge_set)/(no_of_nodes*(no_of_nodes-1)) #2.0 keeps the whole result float row = [cooccurrent_cluster_id, cluster.splat_connectivity, self.return_vertex_set_string(cluster.vertex_set), \ self.return_edge_set_string(cluster.edge_set)] writer.writerow(row) del writer outf.close() sys.stderr.write("Done.\n") def return_vertex_set_string(self, vertex_set): """ 04-12-05 convert the list(vertex_set) into a string form as in copath's result """ vertex_set = map(repr, vertex_set) vertex_set_string = ';'.join(vertex_set) vertex_set_string = '{'+vertex_set_string+';}' return vertex_set_string def return_edge_set_string(self, edge_set): """ 04-12-05 convert the 2d list (edge_set) into a string form as in copath's result """ edge_set_string = '' for edge in edge_set: edge_set_string += '(%s,%s );'%(edge[0],edge[1]) edge_set_string = '{' + edge_set_string + '}' return edge_set_string def run(self): """ 04-12-05 (loop over the INPUTFILE) --copath_parser() --output() --return_vertex_set_string() --return_edge_set_string() """ inf = csv.reader(open(self.infname, 'r'), delimiter='\t') for row in inf: self.copath_parser(row) del inf self.output(self.outfname, self.cooccurrent_cluster_id2cluster) if __name__ == '__main__': if len(sys.argv) != 3: print __doc__ sys.exit(2) else: instance = EdgeClusterFromCopathOutput(sys.argv[1], sys.argv[2]) instance.run()
Python
UTF-8
1,340
2.546875
3
[]
no_license
# -*- coding: utf-8 -*- """ Created on Sat Feb 28 15:40:43 2015 @author: michal """ import numpy as N import modred as MR import matplotlib.pyplot as plt nx = 200 ny = 200 num_vecs = 10 dlen = nx*ny k = 0.1 # Arbitrary data x,y = N.meshgrid(N.linspace(0,1.,ny), N.linspace(0,1.,nx)) f = N.sin(2. * N.pi * y) * N.sin(2. * N.pi * x) vecs = [f + k * N.random.random((nx, ny)) for i in range(num_vecs)] podData = (N.array([ r.reshape(nx*ny) for r in vecs ])).T num_modes = num_vecs #print vecs.shape print podData.shape modes, eig_vals = MR.compute_POD_matrices_snaps_method(podData, range(num_modes)) #plt.imshow(f) #plt.figure() #plt.imshow(vecs[0]) # #plt.figure() #plt.plot(podData[0]) #plt.plot(f.reshape(nx*ny)) #plt.show() f1 = N.zeros_like(f) print eig_vals print modes.shape A = modes print A.shape c = N.linalg.lstsq(A, f.reshape(nx*ny))[0] for i in range(num_modes): v = modes[:,i] f1 = f1 + c[i]*v.reshape(nx,ny) #print v.reshape(nx*ny).dot(f1.reshape(nx*ny,1)) plt.figure() plt.plot(f1.reshape(nx*ny).T,'-') plt.plot(f.reshape(nx*ny)) plt.show() #print N.max(f1) #print N.min(f1) #print "###################" # plt.figure() # res = N.power((f1-f).reshape(nx*ny),2) # print N.sqrt(N.sum(res)) # plt.imshow(res.reshape(nx,ny)) # plt.colorbar() plt.show()
Java
UTF-8
768
2.125
2
[]
no_license
package com.telofast.server; import java.io.Serializable; import java.util.ArrayList; import java.util.List; import javax.persistence.Entity; import javax.persistence.Id; import com.googlecode.objectify.annotation.Serialized; @Entity public class StationStatuses implements Serializable { private static final long serialVersionUID = 13213321811L; @Id private Long key; @Serialized private List<StationStatus> stationStatuses = new ArrayList<StationStatus>(); public Long getKey() { return key; } public void setKey(Long key) { this.key = key; } public List<StationStatus> getStationStatuses() { return stationStatuses; } public void setStationStatuses(List<StationStatus> stationStatuses) { this.stationStatuses = stationStatuses; } }
Markdown
UTF-8
1,182
3.890625
4
[]
no_license
# Fade Library for Arduino # Library for "fading" integers up and down with parallel timers based on millis. mainly aimed to dimm LEDs parallel in different steps and speeds. but might be useful for other stuff where we need incrementation or decrementation of ints # Use # first inanciate a Fade Object: ```cpp #include <Fade.h> Fade Fade1(33, 500, 0, 255,1); ``` the constructor needs 5 parameter: 1. **steps** : *int* - stepsize per step 2. **interval** : *int* - interval in ms 3. **minimum** : *int* - start fade at value 4. **maximum** : *int* - stop fade at value 5. **direction** : *int* - 1 count up; 2 count down; 0 stop then call every instance of Fade as needed via .runFade() method: ```cpp #include <Fade.h> int brightness1 = 255; Fade Fade1(33, 500, 0, 255,1); void setup() { Serial.begin(9600); } void loop() { brightness1 = Fade1.runTimer(); if (Fade1.number == Fade1.mini) { Fade1.direct = 1; } if (Fade1.number == Fade1.maxi) { Fade1.direct = 2; } Serial.println(Fade1.number); } ``` add as many instances of Fade as you like. They will run in parallel (see /Examples/FadeLibrary.ino for more)
Java
UTF-8
18,403
1.789063
2
[]
no_license
package org.xpande.retail.report; import org.adempiere.exceptions.AdempiereException; import org.compiere.process.ProcessInfoParameter; import org.compiere.process.SvrProcess; import org.compiere.util.DB; import org.xpande.retail.utils.ComercialUtils; import java.math.BigDecimal; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.Timestamp; /** * Product: Adempiere ERP & CRM Smart Business Solution. Localization : Uruguay - Xpande * Xpande. Created by Gabriel Vila on 12/4/17. */ public class ControlMargenes extends SvrProcess { private final String TABLA_REPORTE = "Z_RP_Retail_CtrlMargen"; private int adOrgID = 0; private int cBPartnerID = 0; private int mProductID = 0; private int zProductoSeccionID = 0; private int zProductoRubroID = 0; private int zProductoFamiliaID = 0; private int zProductoSubfamiliaID = 0; private String estadoMargen = ""; @Override protected void prepare() { ProcessInfoParameter[] para = getParameter(); for (int i = 0; i < para.length; i++){ String name = para[i].getParameterName(); if (name != null){ if (para[i].getParameter() != null){ if (name.trim().equalsIgnoreCase("AD_Org_ID")){ this.adOrgID = ((BigDecimal)para[i].getParameter()).intValueExact(); } else if (name.trim().equalsIgnoreCase("C_BPartner_ID")){ this.cBPartnerID = ((BigDecimal)para[i].getParameter()).intValueExact(); } else if (name.trim().equalsIgnoreCase("M_Product_ID")){ this.mProductID = ((BigDecimal)para[i].getParameter()).intValueExact(); } else if (name.trim().equalsIgnoreCase("Z_ProductoSeccion_ID")){ this.zProductoSeccionID = ((BigDecimal)para[i].getParameter()).intValueExact(); } else if (name.trim().equalsIgnoreCase("Z_ProductoRubro_ID")){ this.zProductoRubroID = ((BigDecimal)para[i].getParameter()).intValueExact(); } else if (name.trim().equalsIgnoreCase("Z_ProductoFamilia_ID")){ this.zProductoFamiliaID = ((BigDecimal)para[i].getParameter()).intValueExact(); } else if (name.trim().equalsIgnoreCase("Z_ProductoSubfamilia_ID")){ this.zProductoSubfamiliaID = ((BigDecimal)para[i].getParameter()).intValueExact(); } else if (name.trim().equalsIgnoreCase("EstadoMargen")){ this.estadoMargen = (String)para[i].getParameter(); } } } } } @Override protected String doIt() throws Exception { this.deleteData(); this.getData(); this.updateData(); return "OK"; } /*** * Elimina información anterior para este usuario en tablas de reporte * Xpande. Created by Gabriel Vila on 9/11/17. */ private void deleteData() { try{ String action = " delete from " + TABLA_REPORTE + " where ad_user_id =" + this.getAD_User_ID(); DB.executeUpdateEx(action, null); } catch (Exception e){ throw new AdempiereException(e); } } /*** * Obtiene información inicial necesaria para el reporte e inserta la misma en tablas del reporte * Xpande. Created by Gabriel Vila on 9/11/17. */ private void getData() { String sql = "", action = ""; try{ // Cadenas de insert en tablas del reporte action = " insert into " + TABLA_REPORTE + " (ad_client_id, ad_org_id, ad_user_id, c_bpartner_id, m_product_id, pricefinalmargin, pricefinal, priceso, margintolerance, margin, estadomargen) "; // Armo condicion where dinámica del reporte String whereClause = ""; if (this.adOrgID > 0){ whereClause += " ad_orgtrx_id =" + this.adOrgID; } if (this.cBPartnerID > 0){ if (!whereClause.equalsIgnoreCase("")){ whereClause += " and "; } whereClause += " c_bpartner_id =" + this.cBPartnerID; } if (this.mProductID > 0){ if (!whereClause.equalsIgnoreCase("")){ whereClause += " and "; } whereClause += " m_product_id =" + this.mProductID; } if (whereClause.equalsIgnoreCase("")){ whereClause = " 1==1 "; } // Control contra margenes de Productos if (this.estadoMargen.equalsIgnoreCase("RANGO")){ sql = " select distinct ad_client_id, ad_orgtrx_id, " + this.getAD_User_ID() + ", c_bpartner_id, m_product_id, pricefinalmargin, " + " pricefinal, priceso, tol4, margen4, control4 as control " + " from zv_comercial_gralmargen " + " where " + whereClause + " and control1 ='N' and control2 ='N' and control3 ='N' and control4 ='N' AND margen4 is not null "; } else if (this.estadoMargen.equalsIgnoreCase("BAJO")){ sql = " select distinct ad_client_id, ad_orgtrx_id, " + this.getAD_User_ID() + ", c_bpartner_id, m_product_id, pricefinalmargin, " + " pricefinal, priceso, tol4, margen4, control4 as control " + " from zv_comercial_gralmargen " + " where " + whereClause + " and control4 ='YB'"; } else if (this.estadoMargen.equalsIgnoreCase("ALTO")){ sql = " select distinct ad_client_id, ad_orgtrx_id, " + this.getAD_User_ID() + ", c_bpartner_id, m_product_id, pricefinalmargin, " + " pricefinal, priceso, tol4, margen4, control4 as control " + " from zv_comercial_gralmargen " + " where " + whereClause + " and control4 ='YA'"; } else{ sql = " select distinct ad_client_id, ad_orgtrx_id, " + this.getAD_User_ID() + ", c_bpartner_id, m_product_id, pricefinalmargin, " + " pricefinal, priceso, tol4, margen4, control4 as control " + " from zv_comercial_gralmargen " + " where " + whereClause; } DB.executeUpdateEx(action + sql, null); // Control contra margenes de Segmentos if (this.estadoMargen.equalsIgnoreCase("RANGO")){ sql = " select distinct ad_client_id, ad_orgtrx_id, " + this.getAD_User_ID() + ", c_bpartner_id, m_product_id, pricefinalmargin, " + " pricefinal, priceso, tol3, margen3, control3 as control " + " from zv_comercial_gralmargen " + " where " + whereClause + " and control1 ='N' and control2 ='N' and control3 ='N' and control4 ='N' AND margen3 is not null " + " and not exists(select * from " + TABLA_REPORTE + " where ad_org_id = zv_comercial_gralmargen.ad_orgtrx_id " + " and c_bpartner_id = zv_comercial_gralmargen.c_bpartner_id " + " and m_product_id = zv_comercial_gralmargen.m_product_id) " + " and not exists(select * from zv_comercial_gralmargen a where a.ad_orgtrx_id = zv_comercial_gralmargen.ad_orgtrx_id " + " and a.c_bpartner_id = zv_comercial_gralmargen.c_bpartner_id " + " and a.m_product_id = zv_comercial_gralmargen.m_product_id " + " and a.control3 !='N')"; } else if (this.estadoMargen.equalsIgnoreCase("BAJO")){ sql = " select distinct ad_client_id, ad_orgtrx_id, " + this.getAD_User_ID() + ", c_bpartner_id, m_product_id, pricefinalmargin, " + " pricefinal, priceso, tol3, margen3, control3 as control " + " from zv_comercial_gralmargen " + " where " + whereClause + " and control3 ='YB' " + " and not exists(select * from " + TABLA_REPORTE + " where ad_org_id = zv_comercial_gralmargen.ad_orgtrx_id " + " and c_bpartner_id = zv_comercial_gralmargen.c_bpartner_id " + " and m_product_id = zv_comercial_gralmargen.m_product_id)"; } else if (this.estadoMargen.equalsIgnoreCase("ALTO")){ sql = " select distinct ad_client_id, ad_orgtrx_id, " + this.getAD_User_ID() + ", c_bpartner_id, m_product_id, pricefinalmargin, " + " pricefinal, priceso, tol3, margen3, control3 as control " + " from zv_comercial_gralmargen " + " where " + whereClause + " and control3 ='YA' " + " and not exists(select * from " + TABLA_REPORTE + " where ad_org_id = zv_comercial_gralmargen.ad_orgtrx_id " + " and c_bpartner_id = zv_comercial_gralmargen.c_bpartner_id " + " and m_product_id = zv_comercial_gralmargen.m_product_id)"; } else{ sql = " select distinct ad_client_id, ad_orgtrx_id, " + this.getAD_User_ID() + ", c_bpartner_id, m_product_id, pricefinalmargin, " + " pricefinal, priceso, tol3, margen3, control3 as control " + " from zv_comercial_gralmargen " + //" where control3 !='N' " + whereClause + " where " + whereClause + " and not exists(select * from " + TABLA_REPORTE + " where ad_org_id = zv_comercial_gralmargen.ad_orgtrx_id " + " and c_bpartner_id = zv_comercial_gralmargen.c_bpartner_id " + " and m_product_id = zv_comercial_gralmargen.m_product_id)"; } DB.executeUpdateEx(action + sql, null); // Control contra margenes de Lineas if (this.estadoMargen.equalsIgnoreCase("RANGO")){ sql = " select distinct ad_client_id, ad_orgtrx_id, " + this.getAD_User_ID() + ", c_bpartner_id, m_product_id, pricefinalmargin, " + " pricefinal, priceso, tol2, margen2, control2 as control " + " from zv_comercial_gralmargen " + " where " + whereClause + " and control1 ='N' and control2 ='N' and control3 ='N' and control4 ='N' AND margen2 is not null " + " and not exists(select * from " + TABLA_REPORTE + " where ad_org_id = zv_comercial_gralmargen.ad_orgtrx_id " + " and c_bpartner_id = zv_comercial_gralmargen.c_bpartner_id " + " and m_product_id = zv_comercial_gralmargen.m_product_id) " + " and not exists(select * from zv_comercial_gralmargen a where a.ad_orgtrx_id = zv_comercial_gralmargen.ad_orgtrx_id " + " and a.c_bpartner_id = zv_comercial_gralmargen.c_bpartner_id " + " and a.m_product_id = zv_comercial_gralmargen.m_product_id " + " and a.control2 !='N')"; } else if (this.estadoMargen.equalsIgnoreCase("BAJO")){ sql = " select distinct ad_client_id, ad_orgtrx_id, " + this.getAD_User_ID() + ", c_bpartner_id, m_product_id, pricefinalmargin, " + " pricefinal, priceso, tol2, margen2, control2 as control " + " from zv_comercial_gralmargen " + " where " + whereClause + " and control2 ='YB' " + " and not exists(select * from " + TABLA_REPORTE + " where ad_org_id = zv_comercial_gralmargen.ad_orgtrx_id " + " and c_bpartner_id = zv_comercial_gralmargen.c_bpartner_id " + " and m_product_id = zv_comercial_gralmargen.m_product_id)"; } else if (this.estadoMargen.equalsIgnoreCase("ALTO")){ sql = " select distinct ad_client_id, ad_orgtrx_id, " + this.getAD_User_ID() + ", c_bpartner_id, m_product_id, pricefinalmargin, " + " pricefinal, priceso, tol2, margen2, control2 as control " + " from zv_comercial_gralmargen " + " where " + whereClause + " and control2 ='YA' " + " and not exists(select * from " + TABLA_REPORTE + " where ad_org_id = zv_comercial_gralmargen.ad_orgtrx_id " + " and c_bpartner_id = zv_comercial_gralmargen.c_bpartner_id " + " and m_product_id = zv_comercial_gralmargen.m_product_id)"; } else{ sql = " select distinct ad_client_id, ad_orgtrx_id, " + this.getAD_User_ID() + ", c_bpartner_id, m_product_id, pricefinalmargin, " + " pricefinal, priceso, tol2, margen2, control2 as control " + " from zv_comercial_gralmargen " + " where " + whereClause + " and not exists(select * from " + TABLA_REPORTE + " where ad_org_id = zv_comercial_gralmargen.ad_orgtrx_id " + " and c_bpartner_id = zv_comercial_gralmargen.c_bpartner_id " + " and m_product_id = zv_comercial_gralmargen.m_product_id)"; } DB.executeUpdateEx(action + sql, null); // Control contra margenes de Proveedores if (this.estadoMargen.equalsIgnoreCase("RANGO")){ sql = " select distinct ad_client_id, ad_orgtrx_id, " + this.getAD_User_ID() + ", c_bpartner_id, m_product_id, pricefinalmargin, " + " pricefinal, priceso, tol1, margen1, control1 as control " + " from zv_comercial_gralmargen " + " where " + whereClause + " and control1 ='N' and control2 ='N' and control3 ='N' and control4 ='N' AND margen1 is not null " + " and not exists(select * from " + TABLA_REPORTE + " where ad_org_id = zv_comercial_gralmargen.ad_orgtrx_id " + " and c_bpartner_id = zv_comercial_gralmargen.c_bpartner_id " + " and m_product_id = zv_comercial_gralmargen.m_product_id) " + " and not exists(select * from zv_comercial_gralmargen a where a.ad_orgtrx_id = zv_comercial_gralmargen.ad_orgtrx_id " + " and a.c_bpartner_id = zv_comercial_gralmargen.c_bpartner_id " + " and a.m_product_id = zv_comercial_gralmargen.m_product_id " + " and a.control1 !='N')"; } else if (this.estadoMargen.equalsIgnoreCase("BAJO")){ sql = " select distinct ad_client_id, ad_orgtrx_id, " + this.getAD_User_ID() + ", c_bpartner_id, m_product_id, pricefinalmargin, " + " pricefinal, priceso, tol1, margen1, control1 as control " + " from zv_comercial_gralmargen " + " where " + whereClause + " and control1 ='YB' " + " and not exists(select * from " + TABLA_REPORTE + " where ad_org_id = zv_comercial_gralmargen.ad_orgtrx_id " + " and c_bpartner_id = zv_comercial_gralmargen.c_bpartner_id " + " and m_product_id = zv_comercial_gralmargen.m_product_id)"; } else if (this.estadoMargen.equalsIgnoreCase("ALTO")){ sql = " select distinct ad_client_id, ad_orgtrx_id, " + this.getAD_User_ID() + ", c_bpartner_id, m_product_id, pricefinalmargin, " + " pricefinal, priceso, tol1, margen1, control1 as control " + " from zv_comercial_gralmargen " + " where " + whereClause + " and control1 ='YA' " + " and not exists(select * from " + TABLA_REPORTE + " where ad_org_id = zv_comercial_gralmargen.ad_orgtrx_id " + " and c_bpartner_id = zv_comercial_gralmargen.c_bpartner_id " + " and m_product_id = zv_comercial_gralmargen.m_product_id)"; } else{ sql = " select distinct ad_client_id, ad_orgtrx_id, " + this.getAD_User_ID() + ", c_bpartner_id, m_product_id, pricefinalmargin, " + " pricefinal, priceso, tol1, margen1, control1 as control " + " from zv_comercial_gralmargen " + " where " + whereClause + " and not exists(select * from " + TABLA_REPORTE + " where ad_org_id = zv_comercial_gralmargen.ad_orgtrx_id " + " and c_bpartner_id = zv_comercial_gralmargen.c_bpartner_id " + " and m_product_id = zv_comercial_gralmargen.m_product_id)"; } DB.executeUpdateEx(action + sql, null); } catch (Exception e){ throw new AdempiereException(e); } } /*** * Actualiza campos de las Tablas de Reporte. * Xpande. Created by Gabriel Vila on 9/11/17. */ private void updateData() { String action = ""; try{ action = " update " + TABLA_REPORTE + " set estadomargen ='RANGO' " + " where ad_user_id =" + this.getAD_User_ID() + " and estadomargen ='N'"; DB.executeUpdateEx(action, null); action = " update " + TABLA_REPORTE + " set estadomargen ='BAJO' " + " where ad_user_id =" + this.getAD_User_ID() + " and estadomargen ='YB'"; DB.executeUpdateEx(action, null); action = " update " + TABLA_REPORTE + " set estadomargen ='ALTO' " + " where ad_user_id =" + this.getAD_User_ID() + " and estadomargen ='YA'"; DB.executeUpdateEx(action, null); } catch (Exception e){ throw new AdempiereException(e); } } }
Java
UTF-8
1,119
1.90625
2
[]
no_license
package tz.co.ubunifusolutions.screens.activities; import android.os.AsyncTask; import android.os.Bundle; import android.support.annotation.Nullable; import android.support.v7.app.AppCompatActivity; import android.util.Log; import android.widget.ListAdapter; import android.widget.ListView; import android.widget.SimpleAdapter; import android.widget.Toast; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import java.util.ArrayList; import java.util.HashMap; import tz.co.ubunifusolutions.screens.R; import tz.co.ubunifusolutions.screens.api.HttpHandler; public class customerList extends AppCompatActivity { private String TAG = customerList.class.getSimpleName(); ArrayList<HashMap<String, String>> CustomerList; private ListView lv; @Override protected void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); CustomerList = new ArrayList<>(); lv = (ListView) findViewById(R.id.list); } }
Markdown
UTF-8
403
2.71875
3
[]
no_license
- take - take it - take that - take this - take it back/took it back - he took his money back - take it away/took it away - don't take her away - take my money away - take it down/took it down - take him down - take 30 minutes. - take a day. - take 2 months. - take a rest. - take a shower. - take a break. - take this change. - take this opportunity. - take a lot of effort. - take this class.
C
UTF-8
1,628
2.921875
3
[]
no_license
#include "interpret_file.h" static int get_file_content(t_in *in, const char *filename) { int fd; // OPEN fd = open(filename, O_RDONLY); if (fd == -1) return (open_error(filename)); // LSEEK: Get file size in->len = (uint32_t)lseek(fd, 0, SEEK_END); if (in->len & 0x80000000u) return (lseek_error(fd)); if (in->len == 0) return (empty_file(filename, fd)); lseek(fd, 0, SEEK_SET); // allocate buffer to copy the file in->str = malloc(in->len); if (in->str == NULL) return (no_memory(fd)); // copy the file if (read(fd, in->str, in->len) != in->len) return (read_error(fd, in)); close(fd); return (0); } int interpret_file(const char *filename) { t_in in = {NULL}; t_out out = {NULL}; t_data data = {0}; t_ustr buf = {NULL}; uint32_t error = 0; if (get_file_content(&in, filename) != 0) return (1); in.line = 1; in.name = filename; out.name = NULL; while (in.i < in.len) { // skip spaces while (1) { if (in.str[in.i] == '\n') in.line++; else if (in.str[in.i] != ' ' && in.str[in.i] != '\t') break; in.i++; if (in.i == in.len) goto __end_loops; } // using character to get function index and call it { uint8_t chr = in.str[in.i]; uint8_t index = get_func_index[data.base][chr]; if (index == 0xffu) error += err_unexpected_char(&in); else call[index](&in, &out, &data, &buf); } in.i++; } __end_loops: if (out.str == NULL) { dprintf(STDERR_FILENO, "ERROR: not a bwl file\n"); free(in.str); return (1); } if (!error) write(STDOUT_FILENO, out.str, out.i); free(out.str); free(in.str); return (0); }
Swift
UTF-8
245
2.640625
3
[]
no_license
import Foundation /// CHALLENGES OF ITERATING COLLECTIONS /// // Challenge 1 var pastries: [String] = ["cookie", "danish", "cupcake", "donut", "pie", "brownie", "fritter", "cruller"] pastryWithStartLetter(pastries: pastries, str: "d")
Python
UTF-8
208
3.078125
3
[]
no_license
products = {'candy':10,"juice": 5,"pen":50} def check(product,num): if product in products and num>=products[product]: return True else: return False
Markdown
UTF-8
20,029
2.578125
3
[]
no_license
# 在SpringMVC Controller中注入Request成员域 - z69183787的专栏 - CSDN博客 2017年12月20日 11:40:40[OkidoGreen](https://me.csdn.net/z69183787)阅读数:665 [https://www.cnblogs.com/abcwt112/p/7777258.html](https://www.cnblogs.com/abcwt112/p/7777258.html) # 主题   在工作中遇到1个问题....我们定义了一个Controller基类,所有Springmvc自定义的controller都继承它....在它内部定义一个@Autowired HttpServletRequest request;可不可以? 能不能从这个对象里取requestParamters和attributes? 多线程之间会不会影响? # 思考 初次思考,我想这应该是不行的.为什么呢? 注入bean是在spring容器启动的时候...request的实现类是在tomcat里(我使用的servlet容器是tomcat)....我又没在spring的容器里配置这个bean.注入应该是失败的... 退一步说,就算是成功了....那注入的也就是1个对象而已.每次servlet接受到请求都会重新生成1个request...这明显和之前启动的那个对象不同吧....怎么想都不可能成功... 如果确实是这样的....那就没有这篇文章了....后来实践了一下..发现这个注入是可以的.使用起来取数据也没任何问题.... 其实我那个时候debug看了一下,基本就知道为什么可以取到数据了..但是我并不知道原理和Spring(Springmvc)的处理流程...所以现在研究了一下并记录下来... # 原理 首先给大家看一下在方法中注入request作为参数和在成员域中注入request的 注入的request对象之间的区别.... ![](http://images2017.cnblogs.com/blog/721497/201711/721497-20171103100952545-1892831485.png) ![](http://images2017.cnblogs.com/blog/721497/201711/721497-20171103101007576-1932354152.png) 成员域注入的时候注入的是1个代理对象.是 AutowireUtils.ObjectFactoryDelegatingInvocationHandler的实例. 方法注入的就是一般tomcat原生的requestFacade对象. 所以这是不同的... ``` ![](http://images.cnblogs.com/OutliningIndicators/ExpandedBlockStart.gif) ![复制代码](https://common.cnblogs.com/images/copycode.gif) 1 /** 2 * Reflective InvocationHandler for lazy access to the current target object. 3 */ 4 @SuppressWarnings("serial") 5 private static class ObjectFactoryDelegatingInvocationHandler implements InvocationHandler, Serializable { 6 7 private final ObjectFactory<?> objectFactory; 8 9 public ObjectFactoryDelegatingInvocationHandler(ObjectFactory<?> objectFactory) { 10 this.objectFactory = objectFactory; 11 } 12 13 @Override 14 public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { 15 String methodName = method.getName(); 16 if (methodName.equals("equals")) { 17 // Only consider equal when proxies are identical. 18 return (proxy == args[0]); 19 } 20 else if (methodName.equals("hashCode")) { 21 // Use hashCode of proxy. 22 return System.identityHashCode(proxy); 23 } 24 else if (methodName.equals("toString")) { 25 return this.objectFactory.toString(); 26 } 27 try { 28 return method.invoke(this.objectFactory.getObject(), args); 29 } 30 catch (InvocationTargetException ex) { 31 throw ex.getTargetException(); 32 } 33 } 34 } ![复制代码](https://common.cnblogs.com/images/copycode.gif) ``` 当代理对象(就是成员域request)的大部分方法被调用的时候,ObjectFactoryDelegatingInvocationHandler会使用objectFactory获取对象(原生request),再调用对象上的方法. 然后我们来看下XmlWebApplicationContext初始化到请求到进入controller里几个对注入request成员域有影响的步骤. ## refresh方法和postProcessBeanFactory方法 ApplicationContext的抽象实现类AbstractApplicationContext(基本是所有ac的父类)里定义了ac的refresh方法(包含了使用BeanFactory注入bean)的流程.. ``` ![](http://images.cnblogs.com/OutliningIndicators/ExpandedBlockStart.gif) ![复制代码](https://common.cnblogs.com/images/copycode.gif) 1 @Override 2 public void refresh() throws BeansException, IllegalStateException { 3 synchronized (this.startupShutdownMonitor) { 4 // Prepare this context for refreshing. 5 // 记录开始wac开始初始化的时间,设置激活标记,servlet的相关param设置到env(之前做过1次),校验env中必须的props 6 prepareRefresh(); 7 8 // Tell the subclass to refresh the internal bean factory. 9 // 将旧的BF里的bean删掉,新建1个BF,设置部分属性,加载XML配置文件 10 ConfigurableListableBeanFactory beanFactory = obtainFreshBeanFactory(); 11 12 // Prepare the bean factory for use in this context. 13 // 1.设置BF解析bean配置需要用到的一些对象比如env. 2.注册一些BeanPostProcessor比如ApplicationContextAwareProcessor去设置Aware需要的对象 14 // 3.忽略一些特定class注入的对象,设置一些特定class注入的对象为指定值 15 // 4.将一些env中的properties map当做bean注册到BF中 16 prepareBeanFactory(beanFactory); 17 18 try { 19 // Allows post-processing of the bean factory in context subclasses. 20 // 1.设置一个BeanPostProcess为ServletContextAware的实现类注入servlet相关对象 21 // 2.在BF中增加requetsScope等Scope 22 // 3.把servletContext,Config,ServletInitParams,ServletAttribute当做Bean注册到BF中 23 postProcessBeanFactory(beanFactory); 24 25 // Invoke factory processors registered as beans in the context. 26 // 初始化并调用BeanFactoryPostProcessor 27 invokeBeanFactoryPostProcessors(beanFactory); 28 29 // Register bean processors that intercept bean creation. 30 // 注册BeanPostProcessors并注册到BF中去 31 registerBeanPostProcessors(beanFactory); 32 33 // Initialize message source for this context. 34 initMessageSource(); 35 36 // Initialize event multicaster for this context. 37 initApplicationEventMulticaster(); 38 39 // Initialize other special beans in specific context subclasses. 40 onRefresh(); 41 42 // Check for listener beans and register them. 43 registerListeners(); 44 45 // Instantiate all remaining (non-lazy-init) singletons. 46 finishBeanFactoryInitialization(beanFactory); 47 48 // Last step: publish corresponding event. 49 finishRefresh(); 50 } catch (BeansException ex) { 51 logger.warn("Exception encountered during context initialization - cancelling refresh attempt", ex); 52 53 // Destroy already created singletons to avoid dangling resources. 54 destroyBeans(); 55 56 // Reset 'active' flag. 57 cancelRefresh(ex); 58 59 // Propagate exception to caller. 60 throw ex; 61 } 62 } 63 } ![复制代码](https://common.cnblogs.com/images/copycode.gif) ``` 其中有1个模板方法 postProcessBeanFactory(beanFactory); 这个方法允许AbstractApplicationContext的子类覆盖它并实现对BF的定制(这个时候bean的defination路径已经指定了,但是bean还没加载). AbstractRefreshableWebApplicationContext覆盖了这个方法 ``` ![](http://images.cnblogs.com/OutliningIndicators/ExpandedBlockStart.gif) ![复制代码](https://common.cnblogs.com/images/copycode.gif) 1 /** 2 * Register request/session scopes, a {@link ServletContextAwareProcessor}, etc. 3 * 1.设置一个BeanPostProcess为ServletContextAware的实现类注入servlet相关对象 4 * 2.在BF中增加requetsScope等Scope 5 * 3.把servletContext,Config,ServletInitParams,ServletAttribute当做Bean注册到BF中 6 * 7 */ 8 @Override 9 protected void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) { 10 // 设置一个BeanPostProcess为ServletContextAware的实现类注入servlet相关对象 11 beanFactory.addBeanPostProcessor(new ServletContextAwareProcessor(this.servletContext, this.servletConfig)); 12 beanFactory.ignoreDependencyInterface(ServletContextAware.class); 13 beanFactory.ignoreDependencyInterface(ServletConfigAware.class); 14 15 // 在BF中增加requetsScope等Scope 16 WebApplicationContextUtils.registerWebApplicationScopes(beanFactory, this.servletContext); 17 // 把servletContext,Config,ServletInitParams,ServletAttribute当做Bean注册到BF中 18 WebApplicationContextUtils.registerEnvironmentBeans(beanFactory, this.servletContext, this.servletConfig); 19 } ![复制代码](https://common.cnblogs.com/images/copycode.gif) ``` 其中有一步 WebApplicationContextUtils.registerWebApplicationScopes(beanFactory, this.servletContext); 这里设置了一些特殊的bean的scope,比如request,session,globalSession,application.(当然这个不是我这篇文章的主题.) 同时设置了一些特殊的autowired bean beanFactory.registerResolvableDependency(ServletRequest.class, new RequestObjectFactory()); beanFactory.registerResolvableDependency(ServletResponse.class, new ResponseObjectFactory()); beanFactory.registerResolvableDependency(HttpSession.class, new SessionObjectFactory()); beanFactory.registerResolvableDependency(WebRequest.class, new WebRequestObjectFactory()); ServletRequest的实现类(比如HttpServletRequest)被指定使用RequestObjectFactory注入. ## RequestObjectFactory RequestObjectFactory就是1个ObjectFactory就是前面ObjectFactoryDelegatingInvocationHandler里的ObjectFactory.所以在成员域request对象上调用方法其实就是通过RequestObjectFactory获取对象再调用方法. ``` ![](http://images.cnblogs.com/OutliningIndicators/ExpandedBlockStart.gif) ![复制代码](https://common.cnblogs.com/images/copycode.gif) 1 /** 2 * Factory that exposes the current request object on demand. 3 */ 4 @SuppressWarnings("serial") 5 private static class RequestObjectFactory implements ObjectFactory<ServletRequest>, Serializable { 6 7 @Override 8 public ServletRequest getObject() { 9 return currentRequestAttributes().getRequest(); 10 } 11 12 @Override 13 public String toString() { 14 return "Current HttpServletRequest"; 15 } 16 } ![复制代码](https://common.cnblogs.com/images/copycode.gif) ``` ``` ![](http://images.cnblogs.com/OutliningIndicators/ExpandedBlockStart.gif) ![复制代码](https://common.cnblogs.com/images/copycode.gif) 1 /** 2 * Return the current RequestAttributes instance as ServletRequestAttributes. 3 * 4 * @see RequestContextHolder#currentRequestAttributes() 5 */ 6 private static ServletRequestAttributes currentRequestAttributes() { 7 RequestAttributes requestAttr = RequestContextHolder.currentRequestAttributes(); 8 if (!(requestAttr instanceof ServletRequestAttributes)) { 9 throw new IllegalStateException("Current request is not a servlet request"); 10 } 11 return (ServletRequestAttributes) requestAttr; 12 } ![复制代码](https://common.cnblogs.com/images/copycode.gif) ``` RequestObjectFactory的getObject方法很简单,就是调用静态方法 RequestContextHolder.currentRequestAttributes().getRequest() ## RequestContextHolder ``` ![](http://images.cnblogs.com/OutliningIndicators/ExpandedBlockStart.gif) ![复制代码](https://common.cnblogs.com/images/copycode.gif) 1 public static RequestAttributes currentRequestAttributes() throws IllegalStateException { 2 RequestAttributes attributes = getRequestAttributes(); 3 if (attributes == null) { 4 if (jsfPresent) { 5 attributes = FacesRequestAttributesFactory.getFacesRequestAttributes(); 6 } 7 if (attributes == null) { 8 throw new IllegalStateException("No thread-bound request found: " + 9 "Are you referring to request attributes outside of an actual web request, " + 10 "or processing a request outside of the originally receiving thread? " + 11 "If you are actually operating within a web request and still receive this message, " + 12 "your code is probably running outside of DispatcherServlet/DispatcherPortlet: " + 13 "In this case, use RequestContextListener or RequestContextFilter to expose the current request."); 14 } 15 } 16 return attributes; 17 } ![复制代码](https://common.cnblogs.com/images/copycode.gif) ``` ``` ![](http://images.cnblogs.com/OutliningIndicators/ExpandedBlockStart.gif) ![复制代码](https://common.cnblogs.com/images/copycode.gif) 1 /** 2 * Return the RequestAttributes currently bound to the thread. 3 * @return the RequestAttributes currently bound to the thread, 4 * or {@code null} if none bound 5 */ 6 public static RequestAttributes getRequestAttributes() { 7 RequestAttributes attributes = requestAttributesHolder.get(); 8 if (attributes == null) { 9 attributes = inheritableRequestAttributesHolder.get(); 10 } 11 return attributes; 12 } ![复制代码](https://common.cnblogs.com/images/copycode.gif) ``` ``` ![](http://images.cnblogs.com/OutliningIndicators/ExpandedBlockStart.gif) 1 private static final ThreadLocal<RequestAttributes> requestAttributesHolder = 2 new NamedThreadLocal<RequestAttributes>("Request attributes"); 3 4 private static final ThreadLocal<RequestAttributes> inheritableRequestAttributesHolder = 5 new NamedInheritableThreadLocal<RequestAttributes>("Request context"); ``` 上面是一些关键方法 所以最终其实request是从threadlocal中取... ## FrameworkServlet  那么request是什么时候设置到threadlocal中去的呢? 是在Springmvc的dispatcherServlet的父类FrameworkServlet里操作的. ``` ![](http://images.cnblogs.com/OutliningIndicators/ExpandedBlockStart.gif) ![复制代码](https://common.cnblogs.com/images/copycode.gif) 1 /** 2 * Delegate GET requests to processRequest/doService. 3 * <p>Will also be invoked by HttpServlet's default implementation of {@code doHead}, 4 * with a {@code NoBodyResponse} that just captures the content length. 5 * @see #doService 6 * @see #doHead 7 */ 8 @Override 9 protected final void doGet(HttpServletRequest request, HttpServletResponse response) 10 throws ServletException, IOException { 11 12 processRequest(request, response); 13 } 14 15 /** 16 * Delegate POST requests to {@link #processRequest}. 17 * @see #doService 18 */ 19 @Override 20 protected final void doPost(HttpServletRequest request, HttpServletResponse response) 21 throws ServletException, IOException { 22 23 processRequest(request, response); 24 } ![复制代码](https://common.cnblogs.com/images/copycode.gif) ``` 不管你是doGet还是doPost还是doXXX方法都是委托processRequest方法去做的. ``` ![](http://images.cnblogs.com/OutliningIndicators/ExpandedBlockStart.gif) ![复制代码](https://common.cnblogs.com/images/copycode.gif) 1 /** 2 * Process this request, publishing an event regardless of the outcome. 3 * <p>The actual event handling is performed by the abstract 4 * {@link #doService} template method. 5 */ 6 protected final void processRequest(HttpServletRequest request, HttpServletResponse response) 7 throws ServletException, IOException { 8 9 long startTime = System.currentTimeMillis(); 10 Throwable failureCause = null; 11 12 LocaleContext previousLocaleContext = LocaleContextHolder.getLocaleContext(); 13 LocaleContext localeContext = buildLocaleContext(request); 14 15 RequestAttributes previousAttributes = RequestContextHolder.getRequestAttributes(); 16 ServletRequestAttributes requestAttributes = buildRequestAttributes(request, response, previousAttributes); 17 18 WebAsyncManager asyncManager = WebAsyncUtils.getAsyncManager(request); 19 asyncManager.registerCallableInterceptor(FrameworkServlet.class.getName(), new RequestBindingInterceptor()); 20 21 initContextHolders(request, localeContext, requestAttributes); 22 23 try { 24 doService(request, response); 25 } 26 catch (ServletException ex) { 27 failureCause = ex; 28 throw ex; 29 } 30 catch (IOException ex) { 31 failureCause = ex; 32 throw ex; 33 } 34 catch (Throwable ex) { 35 failureCause = ex; 36 throw new NestedServletException("Request processing failed", ex); 37 } 38 39 finally { 40 resetContextHolders(request, previousLocaleContext, previousAttributes); 41 if (requestAttributes != null) { 42 requestAttributes.requestCompleted(); 43 } 44 45 if (logger.isDebugEnabled()) { 46 if (failureCause != null) { 47 this.logger.debug("Could not complete request", failureCause); 48 } 49 else { 50 if (asyncManager.isConcurrentHandlingStarted()) { 51 logger.debug("Leaving response open for concurrent processing"); 52 } 53 else { 54 this.logger.debug("Successfully completed request"); 55 } 56 } 57 } 58 59 publishRequestHandledEvent(request, response, startTime, failureCause); 60 } 61 } ![复制代码](https://common.cnblogs.com/images/copycode.gif) ``` 其中调用了 initContextHolders(request, localeContext, requestAttributes); ``` ![](http://images.cnblogs.com/OutliningIndicators/ExpandedBlockStart.gif) ![复制代码](https://common.cnblogs.com/images/copycode.gif) 1 private void initContextHolders( 2 HttpServletRequest request, LocaleContext localeContext, RequestAttributes requestAttributes) { 3 4 if (localeContext != null) { 5 LocaleContextHolder.setLocaleContext(localeContext, this.threadContextInheritable); 6 } 7 if (requestAttributes != null) { 8 RequestContextHolder.setRequestAttributes(requestAttributes, this.threadContextInheritable); 9 } 10 if (logger.isTraceEnabled()) { 11 logger.trace("Bound request context to thread: " + request); 12 } 13 } ![复制代码](https://common.cnblogs.com/images/copycode.gif) ``` 就是在这里设置到RequestContextHolder的threadlocal中去的... # 小结 1.在controller中注入的request是jdk动态代理对象,ObjectFactoryDelegatingInvocationHandler的实例.当我们调用成员域request的方法的时候其实是调用了objectFactory的getObject()对象的相关方法.这里的objectFactory是RequestObjectFactory. 2.RequestObjectFactory的getObject其实是从RequestContextHolder的threadlocal中去取值的. 3.请求刚进入springmvc的dispatcherServlet的时候会把request相关对象设置到RequestContextHolder的threadlocal中去.
Java
UTF-8
725
1.96875
2
[]
no_license
package com.example.happyapp; import androidx.appcompat.app.AppCompatActivity; import android.os.Bundle; import android.view.View; import android.widget.Button; import Model.DatabaseHandler; public class JournalActivity extends AppCompatActivity { DatabaseHandler objectDatabaseHandler; Button btnSubmitJournal; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_journal); btnSubmitJournal = findViewById(R.id.btnSubmitJournal); } public void SubmitClicked(View view){ //objectDatabaseHandler = new DatabaseHandler(this); //objectDatabaseHandler.tryPopulateDB(); } }
C#
UTF-8
5,043
2.734375
3
[ "MIT" ]
permissive
using Moip.Net.Assinaturas; using Newtonsoft.Json; using Newtonsoft.Json.Converters; using System; using System.IO; using System.Net; using System.Text; namespace Moip.Net { public abstract class BaseClient { #region Properties private readonly string ApiToken; private readonly string ApiKey; private readonly Uri ApiUri; private const string UserAgent = "Moip.NET.v0.0.1"; private readonly Encoding encoding = Encoding.UTF8; #endregion public BaseClient(Uri apiUri, string apiToken, string apiKey) { ApiUri = apiUri; ApiToken = apiToken; ApiKey = apiKey; } #region JsonSerializerSettings protected abstract JsonSerializerSettings JsonSettings { get; } public string ToJson(object item) { return JsonConvert.SerializeObject(item, JsonSettings); } public T FromJson<T>(string json) { return JsonConvert.DeserializeObject<T>(json, JsonSettings); } #endregion #region DoRequest protected virtual WebRequest CreateRequest(string method, Uri uri) { WebRequest webRequest = (WebRequest)WebRequest.Create(uri); webRequest.Method = method; HttpWebRequest httpRequest = webRequest as HttpWebRequest; if (httpRequest != null) { httpRequest.UserAgent = UserAgent; } webRequest.Headers["Authorization"] = GetAuthorizationHeader(); if (method == "POST" || method == "PUT" || method == "DELETE") { webRequest.ContentType = "application/json"; } return webRequest; } private string GetAuthorizationHeader() { var base64Key = Convert.ToBase64String(Encoding.Default.GetBytes(string.Format("{0}:{1}", ApiToken, ApiKey))); return string.Format("Basic {0}", base64Key); } private string GetResponseAsString(WebResponse response) { using (StreamReader sr = new StreamReader(response.GetResponseStream(), encoding)) { return sr.ReadToEnd(); } } protected virtual T DoRequest<T>(Uri uri) { return DoRequest<T>(uri, "GET", null); } protected virtual T DoRequest<T>(Uri uri, string method) { return DoRequest<T>(uri, method, null); } protected virtual T DoRequest<T>(Uri uri, string method, string body) { var json = DoRequest(uri, method, body); return FromJson<T>(json); } protected virtual string DoRequest(Uri uri, string method) { return DoRequest(uri, method, null); } protected virtual string DoRequest(Uri uri, string method, string body) { string result = null; WebRequest req = CreateRequest(method, uri); if (body != null) { byte[] bytes = encoding.GetBytes(body.ToString()); req.ContentLength = bytes.Length; using (Stream st = req.GetRequestStream()) { st.Write(bytes, 0, bytes.Length); } } try { using (WebResponse resp = (WebResponse)req.GetResponse()) { result = GetResponseAsString(resp); } } catch (WebException wexc) { var httpResponse = wexc.Response as HttpWebResponse; if (httpResponse != null) { string jsonResult = GetResponseAsString(wexc.Response); if(httpResponse.ContentType.IndexOf("json") < 0 || string.IsNullOrEmpty(jsonResult)) { throw new MoipException(string.Format("Erro ao acessar {0} - {1}", httpResponse.ResponseUri, httpResponse.StatusDescription), httpResponse.StatusCode); } if(httpResponse.StatusCode == HttpStatusCode.Unauthorized) { throw new MoipException("APIKey ou Token inválidos.", httpResponse.StatusCode); } var responseError = FromJson<ResponseError>(jsonResult); throw new MoipException(responseError, httpResponse.StatusCode); } throw; } return result; } protected virtual Uri PathToUri(string path, string query = null) { UriBuilder uriBuilder = new UriBuilder(ApiUri); uriBuilder.Path = path; if (!string.IsNullOrEmpty(query)) { uriBuilder.Query = query; } return uriBuilder.Uri; } #endregion } }
C
UTF-8
6,038
2.5625
3
[ "MIT" ]
permissive
/** ****************************************************************************** * @file pid.c * @version V1.0.0 * @date 2016年11月11日17:21:36 * @brief 对于PID, 反馈/测量习惯性叫get/measure/real/fdb, 期望输入一般叫set/target/ref *******************************************************************************/ /* Includes ------------------------------------------------------------------*/ #include "pid.h" #include "mytype.h" #include <math.h> //#include "cmsis_os.h" #define ABS(x) ((x>0)? (x): (-x)) void abs_limit(float *a, float ABS_MAX) { if(*a > ABS_MAX) *a = ABS_MAX; if(*a < -ABS_MAX) *a = -ABS_MAX; } /*参数初始化--------------------------------------------------------------*/ static void pid_param_init( pid_t *pid, uint32_t mode, uint32_t maxout, uint32_t intergral_limit, float kp, float ki, float kd) { pid->IntegralLimit = intergral_limit; pid->MaxOutput = maxout; pid->pid_mode = mode; pid->p = kp; pid->i = ki; pid->d = kd; } /*中途更改参数设定(调试)------------------------------------------------------------*/ static void pid_reset(pid_t *pid, float kp, float ki, float kd) { pid->p = kp; pid->i = ki; pid->d = kd; } void pid_reset_kpkd(pid_t *pid, float kp, float kd) { pid->p = kp; pid->d = kd; } /** *@bref. calculate delta PID and position PID *@param[in] set: target *@param[in] real measure */ float pid_calc(pid_t* pid, float get, float set) { pid->get[NOW] = get; pid->set[NOW] = set; pid->err[NOW] = set - get; //set - measure if (pid->max_err != 0 && ABS(pid->err[NOW]) > pid->max_err ) return 0; if (pid->deadband != 0 && ABS(pid->err[NOW]) < pid->deadband) return 0; if(pid->pid_mode == POSITION_PID) //位置式p { pid->pout = pid->p * pid->err[NOW]; pid->iout += pid->i * pid->err[NOW]; pid->dout = pid->d * (pid->err[NOW] - pid->err[LAST] ); abs_limit(&(pid->iout), pid->IntegralLimit); pid->pos_out = pid->pout + pid->iout + pid->dout; abs_limit(&(pid->pos_out), pid->MaxOutput); pid->last_pos_out = pid->pos_out; //update last time } else if(pid->pid_mode == DELTA_PID)//增量式P { pid->pout = pid->p * (pid->err[NOW] - pid->err[LAST]); pid->iout = pid->i * pid->err[NOW]; pid->dout = pid->d * (pid->err[NOW] - 2*pid->err[LAST] + pid->err[LLAST]); abs_limit(&(pid->iout), pid->IntegralLimit); pid->delta_u = pid->pout + pid->iout + pid->dout; pid->delta_out = pid->last_delta_out + pid->delta_u; abs_limit(&(pid->delta_out), pid->MaxOutput); pid->last_delta_out = pid->delta_out; //update last time } pid->err[LLAST] = pid->err[LAST]; pid->err[LAST] = pid->err[NOW]; pid->get[LLAST] = pid->get[LAST]; pid->get[LAST] = pid->get[NOW]; pid->set[LLAST] = pid->set[LAST]; pid->set[LAST] = pid->set[NOW]; return pid->pid_mode==POSITION_PID ? pid->pos_out : pid->delta_out; // } /** *@bref. special calculate position PID @attention @use @gyro data!! *@param[in] set: target *@param[in] real measure */ float pid_sp_calc(pid_t* pid, float get, float set, float gyro) { pid->get[NOW] = get; pid->set[NOW] = set; pid->err[NOW] = set - get; //set - measure if(pid->pid_mode == POSITION_PID) //位置式p { pid->pout = pid->p * pid->err[NOW]; if(fabs(pid->i) >= 0.001f) pid->iout += pid->i * pid->err[NOW]; else pid->iout = 0; pid->dout = -pid->d * gyro/100.0f; abs_limit(&(pid->iout), pid->IntegralLimit); pid->pos_out = pid->pout + pid->iout + pid->dout; abs_limit(&(pid->pos_out), pid->MaxOutput); pid->last_pos_out = pid->pos_out; //update last time } else if(pid->pid_mode == DELTA_PID)//增量式P { // pid->pout = pid->p * (pid->err[NOW] - pid->err[LAST]); // pid->iout = pid->i * pid->err[NOW]; // pid->dout = pid->d * (pid->err[NOW] - 2*pid->err[LAST] + pid->err[LLAST]); // // abs_limit(&(pid->iout), pid->IntegralLimit); // pid->delta_u = pid->pout + pid->iout + pid->dout; // pid->delta_out = pid->last_delta_out + pid->delta_u; // abs_limit(&(pid->delta_out), pid->MaxOutput); // pid->last_delta_out = pid->delta_out; //update last time } pid->err[LLAST] = pid->err[LAST]; pid->err[LAST] = pid->err[NOW]; pid->get[LLAST] = pid->get[LAST]; pid->get[LAST] = pid->get[NOW]; pid->set[LLAST] = pid->set[LAST]; pid->set[LAST] = pid->set[NOW]; return pid->pid_mode==POSITION_PID ? pid->pos_out : pid->delta_out; // } /*pid总体初始化-----------------------------------------------------------------*/ void PID_struct_init( pid_t* pid, uint32_t mode, uint32_t maxout, uint32_t intergral_limit, float kp, float ki, float kd) { /*init function pointer*/ pid->f_param_init = pid_param_init; pid->f_pid_reset = pid_reset; // pid->f_cal_pid = pid_calc; // pid->f_cal_sp_pid = pid_sp_calc; //addition /*init pid param */ pid->f_param_init(pid, mode, maxout, intergral_limit, kp, ki, kd); } //pid_t pid_rol = {0}; //pid_t pid_pit = {0}; //pid_t pid_yaw = {0}; //pid_t pid_yaw_omg = {0};//角速度环 //pid_t pid_pit_omg = {0};//角速度环 //pid_t pid_yaw_alfa = {0}; //angle acce //pid_t pid_chassis_angle={0}; //pid_t pid_poke = {0}; //pid_t pid_poke_omg = {0}; //pid_t pid_imu_tmp; //pid_t pid_x; //pid_t pid_cali_bby; //pid_t pid_cali_bbp; //pid_t pid_omg; //pid_t pid_pos; pid_t pid_pos[8]; pid_t pid_spd[8]; pid_t pid_imu[3] = {0}; pid_t pid_track = {0}; pid_t pid_rotate[2] = {0}; pid_t pid_climbing; pid_t pid_test1; pid_t pid_openmv_dev; void pid_test_init() { //为了解决上位机调参的时候第一次赋值的时候清零其他参数, 应该提前把参数表填充一下! }
JavaScript
UTF-8
5,753
3.125
3
[ "MIT" ]
permissive
/* * File: Options.Events.js * */ /* Object: Options.Events Configuration for adding mouse/touch event handlers to Nodes. Syntax: (start code js) Options.Events = { enable: false, enableForEdges: false, type: 'auto', onClick: $.empty, onRightClick: $.empty, onMouseMove: $.empty, onMouseEnter: $.empty, onMouseLeave: $.empty, onDragStart: $.empty, onDragMove: $.empty, onDragCancel: $.empty, onDragEnd: $.empty, onTouchStart: $.empty, onTouchMove: $.empty, onTouchEnd: $.empty, onTouchCancel: $.empty, onMouseWheel: $.empty }; (end code) Example: (start code js) var viz = new $jit.Viz({ Events: { enable: true, onClick: function(node, eventInfo, e) { viz.doSomething(); }, onMouseEnter: function(node, eventInfo, e) { viz.canvas.getElement().style.cursor = 'pointer'; }, onMouseLeave: function(node, eventInfo, e) { viz.canvas.getElement().style.cursor = ''; } } }); (end code) Parameters: enable - (boolean) Default's *false*. Whether to enable the Event system. enableForEdges - (boolean) Default's *false*. Whether to track events also in arcs. If *true* the same callbacks -described below- are used for nodes *and* edges. A simple duck type check for edges is to check for *node.nodeFrom*. type - (string) Default's 'auto'. Whether to attach the events onto the HTML labels (via event delegation) or to use the custom 'Native' canvas Event System of the library. 'auto' is set when you let the <Options.Label> *type* parameter decide this. onClick(node, eventInfo, e) - Triggered when a user performs a click in the canvas. *node* is the <Graph.Node> clicked or false if no node has been clicked. *e* is the grabbed event (should return the native event in a cross-browser manner). *eventInfo* is an object containing useful methods like *getPos* to get the mouse position relative to the canvas. onRightClick(node, eventInfo, e) - Triggered when a user performs a right click in the canvas. *node* is the <Graph.Node> right clicked or false if no node has been clicked. *e* is the grabbed event (should return the native event in a cross-browser manner). *eventInfo* is an object containing useful methods like *getPos* to get the mouse position relative to the canvas. onMouseMove(node, eventInfo, e) - Triggered when the user moves the mouse. *node* is the <Graph.Node> under the cursor as it's moving over the canvas or false if no node has been clicked. *e* is the grabbed event (should return the native event in a cross-browser manner). *eventInfo* is an object containing useful methods like *getPos* to get the mouse position relative to the canvas. onMouseEnter(node, eventInfo, e) - Triggered when a user moves the mouse over a node. *node* is the <Graph.Node> that the mouse just entered. *e* is the grabbed event (should return the native event in a cross-browser manner). *eventInfo* is an object containing useful methods like *getPos* to get the mouse position relative to the canvas. onMouseLeave(node, eventInfo, e) - Triggered when the user mouse-outs a node. *node* is the <Graph.Node> 'mouse-outed'. *e* is the grabbed event (should return the native event in a cross-browser manner). *eventInfo* is an object containing useful methods like *getPos* to get the mouse position relative to the canvas. onDragStart(node, eventInfo, e) - Triggered when the user mouse-downs over a node. *node* is the <Graph.Node> being pressed. *e* is the grabbed event (should return the native event in a cross-browser manner). *eventInfo* is an object containing useful methods like *getPos* to get the mouse position relative to the canvas. onDragMove(node, eventInfo, e) - Triggered when a user, after pressing the mouse button over a node, moves the mouse around. *node* is the <Graph.Node> being dragged. *e* is the grabbed event (should return the native event in a cross-browser manner). *eventInfo* is an object containing useful methods like *getPos* to get the mouse position relative to the canvas. onDragEnd(node, eventInfo, e) - Triggered when a user finished dragging a node. *node* is the <Graph.Node> being dragged. *e* is the grabbed event (should return the native event in a cross-browser manner). *eventInfo* is an object containing useful methods like *getPos* to get the mouse position relative to the canvas. onDragCancel(node, eventInfo, e) - Triggered when the user releases the mouse button over a <Graph.Node> that wasn't dragged (i.e. the user didn't perform any mouse movement after pressing the mouse button). *node* is the <Graph.Node> being dragged. *e* is the grabbed event (should return the native event in a cross-browser manner). *eventInfo* is an object containing useful methods like *getPos* to get the mouse position relative to the canvas. onTouchStart(node, eventInfo, e) - Behaves just like onDragStart. onTouchMove(node, eventInfo, e) - Behaves just like onDragMove. onTouchEnd(node, eventInfo, e) - Behaves just like onDragEnd. onTouchCancel(node, eventInfo, e) - Behaves just like onDragCancel. onMouseWheel(delta, e) - Triggered when the user uses the mouse scroll over the canvas. *delta* is 1 or -1 depending on the sense of the mouse scroll. */ Options.Events = { $extend: false, enable: false, enableForEdges: false, type: 'auto', onClick: $.empty, onRightClick: $.empty, onMouseMove: $.empty, onMouseEnter: $.empty, onMouseLeave: $.empty, onDragStart: $.empty, onDragMove: $.empty, onDragCancel: $.empty, onDragEnd: $.empty, onTouchStart: $.empty, onTouchMove: $.empty, onTouchEnd: $.empty, onMouseWheel: $.empty };
Java
UTF-8
2,383
3.25
3
[]
no_license
package ESOPCount; import java.io.File; import java.io.IOException; import java.util.ArrayList; import java.util.Scanner; /** * * @author Anika Raghuvanshi */ public class ESOPCount { public static void main(String[] args) throws IOException { Scanner reader = new Scanner(System.in); if (args.length > 0) { int pulses = readESOPFile(args[0]); //System.out.println("Number of pulses for " + args[0] + " = " + pulses); System.out.println(args[0] + " " + pulses); return; } String equation; while(true) { System.out.print("Enter Filename (*.esop): "); equation = reader.nextLine(); if (equation.endsWith(".esop")) { int pulses = readESOPFile(equation); System.out.println("Number of pulses for " + equation + " = " + pulses); //break; } else {System.out.println("Enter filename ending with *.esop");} } } public static int readESOPFile(String fname) throws IOException { Scanner fReader = new Scanner(new File(fname)); int numVars = 0; ArrayList<String> stmts = new ArrayList<>(); while (fReader.hasNext()) { String line = fReader.nextLine(); if(line.startsWith("#") || line.startsWith(".o") || line.startsWith(".p") || line.startsWith(".type")) { continue; } else if (line.startsWith(".i")) { numVars = Integer.parseInt(line.substring(3)); } else if(line.startsWith(".e")) { break; } else {stmts.add(line.substring(0, numVars));} } return countPulses(stmts); } public static int countPulses(ArrayList<String> stmts) { int pulses = 0; int numExor = stmts.size(); pulses += 7 * (numExor-1); //EXOR = 6 pulses for(int i=0; i<stmts.size(); i++) { char[] charArray = stmts.get(i).toCharArray(); for(int j=0; j<charArray.length; j++) { if(charArray[j] == '0') {pulses += 3;} if(charArray[j] == '1') {pulses += 1;} } } return pulses; } }
TypeScript
UTF-8
931
2.734375
3
[]
no_license
import applyRules from "../util/applyRules"; import { GetRules, GenericObject, Meta, Module } from "../types"; export type LetterSpacingSupportedTypes = { [key in keyof typeof defaultNames]?: string; }; export type LetterSpacingModuleType = Module<ConfigVariables>; export interface ConfigVariables { values: GenericObject | string[]; } const defaultNames = { lts: "lts", "lts:n": "lts:n", }; const getRules: GetRules<ConfigVariables> = (names, cfg) => ({ lts: { name: names["lts"], key: "letter-spacing", value: cfg.values }, "lts:n": { name: names["lts:n"], key: "letter-spacing", value: "normal" }, }); const meta: Meta = { module: "letter-spacing", }; const cssModule: LetterSpacingModuleType = (config) => (globalConfig) => { return applyRules({ config, globalConfig, defaultNames, getRules, meta: Object.assign({}, meta, config && config.meta), }); }; export default cssModule;
Java
UTF-8
6,652
2.546875
3
[]
no_license
package crafting.UI; import crafting.Filters; import crafting.Main; import java.awt.*; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.KeyEvent; import java.awt.event.KeyListener; import java.awt.event.MouseEvent; import java.awt.event.MouseListener; import javax.swing.*; import crafting.Filter; import java.awt.event.FocusEvent; import java.awt.event.FocusListener; import java.util.ArrayList; import java.io.File; public class FilterNamePanel extends JPanel { public static ArrayList<FilterNamePanel> filterpanels = new ArrayList<FilterNamePanel>(); public String name = null; public String savedname = null; public Filter filter; public JPanel parent; public String resourcePath; public Main frame; public DeleteButton cb; public FilterTextField ftf; public OpenButton ob; public FilterNamePanel(Main frame, JPanel parent, Filter filter) { String path = "src/resources"; File file = new File(path); path = file.getAbsolutePath(); this.resourcePath = path; this.name = filter.name; this.savedname = filter.name; this.filter = filter; this.parent = parent; this.frame = frame; Dimension size = new Dimension((int)(parent.getWidth() * 0.97),40); setSize(size); setPreferredSize(size); setBackground(new Color(40,40,40)); setLayout(new BoxLayout(this, BoxLayout.X_AXIS)); cb = new DeleteButton(this, size); ftf = new FilterTextField(this, size, name, savedname); ob = new OpenButton(this,size); add(cb); add(ftf); add(ob); parent.add(this); filterpanels.add(this); } public void remove() { parent.requestFocusInWindow(); if (filter.active) { FilterTypePanel.clear(true); frame.hideAddButton(); } setVisible(false); Filters.singleton.remove(name); Filters.saveFilters(); } } class BackgroundListener implements MouseListener { public JComponent object; private Color inside; private Color away; public BackgroundListener(JComponent object, Color inside, Color away) { this.object = object; this.inside = inside; this.away = away; } @Override public void mouseClicked(MouseEvent e) { } @Override public void mousePressed(MouseEvent e) { } @Override public void mouseReleased(MouseEvent e) { } @Override public void mouseEntered(MouseEvent e) { object.setBackground(inside); } @Override public void mouseExited(MouseEvent e) { object.setBackground(away); } } class FilterTextField extends JTextField { public FilterTextField(FilterNamePanel parent, Dimension size, String name, String savedname) { Dimension d = new Dimension((int)(size.width*0.6), (int)(size.height * 0.9)); setBackground(new Color(50,50,50)); setForeground(new Color(255,255,255)); setPreferredSize(d); setText(name); setCursor(Cursor.getPredefinedCursor(Cursor.TEXT_CURSOR)); setBorder(BorderFactory.createEmptyBorder(0, 15, 0, 0)); setFont(parent.frame.getNewFont(14)); KeyListener keyListener = new KeyListener() { @Override public void keyReleased(KeyEvent e) { if (e.getKeyCode() == 10) { parent.requestFocusInWindow(); } } @Override public void keyTyped(KeyEvent e) { } @Override public void keyPressed(KeyEvent e) { } }; addKeyListener(keyListener); addFocusListener(new FocusListener() { @Override public void focusGained(FocusEvent e) { } @Override public void focusLost(FocusEvent e) { Filters.singleton.rename(parent.filter, getText()); Filters.saveFilters(); parent.savedname = getText(); } }); } } class DeleteButton extends JButton { public DeleteButton(FilterNamePanel parent, Dimension size) { Dimension d1 = new Dimension((int)(size.width * 0.15), (int)(size.height * 0.9)); setBorderPainted(false); setFocusPainted(false); setContentAreaFilled(true); setOpaque(true); setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR)); setPreferredSize(d1); setBackground(new Color(40,40,40)); setIcon(new javax.swing.ImageIcon(parent.frame.getClass().getResource("/resources/images/xbuttontransparentsmall.png"))); // NOI18N setToolTipText("Delete this subfilter"); addMouseListener(new BackgroundListener(this, new Color(80,80,80), new Color(40,40,40))); ActionListener actionListener = new ActionListener() { @Override public void actionPerformed(ActionEvent e) { parent.remove(); } }; addActionListener(actionListener); } } class OpenButton extends JButton { public OpenButton(FilterNamePanel parent, Dimension size) { Dimension d1 = new Dimension((int)(size.width * 0.15), (int)(size.height * 0.9)); setBorderPainted(false); setFocusPainted(false); setContentAreaFilled(true); setOpaque(true); setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR)); setPreferredSize(d1); setBackground(new Color(40,40,40)); setIcon(new javax.swing.ImageIcon(parent.frame.getClass().getResource("/resources/images/arrowbuttontransparentsmall.png"))); // NOI18N setToolTipText("Open this subfilter"); addMouseListener(new BackgroundListener(this, new Color(80,80,80), new Color(40,40,40))); ActionListener actionListener = new ActionListener() { @Override public void actionPerformed(ActionEvent e) { parent.frame.genFilterPanel(parent.filter); for (int i=0; i<parent.filterpanels.size(); i++) { parent.filterpanels.get(i).setBackground(new Color(40,40,40)); } parent.setBackground(new Color(70,70,70)); } }; addActionListener(actionListener); } }
Java
UTF-8
762
1.703125
2
[]
no_license
package com.catering.service.impl; import com.catering.mapper.QueryAllCount_xpy; import com.catering.service.QueryAllCountService_xpy; import org.springframework.stereotype.Service; import javax.annotation.Resource; @Service public class QueryAllCountServiceImpl_xpy implements QueryAllCountService_xpy { @Resource private QueryAllCount_xpy queryAllCount; @Override public int findMemCount() { return queryAllCount.findMemCount(); } @Override public int findMerCount() { return queryAllCount.findMerCount(); } @Override public int findIndCount() { return queryAllCount.findIndCount(); } @Override public int findMemuCount() { return queryAllCount.findMemuCount(); } }
Ruby
UTF-8
152
2.765625
3
[]
no_license
def three_sum(nums) nums.combination(3).select { |triplet| triplet.sum.zero? }.map(&:sort).uniq end p three_sum([-1, 0, 1, 2, -1, -4]) # @CAT_IGNORE
C
GB18030
4,682
2.765625
3
[]
no_license
#include "tilt.h" #include "lis3dh_driver.h" #include "calender.h" #include "queue.h" #include "app_trace.h" #include <math.h> static float g_cur_Tilt; //ǰDZ仯ֵ //*****************Ǽ************************** #define PI 3.1415926 #if 0 //ˮƽнǣΧ0~180 static float calculateTilt_A(float ax, float ay, float az) { float g = 9.80665; float temp; float Tiltangle = 0; temp = ((sqrt(2)/2)*g/10); if (az > temp) { Tiltangle = (1-ay*ay) - (1-ax*ax); if (Tiltangle < 0) { Tiltangle = - Tiltangle; } Tiltangle = acos(sqrt(Tiltangle)); Tiltangle = Tiltangle/PI*180; Tiltangle = 90 - Tiltangle; } else { Tiltangle = asin(az); Tiltangle = Tiltangle/PI*180; Tiltangle = 90-Tiltangle; } return Tiltangle; } //ؽǶȲ //flag = 1»ȡǶȻ׼ֵflag = 0ʼ //YΪת static float calculateTilt_run_A(float ax, float ay, float az) { //ʼ׼Ƕֵ static float First_Tiltangle = 0; //һʱ̽Ƕֵ float Tiltangle = 0; //ʼλ 1:>=0, 0:<0 static uint8_t flag_x; //ת,˳ʱת1ʱת0 if (tilt_init_flag == 1) { tilt_init_flag = 0; First_Tiltangle = calculateTilt_A(ax,ay,az); if (ax < 0) { First_Tiltangle = 360 - First_Tiltangle; } flag_x = (ax >= 0); } Tiltangle = calculateTilt_A(ax,ay,az); if (ax < 0) { Tiltangle = 360 - Tiltangle; } if (First_Tiltangle < Tiltangle) { if (flag_x ^ (ax >= 0)) { return (360 -(Tiltangle - First_Tiltangle)); } else return (Tiltangle - First_Tiltangle); } else { if (flag_x ^ (ax >= 0)) { return (360 -(First_Tiltangle - Tiltangle)); } else return (First_Tiltangle - Tiltangle); } } #endif static float calculateTilt_B(float ax, float ay, float az) { /* *ڼǰתǶȳֵ⣬¼ǰһʱx,y,ٶ为+90 */ float temp; float g = 9.80665; float Tiltangle = 0; temp = ((sqrt(2)/2)*g/10); if (fabs(ay) < temp) { Tiltangle = asin(fabs(ay)); Tiltangle = Tiltangle/PI*180; } else { Tiltangle = acos(fabs(ay)); Tiltangle = Tiltangle/PI*180; Tiltangle = 90-Tiltangle; } if((az < 0)&&(ay < 0)) { Tiltangle = 90 + Tiltangle; } else if ((az > 0)&&(ay < 0)) { Tiltangle = 270 - Tiltangle; } else if ((az > 0) && (ay > 0)) { Tiltangle = 270 + Tiltangle; } else if ((az < 0) && (ay > 0)) { Tiltangle = 90 - Tiltangle; } return Tiltangle; } #if 0 //ؽǶȲ //flag = 1»ȡǶȻ׼ֵflag = 0ʼ //YΪת static float calculateTilt_run_B(float ax, float ay, float az) { //ʼ׼Ƕֵ static float First_Tiltangle = 0; float Tiltangle = 0; float Tiltangle_return = 0; //ʼλ 1:>=0, 0:<0 if (tilt_init_flag == 1) { tilt_init_flag = 0; First_Tiltangle = calculateTilt_B(ax,ay,az); if (ax < 0) { First_Tiltangle = 360 - First_Tiltangle; } } Tiltangle = calculateTilt_B(ax,ay,az); TITL_LOG("First_Tiltangle %f,Tiltangle %f\n",First_Tiltangle,Tiltangle); Tiltangle_return = First_Tiltangle - Tiltangle; if (Tiltangle_return < -180.0) { return (360 + Tiltangle_return); } else if (Tiltangle_return > 180) { return (360 - Tiltangle_return); } else if (Tiltangle_return < 0) { return -Tiltangle_return; } else return Tiltangle_return; } #endif float calculateTilt(void) { UTCTimeStruct time; AxesRaw_t Axes_Raw_Data = {0}; float ax,ay,az; uint8_t response; float tilt = 0.0; response = LIS3DH_GetAccAxesRaw(&Axes_Raw_Data); if (response == 1) { ax = Axes_Raw_Data.AXIS_X/16384.0; ay = Axes_Raw_Data.AXIS_Y/16384.0; az = Axes_Raw_Data.AXIS_Z/16384.0; g_cur_Tilt = calculateTilt_B(ax,ay,az); ConvertUTCTime(&time,TimeSeconds); // TITL_LOG("X=%6f Y=%6f Z=%6f \r\n", // ax,ay,az); // TITL_LOG("Tilt = %6f \r\n", g_cur_Tilt); // TITL_LOG("y:%d m:%d d:%d h:%d m:%d s:%d\r\n",\ // time.year,time.month,time.day,time.hour,time.minutes,time.seconds); tilt = g_cur_Tilt; } return tilt; } void save_Tilt(float Tilt) { UTCTimeStruct time; queue_items_t item; ConvertUTCTime(&time,TimeSeconds); item.year = time.year - 2000; item.mon = time.month; item.day = time.day; item.hour = time.hour; item.min = time.minutes; item.second = time.seconds; item.angle = (uint16_t)(g_cur_Tilt*100); queue_push(&item); TITL_LOG("data push y:%d m:%d d:%d h:%d m:%d s:%d\r\n",\ time.year,time.month,time.day,time.hour,time.minutes,time.seconds); }
Markdown
UTF-8
240
2.515625
3
[]
no_license
TimeAssist ========== This application assist me and identifying the exact amount of time it takes to accomplish tasks throughout my day. Then, using its data, we can analyze the results and reflect on how the user can improve their time.
Java
UTF-8
2,031
2.375
2
[]
no_license
package com.tsc.iorder.domain; public class Orderitem { private int id; private String oid; private int fid; private Food food; private int count; private double total; private Order order; public Orderitem(int id, String oid, int fid, Food food, int count, double total, Order order) { this.id = id; this.oid = oid; this.fid = fid; this.food = food; this.count = count; this.total = total; this.order = order; } public Orderitem(String oid, int fid, Food food, int count, double total, Order order) { this.oid = oid; this.fid = fid; this.food = food; this.count = count; this.total = total; this.order = order; } public Orderitem() { } public int getId() { return id; } public void setId(int id) { this.id = id; } public String getOid() { return oid; } public void setOid(String oid) { this.oid = oid; } public int getFid() { return fid; } public void setFid(int fid) { this.fid = fid; } public Food getFood() { return food; } public void setFood(Food food) { this.food = food; } public int getCount() { return count; } public void setCount(int count) { this.count = count; } public double getTotal() { return total; } public void setTotal(double total) { this.total = total; } public Order getOrder() { return order; } public void setOrder(Order order) { this.order = order; } @Override public String toString() { return "Orderitem{" + "id=" + id + ", oid='" + oid + '\'' + ", fid=" + fid + ", food=" + food + ", count=" + count + ", total=" + total + ", order=" + order + '}'; } }
JavaScript
UTF-8
1,472
2.609375
3
[]
no_license
import React, { Component } from 'react'; class UserForm extends Component { state = { username: '', password: '' } updateUser = (event) => { const { name, value } = event.target this.setState(() => ({ [name]: value })) } login = (event) => { event.preventDefault() this.props.login(this.state) } createUser = (event) => { event.preventDefault() this.props.createUser(this.state) } render() { return ( <div className='login-base'> <br/> <br/> <img src='/tamagotchi-friends.jpg' style={{ width: '500px'}} alt='background' /> <br/> <br/> <form className='login-card'> <label>Username</label> <input name="username" type='text' value={this.state.username} onChange={this.updateUser} /> <br/> <label>Password</label> <input name="password" type='password' value={this.state.password} onChange={this.updateUser} /> <br/> <div className='login-button-div'> <button className='login-button' onClick={this.login}>Login</button> <button className='login-button' onClick={this.createUser}>Create User</button> </div> </form> </div> ); } } export default UserForm;
JavaScript
UTF-8
2,860
2.890625
3
[]
no_license
#!/usr/bin/env node import { DecisionTree } from './decision-tree'; import { InteractionService } from './InteractionService'; import getopt from 'node-getopt'; import * as fs from 'fs'; import * as path from 'path'; const { options } = getopt.create([ ['f', 'filepath=PATH', 'The path to the data set .csv'], ['d', 'decision=ATTRIBUTE', 'The attribute we are making a decision for', 'decision'], ['i', 'ignore=ATTRIBUTE,ATTRIBUTE,...', 'Attributes not to consider', ''] ]) .bindHelp() .parseSystem(); if (!options.filepath) { console.error('you must pass a path to a data .csv file (see --help)'); process.exit(1); } const tree = DecisionTree.fromFilePath( options.filepath as string, { classAttribute: (options.decision as string), ignoredAttributes: (options.ignore as string).split(',') } ); async function describeRecord (): Promise<void> { InteractionService.say(`Okay, let me ask you some questions about the "${tree.params.classAttribute}"`); const record = []; const attributes = tree.data.attributes .filter(attribute => attribute !== tree.params.classAttribute) .reverse(); while (attributes.length > 0) { const attribute = attributes.pop(); const existingValues = tree.data.getDistinctValues(attribute); const result = await InteractionService.selectPrompt( `How would you describe its "${attribute}"?`, existingValues ); record.push(result); } const thing = await InteractionService.textPrompt('What would you call it?'); InteractionService.say('Thanks, i\'ll remember that'); const keyIndex = tree.data.attributes.indexOf(tree.params.classAttribute); record.splice(keyIndex, 0, thing); fs.appendFileSync(path.resolve(options.filepath as string), `${record}\n`); } async function handleUnknown () :Promise<void> { InteractionService.say('I cant decide what it is...'); const result = await InteractionService.selectPrompt( 'Can you describe it for me please?', ['Yes', 'No'] ); if (result === 'Yes') { return describeRecord(); } else { InteractionService.say('Okay, no worries.'); } } async function traverseTree (node): Promise<void> { const attribute = node.children[0].attribute; if (attribute === `${options.decision}`.toLowerCase()) { return InteractionService.say(`I think the answer is "${node.children[0].value.join(' or ')}"`); } const values = node.children.map(({ value }) => value); const result = await InteractionService.selectPrompt( `How would you describe the "${attribute}"?`, [...values, 'none of the above'] ); const next = node.children.find(child => child.value === result); if (next) { return traverseTree(next); } return handleUnknown(); } traverseTree(tree).then(() => { process.exit(0); }).catch(error => { console.error(error); process.exit(1); });
Java
UTF-8
845
3.34375
3
[]
no_license
package pl.sda.javalon4.kalisz.dzien4; public class RokPrzystepny { public static void main(String[] args) { boolean przystepny2019 = jestPrzystepny(2019);// tworzymy boolean zmienna i sprawdzamy czy rok jest przystepny metoda na dole boolean przesteony2020=jestPrzystepny(2020); System.out.println("Czy rok 2019 jest przystepny? " + przystepny2019); System.out.println("Czy rok 2019 jest przystepny? " + przesteony2020); } public static boolean jestPrzystepny (int rok){ if(rok%4==0 && rok%100!=0){ return true; } else if(rok%400==0){ return true; } else { return false; } } /* public static boolean jestPrzystepny2 (int rok){ return (rok % 4==0 && rok % 100!=0) || rok%400==0); } */ }
PHP
UTF-8
1,831
2.546875
3
[]
no_license
<?php ob_start(); session_start(); require_once "../Database/Database.php"; $username = mysqli_real_escape_string($conn, trim($_POST['username'])); $password = mysqli_real_escape_string($conn, trim(md5($_POST['password']))); $sql = "SELECT username FROM user WHERE username ='" . $username . "'"; $query = mysqli_query($conn, $sql); $result = mysqli_fetch_array($query, MYSQLI_ASSOC); $cf = trim($_POST['cfpassword']); if ($result) { echo "<script>alert('Username is used!')</script>"; header("Refresh:0 , url = member.html"); exit(); } else { if (trim($_POST['username']) != null && trim($_POST['password']) != null && trim($_POST['name']) != null && trim($_POST['cfpassword']) != null && trim($_POST['cfpassword']) == trim($_POST['password'])) { if (strlen($password) >= 8 && strlen($cf) >=8) { $sql = "INSERT INTO user (username,password,name) VALUES ('" . trim($_POST['username']) . "','" . trim(md5($_POST['password'])) . "','" . trim($_POST['name']) . "')"; if ($conn->query($sql)) { echo "<script>alert('Registration is complete.')</script>"; header("Refresh:0 , url = ../index.html"); exit(); } else { echo "<script>alert('Registration isn't complete.')</script>"; header("Refresh:0 , url = member.html"); exit(); } } else { echo "<script>alert('Please enter new password,password characters should be at least 8 characters.')</script>"; header("Refresh:0 , url = member.html"); exit(); } } else { echo "<script>alert('Please enter new information or the password does not match.')</script>"; header("Refresh:0 , url = member.html"); exit(); } mysqli_close($conn); }
JavaScript
UTF-8
364
3.59375
4
[]
no_license
/** * Return a random number within a range. The min and max values are included * in the possible results. * * @param max {integer} Minimum Value * @param min {integer} Maximum Value * * @returns {integer} Value within the range (inclusive) * */ exports.rand = function(min,max){ return min + Math.floor(Math.random()* (max-min+1)); };
Java
UTF-8
3,267
2.109375
2
[ "MIT" ]
permissive
package com.adouge.secure.interceptor; import cn.hutool.json.JSONUtil; import com.adouge.core.tool.utils.WebUtil; import com.adouge.secure.auth.AuthFun; import com.adouge.secure.props.AuthSecure; import com.adouge.secure.provider.HttpMethod; import com.adouge.secure.provider.ResponseProvider; import lombok.AllArgsConstructor; import lombok.extern.slf4j.Slf4j; import org.springframework.expression.EvaluationContext; import org.springframework.expression.ExpressionParser; import org.springframework.expression.spel.standard.SpelExpressionParser; import org.springframework.expression.spel.support.StandardEvaluationContext; import org.springframework.lang.NonNull; import org.springframework.util.PatternMatchUtils; import org.springframework.web.servlet.handler.HandlerInterceptorAdapter; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.util.List; /** * @author : Vinson * @date : 2020/8/13 11:20 上午 */ @Slf4j @AllArgsConstructor public class AuthInterceptor extends HandlerInterceptorAdapter { private static final ExpressionParser EXPRESSION_PARSER = new SpelExpressionParser(); private static final EvaluationContext EVALUATION_CONTEXT = new StandardEvaluationContext(new AuthFun()); private final List<AuthSecure> authSecures; @Override public boolean preHandle(@NonNull HttpServletRequest request, @NonNull HttpServletResponse response, @NonNull Object handler) { // SecureProperties secureProperties= SpringUtil.getBean(SecureProperties.class); // authSecures.addAll(secureProperties.getAuth()); // FIXME 不能自动更新问题 boolean check = this.authSecures.stream() .filter((authSecure) -> this.checkAuth(request, authSecure)) .findFirst().map((authSecure) -> this.checkExpression(authSecure.getExpression())) .orElse(Boolean.TRUE); if (!check) { log.warn("授权认证失败,请求接口:{},请求IP:{},请求参数:{}", request.getRequestURI(), WebUtil.getIp(request), JSONUtil.toJsonStr(request.getParameterMap())); ResponseProvider.write(response); return false; } else { return true; } } private boolean checkAuth(HttpServletRequest request, AuthSecure authSecure) { return this.checkMethod(request, authSecure.getMethod()) && this.checkPath(request, authSecure.getPattern()); } private boolean checkMethod(HttpServletRequest request, HttpMethod method) { return method == HttpMethod.ALL || method != null && method == HttpMethod.of(request.getMethod()); } private boolean checkPath(HttpServletRequest request, String pattern) { String servletPath = request.getServletPath(); String pathInfo = request.getPathInfo(); if (pathInfo != null && pathInfo.length() > 0) { servletPath = servletPath + pathInfo; } return PatternMatchUtils.simpleMatch(pattern, servletPath); } private boolean checkExpression(String expression) { Boolean result = EXPRESSION_PARSER.parseExpression(expression).getValue(EVALUATION_CONTEXT, Boolean.class); return result != null ? result : false; } }
TypeScript
UTF-8
428
2.734375
3
[]
no_license
export interface User { id: number; name: string; email: string; created_at: string; updated_at: string; role: string; // constructor(id: number, name: string, email: string, created_at: string, updated_at: string, role: string){ // this.id = id; // this.name = name; // this.email = email; // this.created_at = created_at; // this.updated_at = updated_at; // this.role = role; // } }
Java
UTF-8
2,497
2.515625
3
[]
no_license
package bean; import java.sql.Date; import java.util.ArrayList; public class Porudzbina { public enum kom{da,ne,potvdjen,odbijen}; private long id; // 10 karaktera mora da bude private ArrayList<Artikal> artikli; private Restoran restoran; private Date datumPorudzbine; // datum i vreme zajedno private int cena; private String punoImePrezimeKupca; private StatusPorudzbine statusPorudzbine; private String dostavljac; private kom koment; private String usernameKupca; public Porudzbina() { } public Porudzbina(long id, ArrayList<Artikal> artikli, Restoran restoran, Date datumPorudzbine, int cena, String punoImePrezimeKupca, StatusPorudzbine statusPorudzbine, String dostavljac, kom koment, String usernameKupca) { super(); this.id = id; this.artikli = artikli; this.restoran = restoran; this.datumPorudzbine = datumPorudzbine; this.cena = cena; this.punoImePrezimeKupca = punoImePrezimeKupca; this.statusPorudzbine = statusPorudzbine; this.setDostavljac(dostavljac); this.koment = koment; } public long getId() { return id; } public void setId(long id) { this.id = id; } public ArrayList<Artikal> getArtikli() { return artikli; } public void setArtikli(ArrayList<Artikal> artikli) { this.artikli = artikli; } public Restoran getRestoran() { return restoran; } public void setRestoran(Restoran restoran) { this.restoran = restoran; } public Date getDatumPorudzbine() { return datumPorudzbine; } public void setDatumPorudzbine(Date datumPorudzbine) { this.datumPorudzbine = datumPorudzbine; } public int getCena() { return cena; } public void setCena(int cena) { this.cena = cena; } public String getPunoImePrezimeKupca() { return punoImePrezimeKupca; } public void setPunoImePrezimeKupca(String punoImePrezimeKupca) { this.punoImePrezimeKupca = punoImePrezimeKupca; } public StatusPorudzbine getStatusPorudzbine() { return statusPorudzbine; } public void setStatusPorudzbine(StatusPorudzbine statusPorudzbine) { this.statusPorudzbine = statusPorudzbine; } public String getDostavljac() { return dostavljac; } public void setDostavljac(String dostavljac2) { this.dostavljac = dostavljac2; } public kom getKoment() { return koment; } public void setKoment(kom koment) { this.koment = koment; } public String getUsernameKupca() { return usernameKupca; } public void setUsernameKupca(String usernameKupca) { this.usernameKupca = usernameKupca; } }
Python
UTF-8
429
2.921875
3
[]
no_license
# -*- coding: utf-8 -*- """ Created on Mon Oct 1 07:11:24 2018 @author: I340968 """ import networkx as nx import matplotlib.pyplot as plt #G=nx.gnp_random_graph(50,0.3) #Different type of graph G = nx.barabasi_albert_graph(50,2) nx.draw(G) plt.show(G) '''print(G.nodes()) print() print() print() print(G.edges()) print() print(G.degree(0))''' nx.write_gexf(G,"analysis1.gexf") print(G.edges())
Java
UTF-8
1,467
2.9375
3
[]
no_license
package com.example.shaunmesias.assignment_6_2.domain.person; import java.io.Serializable; /** * Created by Shaun Mesias on 2016/04/17. */ public class PersonContact implements Serializable { private String id; private String contactValue; private PersonContact(){} public String getId() { return id; } public String getContactValue() { return contactValue; } public PersonContact(Builder builder) { this.id = builder.id; this.contactValue= builder.contactValue; } public static class Builder{ private String id; private String contactValue; public Builder id(String value) { this.id = value; return this; } public Builder contactValue(String value){ this.contactValue = value; return this; } public Builder copy(PersonContact value){ this.id = value.id; this.contactValue = value.contactValue; return this; } public PersonContact build(){ return new PersonContact(this); } } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; PersonContact that = (PersonContact) o; return id.equals(that.id); } @Override public int hashCode() { return id.hashCode(); } }
SQL
UTF-8
241
2.859375
3
[]
no_license
USE sql_invoicing; -- Procedure with parameters DROP PROCEDURE IF EXISTS get_clients_by_state; DELIMITER $$ CREATE PROCEDURE get_clients_by_state( state CHAR(2)) BEGIN SELECT * FROM clients c WHERE c.state = state; END$$ DELIMITER ;
Java
UTF-8
10,881
1.507813
2
[]
no_license
package com.example.jeliu.bipawallet.Asset; import android.Manifest; import android.content.Intent; import android.content.pm.PackageManager; import android.os.Bundle; import android.support.v4.app.ActivityCompat; import android.support.v4.content.ContextCompat; import android.text.method.HideReturnsTransformationMethod; import android.text.method.PasswordTransformationMethod; import android.view.View; import android.widget.CheckBox; import android.widget.EditText; import android.widget.ImageView; import android.widget.RadioButton; import android.widget.TabHost; import android.widget.Toast; import com.example.jeliu.bipawallet.Base.BaseActivity; import com.example.jeliu.bipawallet.Common.Common; import com.example.jeliu.bipawallet.Common.Constant; import com.example.jeliu.bipawallet.Common.HZWalletManager; import com.example.jeliu.bipawallet.Network.HZHttpRequest; import com.example.jeliu.bipawallet.Network.IWallet; import com.example.jeliu.bipawallet.R; import com.example.jeliu.bipawallet.UserInfo.UserInfoManager; import org.json.JSONException; import org.json.JSONObject; import org.web3j.crypto.Credentials; import java.util.HashMap; import java.util.Map; import butterknife.BindView; import butterknife.ButterKnife; import butterknife.OnClick; import static com.example.jeliu.bipawallet.ui.WalletTypeDialogKt.WALLET_ETH; /** * Created by liuming on 09/05/2018. */ public class ImportWalletActivity extends BaseActivity implements IWallet { @BindView(R.id.et_keystore) EditText etKeyStore; @BindView(R.id.et_keystore_password) EditText etKeyStorePassword; @BindView(R.id.et_key) EditText etKey; @BindView(R.id.et_key_password) EditText etKeyPassword; @BindView(R.id.radioButton_keystore) CheckBox rbKeyStore; @BindView(R.id.ck_cryto) CheckBox ck_cryto; @BindView(R.id.rb_key) CheckBox rbKey; @BindView(R.id.ck_cryto_pk) CheckBox ck_cryto_pk; @BindView(R.id.imageView_eye_store) ImageView ivEyeStore; // @BindView(R.id.imageView_key_eye) ImageView ivKeyEye; @BindView(R.id.editText_name_store) EditText etStoreName; @BindView(R.id.editText_name_key) EditText etKeyName; @OnClick({R.id.textView_privacy, R.id.text_privacy_key}) void onPrivacy() { gotoWebView("http://47.52.224.7:8081"); } private boolean passwordShown; private boolean passwordShownKey; @OnClick({R.id.imageView_question, R.id.btn_keystore}) void onQuestion() { gotoWebView(Common.getCenterUrl() + "#question4"); } @OnClick({R.id.iv_key_question, R.id.btn_key}) void onQuestionKey() { gotoWebView(Common.getCenterUrl() + "#question3"); } @OnClick(R.id.imageView_eye_store) void onEye() { passwordShown = !passwordShown; if (passwordShown) { etKeyStorePassword.setTransformationMethod(HideReturnsTransformationMethod.getInstance()); ivEyeStore.setImageDrawable(getResources().getDrawable(R.drawable.open)); } else { etKeyStorePassword.setTransformationMethod(PasswordTransformationMethod.getInstance()); ivEyeStore.setImageDrawable(getResources().getDrawable(R.drawable.close)); } } // @OnClick(R.id.imageView_key_eye) void onKeyEye() { passwordShownKey = !passwordShownKey; if (passwordShownKey) { etKeyPassword.setTransformationMethod(HideReturnsTransformationMethod.getInstance()); ivKeyEye.setImageDrawable(getResources().getDrawable(R.drawable.open)); } else { etKeyPassword.setTransformationMethod(PasswordTransformationMethod.getInstance()); ivKeyEye.setImageDrawable(getResources().getDrawable(R.drawable.close)); } } @OnClick({R.id.btn_scan_key, R.id.btn_scan_store}) void onScanKey(View view) { if (view.getId() == R.id.btn_scan_key) { scanForKey = true; } else { scanForKey = false; } scanCode(); } private boolean scanForKey; @OnClick({R.id.button_import_key, R.id.button_import_keystore}) void onClick(View view) { String pwd = ""; if (view.getId() == R.id.button_import_key) { if (!checkInputs(etKey, etKeyPassword, etKeyName)) { return; } if (!rbKey.isChecked()) { showToastMessage(getString(R.string.agree_service_privacy_policy)); return; } if (HZWalletManager.getInst().walletNameExist(etKeyName.getText().toString())) { showToastMessage("wallet name already exists, please change another one"); return; } pwd = etKeyPassword.getText().toString(); // HZHttpRequest request = new HZHttpRequest(); // Map<String, String> param = new HashMap<>(); // param.put("privatekey", etKey.getText().toString()); // param.put("password", etKeyPassword.getText().toString()); //// param.put("privatekey", "b77005482c476a3e19c2f3353d5d0edd550439c13bdbcb5c8a61b326ec6efc71"); //// param.put("password", "chenjianlin7"); // showWaiting(); // request.requestPost(Constant.IMPORT_PRIVATE_KEY_URL, param, this); } else { if (!checkInputs(etKeyStore, etKeyStorePassword, etStoreName)) { return; } if (!rbKeyStore.isChecked()) { showToastMessage("请同意服务及隐私条款"); return; } if (HZWalletManager.getInst().walletNameExist(etStoreName.getText().toString())) { showToastMessage("wallet name already exists, please change another one"); return; } pwd = etKeyStorePassword.getText().toString(); // HZHttpRequest request = new HZHttpRequest(); // Map<String, String> param = new HashMap<>(); // param.put("keystore", etKeyStore.getText().toString()); // param.put("password", etKeyStorePassword.getText().toString()); // showWaiting(); // request.requestPost(Constant.IMPORT_KEYSTORE_URL, param, this); } int permissionCheck = ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE); if (permissionCheck != PackageManager.PERMISSION_GRANTED) { ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, REQUEST_PERMISSION_WRITE_STORAGE); } else { loadWallet(th.getCurrentTab(), pwd); } } @Override public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) { super.onRequestPermissionsResult(requestCode, permissions, grantResults); if (requestCode == REQUEST_PERMISSION_WRITE_STORAGE) { if (grantResults.length == 0 || grantResults[0] != PackageManager.PERMISSION_GRANTED) { Toast.makeText(this, "请开启文件读取权限", Toast.LENGTH_SHORT).show(); finish(); } else { Toast.makeText(this, "已经开启文件读取权限", Toast.LENGTH_SHORT).show(); } } } public void loadWallet(int way, String pwd) { showWaiting(); if (way == 0) { Credentials credentials = ck_cryto.isChecked() ? Common.loadWalletByKSBipa(pwd, etKeyStore.getText().toString(), this) : Common.loadWalletByKeyStore(pwd, etKeyStore.getText().toString(), this); } else { Credentials credentials = ck_cryto_pk.isChecked() ? Common.loadWalletByPKBipa(pwd, etKey.getText().toString(), this) : Common.loadWalletByPrivateKey(pwd, etKey.getText().toString(), this); } } @Override public boolean onSuccess(JSONObject jsonObject, String url) { // if (!super.onSuccess(jsonObject, url)) { // return true; // } // if (url == Constant.IMPORT_PRIVATE_KEY_URL || url == Constant.IMPORT_KEYSTORE_URL) { // try { // String address = jsonObject.getString("address"); // if (address != null) { // String name = ""; // if (url == Constant.IMPORT_PRIVATE_KEY_URL) { // name = etKeyName.getText().toString(); // } else { // name = etStoreName.getText().toString(); // } // UserInfoManager.getInst().insertWallet(name, address, 0); // UserInfoManager.getInst().setCurrentWalletAddress(address); // setResult(RESULT_OK); // finish(); // } // } catch (JSONException e) { // e.printStackTrace(); // } // } return true; } private TabHost th; protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_import_wallet); ButterKnife.bind(this); setTitle(getString(R.string.importWallet)); showBackButton(); th = (TabHost) findViewById(R.id.tabhost); setupTabHost(); } private void setupTabHost() { th.setup(); //初始化TabHost容器 //在TabHost创建标签,然后设置:标题/图标/标签页布局 th.addTab(th.newTabSpec("tabKeystore").setIndicator(getResources().getString(R.string.ks_wallet), null).setContent(R.id.tab1)); th.addTab(th.newTabSpec("tabKey").setIndicator(getResources().getString(R.string.privacy_key), null).setContent(R.id.tab2)); th.setOnTabChangedListener(new TabHost.OnTabChangeListener() { @Override public void onTabChanged(String s) { if (s.equalsIgnoreCase("tabKeystore")) { } else { } } }); } protected void scanDone(String barcode) { if (scanForKey) { etKeyStore.setText(barcode); } else { etKey.setText(barcode); } } @Override public void onWalletResult(Credentials credentials, String fileName) { if (credentials != null) { String address = credentials.getAddress(); if (address != null) { hideWaiting(); String name = th.getCurrentTab() == 0 ? etStoreName.getText().toString() : etKeyName.getText().toString(); UserInfoManager.getInst().insertWallet(name, address, 0, fileName, WALLET_ETH); UserInfoManager.getInst().setCurrentWalletAddress(address); setResult(RESULT_OK); finish(); } else { hideWaiting(); } } else { hideWaiting(); } } }
Java
UTF-8
393
2.078125
2
[]
no_license
package com.lmgd02.template_v1; public class TestPaperA extends TestPaper { private static final String answerA = "a"; public TestPaperA() { } @Override protected String answer1() { return answerA; } @Override protected String answer2() { return answerA; } @Override protected String answer3() { return answerA; } }
C#
UTF-8
839
3.046875
3
[ "Apache-2.0" ]
permissive
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace DateiSortierer.Strategy { class SortManager { private static SortManager instance = null; public ISort SortMethode { get; set; } = new SortDate(); /**private ISort sortMethod = new SortDate(); public ISort SortMethod { get { return sortMethod; } set { sortMethod = value; } }**/ private SortManager() { } public static SortManager GetInstance() { if (instance == null) instance = new SortManager(); return instance; } public void Sort(string source, string target) { SortMethode.Execute(source, target); } } }
Python
UTF-8
221
2.734375
3
[]
no_license
#!/usr/bin/python # -*- coding: utf-8 -*- import datetime tagad = datetime.datetime.now() print "Šodienas datums ir", tagad.strftime("%d-%m-%Y"), "plkst.", tagad.strftime("%H:%M") print "vai precīzāk, %s" % tagad