text
stringlengths
1
1.05M
#!/bin/bash -e # Copyright 2017-2018 by SDRausty. All rights reserved. ๐ŸŒŽ ๐ŸŒ ๐ŸŒ ๐ŸŒ ๐Ÿ—บ # Hosting https://sdrausty.github.io/TermuxArch courtesy https://pages.github.com # https://sdrausty.github.io/TermuxArch/CONTRIBUTORS Thank you for your help. # https://sdrausty.github.io/TermuxArch/README has information about this project. # ๐Ÿ•ง๐Ÿ•๐Ÿ•œ๐Ÿ•‘๐Ÿ•๐Ÿ•’๐Ÿ•ž๐Ÿ•“๐Ÿ•Ÿ๐Ÿ•”๐Ÿ• ๐Ÿ••๐Ÿ•ก๐Ÿ•–๐Ÿ•ข๐Ÿ•—๐Ÿ•ฃ๐Ÿ•˜๐Ÿ•ค๐Ÿ•™๐Ÿ•ฅ๐Ÿ•š๐Ÿ•ฆ๐Ÿ•› # Printout statement subroutines for `setupTermuxArch.sh`. ################################################################################ detectsystem2p () { if [[ $(getprop ro.product.device) == *_cheets ]];then printf "Chromebook: \033[36;1mOK\n\033[0m" else printf "$(uname -o) operating system: \033[36;1mOK\n\033[0m" fi } printdetectedsystem () { printf "\n\033[36;1m ๐Ÿ• < ๐Ÿ•› \033[1;34mDetected $(uname -m) " detectsystem2p printf "$spaceMessage" } printdownloading () { printf "\n\033[36;1m ๐Ÿ•’ < ๐Ÿ•› \033[1;34mActivated termux-wake-lock. Downloading checksum and \033[36;1m$file\033[1;34m. \033[37;1mThis may take a long time pending Internet connection.\n\n\033[36;1m"'\033]2; ๐Ÿ•’ < ๐Ÿ•› Downloading the checksum and system image file. \007' } printconfigq () { printf "\n\033[36;1m ๐Ÿ•™ < ๐Ÿ•› \033[1;34mArch Linux in Termux is installed. Answer the following questions to complete the Arch Linux configuration.\n\n\033[0m"'\033]2; ๐Ÿ•™ < ๐Ÿ•› Arch Linux in Termux is installed! Complete the Arch Linux configuration. ๐Ÿ“ฒ \007' } printmd5check () { printf "\n\033[36;1m ๐Ÿ•  < ๐Ÿ•› \033[1;34mChecking download integrity with md5sum. \033[37;1mThis may take a little while.\033[36;1m\n\n" } printmd5error () { printf "\n\033[07;1m\033[31;1m ๐Ÿ”† ERROR md5sum mismatch! The download failed and was removed!\033[36;1m Run \`setupTermuxArch.sh\` again. See \`bash setupTermuxArch.sh --help\` to resolve md5sum errors. This kind of error can go away, like magic. Waiting before executing again is recommended. There are many reasons that generate checksum errors. Proxies are one reason. Mirroring and mirrors are another explaination for md5sum errors. Either way the download did not succeed. If this keeps repeating, copy \`knownconfigurations.sh\` to \`~/setupTermuxArchConfigs.sh\` with prefered parameters. Run \`bash ~/setupTermuxArch.sh\` and \`~/setupTermuxArchConfigs.sh\` loads automaticaly. Change mirror to desired geographic location to resolve md5sum errors.\n\n Run \`setupTermuxArch.sh\` again. \033[31;1mExiting...\n\033[0m" exit } printmd5success () { printf '\033]2; ๐Ÿ•ก < ๐Ÿ•› Uncompressing Arch Linux system image file. This will take a long time; Be patient.\007'"\n\033[36;1m ๐Ÿ•• < ๐Ÿ•› \033[1;34mDownload integrity: \033[36;1mOK\n\n\033[36;1m ๐Ÿ•ก < ๐Ÿ•› \033[1;34mUncompressing \033[36;1m$file\033[37;1m. This will take a long time. Be patient.\n\033[0m" } printmismatch () { printf "\n\033[07;1m\033[31;1m ๐Ÿ”† ERROR Unknown configuration! Did not find an architecture and operating system match in\033[37;1m knownconfigurations.sh\033[31;1m! \033[36;1mDetected $(uname -mo). There still is hope. Check at http://mirror.archlinuxarm.org/os/ and https://www.archlinux.org/mirrors/ for other available images and see if any match the device. If you find a match, then please \033[37;1msubmit a pull request\033[36;1m at https://github.com/sdrausty/TermuxArch/pulls with script modifications. Alternatively, \033[37;1msubmit a modification request\033[36;1m at https://github.com/sdrausty/TermuxArch/issues if you find a configuration match. Please include output from \033[37;1muname -mo\033[36;1m on the device in order to expand autodetection for \033[37;1msetupTermuxArch.sh\033[36;1m. See https://sdrausty.github.io/docs/TermuxArch/Known_Configurations for more information.\n\n \033[36;1mRun setupTermuxArch.sh again. \033[31;1mExiting...\n\033[0m" exit } printfooter () { printf "\n\033[36;1m ๐Ÿ•ฅ < ๐Ÿ•› \033[1;34mUse \033[32;1m./arch/$bin\033[1;34m from the \033[32;1m\$HOME\033[1;34m directory to launch Arch Linux in Termux for future sessions. Alternatively copy \033[32;1m$bin\033[1;34m to the \033[32m\$PATH\033[1;34m which is, \033[37m\"$PATH\"\033[0m.\n\n"'\033]2; Thank you for using `setupTermuxArch.sh` to install Arch Linux in Termux ๐Ÿ“ฒ \007' copybin2path printf "\033[1;32m ๐Ÿ•› = ๐Ÿ•› \033[1;34mTermux-wake-lock released. Arch Linux in Termux is installed. \033[32;1m\`tzselect\`\033[1;34m assits in setting the local time zone. https://github.com/sdrausty/TermuxArch/issues/25 \"Starting Arch Linux from Termux?\" has more information. \n\n\033[0m" } spaceMessageWarning () { spaceMessage="\033[1;31m\nTermuxArch: WARNING! Start thinking about cleaning out some stuff. The user space on this device has just $usrspace. This is less than the recommended minimum to install Arch Linux in Termux PRoot. \033[34mMore than 1G of free user space in \033[36m\$HOME\033[34m is suggested.\n\033[0m" }
/** * MailSlurp API * MailSlurp is an API for sending and receiving emails from dynamically allocated email addresses. It's designed for developers and QA teams to test applications, process inbound emails, send templated notifications, attachments, and more. ## Resources - [Homepage](https://www.mailslurp.com) - Get an [API KEY](https://app.mailslurp.com/sign-up/) - Generated [SDK Clients](https://www.mailslurp.com/docs/) - [Examples](https://github.com/mailslurp/examples) repository * * OpenAPI spec version: 6.5.2 * Contact: <EMAIL> * * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). * https://openapi-generator.tech * Do not edit the class manually. */ import { HttpFile } from '../http/http.ts'; export class OrganizationInboxProjection { /** * ID of the inbox. The ID is a UUID-V4 format string. Use the inboxId for calls to Inbox and Email Controller endpoints. See the emailAddress property for the email address or the inbox. To get emails in an inbox use the WaitFor and Inbox Controller methods `waitForLatestEmail` and `getEmails` methods respectively. Inboxes can be used with aliases to forward emails automatically. */ 'id': string; /** * When the inbox was created. Time stamps are in ISO DateTime Format `yyyy-MM-dd'T'HH:mm:ss.SSSXXX` e.g. `2000-10-31T01:30:00.000-05:00`. */ 'createdAt': Date; /** * Name of the inbox and used as the sender name when sending emails .Displayed in the dashboard for easier search */ 'name'?: string; /** * The inbox's email address. Inbox projections and previews may not include the email address. To view the email address fetch the inbox entity directly. Send an email to this address and the inbox will receive and store it for you. Note the email address in MailSlurp match characters exactly and are case sensitive so `+123` additions are considered different addresses. To retrieve the email use the Inbox and Email Controller endpoints with the inbox ID. */ 'emailAddress'?: string; /** * Is the inbox a favorite inbox. Make an inbox a favorite is typically done in the dashboard for quick access or filtering */ 'favourite': boolean; /** * Tags that inbox has been tagged with. Tags can be added to inboxes to group different inboxes within an account. You can also search for inboxes by tag in the dashboard UI. */ 'tags'?: Array<string>; /** * Does inbox permit team access for organization team members. If so team users can use inbox and emails associated with it. See the team access guide at https://www.mailslurp.com/guides/team-email-account-sharing/ */ 'teamAccess': boolean; /** * Type of inbox. HTTP inboxes are faster and better for most cases. SMTP inboxes are more suited for public facing inbound messages (but cannot send). */ 'inboxType'?: OrganizationInboxProjectionInboxTypeEnum; /** * Is the inbox readOnly for the caller. Read only means can not be deleted or modified. This flag is present when using team accounts and shared inboxes. */ 'readOnly': boolean; static readonly discriminator: string | undefined = undefined; static readonly attributeTypeMap: Array<{name: string, baseName: string, type: string, format: string}> = [ { "name": "id", "baseName": "id", "type": "string", "format": "uuid" }, { "name": "createdAt", "baseName": "createdAt", "type": "Date", "format": "date-time" }, { "name": "name", "baseName": "name", "type": "string", "format": "" }, { "name": "emailAddress", "baseName": "emailAddress", "type": "string", "format": "" }, { "name": "favourite", "baseName": "favourite", "type": "boolean", "format": "" }, { "name": "tags", "baseName": "tags", "type": "Array<string>", "format": "" }, { "name": "teamAccess", "baseName": "teamAccess", "type": "boolean", "format": "" }, { "name": "inboxType", "baseName": "inboxType", "type": "OrganizationInboxProjectionInboxTypeEnum", "format": "" }, { "name": "readOnly", "baseName": "readOnly", "type": "boolean", "format": "" } ]; static getAttributeTypeMap() { return OrganizationInboxProjection.attributeTypeMap; } public constructor() { } } export type OrganizationInboxProjectionInboxTypeEnum = "HTTP_INBOX" | "SMTP_INBOX" ;
package org.queasy.core.network; import com.google.common.base.Preconditions; import com.google.common.base.Splitter; import java.util.Iterator; import java.util.List; /** * @author saroskar * Created on: 2021-03-24 */ public enum Command { DEQUEUE; private final String cmd; private static final Splitter splitter = Splitter.on(" ").trimResults().omitEmptyStrings(); Command() { cmd = "#" + name(); } public boolean matches(final String cmd) { return (cmd != null && cmd.startsWith(this.cmd)); } public Iterator<String> parse(final String mesg) { Iterator<String> iter = splitter.split(mesg).iterator(); Preconditions.checkArgument(iter.hasNext(), mesg); Preconditions.checkArgument(cmd.equals(iter.next()), mesg); // Advance past command name part return iter; } public Long nextArgAsLong(Iterator<String> parsedCmd) { return parsedCmd.hasNext() ? Long.valueOf(parsedCmd.next()) : null; } public Integer nextArgAsInt(Iterator<String> parsedCmd) { return parsedCmd.hasNext() ? Integer.valueOf(parsedCmd.next()) : null; } public Boolean nextArgAsBoolean(Iterator<String> parsedCmd) { return parsedCmd.hasNext() ? Boolean.valueOf(parsedCmd.next()) : null; } public String nextArgAsString(Iterator<String> parsedCmd) { return parsedCmd.hasNext() ? parsedCmd.next() : null; } @Override public String toString() { return cmd; } }
#!/usr/bin/env bash source activate vqa CUDA_VISIBLE_DEVICES=0 python -u test_net.py \ --dataset CLEVR \ --net res101 \ --checksession 1 \ --checkepoch 11 \ --checkpoint 34999 \ --cuda \ --load_dir /hdd/robik/FasterRCNN/models \ --num_images 1000 # Takes 1115 MB GPU mem
#!/bin/bash -xe ## on master branch: analyzes all cpp files ## on other branches: analyzes cpp files changed in this branch, in comparison to master function get_abs_path(){ echo $(echo "$(cd "$(dirname "$1")"; pwd -P)/$(basename "$1")") } function get_files(){ local head=$(git rev-parse --abbrev-ref HEAD) if [[ "${head}" = "master" ]]; then echo $(find . -type f | grep "cpp") else echo $(git diff --name-only HEAD..origin/master | grep "cpp" | grep -v "test") fi } BUILD_DIR=$(get_abs_path $1) cd $(dirname $0)/.. # list of cpp files changed in this branch (in comparison to master); tests are ignored FILES=$(get_files) CLANG_TIDY=$(which clang-tidy) RUN_CLANG_TIDY=$(which run-clang-tidy.py) # filter compile_commands.json echo ${FILES} | python3 ./housekeeping/filter_compile_commands.py -p ${BUILD_DIR} # exec run-clang-tidy.py python3 ${RUN_CLANG_TIDY} -clang-tidy-binary=${CLANG_TIDY} -p ${BUILD_DIR} -header-filter "core/.*\.hpp"
#!/usr/bin/env bash # Load the environment variables for the dev containers ACE2_ENV_PATH="$HOME/.ace2.env" set -a source "$ACE2_ENV_PATH" set +a # Start the entire application and then pause until the database is accessible. # NOTE: If you changed the mapped port for the "db" service in the docker-compose-dev.yml # file, you will need to update it below in the "while" loop as well. docker-compose up -d while !</dev/tcp/localhost/6666; do sleep 1; done; # Create the database revision docker exec ace2-gui-backend alembic upgrade head
#include <iostream> class Weapon { private: int durability; public: // Constructor to initialize the durability Weapon(int initialDurability) : durability(initialDurability) {} // Method to decrease the durability by 5 units void useWeapon() { if (durability >= 5) { durability -= 5; } else { durability = 0; // Ensure durability does not go below 0 } } // Method to get the current durability int getDurability() { return durability; } }; int main() { // Example usage of the Weapon class Weapon sword(50); // Create a sword with initial durability of 50 std::cout << "Initial durability: " << sword.getDurability() << std::endl; sword.useWeapon(); // Simulate using the sword std::cout << "Durability after use: " << sword.getDurability() << std::endl; sword.useWeapon(); // Simulate using the sword again std::cout << "Durability after another use: " << sword.getDurability() << std::endl; return 0; }
struct Connection { id: u32, nat_addr: ([u8; 4], [u8; 4]), nat_port: (u16, u16), } impl Connection { fn new(id: u32, nat_addr: ([u8; 4], [u8; 4]), nat_port: (u16, u16)) -> Self { Connection { id, nat_addr, nat_port, } } fn update_nat_addr(&mut self, new_addr: ([u8; 4], [u8; 4])) { self.nat_addr = new_addr; } fn update_nat_port(&mut self, new_port: (u16, u16)) { self.nat_port = new_port; } fn delete(&mut self) { // Perform any necessary cleanup or resource release for the connection // For example, releasing allocated memory or closing network connections // This method can be customized based on the specific requirements of the system } } impl Default for Connection { fn default() -> Self { Connection { id: 0, nat_addr: ([0; 4], [0; 4]), nat_port: (0, 0), } } } fn main() { // Example usage let mut connection = Connection::default(); println!("Default Connection: {:?}", connection); connection.update_nat_addr(([192, 168, 0, 1], [255, 255, 255, 0])); connection.update_nat_port((8000, 9000)); println!("Updated Connection: {:?}", connection); connection.delete(); // At this point, the connection is deleted and any associated resources are released }
#!/bin/bash set -e example_name="cifar10_fast" # The training arguments # 1. Usually we set the epochs:2, batch_size:2, max_train_steps_per_epoch:10 # 2. The expression for the above setup is "-p epochs 2 -p batch_size 8 -p max_train_steps_per_epoch 10" # 3. The arguement will re-declare the variable right after the jupyter notebook cell with "parameters" tag (there \ # must be one and only cell with "parameters" tag) train_info="-p epochs 2 -p batch_size 8 -p max_train_steps_per_epoch 10 -p max_eval_steps_per_epoch 10" # ============================================================================================== full_path=$(realpath $0) dir_path=$(dirname $full_path) source_dir="${dir_path/'test/apphub_scripts'/'apphub'}" stderr_file="${dir_path}/run_nb_stderr.txt" nb_out="${dir_path}/${example_name}_out.ipynb" nb_in="${source_dir}/${example_name}.ipynb" papermill $nb_in $nb_out $train_info $@ -k nightly_build 2> $stderr_file
<reponame>viniarck/fluxory package ofp import ( "encoding/binary" "errors" ) type ErrorMsg struct { Header Type uint16 Code uint16 Data uint8 } func NewErrorMsg(version uint8, xid uint32, errType uint16, code uint16, data uint8) *ErrorMsg { m := new(ErrorMsg) m.Header = Header{version, OFPT_ERROR, m.Size(), xid} m.Type = errType m.Code = code m.Data = data return m } func (m *ErrorMsg) Encode() []byte { data := make([]byte, m.Size()) hLen := m.Header.Size() copy(data[:hLen], m.Header.Encode()) binary.BigEndian.PutUint16(data[hLen:10], m.Type) binary.BigEndian.PutUint16(data[10:12], m.Code) data[12] = m.Data return data } func (m *ErrorMsg) Decode(data []byte) error { if uint16(len(data)) < m.Size() { return errors.New("bad minimum length size " + string(m.Size())) } err := m.Header.Decode(data[:m.Header.Size()]) if err != nil { return err } hLen := m.Header.Size() m.Type = binary.BigEndian.Uint16(data[hLen:10]) m.Code = binary.BigEndian.Uint16(data[10:12]) m.Data = data[12] return nil } func (m *ErrorMsg) Size() uint16 { return uint16(binary.Size(m)) }
#!/usr/bin/env bash # Start all Yosemite daemons. # Run this on the master nde bin=`dirname "$0"` bin=`cd "$bin"; pwd` # Load the Varys configuration . "$bin/Yosemite-config.sh" # Stop the slaves, then the master "$bin"/stop-slaves.sh "$bin"/stop-master.sh
var webpack = require('webpack'); var path = require('path'); const ExtractTextPlugin = require("extract-text-webpack-plugin"); module.exports = { devtool: 'inline-source-map', entry: [ './resources/assets/js/index.jsx' ], output: { path: "./public/build", publicPath: "http://localhost:5995/_assets/", filename: "bundle.js" }, resolve: { root: path.join(__dirname, './resources/assets/js'), modulesDirectories: ["node_modules"], extensions: ["", ".web.js", ".js", ".jsx", '.css', '.less', '.json'], }, module: { loaders: [ { test: /\.jsx?$/, exclude: /(node_modules|bower_components)/, loader: "babel", }, { test: /\.js?$/, exclude: /(node_modules|bower_components)/, loader: "babel", }, { test: /\.css$/, loader: 'style!css' }, { test: /\.(png|woff|woff2|eot|ttf|svg)$/, loader: 'url-loader?limit=100000' } ] }, plugins:[ new webpack.DefinePlugin({ 'process.env':{ 'NODE_ENV': JSON.stringify('production') } }), new webpack.optimize.UglifyJsPlugin({ compress:{ warnings: false } }), new webpack.HotModuleReplacementPlugin(), new webpack.NoErrorsPlugin() ] };
#!/bin/bash source local.config VBOX_OSTYPE="Windows10_64" VBOX_NAME="$CORP Windows 10" VBOX_NAME_ALPHANUMERIC="acmewin2012" VBOX_ISO="${HOME}/Downloads/ISO/18362.30.190401-1528.19h1_release_svc_refresh_CLIENTENTERPRISEEVAL_OEMRET_x64FRE_en-us.iso" VBOX_NIC_MACADDRESS=0800272389CC VBOX_MEMORY=1024 VBoxManage createvm --name "${VBOX_NAME}" --ostype ${VBOX_OSTYPE} --register VBoxManage createmedium --filename "${VBOX_DIR}/${VBOX_NAME}/${VBOX_NAME_ALPHANUMERIC}.vdi" --size 20240 VBoxManage storagectl "${VBOX_NAME}" --name SATA --add SATA --controller IntelAhci VBoxManage storageattach "${VBOX_NAME}" --storagectl SATA --port 0 --device 0 --type hdd --medium "${VBOX_DIR}/${VBOX_NAME}/${VBOX_NAME_ALPHANUMERIC}.vdi" VBoxManage storagectl "${VBOX_NAME}" --name IDE --add ide VBoxManage storageattach "${VBOX_NAME}" --storagectl IDE --port 0 --device 0 --type dvddrive --medium "${VBOX_ISO}" VBoxManage modifyvm "${VBOX_NAME}" --memory ${VBOX_MEMORY} --vram ${VBOX_VRAM} VBoxManage modifyvm "${VBOX_NAME}" --ioapic on VBoxManage modifyvm "${VBOX_NAME}" --boot1 dvd --boot2 disk --boot3 none --boot4 none VBoxManage modifyvm "${VBOX_NAME}" --cpus 2 VBoxManage modifyvm "${VBOX_NAME}" --audio none VBoxManage modifyvm "${VBOX_NAME}" --nic1 intnet VBoxManage modifyvm "${VBOX_NAME}" --macaddress1 ${VBOX_NIC_MACADDRESS}
<reponame>NYCMOTI/open-bid require "rails_helper" describe WebAuthenticator, type: :model do let(:session) { { user_id: user.id } } let(:controller) { double('controller', session: session) } let(:authenticator) { WebAuthenticator.new(controller) } describe 'require_authentication' do context 'when no current user' do let(:session) { { } } it 'raises a RedirectToLogin error' do expect do authenticator.require_authentication end.to raise_error(UnauthorizedError::RedirectToLogin) end end context 'when user_id is not found in the database' do let(:session) { { user_id: 99_999_999 } } it 'raises a RedirectToLogin error' do expect do authenticator.require_authentication end.to raise_error(UnauthorizedError::RedirectToLogin) end end context 'when the user is logged in' do let(:user) { FactoryGirl.create(:user) } it 'should not raise an error' do expect { authenticator.require_authentication }.to_not raise_error end end end describe 'require_admin' do context 'when current user is a guest' do let(:session) { { } } it 'redirects to authenticate' do expect do authenticator.require_admin end.to raise_error(UnauthorizedError::RedirectToLogin) end end context 'when current user is not an admin' do let(:user) { FactoryGirl.create(:user) } it 'raises an authorization error' do expect { authenticator.require_admin }.to raise_error(UnauthorizedError::MustBeAdmin) end end context 'when current user is an admin' do let(:user) { FactoryGirl.create(:admin_user) } it 'does not raise an error' do expect { authenticator.require_admin }.not_to raise_error end end end end
/* * @Description: Created By Pony * @Author: Pony * @Date: 2021-08-09 21:07:23 * @LastEditors: Pony * @LastEditTime: 2021-08-09 21:07:36 */ import { Button, Result } from 'antd'; import React from 'react'; import { history } from 'umi'; const NoFoundPage: React.FC<{}> = () => ( <Result status="404" title="404" style={{ width: '100%' }} subTitle="ๆญค้กต้ขๆœชๆ‰พๅˆฐ" extra={ <Button type="primary" onClick={() => history.push('/')}> ่ฟ”ๅ›žไธป้กต </Button> } /> ); export default NoFoundPage;
#!/bin/bash NEXUS_USERNAME=$(cat /opt/config/nexus_username.txt) NEXUS_PASSWD=$(cat /opt/config/nexus_password.txt) NEXUS_DOCKER_REPO=$(cat /opt/config/nexus_docker_repo.txt) DOCKER_IMAGE_VERSION=$(cat /opt/config/docker_version.txt) cd /opt/vid git pull cd /opt docker pull mariadb:10 docker login -u $NEXUS_USERNAME -p $NEXUS_PASSWD $NEXUS_DOCKER_REPO docker pull $NEXUS_DOCKER_REPO/openecomp/vid:$DOCKER_IMAGE_VERSION docker rm -f vid-mariadb docker rm -f vid-server docker run --name vid-mariadb -e MYSQL_DATABASE=vid_openecomp_epsdk -e MYSQL_USER=vidadmin -e MYSQL_PASSWORD=Kp8bJ4SXszM0WXlhak3eHlcse2gAw84vaoGGmJvUy2U -e MYSQL_ROOT_PASSWORD=LF+tp_1WqgSY -v /opt/vid/lf_config/vid-my.cnf:/etc/mysql/my.cnf -v /opt/vid/lf_config/vid-pre-init.sql:/docker-entrypoint-initdb.d/vid-pre-init.sql -v /var/lib/mysql -d mariadb:10 docker run -e VID_MYSQL_DBNAME=vid_openecomp_epsdk -e VID_MYSQL_PASS=Kp8bJ4SXszM0WXlhak3eHlcse2gAw84vaoGGmJvUy2U --name vid-server -p 8080:8080 --link vid-mariadb:vid-mariadb-docker-instance -d $NEXUS_DOCKER_REPO/openecomp/vid:$DOCKER_IMAGE_VERSION
#!/bin/bash #SBATCH --nodes=1 #SBATCH --ntasks=4 #SBATCH --ntasks-per-node=4 #SBATCH --cpus-per-task=24 #SBATCH --output=./output/sh3d-%j.out #SBATCH --error=./output/sh3d-%j.err #SBATCH --time=23:00:00 #SBATCH --partition=dc-gpu #SBATCH --gres=gpu:4 #SBATCH --account=delia-mp # export HOROVOD_MPI_THREADS_DISABLE=0 # source /p/home/jusers/cherepashkin1/jureca/cherepashkin1/virt_enves/venv1/activate.sh # # make sure all GPUs on a node are visible # export HOROVOD_MPI_THREADS_DISABLE=0 # export CUDA_VISIBLE_DEVICES="0,1,2,3" # SCRIPT_DIR=$( cd -- "$( dirname -- "${BASH_SOURCE[0]}" )" &> /dev/null && pwd ) # srun --cpu-bind=none,v --accel-bind=gn python -u "../../main.py" -datapath "C:/cherepashkin1/phenoseed/" -realjobname `basename "$0"` -jobname `basename "$0"` -jobdir "$SCRIPT_DIR" -expnum "e074" -epoch 2 -bs 5 -num_input_images 3 -framelim 60 -criterion "L2" -rmdirname -lr 5e-5 -hidden_dim 32 9 -inputt "img" -outputt "orient" -lb "orient" -no_loadh5 -minmax_fn "" -parallel "torch" -machine "lenovo" -merging "batch" -aug_gt "vector_sign_flip" "vector_permute" "svd" -updateFraction 0.25 -steplr 1000 1 -print_minibatch 10 -dfname "598frame"
import {ActionContext} from "./ControllerAttributes"; import {injectable} from "inversify"; /** * A basic controller class to be used with express */ @injectable() export default class Controller { public basePath: string = ""; public getBaseUrl(context: ActionContext, siteroot: string = "/"): string { // Get all the parts let host: string = context.request.hostname; let port: number = context.request.socket.localPort; let protocol: string = (context.request.secure) ? "https" : "http"; // Correct the siteroot siteroot = (siteroot[0] === "/") ? siteroot : `/${siteroot}`; return `${protocol}://${host}:` + `${port}${siteroot}/${this.basePath}`.replace("//", "/"); } }
package core.identifier.identifiers.statements; import core.Block; import core.identifier.Identifier; import core.identifier.IdentifierType; import tokenizer.Token; import java.util.ArrayList; /** * Created by zvekete on 7.1.2017.. */ public class Null extends Identifier<Null> { public Null() { super("null", IdentifierType.STATEMENT); } @Override protected Null execute(Block executeBlock, ArrayList<Token> tokens) { return null; } }
from django.db.models import Manager, QuerySet from django.db.models.expressions import RawSQL from .constants import NONCONNECTABLE_IFACE_TYPES # Regular expressions for parsing Interface names TYPE_RE = r"SUBSTRING({} FROM '^([^0-9\.:]+)')" SLOT_RE = r"COALESCE(CAST(SUBSTRING({} FROM '^(?:[^0-9]+)?(\d{{1,9}})/') AS integer), NULL)" SUBSLOT_RE = r"COALESCE(CAST(SUBSTRING({} FROM '^(?:[^0-9\.:]+)?\d{{1,9}}/(\d{{1,9}})') AS integer), NULL)" POSITION_RE = r"COALESCE(CAST(SUBSTRING({} FROM '^(?:[^0-9]+)?(?:\d{{1,9}}/){{2}}(\d{{1,9}})') AS integer), NULL)" SUBPOSITION_RE = r"COALESCE(CAST(SUBSTRING({} FROM '^(?:[^0-9]+)?(?:\d{{1,9}}/){{3}}(\d{{1,9}})') AS integer), NULL)" ID_RE = r"CAST(SUBSTRING({} FROM '^(?:[^0-9\.:]+)?(\d{{1,9}})([^/]|$)') AS integer)" CHANNEL_RE = r"COALESCE(CAST(SUBSTRING({} FROM '^.*:(\d{{1,9}})(\.\d{{1,9}})?$') AS integer), 0)" VC_RE = r"COALESCE(CAST(SUBSTRING({} FROM '^.*\.(\d{{1,9}})$') AS integer), 0)" class InterfaceQuerySet(QuerySet): def connectable(self): """ Return only physical interfaces which are capable of being connected to other interfaces (i.e. not virtual or wireless). """ return self.exclude(form_factor__in=NONCONNECTABLE_IFACE_TYPES) class InterfaceManager(Manager): def get_queryset(self): """ Naturally order interfaces by their type and numeric position. To order interfaces naturally, the `name` field is split into eight distinct components: leading text (type), slot, subslot, position, subposition, ID, channel, and virtual circuit: {type}{slot or ID}/{subslot}/{position}/{subposition}:{channel}.{vc} Components absent from the interface name are coalesced to zero or null. For example, an interface named GigabitEthernet1/2/3 would be parsed as follows: type = 'GigabitEthernet' slot = 1 subslot = 2 position = 3 subposition = None id = None channel = 0 vc = 0 The original `name` field is considered in its entirety to serve as a fallback in the event interfaces do not match any of the prescribed fields. The `id` field is included to enforce deterministic ordering of interfaces in similar vein of other device components. """ sql_col = '{}.name'.format(self.model._meta.db_table) ordering = [ '_slot', '_subslot', '_position', '_subposition', '_type', '_id', '_channel', '_vc', 'name', 'pk' ] fields = { '_type': RawSQL(TYPE_RE.format(sql_col), []), '_id': RawSQL(ID_RE.format(sql_col), []), '_slot': RawSQL(SLOT_RE.format(sql_col), []), '_subslot': RawSQL(SUBSLOT_RE.format(sql_col), []), '_position': RawSQL(POSITION_RE.format(sql_col), []), '_subposition': RawSQL(SUBPOSITION_RE.format(sql_col), []), '_channel': RawSQL(CHANNEL_RE.format(sql_col), []), '_vc': RawSQL(VC_RE.format(sql_col), []), } return InterfaceQuerySet(self.model, using=self._db).annotate(**fields).order_by(*ordering)
def calculate_total_cost(base_price, discount_type, discount_value, shipping_cost): if discount_type == "percentage": discounted_price = base_price - (base_price * (discount_value / 100)) elif discount_type == "fixed": discounted_price = base_price - discount_value else: raise ValueError("Invalid discount type") total_cost = discounted_price + shipping_cost return total_cost
<gh_stars>0 package com.tactbug.ddd.common.avro; import com.tactbug.ddd.common.avro.product.CategoryCreatedAvro; import com.tactbug.ddd.common.exceptions.TactException; import org.apache.avro.io.DatumReader; import org.apache.avro.io.Decoder; import org.apache.avro.io.DecoderFactory; import org.apache.avro.specific.SpecificDatumReader; import java.io.IOException; import java.util.Arrays; public class AvroDeSerialize { public static CategoryCreatedAvro categoryCreatedAvro(String data){ DatumReader<CategoryCreatedAvro> reader = new SpecificDatumReader<>(CategoryCreatedAvro.class); Decoder decoder; try { decoder = DecoderFactory.get().jsonDecoder( CategoryCreatedAvro.getClassSchema(), data); return reader.read(null, decoder); } catch (IOException e) { throw TactException.serializeOperateError("[" + data + "]ๅๅบๅˆ—ๅŒ–ๅคฑ่ดฅ", e); } } }
#!/bin/bash clear; echo '################################################################################' if [ "$#" -eq "0" ] then git --no-pager log --graph --all --color --pretty=format:"%C(auto)%H %C(auto)%d (%C(magenta)%an%Creset - %cr):%Cgreen'%s'%Creset" --date=relative -35; else git --no-pager log --graph --all --color --pretty=format:"%C(auto)%H %C(auto)%d (%C(magenta)%an%Creset - %cr):%Cgreen'%s'%Creset" --date=relative -$1; fi
<gh_stars>0 import torch import torch.nn as nn import torch.nn.functional as F from torch.nn.parameter import Parameter from torch_geometric.nn.inits import glorot from layers import GraphAttentionLayer, SpGraphAttentionLayer, NMF_Nodes, AltGraphAttentionLayer from torch_geometric.nn.models import InnerProductDecoder from torch_geometric.utils.loop import remove_self_loops, add_self_loops from torch_geometric.utils import negative_sampling import math # def initH(topic_s, topic_e, input_feature): # H_list = [] # for i in range(topic_s, topic_e + 1): # H_list.append(torch.zeros(size=(input_feature, topic_e, 1))) # H is transposed # H_list[i - topic_s][:, i:] = 0 # # TODO ensure the positive H # H_list[i - topic_s] = torch.abs(H_list[i - topic_s]) # # H_list = torch.cat([H for H in H_list], 2).cuda() # return H_list def recon_loss(z, pos_edge_index, neg_edge_index=None): r"""Given latent variables :obj:`z`, computes the binary cross entropy loss for positive edges :obj:`pos_edge_index` and negative sampled edges. Args: z (Tensor): The latent space :math:`\mathbf{Z}`. pos_edge_index (LongTensor): The positive edges to train against. neg_edge_index (LongTensor, optional): The negative edges to train against. If not given, uses negative sampling to calculate negative edges. (default: :obj:`None`) """ EPS = 1e-15 decoder = InnerProductDecoder() pos_loss = -torch.log( decoder(z, pos_edge_index, sigmoid=True) + EPS).mean() # Do not include self-loops in negative samples pos_edge_index, _ = remove_self_loops(pos_edge_index) pos_edge_index, _ = add_self_loops(pos_edge_index) if neg_edge_index is None: neg_edge_index = negative_sampling(pos_edge_index, z.size(0)) neg_loss = -torch.log(1 - decoder(z, neg_edge_index, sigmoid=True) + EPS).mean() return pos_loss + neg_loss class GAT(nn.Module): def __init__(self, nfeat, nhid, nclass, dropout, nheads, use_nmf=False): """Dense version of GAT.""" super(GAT, self).__init__() self.dropout = dropout self.use_nmf = use_nmf self.attentions = [GraphAttentionLayer(nfeat, nhid, dropout=dropout, concat=True) for _ in range(nheads)] for i, attention in enumerate(self.attentions): self.add_module('attention_{}'.format(i), attention) n_out_att_infeat = nhid * nheads if use_nmf: # H_list = initH(topic_s=500, topic_e=510, input_feature=nhid * nheads) self.nmf = NMF_Nodes(input_feature=nhid * nheads, topic_s=20, topic_e=25) n_out_att_infeat = nhid * nheads * 2 self.out_att = GraphAttentionLayer( n_out_att_infeat, nclass, dropout=dropout, concat=False) def forward(self, x, adj): x = F.dropout(x, self.dropout, training=self.training) x = torch.cat([att(x, adj) for att in self.attentions], dim=1) x = F.dropout(x, self.dropout, training=self.training) if self.use_nmf: # X_nmf = x.detach().clone() # x, W_nmf, H_nmf = self.NMFs(X_nmf) # detach here to cut off the BP to other layers! x, hyper = self.nmf(x) # hypergraph # x = self.nmf(x) # default adj = adj - hyper # hypergraph else: X_nmf = None W_nmf = None H_nmf = None # x = F.elu(self.out_att(x, adj)) # x = F.log_softmax(x, dim=1) return x class GATConv(nn.Module): def __init__(self, nfeat, nhid, nclass, dropout, nheads): """Dense version of GAT.""" super(GAT, self).__init__() self.dropout = dropout self.nfeat = nfeat self.nhid = nhid self.nclass = nclass self.nheads = nheads self.linear = nn.Linear(nfeat, nhid * nheads) # W self.att_l = nn.Parameter(torch.Tensor(1, nheads, nclass)) self.att_r = nn.Parameter(torch.Tensor(1, nheads, nclass)) glorot(self.linear.weight) glorot(self.att_l.weight) glorot(self.att_r.weight) # for i, attention in enumerate(self.attentions): # self.add_module('attention_{}'.format(i), attention) # n_out_att_infeat = nhid * nheads # self.out_att = GraphAttentionLayer(n_out_att_infeat, nclass, dropout=dropout, concat=False) def glorot(tensor): if tensor is not None: stdv = math.sqrt(6.0 / (tensor.size(-2) + tensor.size(-1))) tensor.data.uniform_(-stdv, stdv) def forward(self, x, adj): N = adj.shape[0] # change: no initial dropout x_l = x_r = self.linear(x).view(-1, self.nheads, self.nclass) alpha_l = (x_l * self.att_l).sum(dim=-1) # n_node * n_head alpha_r = (x_r * self.att_r).sum(dim=-1) # dist matrix is the outer product of the alpha att_mat = torch.bmm(alpha_l.t().unsqueeze( 2), alpha_r.t().unsqueeze(1)).permute(1, 2, 0) # n_node(l) * n_node(r) * n_head zero_vec = -9e15 * torch.ones_like(att_mat) att_mat = torch.where(torch.stack( [adj for _ in range(self.nheads)]) > 0, att_mat, zero_vec) # mask the inconnected nodes att_mat = F.softmax(att_mat, dim=1) att_mat = F.dropout(att_mat, self.dropout, training=self.training) # x = F.dropout(x, self.dropout, training=self.training) x = F.relu() return x # class MFGAT(nn.Module): # def __init__(self, nfeat, nhid, nclass, dropout, alpha, nheads): # """Dense version of GAT.""" # super(MFGAT, self).__init__() # print('MF', nhid) # self.dropout = dropout # self.attentions = [MFGraphAttentionLayer(nfeat, nhid, dropout=dropout, alpha=alpha, concat=True) for _ in # range(nheads)] # for i, attention in enumerate(self.attentions): # self.add_module('attention_{}'.format(i), attention) # self.out_att = MFGraphAttentionLayer(nhid * nheads, nclass, dropout=dropout, alpha=alpha, concat=False) # self.H = nn.Parameter(torch.zeros(size=(nhid, nclass))) # nn.init.xavier_uniform_(self.H.data, gain=1.414) # def forward(self, x, adj): # x = F.dropout(x, self.dropout, training=self.training) # x = torch.cat([att(x, adj) for att in self.attentions], dim=1) # x = F.dropout(x, self.dropout, training=self.training) # # add multi-head attention # print('x',x.shape) # x = F.elu(self.out_att(x, adj)) # print('out',x.shape) # self.H=nn.Parameter(x) # return F.log_softmax(x, dim=1) class AltGAT(nn.Module): def __init__(self, nfeat, nhid, nclass, dropout, nheads): """Dense version of GAT.""" super(AltGAT, self).__init__() self.dropout = dropout self.attention = AltGraphAttentionLayer( nfeat, nclass * nheads, dropout=dropout, concat=True) # self.attentions = [GraphAttentionLayer(nfeat, nhid, dropout=dropout, concat=True) for _ in # range(nheads)] # for i, attention in enumerate(self.attentions): # self.add_module('attention_{}'.format(i), attention) n_out_att_infeat = nclass * nheads self.out_att = AltGraphAttentionLayer( n_out_att_infeat, nclass, dropout=dropout, concat=False) self.bias = Parameter(torch.Tensor(n_out_att_infeat)) # glorot(self.attention.weight) def glorot(tensor): if tensor is not None: stdv = math.sqrt(6.0 / (tensor.size(-2) + tensor.size(-1))) tensor.data.uniform_(-stdv, stdv) def zeros(tensor): if tensor is not None: tensor.data.fill_(0) def forward(self, x, adj): # x = F.dropout(x, self.dropout, training=self.training) x = self.attention(x, adj) x = F.dropout(x, self.dropout, training=self.training) x = self.out_att(x, adj) return x class SpGAT(nn.Module): def __init__(self, nfeat, nhid, nclass, dropout, alpha, nheads): """Sparse version of GAT.""" super(SpGAT, self).__init__() self.dropout = dropout self.attentions = [SpGraphAttentionLayer(nfeat, nhid, dropout=dropout, alpha=alpha, concat=True) for _ in range(nheads)] for i, attention in enumerate(self.attentions): self.add_module('attention_{}'.format(i), attention) self.out_att = SpGraphAttentionLayer(nhid * nheads, nclass, dropout=dropout, alpha=alpha, concat=False) def forward(self, x, adj): x = F.dropout(x, self.dropout, training=self.training) x = torch.cat([att(x, adj) for att in self.attentions], dim=1) x = F.dropout(x, self.dropout, training=self.training) x = F.elu(self.out_att(x, adj)) return F.log_softmax(x, dim=1)
#!/usr/bin/env bash #Config sshConfigFile=~/.ssh/config WorkFolder=~/my_server RemoteDir=~/ sshname=myremoteserver #Functions: function helpme { echo "how to:" echo "keyfile - file with the ssh key" echo "workdir - directory, where we gonna mount the drive" echo "sshname - name of your part of ssh config. Like Host '$sshname'" echo "sshuser - user for ssh connection" echo "sshconfig - ssh config file. Devault value is ~/.ssh/config" echo "remotedir - directory on the remote server" echo "host - IP address or FQDN" echo "help - print the page" echo "Example:" echo "$0 keyfile=/tmp/secret.pem host=my.secret.server.ie remotedir=/tmp sshconfig=~/.ssh/config sshuser=secretuser" exit 0 } function check_paremeters { if [ ! -z "$keyfile" ] || [ ! -z "$sshuser" ] ||[ ! -z "$sshHostName" ] then echo "some of mandatory parameters not added" echo "If the server already in ssh config - use the 'sshname=' " echo "if the server isn't known - use 'keyfile=', 'sshuser' and 'sshHostName'" helpme exit 1 fi } function check_WorkFolder { if [ ! -d "$WorkFolder" ] then echo "mkdir $WorkFolder" echo "Created $WorkFolder" else echo "Process with $WorkFolder" fi } function modify_ssh_config { echo "Host $sshname" >> $sshConfigFile echo " user $sshuser" >> $sshConfigFile echo " HostName $sshHostName" >> $sshConfigFile echo " IdentityFile $keyfile" >> $sshConfigFile } function check_keyfile { touch $sshConfigFile if (( $(cat $sshConfigFile | grep -c "$sshname") < 1 )) then check_paremeters modify_ssh_config fi } function check_sshfs { if [ ! $(command -v sshfs) ] then if [ ! $(command -v brew) ] then echo "Oh, no, you have no installed sshfs, osxfuse and Homebrew" echo "Installing brew:" /bin/bash -c "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/HEAD/install.sh)" fi brew cask install osxfuse && brew install sshfs fi echo "process with: " echo "sshfs -F $sshConfigFile $sshname:$RemoteDir $WorkFolder -ovolname=$sshname" } #ArgParse for ARGUMENT in "$@" do KEY=$(echo $ARGUMENT | cut -f1 -d=) VALUE=$(echo $ARGUMENT | cut -f2 -d=) case "$KEY" in keyfile) keyfile=${VALUE} ;; workdir) WorkFolder=${VALUE} ;; sshname) sshname=${VALUE} ;; sshuser) sshuser=${VALUE} ;; sshconfig) sshConfigFile=${VALUE} ;; remotedir) RemoteDir=${VALUE} ;; host) sshHostName=${VALUE} ;; help) helpme ;; *) esac done #Main: check_WorkFolder if [ ! -z "$keyfile" ] then echo "go with $keyfile" if [ ! -f "$keyfile" ] then echo "the keyfile does't exit" exit 1 fi else check_keyfile fi check_sshfs sshfs -F $sshConfigFile $sshname:$RemoteDir $WorkFolder -ovolname=$sshname open $WorkFolder
<reponame>pillieshwar/SaleStat package com.javatechie.spring.orm.api.controller; import java.util.List; import javax.servlet.http.HttpServletRequest; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.servlet.ModelAndView; import com.javatechie.spring.orm.api.dao.AdminDao; import com.javatechie.spring.orm.api.dao.DashboardDao; import com.javatechie.spring.orm.api.dao.DoctorDao; import com.javatechie.spring.orm.api.dao.StateDao; import com.javatechie.spring.orm.api.dto.GetSidebarAllDoctorsDto; import com.javatechie.spring.orm.api.model.medicine; import com.javatechie.spring.orm.api.model.state; @Controller public class SidebarController { @Autowired private StateDao stateDao; @Autowired private DoctorDao doctorDao; @Autowired private DashboardDao dashboardDao; @Autowired private AdminDao adminDao; @RequestMapping("/medicine") public String medicine(Model model, HttpServletRequest request) { int int_state_sessionid = (Integer) request.getSession().getAttribute("int_state_sessionid"); List<state> stateDropdownList = dashboardDao.stateDropdown1(int_state_sessionid); model.addAttribute("stateDropdownList", stateDropdownList); List<medicine> medicineList = adminDao.getMedicineList(); model.addAttribute("medicineList", medicineList); return "medicine"; } @RequestMapping("/all_doctors") public ModelAndView allDoctors(Model model, HttpServletRequest request) { List<state> stateList = stateDao.getStateList(); model.addAttribute("stateList", stateList); int int_state_sessionid = (Integer) request.getSession().getAttribute("int_state_sessionid"); List<state> stateDropdownList = dashboardDao.stateDropdown1(int_state_sessionid); model.addAttribute("stateDropdownList", stateDropdownList); List<GetSidebarAllDoctorsDto> sidebarAllDoctorsList = doctorDao.getSidebarAllDoctorsList(); model.addAttribute("sidebarAllDoctorsLists", sidebarAllDoctorsList); return new ModelAndView("all_doctors"); } }
<reponame>salesforce/DataHardness import numpy as np import LinConGauss as lcg import argparse import torch from scipy.linalg import sqrtm class GaussianBayes: def __init__(self, means, cov, marginals=None): self.means = means self.cov = cov self.cov_inv = np.linalg.inv(self.cov) self.K = len(means) if marginals is None: self.marginals = np.array([1./self.K]*self.K) def _integrate(self, A, b, n_samples=2000): lincon = lcg.LinearConstraints(A=A, b=b) subsetsim = lcg.multilevel_splitting.SubsetSimulation(linear_constraints=lincon, n_samples=100, domain_fraction=0.5, n_skip=3) subsetsim.run(verbose=False) shifts = subsetsim.tracker.shift_sequence hdr = lcg.multilevel_splitting.HDR(linear_constraints=lincon, shift_sequence=shifts, n_samples=n_samples, n_skip=9, X_init=subsetsim.tracker.x_inits()) hdr.run(verbose=False) hdr_integral = hdr.tracker.integral() return hdr_integral def _form_constraints(self, k): not_k_ix = [i for i in range(self.K) if i != k] mu_k = self.means[k] b = [] A = [] for j in not_k_ix: mu_j = self.means[j] bjk = np.dot(mu_j, np.dot(self.cov_inv, mu_j)) - np.dot(mu_k, np.dot(self.cov_inv, mu_k)) Ajk = 2*(np.dot(self.cov_inv, mu_k) - np.dot(self.cov_inv, mu_j)) bjk += np.dot(Ajk, mu_k) Ajk = np.dot(np.sqrt(self.cov), Ajk) # NOTE: this assumes covariance is diagonal b.append(bjk) A.append(Ajk) return np.array(A), np.array(b).reshape(-1,1) def compute_bayes_error(self, n_samples=5000): E = 0 for k in range(self.K): A, b = self._form_constraints(k) Ek = self._integrate(A=A, b=b, n_samples=n_samples) E += self.marginals[k]*Ek self.bayes_error = 1-E return 1-E class GaussianBayesDiag: def __init__(self, means, cov, marginals=None): self.means = means self.cov = cov self.cov_inv = 1. / self.cov self.K = len(means) if marginals is None: self.marginals = np.array([1./self.K]*self.K) def _integrate(self, A, b, n_samples=2000): lincon = lcg.LinearConstraints(A=A, b=b) subsetsim = lcg.multilevel_splitting.SubsetSimulation(linear_constraints=lincon, n_samples=100, domain_fraction=0.5, n_skip=3) subsetsim.run(verbose=False) shifts = subsetsim.tracker.shift_sequence hdr = lcg.multilevel_splitting.HDR(linear_constraints=lincon, shift_sequence=shifts, n_samples=n_samples, n_skip=9, X_init=subsetsim.tracker.x_inits()) hdr.run(verbose=False) hdr_integral = hdr.tracker.integral() return hdr_integral def _form_constraints(self, k): not_k_ix = [i for i in range(self.K) if i != k] mu_k = self.means[k] b = [] A = [] for j in not_k_ix: mu_j = self.means[j] bjk = np.dot(mu_j, np.multiply(self.cov_inv[:, None], mu_j)) - np.dot(mu_k, np.multiply(self.cov_inv[:, None], mu_k)) Ajk = 2*(np.multiply(self.cov_inv[:, None], mu_k) - np.multiply(self.cov_inv[:, None], mu_j)) bjk += np.dot(Ajk, mu_k) Ajk = np.multiply(np.sqrt(self.cov)[:, None], Ajk) # NOTE: this assumes covariance is diagonal b.append(bjk) A.append(Ajk) return np.array(A), np.array(b).reshape(-1,1) def compute_bayes_error(self, n_samples=5000): E = 0 for k in range(self.K): A, b = self._form_constraints(k) Ek = self._integrate(A=A, b=b, n_samples=n_samples) E += self.marginals[k]*Ek self.bayes_error = 1-E return 1-E class GaussianBayesLight: def __init__(self, means, cov, marginals=None): self.means = means self.cov = cov self.cov_inv = np.linalg.inv(self.cov) self.K = len(means) if marginals is None: self.marginals = np.array([1. / self.K] * self.K) def _integrate(self, A, b, n_samples=2000): lincon = lcg.LinearConstraints(A=A, b=b) subsetsim = lcg.multilevel_splitting.SubsetSimulation(linear_constraints=lincon, n_samples=100, domain_fraction=0.5, n_skip=3) subsetsim.run(verbose=False) shifts = subsetsim.tracker.shift_sequence hdr = lcg.multilevel_splitting.HDR(linear_constraints=lincon, shift_sequence=shifts, n_samples=n_samples, n_skip=9, X_init=subsetsim.tracker.x_inits()) hdr.run(verbose=False) hdr_integral = hdr.tracker.integral() return hdr_integral def _form_constraints(self, k, fast=True, low_mem=False): not_k_ix = [i for i in range(self.K) if i != k] mu_k = self.means[k] if fast: # this is much more memory efficient since we never need to compute the full matrix A, but just the dot products comprising AA^T if low_mem: b = [] AAT = np.empty(shape=(self.K - 1, self.K - 1)) jj = 0 for j in not_k_ix: mu_j = self.means[j] bjk = np.dot(mu_j, np.dot(self.cov_inv, mu_j)) - np.dot(mu_k, np.dot(self.cov_inv, mu_k)) Ajk = 2 * (np.dot(self.cov_inv, mu_k) - np.dot(self.cov_inv, mu_j)) bjk += np.dot(Ajk, mu_k) Ajk = np.dot(np.sqrt(self.cov), Ajk) # NOTE: this assumes covariance is diagonal b.append(bjk) ii = 0 for i in not_k_ix[:j]: mu_i = self.means[i] Aik = 2 * (np.dot(self.cov_inv, mu_k) - np.dot(self.cov_inv, mu_i)) Aik = np.dot(np.sqrt(self.cov), Aik).reshape(-1, 1) # NOTE: this assumes covariance is diagonal Aji = np.dot(Ajk, Aik) AAT[jj, ii] = Aji AAT[ii, jj] = Aji ii += 1 jj += 1 A = sqrtm(AAT) # compute the full matrix A, and then AA^T, uses lots of memory else: b = [] A = [] for j in not_k_ix: mu_j = self.means[j] bjk = np.dot(mu_j, np.dot(self.cov_inv, mu_j)) - np.dot(mu_k, np.dot(self.cov_inv, mu_k)) Ajk = 2 * (np.dot(self.cov_inv, mu_k) - np.dot(self.cov_inv, mu_j)) bjk += np.dot(Ajk, mu_k) Ajk = np.dot(np.sqrt(self.cov), Ajk) # NOTE: this assumes covariance is diagonal b.append(bjk) A.append(Ajk) A = np.array(A) A = sqrtm(A @ A.T) return A, np.array(b).reshape(-1, 1) # this is the original method, which is slow and memory inefficient else: b = [] A = [] for j in not_k_ix: mu_j = self.means[j] bjk = np.dot(mu_j, np.dot(self.cov_inv, mu_j)) - np.dot(mu_k, np.dot(self.cov_inv, mu_k)) Ajk = 2 * (np.dot(self.cov_inv, mu_k) - np.dot(self.cov_inv, mu_j)) bjk += np.dot(Ajk, mu_k) Ajk = np.dot(np.sqrt(self.cov), Ajk) # NOTE: this assumes covariance is diagonal b.append(bjk) A.append(Ajk) return np.array(A), np.array(b).reshape(-1, 1) def compute_bayes_error(self, n_samples=5000, fast=True, low_mem=False): E = 0 for k in range(self.K): A, b = self._form_constraints(k, fast=fast, low_mem=low_mem) # do it the fast way Ek = self._integrate(A, b=b, n_samples=n_samples) E += self.marginals[k] * Ek self.bayes_error = 1 - E return 1 - E if __name__ == '__main__': parser = argparse.ArgumentParser() parser.add_argument( "--model", type=str, default="mnist-ckpts/best.pth.tar", help="the model path you want to compute Bayes error for", ) parser.add_argument("--temperature", type=float, default=1.0, help="temperature used to generate samples") parser.add_argument("--n_samples", type=int, default=60000, help="number of samples to use for LIN-ESS to estimate Bayes error integral") args = parser.parse_args() checkpoint = torch.load(args.model, map_location=torch.device('cpu')) print('evaluating using model trained with ' + str(checkpoint['epoch']) + ' epochs') print('test loss is ' + str(checkpoint['test_loss'])) net = checkpoint['net'] num_class = net['module.means'].shape[0] means, cov = net['module.means'].view(num_class, -1), net['module.cov_diag'].abs().view(-1) * (args.temperature ** 2) gb = GaussianBayes(means=means.data.numpy(), cov=np.diag(cov.data.numpy())) err = gb.compute_bayes_error(n_samples=args.n_samples) print('Bayes Error is %f' % err)
package io.opensphere.geopackage.model; import static org.junit.Assert.assertEquals; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import org.junit.Test; import io.opensphere.core.model.GeographicBoundingBox; import io.opensphere.core.model.GeographicPosition; import io.opensphere.core.model.LatLonAlt; /** * Unit test for the {@link GeoPackageTile} class. */ public class GeoPackageTileTest { /** * Tests serializing and deserializing the class. * * @throws IOException Bad IO. * @throws ClassNotFoundException Bad class. */ @Test public void test() throws IOException, ClassNotFoundException { GeographicPosition lowerLeft = new GeographicPosition(LatLonAlt.createFromDegrees(10, 10)); GeographicPosition upperRight = new GeographicPosition(LatLonAlt.createFromDegrees(11, 11)); GeographicBoundingBox boundingBox = new GeographicBoundingBox(lowerLeft, upperRight); GeoPackageTile expected = new GeoPackageTile("theLayer", 8, boundingBox, 2, 1); ByteArrayOutputStream out = new ByteArrayOutputStream(); ObjectOutputStream objectOut = new ObjectOutputStream(out); objectOut.writeObject(expected); ByteArrayInputStream in = new ByteArrayInputStream(out.toByteArray()); ObjectInputStream objectIn = new ObjectInputStream(in); GeoPackageTile actual = (GeoPackageTile)objectIn.readObject(); assertEquals("theLayer", actual.getLayerId()); assertEquals(8, actual.getZoomLevel()); assertEquals(lowerLeft, actual.getBoundingBox().getLowerLeft()); assertEquals(upperRight, actual.getBoundingBox().getUpperRight()); assertEquals(2, actual.getX()); assertEquals(1, actual.getY()); } }
<reponame>ncufresh/ncufresh14 $(function(){ window.app = {}; dataSection = $('#data-section'); var userId = getTransferData('user-id'); var userName = getTransferData('user-name'); var lastSend = 0; if(userId == undefined){ userId = 0; userName = '้Šๅฎข'; } if("WebSocket" in window){ var path = $('#chat-room').data('chatroom-url'); app.BrainSocket = new BrainSocket( new WebSocket('ws://'+path+':27704'), new BrainSocketPubSub() ); //get data app.BrainSocket.Event.listen('generic.event',function(msg){ displayMessage(msg.client.data.user_name, msg.client.data.message, ''); }); app.BrainSocket.Event.listen('generic.success',function(data){ displayMessage('็ณป็ตฑ', '้€ฃ็ทšๆˆๅŠŸ', 'success'); }); app.BrainSocket.Event.listen('app.error',function(data){ displayMessage('็ณป็ตฑ', '้€ฃ็ทšๅคฑๆ•—', 'error'); }); $('#chat-message').keypress(function(event) { if(event.keyCode == 13){ if($.now() - lastSend >= 10000){ lastSend = $.now(); app.BrainSocket.message('generic.event', { 'message': $(this).val(), 'user_id': userId, 'user_name': userName } ); $(this).val(''); }else{ $.alertMessage('10็ง’ๅช่ƒฝ็™ผ่จ€ไธ€ๆฌกๅ™ข=D', {type: 'alert-warning'}); } } return event.keyCode != 13; }); var isChatroomOpen = false; $('#chat-room-button').click(function() { if ( !isChatroomOpen ) { $('#chat-room').animate({ right: '0px' }); } else { $('#chat-room').animate({ right: '-230px' }); } isChatroomOpen = !isChatroomOpen; }); $('#chat-room-container').mouseover(function(){ if(isChatroomOpen){ $('#chat-room-notification').fadeOut(); } }); function displayMessage(name, message, type){ //0 default 1 success 2 error var spanName = $('<span class="chat-name"></span>').text(name + '๏ผš'); var spanMessage = $('<span class="chat-message"></span>').text(message); var divRow = $('<div class="chat-row"></div>').append(spanName).append(spanMessage); $('#chat-log').append(divRow); $('#chat-log').scrollTop($('#chat-log').height()*2); $('#chat-room-notification').fadeIn(); } }else{ $('#chat-room-button').click(function() { $.alertMessage('ๆƒณ่Šๅคฉ่ซ‹ไฝฟ็”จๆ›ดไฝณ็š„็€่ฆฝๅ™จ', {type: 'alert-warning'}); }); } });
import requests def fetch_detailed_info(attribute): # Simulated function to fetch detailed information for the given attribute from an external source # Replace this with actual API calls or data retrieval logic return f"Detailed information for {attribute}" def expand_product(product): for attribute in PRODUCT_EXPANDABLE: detailed_info = fetch_detailed_info(attribute) product[attribute] = detailed_info return product # Example usage product = { "id": 12345, "name": "Sample Product", "downloads": None, "expanded_dlcs": None, "description": None, "screenshots": None, "videos": None, "related_products": None, "changelog": None } expanded_product = expand_product(product) print(expanded_product)
<reponame>wandering-sage/Node-School const process = require("process"); const http = require("http"); const fs = require("fs"); var port = process.argv[2]; const server = http.createServer(doOnReq); server.listen(port); function doOnReq(req, res) { if (req.method == "POST") { var body = ""; req.on("data", (chunk) => { body += chunk.toString().toUpperCase(); }); req.on("end", () => { res.end(body); }); } }
<gh_stars>0 package algorithms.ilp; import org.junit.Assert; import org.junit.Test; public class SolverTest { private static final int TIMEOUT_IN_MILISECONDS = 100; @Test public void solveExampleProblemWithBreadthFirst() { solveExampleProblem(TraversingStrategy.BREADTH_FIRST); } @Test public void solveExampleProblemWithDepthFirst() { solveExampleProblem(TraversingStrategy.DEPTH_FIRST); } /** * I have 2 cokes (unit price 20), 1 sprite (unit price 10) and 1 mars bar * (unit price 15) in my shopping basket. There are 3 possible campaigns: * <ul> * <li>buy 2 drinks get 10% rebate</li> * <li>buy 1 coke 1 sprite and get 10kr rebate</li> * <li>buy 1 sprite 1 mars bar and get the mars bar for free.</li> * </ul> * * The possible campaigns products combinations are * <ul> * <li>for the first campaign, 1 coke + 1 sprite (a), or 2 cokes (b)</li> * <li>for the second campaign, 1 coke + 1 sprite (c)</li> * <li>for the third, 1 sprite + 1 mars bar (d)</li> * </ul> * That gives the A matrix: * <ul> * <li>------------(a) (b) (c) (d)</li> * <li>(coke) -----1---2---1---0</li> * <li>(sprite) ----1---0---1---1</li> * <li>(mars bar) -0---0---0---1</li> * </ul> * * Vector b is: * <ul> * <li>(coke) -----2</li> * <li>(sprite) ----1</li> * <li>(mars bar)-1</li> * </ul> * * And vector c (rebates) is: * <ul> * <li>(a) 3 [10% on a coke and a sprite]</li> * <li>(b) 4 [10% on 2 cokes]</li> * <li>(c) 10 [10 DKK rebate]</li> * <li>(d) 15 [1 mars bar free]</li> * </ul> * The solution of the problem gives this array [0,1,0,1]. That means we need * to use solutions (b) (1st campaign) and (d) (3rd campaign). We pick the * corresponding products: 2 cokes for solution (b), 1 sprite and 1 mars bar * for solution (d), and here is the best shopping solution! * </p> * <p> * Extension: in order to take other rebates into account, we add a row in A * per rebated product (privilege that is not from a bundle). The last * elements in x will show how much times we should use these privileges, but * we won't read those values. * </p> */ private void solveExampleProblem(TraversingStrategy traversingStrategy) { double[][] a = { { 1, 2, 1, 0 }, { 1, 0, 1, 1 }, { 0, 0, 0, 1 } }; double[] b = new double[] { 2, 1, 1 }; double[] c = new double[] { 3, 4, 10, 15 }; // x1 + 2*x2 + x3 <= 2 // x1 + x3 <= 1 // x4 <= 1 // Maximize 3*x1+4*x2+10*x3+15*x4 Solver solver = new Solver(a, b, c, TIMEOUT_IN_MILISECONDS, traversingStrategy); int[] solve = solver.solve(); Assert.assertFalse(solver.hasReachedTimout()); Assert.assertEquals(solve[0], 0); Assert.assertEquals(solve[1], 1); Assert.assertEquals(solve[2], 0); Assert.assertEquals(solve[3], 1); } /** * Solves work case used at http://web.mit.edu/15.053/www/AMP-Chapter-09.pdf * (section 9.5) */ @Test public void solveSimpleProblemWithBreadthFirst() { solveSimpleProblem(TraversingStrategy.BREADTH_FIRST); } @Test public void solveSimpleProblemWithDepthFirst() { solveSimpleProblem(TraversingStrategy.DEPTH_FIRST); } private void solveSimpleProblem(TraversingStrategy traversingStrategy) { double[][] a = { { 1, 1 }, { 5, 9 } }; double[] b = new double[] { 6, 45 }; double[] c = new double[] { 5, 8 }; // x1 + x2 <= 6 // 5*x1 + 9*x2 <= 45 // Maximize 5*x1+8*x2 Solver solver = new Solver(a, b, c, TIMEOUT_IN_MILISECONDS, traversingStrategy); int[] solve = solver.solve(); Assert.assertFalse(solver.hasReachedTimout()); Assert.assertEquals(solve[0], 0); Assert.assertEquals(solve[1], 5); } }
public class SearchableItem { private String name; private Boolean searchable; public void setName(String name) { if (name == null || name.isEmpty()) { throw new IllegalArgumentException("Name cannot be null or empty"); } this.name = name; } public void setSearchable(Boolean searchable) { if (searchable == null) { throw new IllegalArgumentException("Searchable status cannot be null"); } this.searchable = searchable; } public String getName() { return name; } public Boolean getSearchable() { return searchable; } }
package fr.syncrase.ecosyst.repository; import fr.syncrase.ecosyst.domain.Reproduction; import org.springframework.data.jpa.repository.*; import org.springframework.stereotype.Repository; /** * Spring Data SQL repository for the Reproduction entity. */ @SuppressWarnings("unused") @Repository public interface ReproductionRepository extends JpaRepository<Reproduction, Long>, JpaSpecificationExecutor<Reproduction> {}
require 'bundler' Bundler.setup require 'rom-viewpoint' require 'minitest/autorun'
VERSION=$(node -e "x = `cat package.json`; console.log('v' + x.version)") git commit -a git tag ${VERSION} git push git push origin ${VERSION} apm publish -t ${VERSION}
<!DOCTYPE html> <html> <head> <title>Email Template</title> <style> h1 { font-size: 20px; } h2 { font-size: 15px; font-weight: bold; } .cta { background-color: #0000cc; padding: 10px; font-size: 17px; color: #ffffff; border-radius: 5px; } </style> </head> <body> <h1>Welcome to our email template!</h1> <h2>Get 10% off your next order!</h2> <a class="cta" href="https://www.example.com/">Click Here To Get The Offer</a> </body> </html>
#!/bin/bash dieharder -d 15 -g 61 -S 538426622
#!/bin/bash # Name: xtra_back_mysql.sh # Desc:่ฏฅ่„šๆœฌไฝฟ็”จxtrabackupๅทฅๅ…ทๅฏนmysqlๆ•ฐๆฎๅบ“่ฟ›่กŒๅขž้‡ๅค‡ไปฝ๏ผŒๆ นๆฎ่‡ชๅทฑ้œ€ๆฑ‚ๅฏไปฅ่‡ช่กŒไฟฎๆ”น # Path:่ฏพๅ ‚็ฌ”่ฎฐ็›ฎๅฝ•้‡Œ # Usage:./xtra_back_mysql.sh # Author:MissHou # Update:2018-08-05 # ๅค‡ไปฝ็ญ–็•ฅ๏ผšๅ‘จ3ใ€ๅ‘จ5ใ€ๅ‘จๆ—ฅๅ…จๅค‡๏ผŒๅ‘จ1๏ผŒๅ‘จ2๏ผŒๅ‘จ4,ๅ‘จ6ๅขžๅค‡ #ๅ˜้‡ๅฎšไน‰ basedir=/usr/local/mysql datadir=/usr/local/mysql/data conf_file=/usr/local/mysql/my.cnf xtra_full_dir=/mydb3307/back_full xtra_increment_dir=/mydb3307/back_increment xtr_full_log=/mydb3307/log/full_$(date +%F).log xtr_increment_log=/mydb3307/log/increment_$(date +%F).log #ๅ…จ้‡ๅค‡ไปฝ full_back() { #ๅค‡ไปฝ /usr/bin/innobackupex --user=admin --password=123 $xtra_full_dir &> $xtr_full_log full_name=$(ls -d $xtra_full_dir/$(date +%F)_*) echo $full_name > $xtra_full_dir/full.txt #ๅบ”็”จๆ—ฅๅฟ— echo "++++++++++++++++++++++++ๆˆ‘ๆ˜ฏๅˆ†ๅ‰ฒ็ฌฆ++++++++++++++++++++++++++" >> $xtr_full_log /usr/bin/innobackupex --apply-log --redo-only $full_name &>> $xtr_full_log } full_back && find $xtra_full_dir -daystart -type d -mtime +1 -exec rm -rf {} \; 2>/dev/null
<filename>pkg/ofp15/errormsg.go<gh_stars>0 package ofp15 import ( "github.com/viniarck/fluxory/pkg/ofp" ) func NewErrorMsg(xid uint32, errType uint16, code uint16, data uint8) *ofp.ErrorMsg { m := new(ofp.ErrorMsg) m.Header = ofp.Header{OFPP_V15, OFPT_ERROR, m.Size(), xid} m.Type = errType m.Code = code m.Data = data return m }
<gh_stars>1000+ from dagster.core.utils import check_dagster_package_version from .event_log import MySQLEventLogStorage from .run_storage import MySQLRunStorage from .schedule_storage import MySQLScheduleStorage from .version import __version__ check_dagster_package_version("dagster-mysql", __version__) __all__ = ["MySQLEventLogStorage", "MySQLRunStorage", "MySQLScheduleStorage"]
<reponame>LiuFang07/bk-cmdb package matchers_test import ( . "github.com/onsi/ginkgo" . "github.com/onsi/gomega" . "github.com/onsi/gomega/matchers" ) var _ = Describe("BeElementOf", func() { Context("when passed a supported type", func() { It("should do the right thing", func() { Expect(2).Should(BeElementOf([2]int{1, 2})) Expect(3).ShouldNot(BeElementOf([2]int{1, 2})) Expect(2).Should(BeElementOf([]int{1, 2})) Expect(3).ShouldNot(BeElementOf([]int{1, 2})) Expect(2).Should(BeElementOf(1, 2)) Expect(3).ShouldNot(BeElementOf(1, 2)) Expect("abc").Should(BeElementOf("abc")) Expect("abc").ShouldNot(BeElementOf("def")) Expect("abc").ShouldNot(BeElementOf()) Expect(7).ShouldNot(BeElementOf(nil)) arr := make([]myCustomType, 2) arr[0] = myCustomType{s: "foo", n: 3, f: 2.0, arr: []string{"a", "b"}} arr[1] = myCustomType{s: "foo", n: 3, f: 2.0, arr: []string{"a", "c"}} Expect(myCustomType{s: "foo", n: 3, f: 2.0, arr: []string{"a", "b"}}).Should(BeElementOf(arr)) Expect(myCustomType{s: "foo", n: 3, f: 2.0, arr: []string{"b", "c"}}).ShouldNot(BeElementOf(arr)) }) }) Context("when passed a correctly typed nil", func() { It("should operate succesfully on the passed in value", func() { var nilSlice []int Expect(1).ShouldNot(BeElementOf(nilSlice)) var nilMap map[int]string Expect("foo").ShouldNot(BeElementOf(nilMap)) }) }) Context("when passed an unsupported type", func() { It("should error", func() { success, err := (&BeElementOfMatcher{Elements: []interface{}{0}}).Match(nil) Expect(success).Should(BeFalse()) Expect(err).Should(HaveOccurred()) success, err = (&BeElementOfMatcher{Elements: nil}).Match(nil) Expect(success).Should(BeFalse()) Expect(err).Should(HaveOccurred()) }) }) It("builds failure message", func() { actual := BeElementOf(1, 2).FailureMessage(123) Expect(actual).To(Equal("Expected\n <int>: 123\nto be an element of\n <[]interface {} | len:2, cap:2>: [1, 2]")) }) It("builds negated failure message", func() { actual := BeElementOf(1, 2).NegatedFailureMessage(123) Expect(actual).To(Equal("Expected\n <int>: 123\nnot to be an element of\n <[]interface {} | len:2, cap:2>: [1, 2]")) }) })
<filename>js/index.js<gh_stars>0 $(document).ready(function () { var $monthsSinceGraduation = $('#monthsSinceGraduation'); var $monthsSinceStartingChordsing = $('#monthsSinceStartingChordsing'); var $yearsOfAge = $('#yearsOfAge'); var now = moment(); var calculateDiff = function (startDate, unitOfTime) { return now.diff(startDate, unitOfTime); }; $monthsSinceGraduation.html(calculateDiff(moment([2013, 5, 15]), 'months')); $monthsSinceStartingChordsing.html(calculateDiff(moment([2013, 10, 11]), 'months')); $yearsOfAge.html(calculateDiff(moment([1990, 7, 25]), 'years')); });
import styled from 'styled-components'; import { size } from 'styled-theme'; export const ViewPanelWrapper = styled.div` display: flex; flex-direction: column; min-height: ${size('panelHeight', '500px')}; `;
#!/usr/bin/env bash # Copyright 2021 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. set -euo pipefail cd site || exit npm i echo "Starting check." # Find all potential entrypoint READMEs # Convert them to valid URLs # Check each link for Docsify 404s find . -name README.md -printf "%P\n" | grep -v node_modules | sed "s/README.md//" \ | sed "s/^/http:\/\/localhost:3001\//" \ | xargs -I {} -n1 sh -c "! (echo Checking $0 && npx href-checker {} --bad-content=\"404 - Not found\" --silent --no-off-site -c=15 | grep .) || exit 255" echo "Success."
<filename>example.py """ Example application showing Python 3.10 structural pattern matching. """ import shlex from dataclasses import dataclass from typing import List def run_command_v1(command: str) -> None: match command: case "quit": print("Quitting the program.") case "reset": print("Resetting the system.") case other: print(f"Unknown command '{other}'.") def run_command_v2(command: str) -> None: match command.split(): case ["load", filename]: print(f"Loading filename {filename}.") case ["save", filename]: print(f"Saving filename {filename}.") case ["quit" | "exit" | "bye", *rest]: if "--force" in rest or "-f" in rest: print("Sending SIGTERM to all processes and quitting the program.") else: print("Quitting the program.") quit() case _: print(f"Unknown command '{command}'.") def run_command_v3(command: str) -> None: match command.split(): case ["load", filename]: print(f"Loading filename {filename}.") case ["save", filename]: print(f"Saving filename {filename}.") case ["quit" | "exit" | "bye", *rest] if "--force" in rest or "-f" in rest: print("Sending SIGTERM to all processes and quitting the program.") quit() case ["quit" | "exit" | "bye"]: print("Quitting the program.") quit() case _: print(f"Unknown command {command!r}.") @dataclass class Command: """Class that represents a command.""" command: str arguments: List[str] def run_command_v4(command: Command) -> None: match command: case Command(command="load", arguments=[filename]): print(f"Loading filename {filename}.") case Command(command="save", arguments=[filename]): print(f"Saving filename {filename}.") case Command(command="quit" | "exit" | "bye", arguments=["--force" | "-f", *rest]): print("Sending SIGTERM to all processes and quitting the program.") quit() case Command(command="quit" | "exit" | "bye"): print("Quitting the program.") quit() case _: print(f"Unknown command {command!r}.") def main() -> None: """Main function.""" while True: # command = input("$ ") # run_command_v3(command) # read a command with arguments from the input command, *arguments = shlex.split(input("$ ")) # run the command run_command_v4(Command(command, arguments)) if __name__ == "__main__": main()
require 'rails_helper' RSpec.describe ApiController, type: :controller do describe "GET #user" do it "returns http success" do get :user, params: { name: 'user_name' } expect(response).to have_http_status(:success) end it "returns name provided in params" do get :user, params: { name: 'user_name' } res_body = JSON.parse(response.body) expect(res_body).to include({ "name": "user_name" }) end end end
<reponame>jonathantneal/postcss-font-weight-names<filename>.tape.js module.exports = { 'postcss-font-weights': { 'basic': { message: 'supports basic usage' }, 'basic:w-prefix': { message: 'ignores basic usage when { prefix: "x" }', options: { prefix: 'x' } }, 'custom': { message: 'supports custom usage', options: { weights: { 'custom-weight-1': 300, 'custom-weight-2': 500 } } }, 'prefix': { message: 'supports prefix usage' }, 'prefix:w-prefix': { message: 'supports prefix usage when { prefix: "x" }', options: { prefix: 'x' } } } };
<gh_stars>1-10 import React from "react"; function Profile() { return ( <div className=" flex flex-col max-w-xl border-r-2 border-gray-100 h-full"> <span className="sticky z-10 top-0 bg-white border-b-2 w-full text-lg font-bold p-4"> Profile </span> </div> ); } export default Profile;
#!/bin/bash dirs="/gws/nopw/j04/c3s311a_lot2/data/cdmlite/r201910/land /gws/smf/j04/c3s311a_lot2/cdmlite/log/prep/land /gws/smf/j04/c3s311a_lot2/cdmlite/log/prep/lotus-land" for dr in $dirs; do if [ -d $dr ]; then echo "[WARN] Removing directory and its contents: $dr" rm -fr $dr fi done rm -f last-land-batch.txt
package core.framework.internal.log; import core.framework.log.Markers; import core.framework.log.message.ActionLogMessage; import core.framework.log.message.PerformanceStatMessage; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import static org.assertj.core.api.Assertions.assertThat; /** * @author neo */ class ActionLogMessageFactoryTest { private ActionLogMessageFactory factory; @BeforeEach void createActionLogMessageFactory() { factory = new ActionLogMessageFactory(); } @Test void actionLog() { var log = new ActionLog("begin", null); log.action("action"); log.process(new LogEvent("logger", Markers.errorCode("ERROR_CODE"), LogLevel.WARN, "message", null, null)); log.track("db", 1000, 1, 2); log.track("http", 2000, 0, 0); ActionLogMessage message = factory.create(log); assertThat(message).isNotNull(); assertThat(message.app).isEqualTo(LogManager.APP_NAME); assertThat(message.action).isEqualTo("action"); assertThat(message.errorCode).isEqualTo("ERROR_CODE"); assertThat(message.traceLog).isNotEmpty(); PerformanceStatMessage stats = message.performanceStats.get("db"); assertThat(stats.totalElapsed).isEqualTo(1000); assertThat(stats.count).isEqualTo(1); assertThat(stats.readEntries).isEqualTo(1); assertThat(stats.writeEntries).isEqualTo(2); stats = message.performanceStats.get("http"); assertThat(stats.totalElapsed).isEqualTo(2000); assertThat(stats.count).isEqualTo(1); assertThat(stats.readEntries).isNull(); assertThat(stats.writeEntries).isNull(); } }
<reponame>gdsimoes/fullstackopen import React, { useState } from "react"; const Button = ({ handleClick, text }) => { return <button onClick={handleClick}>{text}</button>; }; const App = () => { const anecdotes = [ "If it hurts, do it more often", "Adding manpower to a late software project makes it later!", "The first 90 percent of the code accounts for the first 90 percent of the development time...The remaining 10 percent of the code accounts for the other 90 percent of the development time.", "Any fool can write code that a computer can understand. Good programmers write code that humans can understand.", "Premature optimization is the root of all evil.", "Debugging is twice as hard as writing the code in the first place. Therefore, if you write the code as cleverly as possible, you are, by definition, not smart enough to debug it.", ]; function getRandomIndex(array) { return Math.floor(Math.random() * array.length); } // handleClick functions function handleVote() { const copyVotes = [...votes]; copyVotes[selected] += 1; setVotes(copyVotes); } function handleNext() { setSelected(getRandomIndex(anecdotes)); } // return index of most voted anecdote function mostVoted() { function reducer(guessIndex, currentValue, currentIndex) { if (votes[guessIndex] < currentValue) { return currentIndex; } else { return guessIndex; } } const firstIndex = 0; return votes.reduce(reducer, firstIndex); } // new array filled with zeros const baseArray = new Array(anecdotes.length).fill(0); const [selected, setSelected] = useState(getRandomIndex(anecdotes)); const [votes, setVotes] = useState(baseArray); return ( <div> <h2>Anecdote of the day</h2> <p>{anecdotes[selected]}</p> <p>has {votes[selected]} votes</p> <Button handleClick={handleVote} text="vote" /> <Button handleClick={handleNext} text="next anecdote" /> <h2>Anecdote with most votes</h2> <p>{anecdotes[mostVoted()]}</p> </div> ); }; export default App;
/* tslint:disable: ordered-imports*/ import { NgModule } from "@angular/core"; import { Routes, RouterModule, ExtraOptions } from "@angular/router"; /* Module */ import { MudlerModule } from "./mulder.module"; /* Containers */ import * as mulderContainers from "./containers"; import { BlogComponent } from "./containers/blog/blog.component"; import { BlogsComponent } from "./containers/blogs/blogs.component"; import { StaticComponent } from "./containers/static/static.component"; /* Routes */ export const ROUTES: Routes = [ // Demo simple component { path: "", component: mulderContainers.HomeComponent, }, // Demo simple component { path: "about", component: mulderContainers.AboutComponent, }, { path: "surveydemo", component: mulderContainers.SurveyDemoComponent, }, // Demo complex component that consumes microservices (hal) { path: "publications", component: mulderContainers.PublicationsComponent, }, // Demo complex component dynamic md content from microservices { path: "d/:cat/:slug", component: mulderContainers.DynamicMdComponent, }, // Demo blog static { path: "blog/:slug", component: BlogComponent, }, // Demo blog static (list of posts) { path: "blog", component: BlogsComponent, }, // Demo static page from md { path: "s/:slug", component: StaticComponent, }, ]; @NgModule({ imports: [MudlerModule, RouterModule.forChild(ROUTES)], exports: [RouterModule], }) export class BlogRoutingModule {}
<reponame>xuChaoPang/algorithm<gh_stars>1-10 package com.ray.leetcode; /** * Created by xuChaoPang on 2019/4/19. * * Jump Game II -Level H * Given an array of non-negative integers, you are initially positioned at the first index of the array. * Each element in the array represents your maximum jump length at that position. * Your goal is to reach the last index in the minimum number of jumps. */ public class LC45 { /* * ไปŽๅคดๅผ€ๅง‹่ตฐ ๆฏๆฌกๆ‰พๅ‡บ่ท็ฆป่ตทๅง‹็‚นๆœ€่ฟ‘็š„ ่ƒฝๅˆฐ่พพ็ป“ๅฐพ็š„็‚นn * ๆŽฅไธ‹ๆฅ ไปฅnไธบ็ป“ๅฐพ้‡ๅคไธŠ่ฟฐๆ“ไฝœ ็›ดๅˆฐ n ไธบ0 */ public int jump(int[] nums) { if ( nums == null || nums.length <= 1) { return 0; } int end = nums.length - 1; int start = 0; int jumps = 0; while (true) { if (start == end) { break; } if (nums[start] + start >= end) { jumps ++; end = start; start = 0; } else { start ++; } } return jumps; } public static void main(String[] args) { int[] nums = new int[] {2,3,1,1,4}; System.out.println(new LC45().jump(nums)); } }
import React from "react"; import { IFilterField, IFilterObject } from "../utils/models"; interface ITagProps { dir: "ltr" | "rtl"; filter: IFilterObject; fields: IFilterField[]; placement: "bottomLeft" | "bottomRight"; onRemove: () => void; onChange: (filter: IFilterObject) => void; primaryColor?: string; negativeColor?: string; } export declare const RsbFilterTag: React.FC<ITagProps>; export {};
<reponame>johanchouquet/angularfire2 const { rollup } = require('rollup'); const { spawn } = require('child_process'); const { Observable, from, forkJoin } = require('rxjs'); const { switchMap, switchMapTo, tap } = require('rxjs/operators'); const { copy, readFileSync, writeFile, statSync } = require('fs-extra'); const { prettySize } = require('pretty-size'); const gzipSize = require('gzip-size'); const resolve = require('rollup-plugin-node-resolve'); const pkg = require(`${process.cwd()}/package.json`); // Rollup globals const GLOBALS = { 'rxjs': 'rxjs', 'rxjs/operators': 'rxjs.operators', '@angular/common': 'ng.common', '@angular/core': 'ng.core', '@angular/core/testing': 'ng.core.testing', '@angular/platform-browser': 'ng.platformBrowser', 'firebase': 'firebase', 'firebase/app': 'firebase', 'firebase/auth': 'firebase', 'firebase/database': 'firebase', 'firebase/firestore': 'firebase', 'firebase/functions': 'firebase', 'firebase/storage': 'firebase', 'angularfire2': 'angularfire2', 'angularfire2/auth': 'angularfire2.auth', 'angularfire2/database': 'angularfire2.database', 'angularfire2/database-deprecated': 'angularfire2.database_deprecated', 'angularfire2/firestore': 'angularfire2.firestore', 'angularfire2/functions': 'angularfire2.functions', 'angularfire2/storage': 'angularfire2.storage' }; // Map of dependency versions across all packages const VERSIONS = { ANGULAR_VERSION: pkg.dependencies['@angular/core'], FIREBASE_VERSION: pkg.dependencies['firebase'], RXJS_VERSION: pkg.dependencies['rxjs'], ZONEJS_VERSION: pkg.dependencies['zone.js'], ANGULARFIRE2_VERSION: pkg.version, FIRESTORE_VERSION: pkg.dependencies['firestore'], WS_VERSION: pkg.dependencies['ws'], BUFFERUTIL_VERSION: pkg.dependencies['bufferutil'], UTF_8_VALIDATE_VERSION: pkg.dependencies['utf-8-validate'], XMLHTTPREQUEST_VERSION: pkg.dependencies['xmlhttprequest'] }; const MODULE_NAMES = { core: 'angularfire2', auth: 'angularfire2.auth', database: 'angularfire2.database', "database-deprecated": 'angularfire2.database_deprecated', firestore: 'angularfire2.firestore', functions: 'angularfire2.functions', storage: 'angularfire2.storage' }; const ENTRIES = { core: `${process.cwd()}/dist/packages-dist/index.js`, auth: `${process.cwd()}/dist/packages-dist/auth/index.js`, database: `${process.cwd()}/dist/packages-dist/database/index.js`, "database-deprecated": `${process.cwd()}/dist/packages-dist/database-deprecated/index.js`, firestore: `${process.cwd()}/dist/packages-dist/firestore/index.js`, functions: `${process.cwd()}/dist/packages-dist/functions/index.js`, storage: `${process.cwd()}/dist/packages-dist/storage/index.js` }; const SRC_PKG_PATHS = { core: `${process.cwd()}/src/core/package.json`, auth: `${process.cwd()}/src/auth/package.json`, database: `${process.cwd()}/src/database/package.json`, "database-deprecated": `${process.cwd()}/src/database-deprecated/package.json`, firestore: `${process.cwd()}/src/firestore/package.json`, "firebase-node": `${process.cwd()}/src/firebase-node/package.json`, functions: `${process.cwd()}/src/functions/package.json`, storage: `${process.cwd()}/src/storage/package.json` }; const DEST_PKG_PATHS = { core: `${process.cwd()}/dist/packages-dist/package.json`, auth: `${process.cwd()}/dist/packages-dist/auth/package.json`, database: `${process.cwd()}/dist/packages-dist/database/package.json`, "database-deprecated": `${process.cwd()}/dist/packages-dist/database-deprecated/package.json`, firestore: `${process.cwd()}/dist/packages-dist/firestore/package.json`, "firebase-node": `${process.cwd()}/dist/packages-dist/firebase-node/package.json`, functions: `${process.cwd()}/dist/packages-dist/functions/package.json`, storage: `${process.cwd()}/dist/packages-dist/storage/package.json` }; // Constants for running typescript commands const TSC = 'node_modules/.bin/tsc'; const NGC = 'node_modules/.bin/ngc'; const TSC_ARGS = (name, config = 'build') => [`-p`, `${process.cwd()}/src/${name}/tsconfig-${config}.json`]; const TSC_TEST_ARGS = [`-p`, `${process.cwd()}/src/tsconfig-test.json`]; /** * Create an Observable of a spawned child process. * @param {string} command * @param {string[]} args */ function spawnObservable(command, args) { return Observable.create(observer => { const cmd = spawn(command, args); observer.next(''); // hack to kick things off, not every command will have a stdout cmd.stdout.on('data', (data) => { observer.next(data.toString('utf8')); }); cmd.stderr.on('data', (data) => { console.log(data); observer.error(data.toString('utf8')); }); cmd.on('close', (data) => { observer.complete(); }); }); } function generateBundle(entry, { dest, globals, moduleName }) { return rollup({ entry }).then(bundle => { return bundle.write({ format: 'umd', external: Object.keys(globals), plugins: [resolve()], dest, globals, moduleName, }); }); } function createFirebaseBundles(featurePaths, globals) { return Object.keys(featurePaths).map(feature => { return generateBundle(featurePaths[feature], { dest: `${process.cwd()}/dist/bundles/${feature}.js`, globals, moduleName: `firebase.${feature}` }); }); } /** * Create a UMD bundle given a module name. * @param {string} name * @param {Object} globals */ function createUmd(name, globals) { // core module is angularfire2 the rest are angularfire2.feature const moduleName = MODULE_NAMES[name]; const entry = ENTRIES[name]; return generateBundle(entry, { dest: `${process.cwd()}/dist/packages-dist/bundles/${name}.umd.js`, globals, moduleName }); } function createTestUmd(globals) { const entry = `${process.cwd()}/dist/root.spec.js`; const moduleName = 'angularfire2.test'; return generateBundle(entry, { dest: `${process.cwd()}/dist/packages-dist/bundles/test.umd.js`, globals, moduleName }); } /** * Get the file path of the src package.json for a module * @param {string} moduleName */ function getSrcPackageFile(moduleName) { return SRC_PKG_PATHS[moduleName]; } /** * Get the file path of the dist package.json for a module * @param {string} moduleName */ function getDestPackageFile(moduleName) { return DEST_PKG_PATHS[moduleName]; } /** * Create an observable of package.json dependency version replacements. * This keeps the dependency versions across each package in sync. * @param {string} name * @param {Object} versions */ function replaceVersionsObservable(name, versions) { return Observable.create((observer) => { const package = getSrcPackageFile(name); let pkg = readFileSync(package, 'utf8'); const regexs = Object.keys(versions).map(key => ({ expr: new RegExp(key, 'g'), key, val: versions[key] })); regexs.forEach(reg => { pkg = pkg.replace(reg.expr, reg.val); }); const outPath = getDestPackageFile(name); writeFile(outPath, pkg, err => { if (err) { observer.error(err); } else { observer.next(pkg); observer.complete(); } }); }); } function copyPackage(moduleName) { return copy(getSrcPackageFile(moduleName), getDestPackageFile(moduleName)); } function copyRootTest() { return copy(`${process.cwd()}/src/root.spec.js`, `${process.cwd()}/dist/root.spec.js`); } function copyNpmIgnore() { return copy(`${process.cwd()}/.npmignore`, `${process.cwd()}/dist/packages-dist/.npmignore`); } function copyReadme() { return copy(`${process.cwd()}/README.md`, `${process.cwd()}/dist/packages-dist/README.md`); } function copyDocs() { return copy(`${process.cwd()}/docs`, `${process.cwd()}/dist/packages-dist/docs`); } function copyNodeFixes() { return copy(`${process.cwd()}/src/firebase-node`, `${process.cwd()}/dist/packages-dist/firebase-node`); } function measure(module) { const path = `${process.cwd()}/dist/packages-dist/bundles/${module}.umd.js`; const file = readFileSync(path); const gzip = prettySize(gzipSize.sync(file), true); const size = prettySize(statSync(path).size, true); return { size, gzip }; } /** * Returns each version of each AngularFire module. * This is used to help ensure each package has the same verison. */ function getVersions() { const paths = [ getDestPackageFile('core'), getDestPackageFile('auth'), getDestPackageFile('database'), getDestPackageFile('firestore'), getDestPackageFile('firebase-node'), getDestPackageFile('functions'), getDestPackageFile('storage'), getDestPackageFile('database-deprecated') ]; return paths .map(path => require(path)) .map(pkgs => pkgs.version); } function verifyVersions() { const versions = getVersions(); console.log(versions); versions.map(version => { if(version !== pkg.version) { throw new Error('Versions mistmatch'); process.exit(1); } }); } function buildModule(name, globals) { const es2015$ = spawnObservable(NGC, TSC_ARGS(name)); const esm$ = spawnObservable(NGC, TSC_ARGS(name, 'esm')); const test$ = spawnObservable(TSC, TSC_ARGS(name, 'test')); return forkJoin(es2015$, esm$, test$).pipe( switchMap(() => from(createUmd(name, globals))), switchMap(() => replaceVersionsObservable(name, VERSIONS)) ); } /** * Create an observable of module build status. This method builds * @param {Object} globals */ function buildModules(globals) { const core$ = buildModule('core', globals); const auth$ = buildModule('auth', globals); const db$ = buildModule('database', globals); const firestore$ = buildModule('firestore', globals); const functions$ = buildModule('functions', globals); const storage$ = buildModule('storage', globals); const dbdep$ = buildModule('database-deprecated', globals); return forkJoin(core$, from(copyRootTest())).pipe( switchMapTo(auth$), switchMapTo(db$), switchMapTo(firestore$), switchMapTo(functions$), switchMapTo(storage$), switchMapTo(dbdep$) ); } function buildLibrary(globals) { const modules$ = buildModules(globals); return forkJoin(modules$).pipe( switchMap(() => from(createTestUmd(globals))), switchMap(() => from(copyNpmIgnore())), switchMap(() => from(copyReadme())), switchMap(() => from(copyDocs())), switchMap(() => from(copyNodeFixes())), switchMap(() => replaceVersionsObservable('firebase-node', VERSIONS)), tap(() => { const coreStats = measure('core'); const authStats = measure('auth'); const dbStats = measure('database'); const fsStats = measure('firestore'); const functionsStats = measure('functions'); const storageStats = measure('storage'); const dbdepStats = measure('database-deprecated'); console.log(` core.umd.js - ${coreStats.size}, ${coreStats.gzip} auth.umd.js - ${authStats.size}, ${authStats.gzip} database.umd.js - ${dbStats.size}, ${dbStats.gzip} firestore.umd.js - ${fsStats.size}, ${fsStats.gzip} functions.umd.js - ${functionsStats.size}, ${functionsStats.gzip} storage.umd.js - ${storageStats.size}, ${storageStats.gzip} database-deprecated.umd.js - ${dbdepStats.size}, ${dbdepStats.gzip} `); verifyVersions(); })); } buildLibrary(GLOBALS).subscribe( data => { console.log('data', data) }, err => { console.log('err', err) }, () => { console.log('complete') } );
<filename>hedera-node/src/test/java/com/hedera/services/store/models/OwnershipTrackerTest.java package com.hedera.services.store.models; /*- * โ€Œ * Hedera Services Node * โ€‹ * Copyright (C) 2018 - 2021 <NAME>, LLC * โ€‹ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * โ€ */ import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertFalse; class OwnershipTrackerTest { private OwnershipTracker subject = new OwnershipTracker(); private final Id treasury = new Id(1, 2, 3); private final Id account = new Id(4, 5, 6); private final Id token = new Id(0, 0, 1); @BeforeEach void setup(){ // setup the getter/setter test subject = new OwnershipTracker(); } @Test void add() { final var burn = OwnershipTracker.forRemoving(treasury, 1L); subject.add(token, burn); assertEquals(1, subject.getChanges().size()); subject.add(token, burn); assertEquals(1, subject.getChanges().size()); assertFalse(subject.isEmpty()); } @Test void fromMinting() { final var change = OwnershipTracker.forMinting(treasury, 2L); assertEquals(treasury, change.getNewOwner()); assertEquals(Id.DEFAULT, change.getPreviousOwner()); assertEquals(2L, change.getSerialNumber()); } @Test void fromWiping() { final var change = OwnershipTracker.forRemoving(account, 2L); assertEquals(Id.DEFAULT, change.getNewOwner()); assertEquals(account, change.getPreviousOwner()); assertEquals(2L, change.getSerialNumber()); } @Test void newChange(){ final var change = new OwnershipTracker.Change(treasury, Id.DEFAULT, 1L); assertEquals(1L, change.getSerialNumber()); assertEquals(Id.DEFAULT, change.getNewOwner()); assertEquals(treasury, change.getPreviousOwner()); } }
/* * VMware SD-WAN Orchestrator API v1 * * API version: 4.4.0 */ package vcoclient import ( "context" "net/http" "strings" //"log" ) type LoginApiService service func (a *LoginApiService) LoginEnterpriseLogin(ctx context.Context, authorization AuthObject) (*http.Response, error) { var ( localVarHttpMethod = strings.ToUpper("Post") localVarUrl string ) //localVarPostBody := &JsonRpcRequest { // Jsonrpc : "2.0", // Method : "/login/enterpriseLogin", // Params : authorization, // Id : 1, //} localVarPostBody := authorization localVarUrl = a.client.cfg.BasePath + "rest/login/enterpriseLogin" localVarHeaderParams := make(map[string]string) localVarHeaderParams["Content-Type"] = "application/json" //r, err := a.client.prepareRequest(ctx, localVarHttpMethod, localVarPostBody, localVarHeaderParams) //if err != nil { // return nil,err //} r, err := a.client.restRequest(ctx, localVarUrl, localVarHttpMethod, localVarPostBody, localVarHeaderParams) localVarHttpResponse, err := a.client.callAPI(r) if err != nil { return nil, err } localVarHttpResponse.Body.Close() //log.Println(localVarHttpResponse) return localVarHttpResponse, err }
<filename>spec/factories/address.rb FactoryBot.define do factory :address do association :user postal_code {Faker::Address.postcode} prefectures {"ๆฑไบฌ้ƒฝ"} municipality {"ๆธ‹่ฐทๅŒบ"} house_number {"333"} building {"ใ‚ขใ‚ธใ‚ขใƒ“ใƒซ"} end end
class BankAccount: def __init__(self, initial_balance): self.balance = initial_balance def deposit(self, amount): self.balance += amount def withdraw(self, amount): if amount <= self.balance: self.balance -= amount else: print("Insufficient funds") # Test the BankAccount class example = BankAccount(initial_balance=11) assert example.balance == 11
<gh_stars>0 import { line, curveLinearClosed } from 'd3-shape'; export default function () { var _lineConstructor = line(); var _xAccessor = function (d) {return d.x}; var _yAccessor = function (d) {return d.y}; var _rAccessor = function (d) {return d.r}; var _curve = curveLinearClosed; function _streamline(pathData) { var bothPoints = buildStreamline(pathData); return _lineConstructor.x(function (d) {return d.x}).y(function (d) {return d.y}).curve(_curve)(bothPoints); } _streamline.x = function (_value) { if (!arguments.length) return _xAccessor; _xAccessor = _value; return _streamline; }; _streamline.y = function (_value) { if (!arguments.length) return _yAccessor; _yAccessor = _value; return _streamline; }; _streamline.r = function (_value) { if (!arguments.length) return _rAccessor; _rAccessor = _value; return _streamline; }; _streamline.curve = function(_value) { if (!arguments.length) return _curve; _curve = _value; return _streamline; }; return _streamline; function offsetEdge(d) { var diffX = _yAccessor(d.target) - _yAccessor(d.source); var diffY = _xAccessor(d.target) - _xAccessor(d.source); var angle0 = ( Math.atan2( diffY, diffX ) + ( Math.PI / 2 ) ); var angle1 = angle0 + ( Math.PI * 0.5 ); var angle2 = angle0 + ( Math.PI * 0.5 ); var x1 = _xAccessor(d.source) + (_rAccessor(d.source) * Math.cos(angle1)); var y1 = _yAccessor(d.source) - (_rAccessor(d.source) * Math.sin(angle1)); var x2 = _xAccessor(d.target) + (_rAccessor(d.target) * Math.cos(angle2)); var y2 = _yAccessor(d.target) - (_rAccessor(d.target) * Math.sin(angle2)); return {x1: x1, y1: y1, x2: x2, y2: y2} } function buildStreamline(points) { var bothCode = []; var x = 0; var transformedPoints = {}; while (x < points.length) { if (x !== points.length - 1) { transformedPoints = offsetEdge({source: points[x], target: points[x + 1]}); var p1 = {x: transformedPoints.x1, y: transformedPoints.y1}; var p2 = {x: transformedPoints.x2, y: transformedPoints.y2}; bothCode.push(p1,p2); if (bothCode.length > 3) { var l = bothCode.length - 1; var lineA = {a: bothCode[l - 3], b: bothCode[l - 2]}; var lineB = {a: bothCode[l - 1], b: bothCode[l]}; var intersect = findIntersect(lineA.a.x, lineA.a.y, lineA.b.x, lineA.b.y, lineB.a.x, lineB.a.y, lineB.b.x, lineB.b.y); if (intersect.found === true) { lineA.b.x = intersect.x; lineA.b.y = intersect.y; lineB.a.x = intersect.x; lineB.a.y = intersect.y; } } } x++; } x--; //Back while (x >= 0) { if (x !== 0) { transformedPoints = offsetEdge({source: points[x], target: points[x - 1]}); var p1 = {x: transformedPoints.x1, y: transformedPoints.y1}; var p2 = {x: transformedPoints.x2, y: transformedPoints.y2}; bothCode.push(p1,p2); if (bothCode.length > 3) { var l = bothCode.length - 1; var lineA = {a: bothCode[l - 3], b: bothCode[l - 2]}; var lineB = {a: bothCode[l - 1], b: bothCode[l]}; var intersect = findIntersect(lineA.a.x, lineA.a.y, lineA.b.x, lineA.b.y, lineB.a.x, lineB.a.y, lineB.b.x, lineB.b.y); if (intersect.found === true) { lineA.b.x = intersect.x; lineA.b.y = intersect.y; lineB.a.x = intersect.x; lineB.a.y = intersect.y; } } } x--; } return bothCode; } function findIntersect(l1x1, l1y1, l1x2, l1y2, l2x1, l2y1, l2x2, l2y2) { var d, a, b, n1, n2, result = { x: null, y: null, found: false }; d = ((l2y2 - l2y1) * (l1x2 - l1x1)) - ((l2x2 - l2x1) * (l1y2 - l1y1)); if (d === 0) { return result; } a = l1y1 - l2y1; b = l1x1 - l2x1; n1 = ((l2x2 - l2x1) * a) - ((l2y2 - l2y1) * b); n2 = ((l1x2 - l1x1) * a) - ((l1y2 - l1y1) * b); a = n1 / d; b = n2 / d; result.x = l1x1 + (a * (l1x2 - l1x1)); result.y = l1y1 + (a * (l1y2 - l1y1)); if ((a > 0 && a < 1) && (b > 0 && b < 1)) { result.found = true; } return result; } }
import { Uploader } from '@/utils/Uploader'; import { Input } from 'antd'; import React, { useEffect, useRef, useState } from 'react'; import { UploadOutlined, LoadingOutlined } from '@ant-design/icons'; export interface UploadFieldProps { onChange: (val: string) => void; value: string; inputDisabled?: boolean; accept?: string; uploadHandler: (file: File) => Promise<string>; } export function UploadField(props: UploadFieldProps) { const { onChange, inputDisabled = false, accept, uploadHandler } = props; const [loading, setLoading] = useState(false); const { current: uploader } = useRef(new Uploader(uploadHandler, { limit: 1, accept })); useEffect(() => { uploader.on('start', () => { setLoading(true); uploader.on('end', (photos) => { setLoading(false); onChange(photos.filter(item => item.status === 'done').map(item => item.url)[0] || ''); }); }); }, [onChange, uploader]); const onClick = () => { if (loading) return; uploader.chooseFile(); }; return ( <Input prefix={loading ? <LoadingOutlined /> : <UploadOutlined onClick={onClick} />} value={props.value} onChange={inputDisabled ? undefined : (e) => onChange(e.target.value)} /> ); }
docker stop $(docker ps -aq) docker rm $(docker ps -aq) docker rmi $(docker images -q) docker system prune -a -f
<filename>src/main/scala/Hascalator/Prelude/Ordering.scala<gh_stars>1-10 package Hascalator.Prelude /** * Created by Glavo on 17-7-26. * * @author Glavo * @since 0.1.0 */ final class Ordering private[Prelude](override val toString: String, override val hashCode: Int) object Ordering { }
#!/bin/bash # Copyright 2018 The Knative Authors # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. set -e -x -u go fmt ./cmd/... ./pkg/... ./test/... go build ./cmd/... ./knctl version ./hack/generate-docs.sh echo "Success"
def sort_string(sentence): words = sentence.split() words.sort() return ' '.join(words)
#!/usr/bin/env bash # # Onix Config Manager - OxTerra - Terraform Http Backend for Onix # Copyright (c) 2018-2020 by www.gatblau.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. # # Contributors to this project, hereby assign copyright in this code to the project, # to be licensed under the same terms as the rest of the code. # # Usage: sh terra_up.sh # Description: launches 3 containers using Docker in the local manchine: # - Terra (on TCP port 8081 and connects to the Onix Web API) # - Onix Web API (on TCP port 8080 connects to the bacing database) # - PosgreSQL database (on TCP port 5432) # echo check docker is installed if [ ! -x "$(command -v docker)" ]; then echo "Docker is required to execute this script." exit 1 fi echo deletes any images with no tag images_with_no_tag=$(docker images -f dangling=true -q) if [ -n "$images_with_no_tag" ]; then docker rmi $images_with_no_tag fi echo try and delete existing Onix containers docker rm -f oxterra docker rm -f oxdb docker rm -f ox echo "checking port 8081 is available for the Terra" lsof -i:8081 | grep LISTEN RESULT=$? if [ $RESULT -eq 0 ]; then echo port 8081 is in use, cannot continue: ensure there is no process using 8081/tcp port exit 1 fi echo "checking port 8080 is available for the Onix Web API process" lsof -i:8080 | grep LISTEN RESULT=$? if [ $RESULT -eq 0 ]; then echo port 8080 is in use, cannot continue: ensure there is no process using 8080/tcp port exit 1 fi echo "checking port 5432 is available for the Onix database process" lsof -i:5432 | grep LISTEN RESULT=$? if [ $RESULT -eq 0 ]; then echo port 5432 is in use, cannot continue: ensure there is no process using 5432/tcp port exit 1 fi echo creates the Onix database container docker run --name oxdb -it -d -p 5432:5432 \ -e POSTGRESQL_ADMIN_PASSWORD=onix \ "centos/postgresql-12-centos7" echo creates the Onix Web API container docker run --name ox -it -d -p 8080:8080 --link oxdb \ -e DB_HOST=oxdb \ -e DB_ADMIN_PWD=onix \ -e WAPI_AUTH_MODE=basic \ -e WAPI_ADMIN_USER=admin \ -e WAPI_ADMIN_PWD=0n1x \ "gatblau/onix-snapshot" echo "please wait for the Web API to become available" until $(curl --output /dev/null --silent --head --fail http://localhost:8080); do printf '.' sleep 2 done echo "deploying database schemas" curl localhost:8080/ready echo echo "Web API ready to use @ localhost:8080" echo creates Terra container docker run --name oxterra -it -d -p 8081:8081 --link ox \ -e OX_TERRA_SERVICE_PATH=state \ -e OX_TERRA_ONIX_URL=http://ox:8080 \ -e OX_TERRA_ONIX_AUTHMODE=basic \ -e OX_TERRA_ONIX_USERNAME=admin \ -e OX_TERRA_ONIX_PASSWORD=0n1x \ -e OX_TERRA_SERVICE_INSECURESKIPVERIFY=false \ -e OX_TERRA_SERVICE_METRICS=false \ "gatblau/oxterra-snapshot"
#!/bin/sh exec < /dev/null export COLUMNS=80 ( for n in test/[A-Z]*.nim; do echo "Test: $n" nim c "$@" --run $n --help 2>&1 | grep -v '^CC:' echo "====================================" done ./test/FullyAutoMulti help 2>&1 ) | grep -v 'Warning: \(expr\|stmt\) is deprecated' | grep -v '^Hint: ' | sed 's@.*/cligen[-a-z]*/cligen.nim(@cligen/cligen.nim(@' > test/out diff --ignore-all-space test/ref test/out
#!/bin/bash # # A script to run Drupal VM functional tests. # Set defaults if they're not set upstream. CONFIG="${CONFIG:-tests/config.yml}" MAKEFILE="${MAKEFILE:-example.drupal.make.yml}" COMPOSERFILE="${COMPOSERFILE:-example.drupal.composer.json}" HOSTNAME="${HOSTNAME:-drupalvm.test}" MACHINE_NAME="${MACHINE_NAME:-drupalvm}" IP="${IP:-192.168.88.88}" DRUPALVM_DIR="${DRUPALVM_DIR:-/var/www/drupalvm}" DRUSH_BIN="${DRUSH_BIN:-drush}" TEST_INSTALLED_EXTRAS="${TEST_INSTALLED_EXTRAS:-true}" CONTAINER_ID="${CONTAINER_ID:-dvm-test}" type="${type:-tests/defaults}" distro="${distro:-ubuntu1604}" cleanup="${cleanup:-true}" ## Set up vars for Docker setup. # CentOS 7 if [ $distro = 'centos7' ]; then init="/usr/lib/systemd/systemd" opts="--privileged --volume=/sys/fs/cgroup:/sys/fs/cgroup:ro" # CentOS 6 elif [ $distro = 'centos6' ]; then init="/sbin/init" opts="--privileged" # Ubuntu 18.04 elif [ $distro = 'ubuntu1804' ]; then init="/lib/systemd/systemd" opts="--privileged --volume=/sys/fs/cgroup:/sys/fs/cgroup:ro" # Ubuntu 16.04 elif [ $distro = 'ubuntu1604' ]; then init="/lib/systemd/systemd" opts="--privileged --volume=/sys/fs/cgroup:/sys/fs/cgroup:ro" # Debian 9 elif [ $distro = 'debian9' ]; then init="/lib/systemd/systemd" opts="--privileged --volume=/sys/fs/cgroup:/sys/fs/cgroup:ro" fi # Set OS-specific options. if [[ "$OSTYPE" == "darwin"* ]]; then volume_opts='rw,cached' else volume_opts='rw' fi # Use correct xargs command depending if it's GNU or BSD. if xargs --version 2>&1 | grep -s GNU >/dev/null; then xargs_command='xargs -r' else xargs_command='xargs' fi # Exit on any individual command failure. set -e # Pretty colors. red='\033[0;31m' green='\033[0;32m' neutral='\033[0m' # Remove test container if it already exists. printf "\n"${green}"Removing any existing test containers..."${neutral}"\n" docker ps -aq --filter name=$CONTAINER_ID | $xargs_command docker rm -f -v printf ${green}"...done!"${neutral}"\n" # Run the container. printf "\n"${green}"Starting Docker container: geerlingguy/docker-$distro-ansible."${neutral}"\n" docker run --name=$CONTAINER_ID -d \ --add-host "$HOSTNAME drupalvm":127.0.0.1 \ -v $PWD:/var/www/drupalvm/:$volume_opts \ $opts \ geerlingguy/docker-$distro-ansible:latest \ $init # Set up directories. docker exec $CONTAINER_ID mkdir -p /var/www/drupalvm/drupal [[ ! -z "$config_dir" ]] && docker exec $CONTAINER_ID mkdir -p $config_dir || true # Copy configuration into place. docker exec $CONTAINER_ID cp $DRUPALVM_DIR/$CONFIG ${config_dir:-$DRUPALVM_DIR}/config.yml docker exec $CONTAINER_ID cp $DRUPALVM_DIR/$MAKEFILE ${config_dir:-$DRUPALVM_DIR}/drupal.make.yml docker exec $CONTAINER_ID cp $DRUPALVM_DIR/$COMPOSERFILE ${config_dir:-$DRUPALVM_DIR}/drupal.composer.json [[ ! -z "$DRUPALVM_ENV" ]] && docker exec $CONTAINER_ID bash -c "cp $DRUPALVM_DIR/tests/$DRUPALVM_ENV.config.yml ${config_dir:-$DRUPALVM_DIR}/$DRUPALVM_ENV.config.yml" || true # Override configuration variables with local config. [[ ! -z "$local_config" ]] && docker exec $CONTAINER_ID bash -c "cp $DRUPALVM_DIR/$local_config ${config_dir:-$DRUPALVM_DIR}/local.config.yml" || true # Check playbook syntax. printf "\n"${green}"Checking playbook syntax..."${neutral}"\n" docker exec --tty $CONTAINER_ID env TERM=xterm ansible-playbook $DRUPALVM_DIR/provisioning/playbook.yml --syntax-check # Run Ansible Lint. docker exec $CONTAINER_ID bash -c "pip install ansible-lint" docker exec $CONTAINER_ID bash -c "cd $DRUPALVM_DIR/provisioning && ansible-lint playbook.yml" || true # Run the setup playbook. printf "\n"${green}"Running the setup playbook..."${neutral}"\n" docker exec --tty $CONTAINER_ID env TERM=xterm ansible-playbook /var/www/drupalvm/tests/test-setup.yml # Run the Drupal VM playbook. printf "\n"${green}"Running the Drupal VM playbook..."${neutral}"\n" if [ ! -z "${config_dir}" ]; then # Run with config_dir specified. docker exec $CONTAINER_ID env TERM=xterm ANSIBLE_FORCE_COLOR=true DRUPALVM_ENV=$DRUPALVM_ENV \ ansible-playbook $DRUPALVM_DIR/provisioning/playbook.yml \ --extra-vars="config_dir=$config_dir"; else # Run without config_dir specified. docker exec $CONTAINER_ID env TERM=xterm ANSIBLE_FORCE_COLOR=true DRUPALVM_ENV=$DRUPALVM_ENV \ ansible-playbook $DRUPALVM_DIR/provisioning/playbook.yml; fi # Drupal. printf "\n"${green}"Running functional tests..."${neutral}"\n" docker exec $CONTAINER_ID curl -sSi --header Host:$HOSTNAME localhost \ | tee /tmp/dvm-test \ | grep -q '<title>Welcome to Drupal' \ && (echo 'Drupal install pass' && exit 0) \ || (echo 'Drupal install fail' && cat /tmp/dvm-test && exit 1) # Adminer. if [ $TEST_INSTALLED_EXTRAS = true ]; then docker exec $CONTAINER_ID curl -sSi --header Host:adminer.$HOSTNAME localhost \ | tee /tmp/dvm-test \ | grep -q '<title>Login - Adminer' \ && (echo 'Adminer install pass' && exit 0) \ || (echo 'Adminer install fail' && cat /tmp/dvm-test && exit 1) fi # Pimp My Log. if [ $TEST_INSTALLED_EXTRAS = true ]; then docker exec $CONTAINER_ID curl -sSi --header Host:pimpmylog.$HOSTNAME localhost \ | tee /tmp/dvm-test \ | grep -q '<title>Pimp my Log' \ && (echo 'Pimp my Log install pass' && exit 0) \ || (echo 'Pimp my Log install fail' && cat /tmp/dvm-test && exit 1) fi # MailHog. if [ $TEST_INSTALLED_EXTRAS = true ]; then docker exec $CONTAINER_ID curl -sSi localhost:8025 \ | tee /tmp/dvm-test \ | grep -q '<title>MailHog' \ && (echo 'MailHog install pass' && exit 0) \ || (echo 'MailHog install fail' && cat /tmp/dvm-test && exit 1) fi # Varnish. if [ $TEST_INSTALLED_EXTRAS = true ]; then docker exec $CONTAINER_ID curl -sSI --header Host:$HOSTNAME localhost:81 \ | tee /tmp/dvm-test \ | grep -q 'Via: .* varnish' \ && (echo 'Varnish install pass' && exit 0) \ || (echo 'Varnish install fail' && cat /tmp/dvm-test && exit 1) fi # Dashboard. docker exec $CONTAINER_ID curl -sSi --header Host:$IP localhost \ | tee /tmp/dvm-test \ | grep -q "<li>$IP $HOSTNAME</li>" \ && (echo 'Dashboard install pass' && exit 0) \ || (echo 'Dashboard install fail' && cat /tmp/dvm-test && exit 1) # Drush - see https://github.com/drush-ops/drush/issues/3336. This test would # also test generated global Drush aliases, but it's currently not working due # to $reasons. # docker exec $CONTAINER_ID $DRUSH_BIN @$MACHINE_NAME.$HOSTNAME status \ # | tee /tmp/dvm-test \ # | grep -q 'Drupal bootstrap.*Successful' \ # && (echo 'Drush install pass' && exit 0) \ # || (echo 'Drush install fail' && cat /tmp/dvm-test && exit 1) # Drush. docker exec $CONTAINER_ID bash -c "cd $DRUPALVM_DIR/drupal && $DRUSH_BIN status" \ | tee /tmp/dvm-test \ | grep -q 'Drush' \ && (echo 'Drush install pass' && exit 0) \ || (echo 'Drush install fail' && cat /tmp/dvm-test && exit 1) # Remove test container. if [ $cleanup = true ]; then printf "\n"${green}"Cleaning up..."${neutral}"\n" docker rm -f $CONTAINER_ID printf ${green}"...done!"${neutral}"\n\n" else printf "\n"${green}"Skipping cleanup for container id: ${CONTAINER_ID}!"${neutral}"\n" printf ${green}"Done!"${neutral}"\n\n" fi
# This script has shell commands to get most of the basics folder items from github. wget https://raw.githubusercontent.com/MXET/SCUTTLE/master/software/python/basics/L0_mjpg_streamer_filter.py wget https://raw.githubusercontent.com/MXET/SCUTTLE/master/software/python/basics/L1_adc.py wget https://raw.githubusercontent.com/MXET/SCUTTLE/master/software/python/basics/L1_bmp.py wget https://raw.githubusercontent.com/MXET/SCUTTLE/master/software/python/basics/L1_camera.py wget https://raw.githubusercontent.com/MXET/SCUTTLE/master/software/python/basics/L1_encoder.py wget https://raw.githubusercontent.com/MXET/SCUTTLE/master/software/python/basics/L1_gamepad.py wget https://raw.githubusercontent.com/MXET/SCUTTLE/master/software/python/basics/L1_gpio.py wget https://raw.githubusercontent.com/MXET/SCUTTLE/master/software/python/basics/L1_lidar.py wget https://raw.githubusercontent.com/MXET/SCUTTLE/master/software/python/basics/L1_motors.py wget https://raw.githubusercontent.com/MXET/SCUTTLE/master/software/python/basics/L1_mpu.py wget https://raw.githubusercontent.com/MXET/SCUTTLE/master/software/python/basics/L1_mqtt.py wget https://raw.githubusercontent.com/MXET/SCUTTLE/master/software/python/basics/L1_rfid.py wget https://raw.githubusercontent.com/MXET/SCUTTLE/master/software/python/basics/L1_rssi.py wget https://raw.githubusercontent.com/MXET/SCUTTLE/master/software/python/basics/L1_servo.py wget https://raw.githubusercontent.com/MXET/SCUTTLE/master/software/python/basics/L1_text2speech.py wget https://raw.githubusercontent.com/MXET/SCUTTLE/master/software/python/basics/L2_color_target.py wget https://raw.githubusercontent.com/MXET/SCUTTLE/master/software/python/basics/L2_heading.py wget https://raw.githubusercontent.com/MXET/SCUTTLE/master/software/python/basics/L2_inverse_kinematics.py wget https://raw.githubusercontent.com/MXET/SCUTTLE/master/software/python/basics/L2_joint.py wget https://raw.githubusercontent.com/MXET/SCUTTLE/master/software/python/basics/L2_kinematics.py wget https://raw.githubusercontent.com/MXET/SCUTTLE/master/software/python/basics/L2_log.py wget https://raw.githubusercontent.com/MXET/SCUTTLE/master/software/python/basics/L2_obstacle.py wget https://raw.githubusercontent.com/MXET/SCUTTLE/master/software/python/basics/L2_speed_control.py wget https://raw.githubusercontent.com/MXET/SCUTTLE/master/software/python/basics/L2_track_target.py wget https://raw.githubusercontent.com/MXET/SCUTTLE/master/software/python/basics/L2_vector.py wget https://raw.githubusercontent.com/MXET/SCUTTLE/master/software/python/basics/L3_telemetry.py
package com.example.ts.grallery; import android.content.Intent; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.os.Bundle; import android.util.DisplayMetrics; import android.util.Log; import android.view.View; import android.widget.Button; import android.widget.TextView; import com.example.ts.grallery.bean.Image; import com.example.ts.grallery.bean.ImageFolder; import com.example.ts.grallery.utils.BitmapUtil; import com.example.ts.grallery.utils.QueryImageUtil; import com.example.ts.grallery.view.CropImageView; import java.io.File; import java.io.Serializable; import java.util.ArrayList; import java.util.List; /** */ public class ImageCropActivity extends ImageBaseActivity implements View.OnClickListener, CropImageView.OnBitmapSaveCompleteListener { private CropImageView mCropImageView; private Bitmap mBitmap; private boolean mIsSaveRectangle; private int mOutputX; private int mOutputY; private ArrayList<Image> mImages; private ImagePicker imagePicker; private Image mImage; private static final String EDITED_IMAGE = "edited_image"; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_image_crop); imagePicker = ImagePicker.getInstance(); //ๅˆๅง‹ๅŒ–View findViewById(R.id.btn_back).setOnClickListener(this); TextView tv_des = (TextView) findViewById(R.id.tv_des); tv_des.setText(getString(R.string.ip_photo_crop)); Button btn_ok = (Button) findViewById(R.id.btn_ok); btn_ok.setVisibility(View.VISIBLE); btn_ok.setText(getString(R.string.ip_complete)); btn_ok.setOnClickListener(this); mCropImageView = (CropImageView) findViewById(R.id.cv_crop_image); mCropImageView.setOnBitmapSaveCompleteListener(this); //่Žทๅ–้œ€่ฆ็š„ๅ‚ๆ•ฐ mOutputX = imagePicker.getOutPutX(); mOutputY = imagePicker.getOutPutY(); mIsSaveRectangle = imagePicker.isSaveRectangle(); Intent intent = getIntent(); if (intent.hasExtra(EDITED_IMAGE)) { mImage = (com.example.ts.grallery.bean.Image) intent.getSerializableExtra(EDITED_IMAGE); } else { mImages = imagePicker.getSelectedImages(); mImage = mImages.get(0); } String imagePath; if (null != mImage) { imagePath = mImage.getPath(); } else { return; } mCropImageView.setFocusStyle(imagePicker.getStyle()); mCropImageView.setFocusWidth(imagePicker.getFocusWidth()); mCropImageView.setFocusHeight(imagePicker.getFocusHeight()); //็ผฉๆ”พๅ›พ็‰‡ BitmapFactory.Options options = new BitmapFactory.Options(); options.inJustDecodeBounds = true; BitmapFactory.decodeFile(imagePath, options); DisplayMetrics displayMetrics = getResources().getDisplayMetrics(); options.inSampleSize = calculateInSampleSize(options, displayMetrics.widthPixels, displayMetrics.heightPixels); options.inJustDecodeBounds = false; mBitmap = BitmapFactory.decodeFile(imagePath, options); //่ฎพ็ฝฎ้ป˜่ฎคๆ—‹่ฝฌ่ง’ๅบฆ mCropImageView.setImageBitmap(mCropImageView.rotate(mBitmap, BitmapUtil.getBitmapDegree(imagePath))); // mCropImageView.setImageURI(Uri.fromFile(new File(imagePath))); } public int calculateInSampleSize(BitmapFactory.Options options, int reqWidth, int reqHeight) { int width = options.outWidth; int height = options.outHeight; int inSampleSize = 1; if (height > reqHeight || width > reqWidth) { if (width > height) { inSampleSize = width / reqWidth; } else { inSampleSize = height / reqHeight; } } return inSampleSize; } @Override public void onClick(View v) { int id = v.getId(); if (id == R.id.btn_back) { setResult(RESULT_CANCELED); finish(); } else if (id == R.id.btn_ok) { File image = new File(mImage.getPath()); String parentFloder = image.getParent(); File floder = new File(parentFloder); mCropImageView.saveBitmapToFile(floder, mOutputX, mOutputY, mIsSaveRectangle); } } @Override public void onBitmapSaveSuccess(File file) { // Toast.makeText(ImageCropActivity.this, "่ฃๅ‰ชๆˆๅŠŸ:" + file.getAbsolutePath(), Toast.LENGTH_SHORT).show(); //่ฃๅ‰ชๅŽๆ›ฟๆขๆމ่ฟ”ๅ›žๆ•ฐๆฎ็š„ๅ†…ๅฎน๏ผŒไฝ†ๆ˜ฏไธ่ฆๆ”นๅ˜ๅ…จๅฑ€ไธญ็š„้€‰ไธญๆ•ฐๆฎ Image image = new Image(); String path = file.getAbsolutePath(); Log.d("ImageCrop",path); image.setPath(path); image.setName(path.substring(0,path.length()-1)); Intent intent = new Intent(); intent.putExtra("new_image", (Serializable) image); setResult(RESULT_OK, intent); finish(); } @Override public void onBitmapSaveError(File file) { Log.d("ImageCrop","save error"); } @Override protected void onDestroy() { super.onDestroy(); mCropImageView.setOnBitmapSaveCompleteListener(null); if (null != mBitmap && !mBitmap.isRecycled()) { mBitmap.recycle(); mBitmap = null; } new QueryImageUtil(this,null,new QueryImageUtil.OnImagesLoadedListener(){ @Override public void onImagesLoaded(List<ImageFolder> imageFolders) { ImagePicker imagePicker = ImagePicker.getInstance(); imagePicker.setImageFolders(imageFolders); } }); } }
#!/bin/bash JOB_HOME="." SERV_NAME="MiddleManager-server" OUT_LOG="logs/middleManager.log" RUN_PID="run/middleManager" function startJob() { echo "prepare to start ..." java `cat conf/druid/middleManager/jvm.config | xargs` -cp conf/druid/_common:conf/druid/middleManager:lib/* org.apache.druid.cli.Main server middleManager > ${JOB_HOME}/${OUT_LOG} 2>&1 & PID=$! echo $PID > ${JOB_HOME}/${RUN_PID} echo "${SERV_NAME} is started as pid $! ." } if [ -f "${JOB_HOME}/${RUN_PID}" ] then PID=`cat ${JOB_HOME}/${RUN_PID}` if ps -p $PID > /dev/null then echo "${SERV_NAME} is running as pid is $PID, stop it first" exit 1 else startJob exit 1 fi else startJob exit 1 fi
#!/bin/bash set -ev echo "Uploading documentation to FTP server" if [[ $TRAVIS_PULL_REQUEST == "false" && $FTP_USER ]]; then ncftpput -R -v -u $FTP_USER -p $FTP_PASSWORD 104.130.212.175 / output/*; else echo "On a PR, skipping upload. Only direct commits are uploaded."; fi
#!/system/bin/sh # MagiskHide Props Config # Copyright (c) 2018-2019 Didgeridoohan @ XDA Developers # Licence: MIT PRINTSV=63 PRINTSTRANSF=350 # Certified fingerprints PRINTSLIST=" Asus Zenfone 2 Laser (6.0.1)=asus/WW_Z00L/ASUS_Z00L_63:6.0.1/MMB29P/WW_user_21.40.1220.2196_20180308:user/release-keys Asus Zenfone 3 Max (7.1.1 & 8.1.0)=asus/WW_Phone/ASUS_X00DD:7.1.1/NMF26F/14.0200.1712.347-20171214:user/release-keys;asus/WW_Phone/ASUS_X00DD:8.1.0/OPM1.171019.011/15.0200.1812.503-0:user/release-keys__2018-12-05 Asus Zenfone 4 Max (7.1.1)=asus/WW_Phone/ASUS_X00HD_4:7.1.1/NMF26F/14.2016.1801.372-20180119:user/release-keys Asus ZenFone 5Z (9)=asus/WW_Z01RD/ASUS_Z01R_1:9/PPR1.180610.009/WW_90.11.162.72_20190531:user/release-keys__2019-05-01 Asus Zenfone 6 (9.0)=asus/WW_I01WD/ASUS_I01WD:9/PPR2.181005.003/16.1210.1906.156-0:user/release-keys__2019-06-01 Asus Zenfone Max M1 (8.0.0)=asus/WW_X00PD/ASUS_X00P_4:8.0.0/OPR1.170623.032/15.00.1907.103:user/release-keys__2019-07-05 Asus Zenfone Max Pro M1 (8.1.0)=asus/RU_X00TD/ASUS_X00T_6:8.1.0/OPM1/15.2016.1902.340-20190216:user/release-keys__2019-02-01 Asus ZenPad S 8.0 (6.0.1)=asus/WW_P01M/P01M_3:6.0.1/MMB29P/WW_P01M-V5.6.0-20170608:user/release-keys BLU R1 HD 2018 (7.0)=BLU/BLU_S1/S0320WW:7.0/NRD90M/1514191903:user/release-keys Elephone U Pro (8.0.0)=Elephone/U_Pro/U_Pro:8.0.0/Elephone_U_Pro_20180917/09172123:user/release-keys__2018-09-05 Essential PH-1 (9)=essential/mata/mata:9/PQ1A.190105.112/550:user/release-keys__2019-08-05 Google Nexus 4 (5.1.1)=google/occam/mako:5.1.1/LMY48T/2237560:user/release-keys Google Nexus 5 (6.0.1)=google/hammerhead/hammerhead:6.0.1/M4B30Z/3437181:user/release-keys Google Nexus 5X (8.1.0)=google/bullhead/bullhead:8.1.0/OPM7.181205.001/5080180:user/release-keys__2018-12-05 Google Nexus 6 (7.1.1)=google/shamu/shamu:7.1.1/N6F27M/4299435:user/release-keys Google Nexus 6P (8.1.0)=google/angler/angler:8.1.0/OPM7.181205.001/5080180:user/release-keys__2018-12-05 Google Nexus 7 2012 WiFi (5.1.1)=google/nakasi/grouper:5.1.1/LMY47V/1836172:user/release-keys Google Nexus 7 2012 LTE (5.1.1)=google/nakasig/tilapia:5.1.1/LMY47V/1836172:user/release-keys Google Nexus 7 2013 WiFi (6.0.1)=google/razor/flo:6.0.1/MOB30X/3036618:user/release-keys Google Nexus 7 2013 LTE (6.0.1)=google/razorg/deb:6.0.1/MOB30X/3036618:user/release-keys Google Nexus 9 WiFi (7.1.1)=google/volantis/flounder:7.1.1/N9F27M/4333998:user/release-keys Google Nexus 9 LTE (7.1.1)=google/volantisg/flounder_lte:7.1.1/N4F27P/4333386:user/release-keys Google Nexus 10 (5.1.1)=google/mantaray/manta:5.1.1/LMY49J/2640980:user/release-keys Google Nexus Player (6.0.1)=google/fugu/fugu:6.0.1/MMB29U/2495654:user/release-keys Google Pixel (8.1.0 & 9)=google/sailfish/sailfish:8.1.0/OPM2.171019.029/4657601:user/release-keys;google/sailfish/sailfish:9/PQ3A.190801.002/5670241:user/release-keys__2019-08-01 Google Pixel XL (8.1.0 & 9)=google/marlin/marlin:8.1.0/OPM2.171019.029/4657601:user/release-keys;google/marlin/marlin:9/PQ3A.190801.002/5670241:user/release-keys__2019-08-01 Google Pixel 2 (8.1.0 & 9)=google/walleye/walleye:8.1.0/OPM2.171019.029/4657601:user/release-keys;google/walleye/walleye:9/PQ3A.190801.002/5670241:user/release-keys__2019-08-01 Google Pixel 2 XL (8.1.0 & 9)=google/taimen/taimen:8.1.0/OPM4.171019.016.B1/4720843:user/release-keys;google/taimen/taimen:9/PQ3A.190801.002/5670241:user/release-keys__2019-08-01 Google Pixel 3 (9)=google/blueline/blueline:9/PQ3A.190801.002/5670241:user/release-keys__2019-08-01 Google Pixel 3 XL (9)=google/crosshatch/crosshatch:9/PQ3A.190801.002/5670241:user/release-keys__2019-08-01 Google Pixel 3a (9)=google/sargo/sargo:9/PQ3B.190801.002/5674421:user/release-keys__2019-08-01 Google Pixel 3a XL (9)=google/bonito/bonito:9/PQ3B.190801.002/5674421:user/release-keys__2019-08-01 Google Pixel C (8.1.0)=google/ryu/dragon:8.1.0/OPM8.190605.003/5524042:user/release-keys__2019-06-05 HTC 10 (6.0.1)=htc/HTCOneM10vzw/htc_pmewl:6.0.1/MMB29M/774095.8:user/release-keys HTC U11 (8.0.0)=htc/ocndtwl_01405/htc_ocndtwl:8.0.0/OPR6.170623.013/1017190.2:user/release-keys HTC U12 Plus (8.0.0)=htc/imeuhl_00617/htc_imeuhl:8.0.0/OPR1.170623.032/1041457.3:user/release-keys__2018-06-01 Huawei Honor 6X (8.0.0)=HONOR/BLN-AL10/HWBLN-H:8.0.0/HONORBLN-AL10/528(C00):user/release-keys Huawei Honor 8X (8.1.0)=HONOR/JSN-L21RU/HWJSN-H:8.1.0/HONORJSN-L21/101(C10):user/release-keys__2018-10-01 Huawei Honor 9 (8.0.0 & 9)=HONOR/STF-L09/HWSTF:8.0.0/HUAWEISTF-L09/364(C432):user/release-keys;HONOR/STF-L09/HWSTF:9/HUAWEISTF-L09/157C432R1:user/release-keys__2019-02-01 Huawei Mate 10 (8.0.0)=HUAWEI/ALP-L29/HWALP:8.0.0/HUAWEIALP-L29S/143(C636):user/release-keys__2018-10-01 Huawei Mate 10 Pro (8.0.0)=HUAWEI/BLA-L29/HWBLA:8.0.0/HUAWEIBLA-L29S/137(C432):user/release-keys Huawei Mate 20 Pro (9)=HUAWEI/LYA-L29/HWLYA:9/HUAWEILYA-L29/310C432:user/release-keys__2019-07-05 Huawei P8 Lite (8.0.0)=HUAWEI/PRA-LX1/HWPRA-H:8.0.0/HUAWEIPRA-LX1/401(C432):user/release-keys__2019-01-01 Huawei P9 (7.0)=HUAWEI/EVA-L09/HWEVA:7.0/HUAWEIEVA-L09/C432B502:user/release-keys Huawei P9 Lite (7.0)=HUAWEI/VNS-L31/HWVNS-H:7.0/HUAWEIVNS-L31/C432B414:user/release-keys__2018-06-01 Huawei P9 Plus (7.0)=HUAWEI/VIE-L09/HWVIE:7.0/HUAWEIVIE-L09/C432B387:user/release-keys__2018-07-01 Huawei P20 (9)=HUAWEI/EML-L29/HWEML:9/HUAWEIEML-L29/197C432R1:user/release-keys__2019-01-01 Huawei P20 Lite (8.0.0 & 9)=HUAWEI/ANE-LX1/HWANE:8.0.0/HUAWEIANE-LX1/180(C432):user/release-keys__2019-04-05;HUAWEI/ANE-LX1/HWANE:9/HUAWEIANE-L21/132C432R1:user/release-keys__2019-05-05 Huawei P20 Pro (8.1.0 & 9)=HUAWEI/CLT-L29/HWCLT:8.1.0/HUAWEICLT-L29/128(C432):user/release-keys;HUAWEI/CLT-L09/HWCLT:9/HUAWEICLT-L09/203C432R1:user/release-keys__2019-02-01 Lenovo K6 Note (7.0)=Lenovo/karatep/K53a48:7.0/NRD90N/K53_S228_171114_ROW:user/release-keys LeEco Le Pro3 (6.0.1)=LeEco/ZL1_NA/le_zl1:6.0.1/WEXNAOP5802101261S/letv01261206:user/release-keys LG G2 BS980 (5.0.2)=lge/g2_vzw/g2:5.0.2/LRX22G/15046001715f9:user/release-keys LG G4 H812 (6.0)=lge/p1_rgs_ca/p1:6.0/MRA58K/1601215569825:user/release-keys LG G5 H850 (8.0.0)=lge/h1_global_com/h1:8.0.0/OPR1.170623.032/190380127377a:user/release-keys__2018-12-01 LG G5 H830 (8.0.0)=lge/h1_tmo_us/h1:8.0.0/OPR1.170623.032/182251913485f:user/release-keys__2018-08-01 LG G5 RS988 (7.0)=lge/h1_lra_us/h1:7.0/NRD90U/1707917149a1b:user/release-keys LG G6 H870 (7.0 & 8.0.0)=lge/lucye_global_com/lucye:7.0/NRD90U/171732341982c:user/release-keys;lge/lucye_global_com/lucye:8.0.0/OPR1.170623.032/183301757502c:user/release-keys__2018-11-01 LG G6 H872 (8.0.0)=lge/lucye_tmo_us/lucye:8.0.0/OPR1.170623.032/183621644ce05:user/release-keys__2019_01-01 LG V20 H918 (8.0.0)=lge/elsa_tmo_us/elsa:8.0.0/OPR1.170623.032/1831917495b33:user/release-keys__2018-11-01 LG V20 H910 (8.0.0)=lge/elsa_att_us/elsa:8.0.0/OPR1.170623.032/181871124f959:user/release-keys__2018-06-01 LG V20 H990DS (7.0)=lge/elsa_global_com/elsa:7.0/NRD90M/1801800193678:user/release-keys LG V20 LS997 (8.0.0)=lge/elsa_spr_us/elsa:8.0.0/OPR1.170623.032/1819814314eb7:user/release-keys__2018-07-01 LG V20 US996 (8.0.0)=lge/elsa_nao_us/elsa:8.0.0/OPR1.170623.032/183241436cd40:user/release-keys__2018-11-01 LG V20 VS995 (8.0.0)=lge/elsa_vzw/elsa:8.0.0/OPR1.170623.032/183141449275f:user/release-keys__2018-10-01 LG V30 H930 (8.0.0)=lge/joan_global_com/joan:8.0.0/OPR1.170623.026/181381736b4e9:user/release-keys__2018-11-05 Mecool KM8 (8.0.0 & 9)=MECOOL/KM8/KM8:8.0.0/OPR6.170623.013/V0412.201806271453:user/release-keys__2018-05-05;MECOOL/KM8/KM8:9/PI/20190315:user/release-keys__2019-02-05 Motorola Moto C Plus (7.0)=motorola/panell_21_d/panell_d:7.0/NRD90M.03.040/040:user/release-keys Motorola Moto E4 (7.1.1)=motorola/sperry_sprint/sperry:7.1.1/NCQ26.69-64/68:user/release-keys Motorola Moto E4 Plus (7.1.1)=motorola/nicklaus_fn/nicklaus_fn:7.1.1/NMA26.42-156/183:user/release-keys Motorola Moto E5 Play (8.0.0)=motorola/james_sprint/james:8.0.0/OCPS27.91-140-1/1:user/release-keys__2018-10-01 Motorola Moto E5 Plus (8.0.0)=motorola/hannah_sprint/hannah:8.0.0/OCPS27.91-32-4/4:user/release-keys__2018-10-01 Motorola Moto G4 (7.0 & 8.1.0)=motorola/athene/athene:7.0/NPJS25.93-14-13/3:user/release-keys;motorola/athene/athene:8.1.0/OPJ28.111-22/532da:user/release-keys__2018-12-01 Motorola Moto G5 (7.0)=motorola/cedric/cedric:7.0/NPPS25.137-15-11/11:user/release-keys Motorola Moto G5 Plus (7.0)=motorola/potter_n/potter_n:7.0/NPNS25.137-33-11/11:user/release-keys Motorola Moto G5S (7.1.1 & 8.1.0)=motorola/montana/montana:7.1.1/NPPS26.102-49-8/6:user/release-keys;motorola/montana/montana:8.1.0/OPPS28.65-37-7-4/1dd5:user/release-keys__2019-02-01 Motorola Moto G6 (9)=motorola/ali/ali:9/PPS29.55-34/0c5d:user/release-keys__2019-02-01 Motorola Moto G6 Play (8.0.0 & 9)=motorola/jeter_sprint/jeter:8.0.0/OCP27.91-23/23:user/release-keys;motorola/aljeter/aljeter:9/PPP29.55-25/08c6:user/release-keys__2019-01-01 Motorola Moto G6 Plus (9)=motorola/evert_amx_n/evert_n:9/PPWS29.116-16-6/5cbfe:user/release-keys__2019-05-01 Motorola Moto X4 (8.0.0)=motorola/payton/payton:8.0.0/OPWS27.57-25-6-10/12:user/release-keys Motorola Moto Z2 Play (8.0.0)=motorola/albus/albus:8.0.0/OPS27.76-12-25/26:user/release-keys Nextbook Ares 8A (6.0.1)=NextBook/NX16A8116K/NX16A8116K:6.0.1/MMB29M/V4.0.3:user/release-keys Nokia 7 Plus (9)=Nokia/Onyx_00WW/B2N_sprout:9/PPR1.180610.011/00WW_3_53B:user/release-keys__2019-05-01 Nvidia Shield K1 (7.0)=nvidia/sb_na_wf/shieldtablet:7.0/NRD90M/1928188_1065.2559:user/release-keys Nvidia Shield Tablet (7.0)=nvidia/wx_na_wf/shieldtablet:7.0/NRD90M/1928188_904.2811:user/release-keys OnePlus 2 (6.0.1)=OnePlus/OnePlus2/OnePlus2:6.0.1/MMB29M/1447858500:user/release-keys OnePlus X (6.0.1)=OnePlus/OnePlus/OnePlus:6.0.1/MMB29M/10281213:user/release-keys OnePlus 3 (8.0.0 & 9)=OnePlus/OnePlus3/OnePlus3:8.0.0/OPR1.170623.032/1809142047:user/release-keys__2018-09-01;OnePlus/OnePlus3/OnePlus3:9/PKQ1.181203.001/1907311932:user/release-keys__2019-08-01 OnePlus 3T (8.0.0 & 9)=OnePlus/OnePlus3/OnePlus3T:8.0.0/OPR1.170623.032/1812060016:user/release-keys__2018-11-01;OnePlus/OnePlus3/OnePlus3T:9/PKQ1.181203.001/1907311932:user/release-keys__2019-08-01 OnePlus 5 (8.1.0 & 9)=OnePlus/OnePlus5/OnePlus5:8.1.0/OPM1.171019.011/1809241512:user/release-keys__2018-09-01;OnePlus/OnePlus5/OnePlus5:9/PKQ1.180716.001/1907311824:user/release-keys__2019-08-01 OnePlus 5T (8.1.0 & 9)=OnePlus/OnePlus5T/OnePlus5T:8.1.0/OPM1.171019.011/1809241512:user/release-keys__2018-09-01;OnePlus/OnePlus5T/OnePlus5T:9/PKQ1.180716.001/1907311828:user/release-keys__2019-08-01 OnePlus 6 (8.1.0 & 9)=OnePlus/OnePlus6/OnePlus6:8.1.0/OPM1.171019.011/06140300:user/release-keys;OnePlus/OnePlus6/OnePlus6:9/PKQ1.180716.001/1908012000:user/release-keys__2019-08-01 OnePlus 6T (9)=OnePlus/OnePlus6T/OnePlus6T:9/PKQ1.180716.001/1908012000:user/release-keys__2019-08-01 OnePlus 7 GM1901/GM1905 (9)=OnePlus/OnePlus7/OnePlus7:9/PKQ1.190110.001/1907280700:user/release-keys__2019-08-01 OnePlus 7 GM1903 (9)=OnePlus/OnePlus7_EEA/OnePlus7:9/PKQ1.190110.001/1907280700:user/release-keys__2019-08-01 OnePlus 7 Pro GM1911/GM1917 (9)=OnePlus/OnePlus7Pro/OnePlus7Pro:9/PKQ1.190110.001/1907281556:user/release-keys__2019-08-01 OnePlus 7 Pro GM1913 (9)=OnePlus/OnePlus7Pro_EEA/OnePlus7Pro:9/PKQ1.190110.001/1907281556:user/release-keys__2019-08-01 OnePlus 7 Pro NR GM1920 (9)=OnePlus/OnePlus7ProNR_EEA/OnePlus7ProNR:9/PKQ1.190223.001/1907280803:user/release-keys__2019-06-01 OPPO Neo 7 A33w (5.1)=OPPO/A33w/A33w:5.1/LMY47I/1487829433:user/release-keys OPPO Neo 7 A1603 (5.1)=OPPO/A1603/A1603:5.1/LMY47I/1489407760:user/release-keys Razer Phone (8.1.0)=razer/cheryl/cheryl:8.1.0/OPM1.171019.011-RZR-180803/6033:user/release-keys__2018-07-05 Razer Phone 2 (8.1.0)=razer/cheryl2/aura:8.1.0/O-MR2-RC009-RZR-181124/2009:user/release-keys__2018-10-05 Samsung Galaxy A5 2015 (6.0.1)=samsung/a5ultexx/a5ulte:6.0.1/MMB29M/A500FUXXU1CPH3:user/release-keys Samsung Galaxy A5 2017 (8.0.0)=samsung/a5y17ltexx/a5y17lte:8.0.0/R16NW/A520FXXU4CRE8:user/release-keys__2018-05-01 Samsung Galaxy A6 Plus (9)=samsung/a6pltedx/a6plte:9/PPR1.180610.011/A605GDXU3BSC6:user/release-keys__2019-03-01 Samsung Galaxy A8 Plus (7.1.1)=samsung/jackpot2ltexx/jackpot2lte:7.1.1/NMF26X/A730FXXU2ARD1:user/release-keys Samsung Galaxy Grand Prime (5.0.2)=samsung/fortuna3gdtvvj/fortuna3gdtv:5.0.2/LRX22G/G530BTVJU1BPH4:user/release-keys Samsung Galaxy J2 (5.1.1)=samsung/j23gdd/j23g:5.1.1/LMY48B/J200HXXU0AQK2:user/release-keys Samsung Galaxy J3 (5.1.1)=samsung/j3xnltexx/j3xnlte:5.1.1/LMY47V/J320FNXXU0ARB1:user/release-keys Samsung Galaxy J5 2015 (6.0.1)=samsung/j5nltexx/j5nlte:6.0.1/MMB29M/J500FNXXS1BQG1:user/release-keys Samsung Galaxy J5 2016 (7.1.1)=samsung/j5xnltexx/j5xnlte:7.1.1/NMF26X/J510FNXXS2BRA2:user/release-keys Samsung Galaxy J5 Prime (7.0)=samsung/on5xeltejv/on5xelte:7.0/NRD90M/G570FXXU1BQI6:user/release-keys Samsung Galaxy J7 2017 (8.1.0)=samsung/j7y17ltexx/j7y17lte:8.1.0/M1AJQ/J730FXXU3BRK2:user/release-keys__2018-11-01 Samsung Galaxy J7 Prime (6.0.1)=samsung/on7xeltedd/on7xelte:6.0.1/MMB29K/G610FDDU1AQG2:user/release-keys Samsung Galaxy Note 3 (5.0)=samsung/hltezh/hlte:5.0/LRX21V/N9005ZSUGPJ2:user/release-keys Samsung Galaxy Note 4 (6.0.1)=samsung/trltexx/trlte:6.0.1/MMB29M/N910FXXS1DQH9:user/release-keys Samsung Galaxy Note 5 (7.0)=samsung/nobleltejv/noblelte:7.0/NRD90M/N920CXXU3CQH6:user/release-keys Samsung Galaxy Note 8 (8.0.0)=samsung/greatltexx/greatlte:8.0.0/R16NW/N950FXXU3CRC1:user/release-keys Samsung Galaxy Note 10.1 2014 (5.1.1)=samsung/lt03wifixx/lt03wifi:5.1.1/LMY47X/P600XXUDOJ3:user/release-keys Samsung Galaxy S3 Neo (4.4.4)=samsung/s3ve3gdd/s3ve3gdd:4.4.4/KTU84P/I9300IDDUBQE2:user/release-keys Samsung Galaxy S4 (5.0.1)=samsung/jfltexx/jflte:5.0.1/LRX22C/I9505XXUHPF4:user/release-keys Samsung Galaxy S4 Active (5.0.1)=samsung/jactiveltexx/jactivelte:5.0.1/LRX22C/I9295XXSDQD6:user/release-keys Samsung Galaxy S5 (6.0.1)=samsung/k3gxx/k3g:6.0.1/MMB29K/G900HXXU1CPF2:user/release-keys Samsung Galaxy S6 (7.0)=samsung/zerofltexx/zeroflte:7.0/NRD90M/G920FXXS5EQL1:user/release-keys Samsung Galaxy S6 Edge (7.0)=samsung/zeroltexx/zerolte:7.0/NRD90M/G925FXXS5EQL1:user/release-keys Samsung Galaxy S7 (8.0.0)=samsung/heroltexx/herolte:8.0.0/R16NW/G930FXXU2ERD5:user/release-keys Samsung Galaxy S7 Edge (8.0.0)=samsung/hero2ltexx/hero2lte:8.0.0/R16NW/G935FXXS4ESC3:user/release-keys__2019-03-01 Samsung Galaxy S8 (8.0.0)=samsung/dreamltexx/dreamlte:8.0.0/R16NW/G950FXXU1CRC7:user/release-keys Samsung Galaxy S8 Plus (8.0.0)=samsung/dream2ltexx/dream2lte:8.0.0/R16NW/G955FXXU1CRC7:user/release-keys Samsung Galaxy S9 (8.0.0)=samsung/starltexx/starlte:8.0.0/R16NW/G960FXXU1ARCC:user/release-keys Samsung Galaxy S9 Plus (8.0.0)=samsung/star2ltexx/star2lte:8.0.0/R16NW/G965FXXU1ARCC:user/release-keys Samsung Galaxy S10 Plus (9)=samsung/beyond2qlteue/beyond2q:9/PPR1.180610.011/G975U1UEU1ASD3:user/release-keys__2019-03-01 Samsung Galaxy Tab 2 7.0 (4.2.2)=samsung/espresso10wifixx/espresso10wifi:4.2.2/JDQ39/P5110XXDML1:user/release-keys Samsung Galaxy Tab S3 (LTE SM-T825) (8.0.0)=samsung/gts3lltexx/gts3llte:8.0.0/R16NW/T825XXU2BRL2:user/release-keys__2018-12-01 Sony Xperia X (8.0.0)=Sony/F5121/F5121:8.0.0/34.4.A.2.118/1631208121:user/release-keys__2018-09-01 Sony Xperia X Compact (8.0.0)=Sony/F5321/F5321:8.0.0/34.4.A.2.118/1631208121:user/release-keys__2018-09-01 Sony Xperia X Dual (8.0.0)=Sony/F5122/F5122:8.0.0/34.4.A.2.118/1631208121:user/release-keys__2018-09-01 Sony Xperia X Performance (8.0.0)=Sony/F8131/F8131:8.0.0/41.3.A.2.99/1455830589:user/release-keys Sony Xperia X Performance Dual (8.0.0)=Sony/F8132/F8132:8.0.0/41.3.A.2.99/1455830589:user/release-keys Sony Xperia XA2 Dual (8.0.0)=Sony/H4113/H4113:8.0.0/50.1.A.4.76/2209478692:user/release-keys Sony Xperia XZ (8.0.0)=Sony/F8331/F8331:8.0.0/41.3.A.2.99/1455830589:user/release-keys Sony Xperia XZ Dual (8.0.0)=Sony/F8332/F8332:8.0.0/41.3.A.2.99/1455830589:user/release-keys Sony Xperia XZ Premium (8.0.0)=Sony/G8141/G8141:8.0.0/47.1.A.12.179/1909673090:user/release-keys Sony Xperia XZ Premium Dual (8.0.0)=Sony/G8142/G8142:8.0.0/47.1.A.12.179/1909673090:user/release-keys Sony Xperia XZ1 (8.0.0)=Sony/G8341/G8341:8.0.0/47.1.A.12.179/1909673090:user/release-keys Sony Xperia XZ1 Compact (8.0.0 & 9)=Sony/G8441/G8441:8.0.0/47.1.A.12.179/1909673090:user/release-keys;Sony/G8441/G8441:9/47.2.A.2.33/3676206253:user/release-keys__2018-11-01 Sony Xperia XZ1 Dual (8.0.0)=Sony/G8342/G8342:8.0.0/47.1.A.12.179/1909673090:user/release-keys Sony Xperia XZ2 (8.0.0)=Sony/H8216/H8216:8.0.0/51.1.A.3.159/620448843:user/release-keys Sony Xperia XZ2 Compact (8.0.0)=Sony/H8314/H8314:8.0.0/51.1.A.3.159/620448843:user/release-keys Sony Xperia XZ2 Compact Dual (8.0.0)=Sony/H8324/H8324:8.0.0/51.1.A.3.159/620448843:user/release-keys Sony Xperia XZ2 Dual (8.0.0)=Sony/H8266/H8266:8.0.0/51.1.A.3.159/620448843:user/release-keys Sony Xperia Z (5.1.1)=Sony/C6603/C6603:5.1.1/10.7.A.0.228/58103698:user/release-keys Sony Xperia Z1 (5.1.1)=Sony/C6903/C6903:5.1.1/14.6.A.1.236/2031203603:user/release-keys Sony Xperia Z2 (6.0.1)=Sony/D6503/D6503:6.0.1/23.5.A.1.291/2769308465:user/release-keys Sony Xperia Z3 (6.0.1)=Sony/D6633/D6633:6.0.1/23.5.A.1.291/2769308465:user/release-keys Sony Xperia Z3 Compact (6.0.1)=Sony/D5803/D5803:6.0.1/23.5.A.1.291/2769308465:user/release-keys Sony Xperia Z3 Tablet Compact (6.0.1)=Sony/SGP621/SGP621:6.0.1/23.5.A.1.291/3706784398:user/release-keys Sony Xperia Z4 Tablet LTE (7.1.1)=Sony/SGP771/SGP771:7.1.1/32.4.A.1.54/219395100:user/release-keys Sony Xperia Z5 (7.1.1)=Sony/E6603/E6603:7.1.1/32.4.A.1.54/3761073091:user/release-keys Sony Xperia Z5 Compact (7.1.1)=Sony/E5823/E5823:7.1.1/32.4.A.1.54/3761073091:user/release-keys Sony Xperia Z5 Dual (7.1.1)=Sony/E6633/E6633:7.1.1/32.4.A.1.54/3761073091:user/release-keys Sony Xperia Z5 Premium (7.1.1)=Sony/E6853/E6853:7.1.1/32.4.A.1.54/3761073091:user/release-keys Sony Xperia Z5 Premium Dual (7.1.1)=Sony/E6883/E6883:7.1.1/32.4.A.1.54/3761073091:user/release-keys Vodafone Smart Ultra 6 (5.1.1)=Vodafone/P839V55/P839V55:5.1.1/LMY47V/20161227.134319.15534:user/release-keys Xiaomi Mi 3/4 (6.0.1)=Xiaomi/cancro/cancro:6.0.1/MMB29M/V9.5.2.0.MXDMIFA:user/release-keys Xiaomi Mi 4C (7.0)=Xiaomi/libra/libra:7.0/NRD90M/V9.6.2.0.NXKCNFD:user/release-keys Xiaomi Mi 5/5 Pro (7.0 & 8.0.0)=Xiaomi/gemini/gemini:7.0/NRD90M/V9.2.1.0.NAAMIEK:user/release-keys;Xiaomi/gemini/gemini:8.0.0/OPR1.170623.032/V9.6.1.0.OAAMIFD:user/release-keys Xiaomi Mi 5S (7.0)=Xiaomi/capricorn/capricorn:7.0/NRD90M/V9.5.4.0.NAGMIFD:user/release-keys Xiaomi Mi 5S Plus (6.0.1 & 7.0)=Xiaomi/natrium/natrium:6.0.1/MXB48T/V8.5.2.0.MBGMIED:user/release-keys;Xiaomi/natrium/natrium:7.0/NRD90M/V9.6.2.0.NBGMIFD:user/release-keys Xiaomi Mi 6 (8.0.0)=Xiaomi/sagit/sagit:8.0.0/OPR1.170623.027/V9.2.3.0.OCAMIEK:user/release-keys Xiaomi Mi 8 (8.1.0 & 9)=Xiaomi/dipper/dipper:8.1.0/OPM1.171019.011/V9.5.5.0.OEAMIFA:user/release-keys;Xiaomi/dipper/dipper:9/PKQ1.180729.001/V10.2.3.0.PEAMIXM:user/release-keys__2019-02-01 Xiaomi Mi 9 (9)=Xiaomi/cepheus_eea/cepheus:9/PKQ1.181121.001/V10.2.27.0.PFAEUXM:user/release-keys__2019-06-01 Xiaomi Mi A1 (8.0.0 & 9)=xiaomi/tissot/tissot_sprout:8.0.0/OPR1.170623.026/V.9.5.10.0.ODHMIFA:user/release-keys;xiaomi/tissot/tissot_sprout:9/PKQ1.180917.001/V10.0.4.0.PDHMIXM:user/release-keys__2019-01-05 Xiaomi Mi A2 (8.1.0 & 9)=xiaomi/jasmine/jasmine_sprout:8.1.0/OPM1.171019.011/V9.6.16.0.ODIMIFE:user/release-keys__2018-11-05;xiaomi/jasmine/jasmine_sprout:9/PKQ1.180904.001/V10.0.7.0.PDIMIXM:user/release-keys__2019-03-05 Xiaomi Mi A2 Lite (9)=xiaomi/daisy/daisy_sprout:9/PKQ1.180917.001/V10.0.1.0.PDLMIFJ:user/release-keys__2018-11-05 Xiaomi Mi Max (6.0.1)=Xiaomi/helium/helium:6.0.1/MMB29M/V8.2.3.0.MBDMIDL:user/release-keys Xiaomi Mi Max 2 (7.1.1)=Xiaomi/oxygen/oxygen:7.1.1/NMF26F/V9.5.4.0.NDDMIFA:user/release-keys Xiaomi Mi Max 3 (9)=Xiaomi/nitrogen/nitrogen:9/PKQ1.181007.001/V10.3.1.0.PEDMIXM:user/release-keys__2019-03-01 Xiaomi Mi Mix 2 (8.0.0)=Xiaomi/chiron/chiron:8.0.0/OPR1.170623.027/V10.2.2.0.ODEMIXM:user/release-keys__2018-12-01 Xiaomi Mi Mix 2S (8.0.0 & 9)=Xiaomi/polaris/polaris:8.0.0/OPR1.170623.032/V9.5.19.0.ODGMIFA:user/release-keys;Xiaomi/polaris/polaris:9/PKQ1.180729.001/V10.3.3.0.PDGMIXM:user/release-keys__2019-05-01 Xiaomi Mi Mix 3 (9)=Xiaomi/perseus/perseus:9/PKQ1.180729.001/V10.3.1.0.PEEMIXM:user/release-keys__2019-03-01 Xiaomi Mi Note 2 (7.0 & 8.0.0)=Xiaomi/scorpio/scorpio:7.0/NRD90M/V9.2.1.0.NADMIEK:user/release-keys;Xiaomi/scorpio/scorpio:8.0.0/OPR1.170623.032/V9.6.1.0.OADCNFD:user/release-keys Xiaomi Mi Note 3 (8.1.0)=Xiaomi/jason/jason:8.1.0/OPM1.171019.019/V10.2.2.0.OCHMIXM:user/release-keys__2018-12-01 Xiaomi Mi Pad 4 (8.1.0)=Xiaomi/clover/clover:8.1.0/OPM1.171019.019/V10.1.1.0.ODJCNFI:user/release-keys__2018-10-01 Xiaomi Pocophone F1 (9)=Xiaomi/beryllium/beryllium:9/PKQ1.180729.001/V10.3.6.0.PEJMIXM:user/release-keys__2019-06-01 Xiaomi Redmi 3/3 Pro (5.1.1)=Xiaomi/ido/ido:5.1.1/LMY47V/V9.6.2.0.LAIMIFD:user/release-keys Xiaomi Redmi 3S/X Prime (6.0.1)=Xiaomi/land/land:6.0.1/MMB29M/V9.5.1.0.MALMIFA:user/release-keys Xiaomi Redmi 4 Prime (6.0.1)=Xiaomi/markw/markw:6.0.1/MMB29M/V9.5.3.0.MBEMIFA:user/release-keys Xiaomi Redmi 4A (7.1.2)=Xiaomi/rolex/rolex:7.1.2/N2G47H/V9.2.6.0.NCCMIEK:user/release-keys Xiaomi Redmi 4X (6.0.1)=Xiaomi/santoni/santoni:6.0.1/MMB29M/V8.5.4.0.MAMCNED:user/release-keys Xiaomi Redmi 5A (7.1.2 & 8.1.0)=Xiaomi/riva/riva:7.1.2/N2G47H/V9.1.8.0.NCKMIEI:user/release-keys;Xiaomi/riva/riva:8.1.0/OPM1.171019.026/V10.3.2.0.OCKMIXM:user/release-keys__2019-06-01 Xiaomi Redmi Go (8.1.0)=Xiaomi/tiare/tiare:8.1.0/OPM1.171019.026/V10.2.6.0.OCLMIXM:user/release-keys__2019-01-01 Xiaomi Redmi K20 Pro (9)=Xiaomi/raphael/raphael:9/PKQ1.181121.001/V10.3.14.0.PFKCNXM:user/release-keys__2019-06-01 Xiaomi Redmi Note 2 (5.0.2)=Xiaomi/hermes/hermes:5.0.2/LRX22G/V9.2.4.0.LHMMIEK:user/release-keys Xiaomi Redmi Note 3 Pro (6.0.1)=Xiaomi/kenzo/kenzo:6.0.1/MMB29M/V8.2.1.0.MHOCNDL:user/release-keys Xiaomi Redmi Note 3 Pro SE (6.0.1)=Xiaomi/kate/kate:6.0.1/MMB29M/V8.1.3.0.MHRMIDI:user/release-keys Xiaomi Redmi Note 4 Mediatek (6.0)=Xiaomi/nikel/nikel:6.0/MRA58K/V9.2.2.0.MBFMIEK:user/release-keys Xiaomi Redmi Note 4/4X (7.0)=xiaomi/mido/mido:7.0/NRD90M/V9.2.1.0.NCFMIEK:user/release-keys Xiaomi Redmi Note 5/5 Plus (7.1.2 & 8.1.0)=xiaomi/vince/vince:7.1.2/N2G47H/V9.5.4.0.NEGMIFA:user/release-keys;xiaomi/vince/vince:8.1.0/OPM1.171019.019/V10.2.1.0.OEGMIXM:user/release-keys__2019-03-01 Xiaomi Redmi Note 5 Pro (8.1.0 & 9)=xiaomi/whyred/whyred:8.1.0/OPM1.171019.011/V10.0.6.0.OEIMIFH:user/release-keys__2018-11-01;xiaomi/whyred/whyred:9/PKQ1.180904.001/V10.3.1.0.PEIMIXM:user/release-keys__2019-05-05 Xiaomi Redmi Note 5A Lite (7.1.2)=xiaomi/ugglite/ugglite:7.1.2/N2G47H/V9.1.2.0.NDFMIEI:user/release-keys Xiaomi Redmi Note 6 Pro (8.1.0)=xiaomi/tulip/tulip:8.1.0/OPM1.171019.011/V10.0.5.0.OEKMIFH:user/release-keys__2018-10-01 Xiaomi Redmi Note 7 (9)=xiaomi/lavender/lavender:9/PKQ1.180904.001/V10.3.12.0.PFGMIXM:user/release-keys__2019-08-05 Xiaomi Redmi Y1 (7.1.2)=xiaomi/ugg/ugg:7.1.2/N2G47H/V9.6.2.0.NDKMIFD:user/release-keys__2018-07-01 ZTE Axon 7 (7.1.1 & 8.0.0)=ZTE/P996A01_N/ailsa_ii:7.1.1/NMF26V/20171211.005949:user/release-keys;ZTE/P996A01_O/ailsa_ii:8.0.0/OPR1.170623.032/20180815.171922:user/release-keys__2018-07-01 ZTE Blade (6.0.1)=ZTE/P809A50_MY_MAX/P809A50:6.0.1/MMB29M/20161017.095504:user/release-keys ZTE Nubia Z17 (7.1.1)=nubia/NX563J/NX563J:7.1.1/NMF26X/eng.nubia.20171019.101529:user/release-keys Zuk Z2 Pro (7.0)=ZUK/z2_row/z2_row:7.0/NRD90M/2.5.435_170525:user/release-keys "
#!/bin/sh echo . > mtgapbeak30v$1.txt echo . > mtgapbeak30v$1-main.txt echo . > mtgapbeak30v$1-shift.txt echo . > mtgapbeak30v$1-altGr.txt # echo . > mtgapbeak$1-shiftAltGr.txt
# -*- coding: utf-8 -*- import rest_framework.serializers as drf import app.comments.serializers as serializers import testutils.cases as cases import testutils.factories as factories import app.votes.models as votemodels class CommentSerializerCreateTests(cases.SerializerTestCase): """Test cases for the creating instances via CommentSerializer class. """ factory = factories.CommentFactory serializer_class = serializers.CommentSerializer serializer_resource_name = 'Comment' @classmethod def setUpTestData(cls): cls.commentable = factories.TableFactory() cls.workspace = cls.commentable.workspace cls.user = factories.UserFactory() def _get_attributes(self, **overrides): """Generate testing data. """ attributes = { 'html': '<p>Hello, this is my first comment.</p>', 'content_object': self.commentable, 'parent': None, } attributes.update(**overrides) return attributes def test_when_valid(self): """It should be able to create the resource. """ attributes = self._get_attributes() serializer = self.serializer_class(data=attributes) self.assertTrue(serializer.is_valid()) self.assertTrue(serializer.save(author=self.user)) def test_validate_html(self): og_html = '<p>This is a <script>test</script>.</p>' attributes = self._get_attributes(html=og_html) serializer = self.serializer_class(data=attributes) self.assertTrue(serializer.is_valid()) self.assertTrue(serializer.save(author=self.user)) self.assertEqual( serializer.instance.html, '<p>This is a &lt;script&gt;test&lt;/script&gt;.</p>', ) class CommentSerializerUpdateTests(cases.SerializerTestCase): """Test cases for the updating instances via CommentSerializer class. """ factory = factories.CommentFactory serializer_class = serializers.CommentSerializer serializer_resource_name = 'Comment' def test_when_valid(self): """It should be able to update the resource. """ og_html = '<p>This is a test.</p>' comment = self.factory(html=og_html) serializer = self.serializer_class( instance=comment, data={ 'html': '<p>This is a <b>test</b>.</p>', }, partial=True, ) self.assertTrue(serializer.is_valid()) self.assertTrue(serializer.save()) class PinCommentSerializerTests(cases.SerializerTestCase): """Test cases for the pinning comments. """ factory = None serializer_class = serializers.TogglePinCommentSerializer serializer_resource_name = 'Comment' @classmethod def setUpTestData(cls): cls.commentable = factories.TableFactory() cls.workspace = cls.commentable.workspace cls.user = factories.UserFactory() cls.comment = cls.commentable.comments.create( author=cls.user, html='This is a test', ) def test_pin_when_valid(self): """It should be able to create the resource. """ serializer = self.serializer_class( instance=self.comment, data={}, partial=True, ) self.assertTrue(serializer.is_valid()) self.assertTrue(serializer.save(pinned_by=self.user)) self.comment.refresh_from_db() self.assertTrue(self.comment.pinned) def test_pin_when_not_user(self): """You can only pin """ serializer = self.serializer_class( instance=self.comment, data={}, partial=True, ) self.assertTrue(serializer.is_valid()) with self.assertRaises(drf.ValidationError): serializer.save(pinned_by=None) def test_unpin(self): """It should be able to create the resource. """ self.comment.pin(self.user) serializer = self.serializer_class( instance=self.comment, data={}, partial=True, ) self.assertTrue(serializer.is_valid()) self.assertTrue(serializer.save(pinned_by=self.user)) self.comment.refresh_from_db() self.assertFalse(self.comment.pinned) class VoteForCommentSerializerTests(cases.SerializerTestCase): """Test cases for the pinning instances via CommentSerializer class. """ factory = None serializer_class = serializers.VoteForCommentSerializer serializer_resource_name = 'Comment' @classmethod def setUpTestData(cls): cls.commentable = factories.TableFactory() cls.workspace = cls.commentable.workspace cls.user = factories.UserFactory() cls.comment = cls.commentable.comments.create( author=cls.user, html='This is a test', ) def test_when_valid(self): """It should be able to create the resource. """ serializer = self.serializer_class( instance=self.comment, data={'action': votemodels.Vote.UP}, partial=True, ) self.assertTrue(serializer.is_valid()) self.assertTrue(serializer.save(user=self.user)) def test_when_invalid_action(self): """It should be able to create the resource. """ serializer = self.serializer_class( instance=self.comment, data={'action': 2}, partial=True, ) self.assertFalse(serializer.is_valid()) self.assertSerializerErrorsEqual(serializer, [ { 'resource': 'Comment', 'field': 'action', 'code': 'invalid_choice', } ])
var restful = require('node-restful') var mong = require('mongoose') // app.jokes, /jokes // app.images,/images module.exports = function (app){ var mongoose = restful.mongoose //databases mongoose.connect("mongodb://localhost/jsjokes") //collection 1, var Jokes = app.blogs = restful.model( 'jokes', mongoose.Schema({ title: String, content:String, createdate :{type:Date, default:Date.now }, pv: {type:Number,default:0}, joke: {type:Number,default:0}, unjoke: {type:Number, default: 0}, published: {type :Number, default: 1},// 1 ,show. 0. hide comments: [{type : mongoose.Schema.ObjectId, ref : 'comments'}], // 1 ,show. 0. hide author : [{type : mongoose.Schema.ObjectId, ref : 'accounts'}], })) .methods(['get']); var accounts = restful.model( 'accounts',mongoose.Schema({ nickname: String, avatar: String, //image url createdate: {type:Date, default: Date.now }, level: {type:Number,default: 0 }, })); var comments = restful.model( 'comments',mongoose.Schema({ content : String, createdate: {type:Date, default: Date.now }, author : {type : mongoose.Schema.ObjectId, ref : 'accounts'}, joke : {type : mongoose.Schema.ObjectId, ref : 'jokes'}, })) app.get('/jokes' ,function (req,res){ Jokes.find() .sort('-_id') .populate({ path: 'author', select: {'avatar':1,'nickname':1,'level':1,'username':1} }) .populate({ path: 'comments', // options: {sort: {'_id': -1 }}, populate: {path: 'author', select: {'nickname':1,'username':1}}}) .exec(function (err, jokes) { if (err) return handleError(err); res.json(jokes) }) }) // get jokes end // joke or unjoke app.get('/jokes/:id',function(req,res){ Jokes.findOne({'_id': req.params['id']},function(err,j){ if (req.query['joke']){ j.joke = j.joke + 1 update_author_level(req.params['id']) // joke j.save(function(err,data){ res.json(data) }) } else if (req.query['unjoke']) { j.unjoke = j.unjoke + 1 j.save(function(err,data){ res.json(data) }) } else { res.json(j) } }) }) /*****************************************************/ function update_author_level (id) { Jokes.findOne({_id:id}) .populate('author') .exec(function(error,cursor) { var author = cursor.author[0] accounts.update({_id:author._id},{level:author.level+1},function(e,a){ }) }) } } /* GET /jokes GET /jokes/:id POST /jokes PUT /jokes/:id DELETE /jokes/:id */
#!/bin/bash # Copyright (c) 2020, NVIDIA CORPORATION. ######################################### # cuDF GPU build and test script for CI # ######################################### set -e NUMARGS=$# ARGS=$* # Logger function for build status output function logger() { echo -e "\n>>>> $@\n" } # Arg parsing function function hasArg { (( ${NUMARGS} != 0 )) && (echo " ${ARGS} " | grep -q " $1 ") } # Set path and build parallel level export PATH=/conda/bin:/usr/local/cuda/bin:$PATH export PARALLEL_LEVEL=4 export CUDA_REL=${CUDA_VERSION%.*} export HOME="$WORKSPACE" # Parse git describe cd "$WORKSPACE" export GIT_DESCRIBE_TAG=`git describe --tags` export MINOR_VERSION=`echo $GIT_DESCRIBE_TAG | grep -o -E '([0-9]+\.[0-9]+)'` # Set Benchmark Vars export GBENCH_BENCHMARKS_DIR="$WORKSPACE/cpp/build/gbenchmarks/" # Set `LIBCUDF_KERNEL_CACHE_PATH` environment variable to $HOME/.jitify-cache because # it's local to the container's virtual file system, and not shared with other CI jobs # like `/tmp` is. export LIBCUDF_KERNEL_CACHE_PATH="$HOME/.jitify-cache" function remove_libcudf_kernel_cache_dir { EXITCODE=$? logger "removing kernel cache dir: $LIBCUDF_KERNEL_CACHE_PATH" rm -rf "$LIBCUDF_KERNEL_CACHE_PATH" || logger "could not rm -rf $LIBCUDF_KERNEL_CACHE_PATH" exit $EXITCODE } trap remove_libcudf_kernel_cache_dir EXIT mkdir -p "$LIBCUDF_KERNEL_CACHE_PATH" || logger "could not mkdir -p $LIBCUDF_KERNEL_CACHE_PATH" ################################################################################ # SETUP - Check environment ################################################################################ logger "Check environment..." env logger "Check GPU usage..." nvidia-smi logger "Activate conda env..." . /opt/conda/etc/profile.d/conda.sh conda activate rapids # Enter dependencies to be shown in ASV tooltips. CUDF_DEPS=(librmm) LIBCUDF_DEPS=(librmm) conda install "rmm=$MINOR_VERSION.*" "cudatoolkit=$CUDA_REL" \ "rapids-build-env=$MINOR_VERSION.*" \ "rapids-notebook-env=$MINOR_VERSION.*" \ rapids-pytest-benchmark # https://docs.rapids.ai/maintainers/depmgmt/ # conda remove -f rapids-build-env rapids-notebook-env # conda install "your-pkg=1.0.0" # Install the master version of dask, distributed, and streamz logger "pip install git+https://github.com/dask/distributed.git@2021.06.0 --upgrade --no-deps" pip install "git+https://github.com/dask/distributed.git@2021.06.0" --upgrade --no-deps logger "pip install git+https://github.com/dask/dask.git@2021.06.0 --upgrade --no-deps" pip install "git+https://github.com/dask/dask.git@2021.06.0" --upgrade --no-deps logger "pip install git+https://github.com/python-streamz/streamz.git --upgrade --no-deps" pip install "git+https://github.com/python-streamz/streamz.git" --upgrade --no-deps logger "Check versions..." python --version $CC --version $CXX --version conda info conda config --show-sources conda list --show-channel-urls ################################################################################ # BUILD - Build libcudf, cuDF and dask_cudf from source ################################################################################ logger "Build libcudf..." if [[ ${BUILD_MODE} == "pull-request" ]]; then "$WORKSPACE/build.sh" clean libcudf cudf dask_cudf benchmarks tests --ptds else "$WORKSPACE/build.sh" clean libcudf cudf dask_cudf benchmarks tests -l --ptds fi ################################################################################ # BENCHMARK - Run and parse libcudf and cuDF benchmarks ################################################################################ logger "Running benchmarks..." #Download GBench results Parser curl -L https://raw.githubusercontent.com/rapidsai/benchmark/main/parser/GBenchToASV.py --output GBenchToASV.py ### # Generate Metadata for dependencies ### # Concatenate dependency arrays, convert to JSON array, # and remove duplicates. X=("${CUDF_DEPS[@]}" "${LIBCUDF_DEPS[@]}") DEPS=$(printf '%s\n' "${X[@]}" | jq -R . | jq -s 'unique') # Build object with k/v pairs of "dependency:version" DEP_VER_DICT=$(jq -n '{}') for DEP in $(echo "${DEPS}" | jq -r '.[]'); do VER=$(conda list | grep "^${DEP}" | awk '{print $2"-"$3}') DEP_VER_DICT=$(echo "${DEP_VER_DICT}" | jq -c --arg DEP "${DEP}" --arg VER "${VER}" '. + { ($DEP): $VER }') done # Pass in an array of dependencies to get a dict of "dependency:version" function getReqs() { local DEPS_ARR=("$@") local REQS="{}" for DEP in "${DEPS_ARR[@]}"; do VER=$(echo "${DEP_VER_DICT}" | jq -r --arg DEP "${DEP}" '.[$DEP]') REQS=$(echo "${REQS}" | jq -c --arg DEP "${DEP}" --arg VER "${VER}" '. + { ($DEP): $VER }') done echo "${REQS}" } ### # Run LIBCUDF Benchmarks ### REQS=$(getReqs "${LIBCUDF_DEPS[@]}") mkdir -p "$WORKSPACE/tmp/benchmark" touch "$WORKSPACE/tmp/benchmark/benchmarks.txt" ls ${GBENCH_BENCHMARKS_DIR} > "$WORKSPACE/tmp/benchmark/benchmarks.txt" #Disable error aborting while tests run, failed tests will not generate data logger "Running libcudf GBenchmarks..." cd ${GBENCH_BENCHMARKS_DIR} set +e while read BENCH; do nvidia-smi ./${BENCH} --benchmark_out=${BENCH}.json --benchmark_out_format=json EXITCODE=$? if [[ ${EXITCODE} != 0 ]]; then rm ./${BENCH}.json JOBEXITCODE=1 fi done < "$WORKSPACE/tmp/benchmark/benchmarks.txt" set -e rm "$WORKSPACE/tmp/benchmark/benchmarks.txt" cd "$WORKSPACE" mv ${GBENCH_BENCHMARKS_DIR}/*.json "$WORKSPACE/tmp/benchmark/" python GBenchToASV.py -d "$WORKSPACE/tmp/benchmark/" -t ${S3_ASV_DIR} -n libcudf -b branch-${MINOR_VERSION} -r "${REQS}" ### # Run Python Benchmarks ### #REQS=$(getReqs "${CUDF_DEPS[@]}") #BENCHMARK_META=$(jq -n \ # --arg NODE "${NODE_NAME}" \ # --arg BRANCH "branch-${MINOR_VERSION}" \ # --argjson REQS "${REQS}" ' # { # "machineName": $NODE, # "commitBranch": $BRANCH, # "requirements": $REQS # } #') #echo "Benchmark meta:" #echo "${BENCHMARK_META}" | jq "."
export * from './init_controller'; export * from './init_guard'; export * from './init_shield'; export * from './init_wall';
class InvalidTimeException(Exception): pass class IterativeProcess: def get_iterations(self, iteration_time, total_time): if iteration_time <= total_time: return int(total_time / iteration_time) else: raise InvalidTimeException("Iteration time exceeds total time") # Example usage process = IterativeProcess() try: iterations = process.get_iterations(2.5, 10.0) # Returns 4 print(iterations) iterations = process.get_iterations(5.0, 3.0) # Raises InvalidTimeException except InvalidTimeException as e: print(e)
# This change from the default is for running Ceedling out of another folder. PROJECT_CEEDLING_ROOT = "../../../.." load "#{PROJECT_CEEDLING_ROOT}/lib/ceedling.rb" Ceedling.load_project task :default => %w[ test:all release ]
var arm_cm = [ [ "Directories and Files", "arm-cm.html#arm-cm_files", null ], [ "Interrupts in the QP Ports to ARM Cortex-M", "arm-cm.html#arm-cm_int", [ [ "\"Kernel-Aware\" and \"Kernel-Unaware\" Interrupts", "arm-cm.html#arm-cm_kernel-aware", null ], [ "Assigning Interrupt Priorities", "arm-cm.html#arm-cm_int-assign", null ], [ "Interrupts and the FPU (Cortex-M4F/M7)", "arm-cm.html#arm-cm_int-fpu", null ] ] ], [ "References", "arm-cm.html#arm-cm_ref", null ], [ "Cooperative QV Kernel", "arm-cm_qv.html", [ [ "Synopsis of the QV Port on ARM Cortex-M", "arm-cm_qv.html#arm-cm_qv-synopsis", null ], [ "The qep_port.h Header File", "arm-cm_qv.html#arm-cm_qv-qep_port", null ], [ "The qf_port.h Header File", "arm-cm_qv.html#arm-cm_qv-qf_port", null ], [ "The qv_port.h Header File", "arm-cm_qv.html#arm-cm_qv_port_h", null ], [ "The qv_port.c Implementation File", "arm-cm_qv.html#arm-cm_qv_port_c", null ], [ "Writing ISRs for QV", "arm-cm_qv.html#arm-cm_qv-isr", null ], [ "Using the FPU in the QV Port (Cortex-M4F/M7)", "arm-cm_qv.html#arm-cm_qv-fpu", [ [ "FPU NOT used in the ISRs", "arm-cm_qv.html#arm-cm_qv-fpu_noisr", null ], [ "FPU used in the ISRs", "arm-cm_qv.html#arm-cm_qv-fpu_isr", null ] ] ], [ "QV Idle Processing Customization in QV_onIdle()", "arm-cm_qv.html#arm-cm_qv-idle", null ] ] ], [ "Preemptive Non-Blocking QK Kernel", "arm-cm_qk.html", [ [ "Synopsis of the QK Port on ARM Cortex-M", "arm-cm_qk.html#arm-cm_qk-synopsis", [ [ "Preemption Scenarios in QK on ARM Cortex-M", "arm-cm_qk.html#arm-cm_qk-preempt", null ] ] ], [ "The qf_port.h Header File", "arm-cm_qk.html#arm-cm_qk-qf_port", null ], [ "QK Port Implementation for ARM Cortex-M", "arm-cm_qk.html#arm-cm_qk-qk_impl", [ [ "QK_init() Implementation", "arm-cm_qk.html#arm-cm_qk_port-asm_init", null ], [ "PendSV_Handler() Implementation", "arm-cm_qk.html#arm-cm_qk_port-asm_pendsv", null ], [ "NMI_Handler() Implementation", "arm-cm_qk.html#arm-cm_qk_port-asm_nmi", null ] ] ], [ "Writing ISRs for QK", "arm-cm_qk.html#arm-cm_qk-isr", null ], [ "Using the FPU in the QK Port (Cortex-M4F/M7)", "arm-cm_qk.html#arm-cm_qk-fpu", [ [ "FPU used in ONE thread only and not in any ISR", "arm-cm_qk.html#arm-cm_qk-fpu_1thread", null ], [ "FPU used in more than one thread only or the ISR", "arm-cm_qk.html#arm-cm_qk-fpu_nthreadd", null ] ] ], [ "QK Idle Processing Customization in QK_onIdle()", "arm-cm_qk.html#arm-cm_qk-idle", null ], [ "Testing QK Preemption Scenarios", "arm-cm_qk.html#arm-cm_qk-testing", [ [ "Interrupt Nesting Test", "arm-cm_qk.html#arm-cm_qk-test-isr", null ], [ "Thread Preemption Test", "arm-cm_qk.html#arm-cm_qk-test-thread", null ], [ "Testing the FPU (Cortex-M4F/M7)", "arm-cm_qk.html#arm-cm_qk-test-fpu", null ], [ "Other Tests", "arm-cm_qk.html#arm-cm_qk-test-other", null ] ] ] ] ], [ "Preemptive \"Dual-Mode\" QXK Kernel", "arm-cm_qxk.html", [ [ "Synopsis of the QXK Port on ARM Cortex-M", "arm-cm_qxk.html#arm-cm_qxk-synopsis", [ [ "Using the VFP", "arm-cm_qxk.html#arm-com_qxk_vfp", null ] ] ] ] ] ];
import React from 'react'; import "../../assets/usuarios.css" export default function index() { return ( <div className="container d-flex justify-content-center align-items-center col-12"> <div className="TablaContenedor col-8"> <table className="table table-bordered table-hover table-success table-striped m-2"> <thead> <tr> <th scope='col'>ID</th> <th scope='col'>Nombre</th> <th scope='col'>Apellido</th> </tr> </thead> <tbody> <tr> <th scope='col'>1</th> <td>Daniel</td> <td>Estrada</td> </tr> <tr> <th scope='col'>2</th> <td>Pablo</td> <td>Sergio</td> </tr> <tr> <th scope='col'>3</th> <td>Rudy</td> <td>Escobar</td> </tr> <tr> <th scope='col'>3</th> <td>Jose</td> <td>Ventura</td> </tr> <tr> <th scope='col'>3</th> <td>Alvarado</td> <td>Fallas</td> </tr> <tr> <th scope='col'>3</th> <td>Alfaro</td> <td>Castro</td> </tr> </tbody> </table> </div> </div> ); }
import styled from 'styled-components'; import Image from '@crystallize/react-image'; import { responsive } from 'ui'; export const Outer = styled.a` display: flex; height: 100%; color: var(--color-main-background); position: relative; padding: 20px; justify-content: center; background: var(--color-box-background); transition: all 0.1s ease-in-out; grid-column-end: span 3; ${responsive.xs} { margin-bottom: 15px; } `; export const Inner = styled.div` padding: 20px; height: 100%; display: flex; justify-content: center; flex-direction: column; `; export const ImageWrapper = styled.div` position: relative; z-index: 1; overflow: hidden; width: 100%; height: 250px; `; export const Img = styled(Image)` width: 100%; height: 100%; overflow: hidden; > img { display: block; object-fit: cover; object-position: center; width: 100%; height: 100%; overflow: hidden; } `; export const Text = styled.div` z-index: 2; width: 100%; height: 150px; display: flex; flex-direction: column; justify-content: center; text-align: center; left: 0; width: 100%; padding: 1em; color: var(--color-text-main); h3 { font-size: 1.5rem; text-transform: uppercase; color: inherit; font-family: 'Roboto', sans-serif; margin: 0; } `; export const Price = styled.span` color: var(--color-price); font-weight: bold; padding-bottom: 5px; `;
#!/bin/bash # --------------------------------------------------------------------------- # Trivadis AG, Infrastructure Managed Services # Saegereistrasse 29, 8152 Glattbrugg, Switzerland # --------------------------------------------------------------------------- # Name.......: create_OUD_instance.sh # Author.....: Stefan Oehrli (oes) stefan.oehrli@trivadis.com # Editor.....: Stefan Oehrli # Date.......: 2017.12.04 # Revision...: # Purpose....: Helper script to create the OUD instance # Notes......: Script to create an OUD instance. If configuration files are # provided, the will be used to configure the instance. # Reference..: -- # License....: CDDL 1.0 + GPL 2.0 # --------------------------------------------------------------------------- # Modified...: # see git revision history for more information on changes/updates # TODO.......: # --------------------------------------------------------------------------- # - Customization ----------------------------------------------------------- export PORT=${PORT:-1389} # Default LDAP port export PORT_SSL=${PORT_SSL:-1636} # Default LDAPS port export PORT_REP=${PORT_REP:-8989} # Default replication port export PORT_ADMIN=${PORT_ADMIN:-4444} # Default admin port export ADMIN_USER=${ADMIN_USER:-'cn=Directory Manager'} # Default directory admin user export ADMIN_PASSWORD=${ADMIN_PASSWORD:-""} # Default directory admin password export BASEDN=${BASEDN:-'dc=postgasse,dc=org'} # Default directory base DN export SAMPLE_DATA=${SAMPLE_DATA:-'TRUE'} # Flag to load sample data export OUD_PROXY=${OUD_PROXY:-'FALSE'} # Flag to create proxy instance # default folder for OUD instance init scripts export OUD_INSTANCE_INIT=${OUD_INSTANCE_INIT:-$ORACLE_DATA/scripts} # - End of Customization ---------------------------------------------------- echo "--- Setup OUD environment on volume ${ORACLE_DATA} --------------------" # create instance directories on volume mkdir -v -p ${ORACLE_DATA} for i in admin backup etc instances domains log scripts; do mkdir -v -p ${ORACLE_DATA}/${i} done # create oudtab file OUDTAB=${ORACLE_DATA}/etc/oudtab echo "# OUD Config File" > ${OUDTAB} echo "# 1 : OUD Instance Name" >>${OUDTAB} echo "# 2 : OUD LDAP Port" >>${OUDTAB} echo "# 3 : OUD LDAPS Port" >>${OUDTAB} echo "# 4 : OUD Admin Port" >>${OUDTAB} echo "# 5 : OUD Replication Port" >>${OUDTAB} echo "# 6 : Directory type eg OUD, OID, ODSEE or OUDSM" >>${OUDTAB} echo "#---------------------------------------------" >>${OUDTAB} echo "${OUD_INSTANCE}:${PORT}:${PORT_SSL}:${PORT_ADMIN}:${PORT_REP}:OUD" >>${OUDTAB} # Create default config file in ETC_BASE in case they are not yet available... for i in oud._DEFAULT_.conf oudenv_custom.conf oudenv.conf oudtab; do if [ ! -f "${ORACLE_DATA}/etc/${i}" ]; then cp ${ORACLE_BASE}/templates/etc/${i} ${ORACLE_DATA}/etc fi done # create also some soft links from ETC_CORE to ETC_BASE for i in oudenv.conf oudtab; do if [ ! -f "${ORACLE_DATA}/etc/${i}" ]; then ln -sf ${ORACLE_DATA}/etc/${i} ${ORACLE_BASE}/etc/${i} fi done # Load OUD environment for this instance . ${ORACLE_BASE}/local/bin/oudenv.sh ${OUD_INSTANCE} SILENT # generate a password if [ -z ${ADMIN_PASSWORD} ]; then # Auto generate Oracle WebLogic Server admin password while true; do s=$(cat /dev/urandom | tr -dc "A-Za-z0-9" | fold -w 8 | head -n 1) if [[ ${#s} -ge 8 && "$s" == *[A-Z]* && "$s" == *[a-z]* && "$s" == *[0-9]* ]]; then break else echo "Password does not Match the criteria, re-generating..." fi done echo "---------------------------------------------------------------" echo " Oracle Unified Directory Server auto generated instance" echo " admin password :" echo " ----> Directory Admin : ${ADMIN_USER} " echo " ----> Admin password : $s" echo "---------------------------------------------------------------" else s=${ADMIN_PASSWORD} echo "---------------------------------------------------------------" echo " Oracle Unified Directory Server auto generated instance" echo " admin password :" echo " ----> Directory Admin : ${ADMIN_USER} " echo " ----> Admin password : $s" echo "---------------------------------------------------------------" fi # write password file echo "$s" > ${OUD_INSTANCE_ADMIN}/etc/${OUD_INSTANCE}_pwd.txt # set instant init location create folder if it does exists if [ -d "${OUD_INSTANCE_ADMIN}/create" ]; then OUD_INSTANCE_INIT="${OUD_INSTANCE_ADMIN}/create" else OUD_INSTANCE_INIT="${OUD_INSTANCE_INIT}/setup" fi echo "--- Create OUD instance --------------------------------------------------------" echo " OUD_INSTANCE = ${OUD_INSTANCE}" echo " OUD_INSTANCE_BASE = ${OUD_INSTANCE_BASE}" echo " OUD_INSTANCE_ADMIN = ${OUD_INSTANCE_ADMIN}" echo " OUD_INSTANCE_INIT = ${OUD_INSTANCE_INIT}" echo " OUD_INSTANCE_HOME = ${INSTANCE_BASE}/${OUD_INSTANCE}" echo " PORT = ${PORT}" echo " PORT_SSL = ${PORT_SSL}" echo " PORT_REP = ${PORT_REP}" echo " PORT_ADMIN = ${PORT_ADMIN}" echo " ADMIN_USER = ${ADMIN_USER}" echo " BASEDN = ${BASEDN}" echo " OUD_PROXY = ${OUD_PROXY}" echo "" # Normalize CREATE_INSTANCE export OUD_PROXY=$(echo $OUD_PROXY| sed 's/^false$/0/gi') export OUD_PROXY=$(echo $OUD_PROXY| sed 's/^true$/1/gi') if [ ${OUD_PROXY} -eq 0 ]; then # Create an directory ${ORACLE_BASE}/product/${ORACLE_HOME_NAME}/oud/oud-setup \ --cli \ --instancePath ${OUD_INSTANCE_HOME}/OUD \ --adminConnectorPort ${PORT_ADMIN} \ --rootUserDN "${ADMIN_USER}" \ --rootUserPasswordFile ${OUD_INSTANCE_ADMIN}/etc/${OUD_INSTANCE}_pwd.txt \ --ldapPort ${PORT} \ --ldapsPort ${PORT_SSL} \ --generateSelfSignedCertificate \ --hostname $(hostname) \ --baseDN ${BASEDN} \ --addBaseEntry \ --serverTuning jvm-default \ --offlineToolsTuning autotune \ --no-prompt \ --noPropertiesFile if [ $? -eq 0 ]; then echo "--- Successfully created OUD instance (${OUD_INSTANCE}) ------------------------" # Execute custom provided setup scripts ${DOCKER_SCRIPTS}/config_OUD_Instance.sh ${OUD_INSTANCE_INIT} else echo "--- ERROR creating OUD instance (${OUD_INSTANCE}) ------------------------------" exit 1 fi fi # --- EOF -------------------------------------------------------------------
<filename>lib/net/ftp/list/parser.rb require 'date' # Abstract FTP LIST parser. It really just defines and documents the interface. class Net::FTP::List::Parser class << self # Returns registered parsers. def parsers @parsers ||= [] end # Manuall register a parser. def register(parser) parsers.push(parser) unless parsers.include?(parser) end # Automatically add an inheriting parser to the list of known parsers. def inherited(klass) super register(klass) end # The main parse method. Return false from it if parsing fails (this is cheaper than raising an exception) def parse(_raw, **) false end private # Automatically adds the name of the parser class to the server_type field def emit_entry(raw, **extra) Net::FTP::List::Entry.new raw, **extra, server_type: to_s.split('::').pop end def parse_time(str, timezone:, format: nil) case timezone when :utc (format ? DateTime.strptime(str, format) : DateTime.parse(str)).to_time when :local format ? Time.strptime(str, format) : Time.parse(str) else raise ArgumentError, "invalid timezone #{timezone}, only :utc and :local are allowed" end end end end
<filename>bowling-game-kata/iteration-1/bowling-game-day-9/src/main/java/ua/kata/BowlingGame.java package ua.kata; import java.util.stream.IntStream; import io.reactivex.Observable; public class BowlingGame { private static final int NUMBER_OF_FRAMES = 10; private int[] rolls = new int[21]; private int current; public void roll(int pin) { rolls[current++] += pin; } public int score() { return Observable.fromArray( IntStream.iterate(0, this::generateNextFrameIndex) .limit(NUMBER_OF_FRAMES) .boxed() .toArray(Integer[]::new) ).map(this::computeFramePoints) .reduce(0, (acc, item) -> acc + item) .blockingGet(); } private int computeFramePoints(int frameIndex) { if (isStrike(frameIndex)) { return 10 + strikeBonus(frameIndex); } else if (isSpare(frameIndex)) { return 10 + spareBonus(frameIndex); } else { return rolls[frameIndex] + rolls[frameIndex + 1]; } } private int generateNextFrameIndex(int frameIndex) { if (isStrike(frameIndex)) return frameIndex + 1; else return frameIndex + 2; } private boolean isStrike(int frameIndex) { return rolls[frameIndex] == 10; } private int strikeBonus(int frameIndex) { return rolls[frameIndex + 1] + rolls[frameIndex + 2]; } private boolean isSpare(int frameIndex) { return rolls[frameIndex] + rolls[frameIndex + 1] == 10; } private int spareBonus(int frameIndex) { return rolls[frameIndex + 2]; } }
#!/bin/bash gem uninstall remove_double_blank bin/setup echo '-----------------' echo 'BEGIN TESTING gem' rake echo 'FINISHED TESTING gem' echo '--------------------'
#include <algorithm> #include "gtest/gtest.h" #include "ScaFES_GridTest1D.hpp" #include "ScaFES_Ntuple.hpp" #include "ScaFES_Grid.hpp" namespace ScaFES_test { const double EPS = 2.2e-14; /******************************************************************************* * TESTS OF GETTER METHODS. ******************************************************************************/ TYPED_TEST_P(GridTest1D, GlobalNodeFirst) { EXPECT_TRUE(this->mIdxNodeFirstA == this->mObjA.idxNodeFirst()); } /*----------------------------------------------------------------------------*/ TYPED_TEST_P(GridTest1D, GlobalNodeLast) { EXPECT_TRUE(this->mIdxNodeLastA == this->mObjA.idxNodeLast()); } /*----------------------------------------------------------------------------*/ TYPED_TEST_P(GridTest1D, GlobalNodeFirstInOneDirection) { const int DIM = 1; for (int ii = 0; ii < DIM; ++ii) { EXPECT_TRUE(this->mIdxNodeFirstA.elem(ii) == this->mObjA.idxNodeFirst(ii)); } } /*----------------------------------------------------------------------------*/ TYPED_TEST_P(GridTest1D, GlobalNodeLastInOneDirection) { const int DIM = 1; for (int ii = 0; ii < DIM; ++ii) { EXPECT_TRUE(this->mIdxNodeLastA.elem(ii) == this->mObjA.idxNodeLast(ii)); } } /*----------------------------------------------------------------------------*/ TYPED_TEST_P(GridTest1D, Nnodes) { EXPECT_TRUE(this->mNnodesA == this->mObjA.nNodes()); } /*----------------------------------------------------------------------------*/ TYPED_TEST_P(GridTest1D, NnodesInOneDirection) { const int DIM = 1; for (int ii = 0; ii < DIM; ++ii) { EXPECT_TRUE(this->mNnodesA.elem(ii) == this->mObjA.nNodes(ii)); } } /*----------------------------------------------------------------------------*/ TYPED_TEST_P(GridTest1D, GridSize) { const int DIM = 1; ScaFES::Ntuple<double, DIM> tmpGridSize = this->mObjA.gridsize(); for (int ii = 0; ii < DIM; ++ii) { EXPECT_TRUE(::fabs(this->mGridSizeA.elem(ii) - tmpGridSize.elem(ii)) < EPS); } } /*----------------------------------------------------------------------------*/ TYPED_TEST_P(GridTest1D, GridSizeInOneDirection) { const int DIM = 1; for (int ii = 0; ii < DIM; ++ii) { EXPECT_TRUE(::fabs(this->mGridSizeA.elem(ii) - this->mObjA.gridsize(ii)) < EPS); } } /*----------------------------------------------------------------------------*/ TYPED_TEST_P(GridTest1D, CoordNodeFirst) { const int DIM = 1; ScaFES::Ntuple<double, DIM> tmpCoordNodeFirst = this->mObjA.coordNodeFirst(); for (int ii = 0; ii < DIM; ++ii) { EXPECT_TRUE(this->mCoordNodeFirstA.elem(ii) == tmpCoordNodeFirst.elem(ii)); } } /*----------------------------------------------------------------------------*/ TYPED_TEST_P(GridTest1D, CoordNodeLast) { const int DIM = 1; ScaFES::Ntuple<double, DIM> tmpCoordNodeLast = this->mObjA.coordNodeLast(); for (int ii = 0; ii < DIM; ++ii) { EXPECT_TRUE(::fabs(this->mCoordNodeLastA.elem(ii) - tmpCoordNodeLast.elem(ii)) < EPS); } } /*----------------------------------------------------------------------------*/ TYPED_TEST_P(GridTest1D, IsNumberedStyleC) { EXPECT_TRUE(this->mIsNumberedStyleCA == this->mObjA.isNumberedStyleC()); } /******************************************************************************* * TESTS OF operator==(). ******************************************************************************/ TYPED_TEST_P(GridTest1D, OperatorEqualsComponentwise) { const int DIM = 1; EXPECT_TRUE(this->mObjCopyA.nNodes() == this->mObjA.nNodes()); EXPECT_TRUE(this->mObjCopyA.gridsize() == this->mObjA.gridsize()); EXPECT_TRUE(this->mObjCopyA.idxNodeFirst() == this->mObjA.idxNodeFirst()); EXPECT_TRUE(this->mObjCopyA.idxNodeLast() == this->mObjA.idxNodeLast()); for (int ii = 0; ii < DIM; ++ii) { EXPECT_TRUE(this->mObjCopyA.nNodes(ii) == this->mObjA.nNodes(ii)); } for (int ii = 0; ii < DIM; ++ii) { EXPECT_TRUE(::fabs(this->mObjCopyA.gridsize(ii) - this->mObjA.gridsize(ii)) < EPS); } } /*----------------------------------------------------------------------------*/ TYPED_TEST_P(GridTest1D, OperatorEquals) { EXPECT_TRUE(this->mObjA == this->mObjA); EXPECT_TRUE(this->mObjCopyA == this->mObjA); EXPECT_FALSE(this->mObjLess == this->mObjGreater); EXPECT_FALSE(this->mObjGreater == this->mObjLess); } /*----------------------------------------------------------------------------*/ TYPED_TEST_P(GridTest1D, OperatorUnequals) { EXPECT_FALSE(this->mObjA != this->mObjA); EXPECT_FALSE(this->mObjCopyA != this->mObjA); EXPECT_TRUE(this->mObjLess != this->mObjGreater); EXPECT_TRUE(this->mObjGreater != this->mObjLess); } /******************************************************************************* * TESTS OF LIFE CYCLE METHODS. ******************************************************************************/ TYPED_TEST_P(GridTest1D, ConstructorWithParameters) { const int DIM = 1; ScaFES::Grid<DIM> objTmp(this->mIdxNodeFirstA, this->mIdxNodeLastA, this->mCoordNodeFirstA, this->mCoordNodeLastA); EXPECT_TRUE(this->mObjA == objTmp); } /*----------------------------------------------------------------------------*/ TYPED_TEST_P(GridTest1D, ConstructorDefault) { const int DIM = 1; ScaFES::Grid<DIM> objTmp; EXPECT_TRUE((ScaFES::Ntuple<double, DIM>(1.0) == objTmp.gridsize())); EXPECT_TRUE((ScaFES::Ntuple<int, DIM>(0) == objTmp.idxNodeFirst())); EXPECT_TRUE((ScaFES::Ntuple<int, DIM>(1) == objTmp.idxNodeLast())); EXPECT_TRUE((ScaFES::Ntuple<int, DIM>(2) == objTmp.nNodes())); EXPECT_TRUE((ScaFES::Ntuple<double, DIM>(0.0) == objTmp.coordNodeFirst())); EXPECT_TRUE((ScaFES::Ntuple<double, DIM>(1.0) == objTmp.coordNodeLast())); } /*----------------------------------------------------------------------------*/ TYPED_TEST_P(GridTest1D, CopyConstructor) { const int DIM = 1; ScaFES::Grid<DIM> objTmp = this->mObjA; EXPECT_TRUE(this->mObjA == objTmp); } /*----------------------------------------------------------------------------*/ TYPED_TEST_P(GridTest1D, AssignmentOperator) { const int DIM = 1; ScaFES::Grid<DIM> objTmp; objTmp = this->mObjA; EXPECT_TRUE(this->mObjA == objTmp); } /******************************************************************************* * TESTS OF WORK METHODS. ******************************************************************************/ TYPED_TEST_P(GridTest1D, IdxNodeTuple2Scalar) { const int DIM = 1; ScaFES::Grid<DIM> objTmp = this->mObjA; unsigned long int idxNodeExpected; unsigned long int idxNodeActual; ScaFES::Ntuple<int, DIM> idxNode; idxNode[0] = objTmp.idxNodeFirst().elem(0); idxNodeActual = objTmp.idxNodeTuple2Scalar(idxNode); idxNodeExpected = 0; EXPECT_TRUE(idxNodeExpected == idxNodeActual); idxNode[0] = objTmp.idxNodeLast().elem(0); idxNodeActual = objTmp.idxNodeTuple2Scalar(idxNode); idxNodeExpected = objTmp.nNodes(0) - 1; EXPECT_TRUE(idxNodeExpected == idxNodeActual); // Arbitrary node. idxNode[0] = objTmp.idxNodeLast().elem(0) - 1; idxNodeActual = objTmp.idxNodeTuple2Scalar(idxNode); idxNodeExpected = objTmp.nNodes(0) - 2; EXPECT_TRUE(idxNodeExpected == idxNodeActual); } /*----------------------------------------------------------------------------*/ TYPED_TEST_P(GridTest1D, Coordinates) { const int DIM = 1; ScaFES::Grid<DIM> objTmp = this->mObjA; ScaFES::Ntuple<double, DIM> coordNodeExpected; ScaFES::Ntuple<double, DIM> coordNodeActual; ScaFES::Ntuple<int, DIM> idxNode; idxNode[0] = objTmp.idxNodeFirst().elem(0); coordNodeActual = objTmp.coordinates(idxNode); coordNodeExpected = ScaFES::Ntuple<double, DIM>( objTmp.coordNodeFirst().elem(0) ); EXPECT_TRUE(coordNodeExpected == coordNodeActual); idxNode[0] = objTmp.idxNodeLast().elem(0); coordNodeActual = objTmp.coordinates(idxNode); coordNodeExpected = ScaFES::Ntuple<double, DIM>( objTmp.coordNodeLast().elem(0) ); EXPECT_TRUE(coordNodeExpected == coordNodeActual); // Arbitrary node. idxNode[0] = objTmp.idxNodeLast().elem(0) - 1; coordNodeActual = objTmp.coordinates(idxNode); coordNodeExpected = ScaFES::Ntuple<double, DIM>( objTmp.coordNodeLast().elem(0) - objTmp.gridsize(0)); EXPECT_TRUE(coordNodeExpected == coordNodeActual); } /*----------------------------------------------------------------------------*/ TYPED_TEST_P(GridTest1D, MethodInside) { const int DIM = 1; ScaFES::Grid<DIM> objTmp = this->mObjA; EXPECT_TRUE(objTmp.inside(objTmp.idxNodeFirst())); EXPECT_TRUE(objTmp.inside(objTmp.idxNodeLast())); ScaFES::Ntuple<int, DIM> shift(1); EXPECT_FALSE(objTmp.inside(objTmp.idxNodeFirst() - shift)); EXPECT_FALSE(objTmp.inside(objTmp.idxNodeLast() + shift)); EXPECT_TRUE(objTmp.inside(objTmp.idxNodeFirst() + shift)); EXPECT_TRUE(objTmp.inside(objTmp.idxNodeLast() - shift)); } /*----------------------------------------------------------------------------*/ TYPED_TEST_P(GridTest1D, UnionWith) { const int DIM = 1; ScaFES::Ntuple<int, DIM> idxNode1(1); ScaFES::Ntuple<int, DIM> idxNode2(2); ScaFES::Ntuple<int, DIM> idxNode3(3); ScaFES::Ntuple<double, DIM> coordNode1(1.0); ScaFES::Ntuple<double, DIM> coordNode2(2.0); ScaFES::Ntuple<double, DIM> coordNode3(3.0); ScaFES::Grid<DIM> objTmpA(idxNode1, idxNode3, coordNode1, coordNode3); ScaFES::Grid<DIM> objTmpB(idxNode2, idxNode3, coordNode2, coordNode3); ScaFES::Grid<DIM> objExpected(idxNode1, idxNode3, coordNode1, coordNode3); EXPECT_TRUE(objExpected == objTmpA.unionWith(objTmpB)); } /*----------------------------------------------------------------------------*/ TYPED_TEST_P(GridTest1D, IntersectWith) { const int DIM = 1; ScaFES::Ntuple<int, DIM> idxNode1(1); ScaFES::Ntuple<int, DIM> idxNode2(2); ScaFES::Ntuple<int, DIM> idxNode3(3); ScaFES::Ntuple<double, DIM> coordNode1(1.0); ScaFES::Ntuple<double, DIM> coordNode2(2.0); ScaFES::Ntuple<double, DIM> coordNode3(3.0); ScaFES::Grid<DIM> objTmpA(idxNode1, idxNode3, coordNode1, coordNode3); ScaFES::Grid<DIM> objTmpB(idxNode2, idxNode3, coordNode2, coordNode3); ScaFES::Grid<DIM> objExpected(idxNode2, idxNode3, coordNode2, coordNode3); EXPECT_TRUE(objExpected == objTmpA.intersectWith(objTmpB)); } /*----------------------------------------------------------------------------*/ TYPED_TEST_P(GridTest1D, MethodValid) { const int DIM = 1; ScaFES::Grid<DIM> objTmp = this->mObjA; EXPECT_TRUE(objTmp.valid()); } /*---------------------------------------------------------------------------*/ TYPED_TEST_P(GridTest1D, ExtendRight) { const int DIM = 1; int borderwidth; int direction = 0; ScaFES::Grid<DIM> objTmp = this->mObjA; ScaFES::Grid<DIM> objExpected; ScaFES::Ntuple<int, DIM> idxNodeFirst = objTmp.idxNodeFirst(); ScaFES::Ntuple<int, DIM> idxNodeLast = objTmp.idxNodeLast(); for (int ii = 0; ii < 5; ++ii) { borderwidth = ii; idxNodeLast[0] += borderwidth; objExpected = ScaFES::Grid<DIM>(idxNodeFirst, idxNodeLast, objTmp.coordNodeFirst(), objTmp.coordNodeLast()); EXPECT_TRUE( (objTmp.extend(direction, borderwidth) == objExpected) ); idxNodeFirst = objTmp.idxNodeFirst(); idxNodeLast = objTmp.idxNodeLast(); } } /*----------------------------------------------------------------------------*/ TYPED_TEST_P(GridTest1D, ExtendLeft) { const int DIM = 1; int borderwidth; int direction = 1; ScaFES::Grid<DIM> objTmp = this->mObjA; ScaFES::Grid<DIM> objExpected; ScaFES::Ntuple<int, DIM> idxNodeFirst = objTmp.idxNodeFirst(); ScaFES::Ntuple<int, DIM> idxNodeLast = objTmp.idxNodeLast(); for (int ii = 0; ii < 5; ++ii) { borderwidth = ii; idxNodeFirst[0] -= borderwidth; objExpected = ScaFES::Grid<DIM>(idxNodeFirst, idxNodeLast, objTmp.coordNodeFirst(), objTmp.coordNodeLast()); EXPECT_TRUE( (objTmp.extend(direction, borderwidth) == objExpected) ); idxNodeFirst = objTmp.idxNodeFirst(); idxNodeLast = objTmp.idxNodeLast(); } } /******************************************************************************* * TESTS OF INTERNAL CLASS ITERATOR: GETTER METHODS. ******************************************************************************/ TYPED_TEST_P(GridTest1D, IteratorGlobalNode) { const int DIM = 1; ScaFES::Grid<DIM> objTmp = this->mObjA; ScaFES::Grid<DIM>::iterator iter(&objTmp, objTmp.idxNodeFirst()); ScaFES::Ntuple<int, DIM> idxNodeActual; ScaFES::Ntuple<int, DIM> idxNodeExpected; ScaFES::Ntuple<int, DIM> idxNode; for (int ii = 0; ii < 2; ++ii) { if (1 == ii) { idxNode.elem(0) = objTmp.idxNodeLast().elem(0); } else { idxNode.elem(0) = objTmp.idxNodeFirst().elem(0); } iter = ScaFES::Grid<DIM>::iterator(&(objTmp), idxNode); idxNodeExpected = idxNode; idxNodeActual = iter.idxNode(); EXPECT_TRUE(idxNodeExpected == idxNodeActual); } // Arbitrary node. idxNode[0] = objTmp.idxNodeLast().elem(0) - 1; idxNodeExpected = idxNode; iter = ScaFES::Grid<DIM>::iterator(&(objTmp), idxNode); idxNodeActual = iter.idxNode(); EXPECT_TRUE(idxNodeExpected == idxNodeActual); } /*----------------------------------------------------------------------------*/ TYPED_TEST_P(GridTest1D, IteratorLocNode) { const int DIM = 1; ScaFES::Grid<DIM> objTmp = this->mObjA; ScaFES::Grid<DIM>::iterator iter(&objTmp, objTmp.idxNodeFirst()); ScaFES::Ntuple<int, DIM> idxNode; unsigned long int idxNodeActual; unsigned long int idxNodeExpected; // Checking all corner points of the cuboid. for (int ii = 0; ii < 2; ++ii) { if (1 == ii) { idxNode.elem(0) = objTmp.idxNodeLast().elem(0); } else { idxNode.elem(0) = objTmp.idxNodeFirst().elem(0); } idxNodeExpected = objTmp.idxNodeTuple2Scalar(idxNode); iter = ScaFES::Grid<DIM>::iterator(&(objTmp), idxNode); idxNodeActual = iter.idxScalarNode(); EXPECT_TRUE(idxNodeExpected == idxNodeActual); } // Arbitrary node. idxNode[0] = objTmp.idxNodeLast().elem(0) - 1; idxNodeExpected = objTmp.idxNodeTuple2Scalar(idxNode); iter = ScaFES::Grid<DIM>::iterator(&(objTmp), idxNode); idxNodeActual = iter.idxScalarNode(); EXPECT_TRUE(idxNodeExpected == idxNodeActual); } /******************************************************************************* * TESTS OF INTERNAL CLASS ITERATOR: WORK METHODS. ******************************************************************************/ TYPED_TEST_P(GridTest1D, IteratorOperatorStar) { const int DIM = 1; ScaFES::Grid<DIM> objTmp = this->mObjA; ScaFES::Grid<DIM>::iterator iter(&objTmp, objTmp.idxNodeFirst()); ScaFES::Ntuple<int, DIM> idxNodeActual; ScaFES::Ntuple<int, DIM> idxNodeExpected; ScaFES::Ntuple<int, DIM> idxNode; for (int ii = 0; ii < 2; ++ii) { if (1 == ii) { idxNode.elem(0) = objTmp.idxNodeLast().elem(0); } else { idxNode.elem(0) = objTmp.idxNodeFirst().elem(0); } idxNodeExpected = idxNode; iter = ScaFES::Grid<DIM>::iterator(&(objTmp), idxNode); idxNodeActual = iter.operator * (); EXPECT_TRUE(idxNodeExpected == idxNodeActual); } // Arbitrary node. idxNode[0] = objTmp.idxNodeLast().elem(0) - 1; idxNodeExpected = idxNode; iter = ScaFES::Grid<DIM>::iterator(&(objTmp), idxNode); idxNodeActual = iter.operator * (); EXPECT_TRUE(idxNodeExpected == idxNodeActual); } /*----------------------------------------------------------------------------*/ TYPED_TEST_P(GridTest1D, IteratorOperatorPlusPlusPrefix) { const int DIM = 1; ScaFES::Grid<DIM> objTmp = this->mObjA; ScaFES::Grid<DIM>::iterator iter(&objTmp, objTmp.idxNodeFirst()); ScaFES::Ntuple<int, DIM> idxNodeActual; ScaFES::Ntuple<int, DIM> idxNodeExpected; ScaFES::Ntuple<int, DIM> idxNode; idxNode = objTmp.idxNodeFirst(); idxNodeExpected[0] = objTmp.idxNodeFirst().elem(0) + 1; iter = ScaFES::Grid<DIM>::iterator(&(objTmp), idxNode); iter.operator++(); idxNodeActual = iter.idxNode(); EXPECT_TRUE(idxNodeExpected == idxNodeActual); idxNode[0] = objTmp.idxNodeLast().elem(0); idxNodeExpected[0] = objTmp.idxNodeLast().elem(0) + 1; iter = ScaFES::Grid<DIM>::iterator(&(objTmp), idxNode); iter.operator++(); idxNodeActual = iter.idxNode(); EXPECT_TRUE(idxNodeExpected == idxNodeActual); // Arbitrary node. idxNode[0] = objTmp.idxNodeLast().elem(0) - 1; idxNodeExpected[0] = objTmp.idxNodeLast().elem(0); iter = ScaFES::Grid<DIM>::iterator(&(objTmp), idxNode); iter.operator++(); idxNodeActual = iter.idxNode(); EXPECT_TRUE(idxNodeExpected == idxNodeActual); } /*----------------------------------------------------------------------------*/ TYPED_TEST_P(GridTest1D, IteratorOperatorPlusPlusPostfix) { const int DIM = 1; ScaFES::Grid<DIM> objTmp = this->mObjA; ScaFES::Grid<DIM>::iterator iter(&objTmp, objTmp.idxNodeFirst()); ScaFES::Ntuple<int, DIM> idxNodeActual; ScaFES::Ntuple<int, DIM> idxNodeExpected; ScaFES::Ntuple<int, DIM> idxNode; idxNode = objTmp.idxNodeFirst(); idxNodeExpected[0] = objTmp.idxNodeFirst().elem(0) + 1; iter = ScaFES::Grid<DIM>::iterator(&(objTmp), idxNode); iter.operator++(1); idxNodeActual = iter.idxNode(); EXPECT_TRUE(idxNodeExpected == idxNodeActual); idxNode[0] = objTmp.idxNodeLast().elem(0); idxNodeExpected[0] = objTmp.idxNodeLast().elem(0) + 1; iter = ScaFES::Grid<DIM>::iterator(&(objTmp), idxNode); iter.operator++(1); idxNodeActual = iter.idxNode(); EXPECT_TRUE(idxNodeExpected == idxNodeActual); // Arbitrary node. idxNode[0] = objTmp.idxNodeLast().elem(0) - 1; idxNodeExpected[0] = objTmp.idxNodeLast().elem(0); iter = ScaFES::Grid<DIM>::iterator(&(objTmp), idxNode); iter.operator++(1); idxNodeActual = iter.idxNode(); EXPECT_TRUE(idxNodeExpected == idxNodeActual); } /*----------------------------------------------------------------------------*/ TYPED_TEST_P(GridTest1D, IteratorOperatorNotEquals) { const int DIM = 1; ScaFES::Grid<DIM> objTmp = this->mObjA; ScaFES::Ntuple<int, DIM> idxNode1; ScaFES::Ntuple<int, DIM> idxNode2; idxNode1 = objTmp.idxNodeFirst(); idxNode2 = objTmp.idxNodeLast(); ScaFES::Grid<DIM>::iterator iter1(&(objTmp), idxNode1); ScaFES::Grid<DIM>::iterator iter2(&(objTmp), idxNode2); EXPECT_TRUE(iter1.operator != (iter2)); } /*----------------------------------------------------------------------------*/ TYPED_TEST_P(GridTest1D, IteratorOperatorSmallerThan) { const int DIM = 1; ScaFES::Grid<DIM> objTmp = this->mObjA; ScaFES::Ntuple<int, DIM> idxNode1; ScaFES::Ntuple<int, DIM> idxNode2; idxNode1 = objTmp.idxNodeFirst(); idxNode2 = objTmp.idxNodeLast(); ScaFES::Grid<DIM>::iterator iter1(&(objTmp), idxNode1); ScaFES::Grid<DIM>::iterator iter2(&(objTmp), idxNode2); EXPECT_TRUE(iter1.operator < (iter2)); } /******************************************************************************* * TESTS OF FREE METHODS. ******************************************************************************/ TYPED_TEST_P(GridTest1D, Swap) { const int DIM = 1; ScaFES::Grid<DIM> mTmpA = this->mObjA; ScaFES::Grid<DIM> mTmpB = this->mObjB; ScaFES::swap(this->mObjA, this->mObjB); EXPECT_TRUE(mTmpA == this->mObjB); EXPECT_TRUE(mTmpB == this->mObjA); } /******************************************************************************* ******************************************************************************/ REGISTER_TYPED_TEST_CASE_P(GridTest1D, GlobalNodeFirst, GlobalNodeLast, GlobalNodeFirstInOneDirection, GlobalNodeLastInOneDirection, Nnodes, NnodesInOneDirection, GridSize, GridSizeInOneDirection, CoordNodeFirst, CoordNodeLast, IsNumberedStyleC, OperatorEqualsComponentwise, OperatorEquals, OperatorUnequals, ConstructorDefault, ConstructorWithParameters, CopyConstructor, AssignmentOperator, IdxNodeTuple2Scalar, Coordinates, MethodValid, MethodInside, UnionWith, IntersectWith, ExtendRight, ExtendLeft, IteratorGlobalNode, IteratorLocNode, IteratorOperatorStar, IteratorOperatorPlusPlusPrefix, IteratorOperatorPlusPlusPostfix, IteratorOperatorNotEquals, IteratorOperatorSmallerThan, Swap ); /******************************************************************************* ******************************************************************************/ typedef ::testing::Types<int> MyGridTest1DTypes; INSTANTIATE_TYPED_TEST_CASE_P(My, GridTest1D, MyGridTest1DTypes); } // end namespace
<reponame>astrionic/advent-of-code-2020 package astrionic.adventofcode2020.solutions.day02 import astrionic.adventofcode2020.framework.AdventSolution object Day02 extends AdventSolution { override def solvePart1(input: String): String = { val passwords = parseInput(input) val validPasswords = passwords.filter(_.isValidPart1) validPasswords.length.toString } override def solvePart2(input: String): String = { val passwords = parseInput(input) val validPasswords = passwords.filter(_.isValidPart2) validPasswords.length.toString } private def parseInput(input: String): Array[Password] = input.split('\n').map(Password.fromString) }
import requests from termcolor import colored # Assuming the use of the termcolor library for colored output def search_books_by_title(title): # Make a request to the book database API to search for books with the given title response = requests.get('https://book-database-api.com/search', params={'title': title}) # Check if the request was successful and process the response if response.status_code == 200: book_data = response.json() if book_data['totalItems'] == 0: print(colored("Sorry. No books were found with that title. ", 'red')) else: # Process and display the found books for book in book_data['items']: print(f"Title: {book['volumeInfo']['title']}") print(f"Author(s): {', '.join(book['volumeInfo']['authors'])}") print("-------------") else: print(colored("Error: Failed to retrieve book data. Please try again later.", 'red')) # Example usage search_books_by_title("Python Programming")
package org.hzero.sso.core.config; import org.springframework.boot.context.properties.ConfigurationProperties; @ConfigurationProperties(prefix = SsoProperties.PREFIX) public class SsoProperties { public static final String PREFIX = "hzero.oauth"; private Login login = new Login(); private Sso sso = new Sso(); public static class Sso { /** * ๅฏ็”จไบŒ็บงๅŸŸๅๅ•็‚น็™ปๅฝ• */ private boolean enabled = true; /** * ๅฏ้€š่ฟ‡ๆญคๅ‚ๆ•ฐ็ฆๆญข่ทณ่ฝฌๅˆฐ sso ้กต้ข */ private String disableSsoParameter = "disable_sso"; private Service service = new Service(); private Provider provider = new Provider(); private Saml saml = new Saml(); public static class Service { /** * CAS Service base url (your application base url) */ private String baseUrl; /** * CAS Service login path that will be append to * {@link Service#baseUrl} */ private String loginPath = "/login/cas"; /** * CAS Service logout path that will be append to * {@link Service#baseUrl} */ private String logoutPath = "/logout"; /** * CAS Service proxy callback url */ private String proxyReceptorUrl; /** * CAS Service failure handler url */ private String failureHandlerUrl; /** * CAS Service proxy failure handler url */ private String proxyFailureHandlerUrl; public String getBaseUrl() { return baseUrl; } public void setBaseUrl(String baseUrl) { this.baseUrl = baseUrl; } public String getLoginPath() { return loginPath; } public void setLoginPath(String loginPath) { this.loginPath = loginPath; } public String getLogoutPath() { return logoutPath; } public void setLogoutPath(String logoutPath) { this.logoutPath = logoutPath; } public String getProxyReceptorUrl() { return proxyReceptorUrl; } public void setProxyReceptorUrl(String proxyReceptorUrl) { this.proxyReceptorUrl = proxyReceptorUrl; } public String getFailureHandlerUrl() { return failureHandlerUrl; } public void setFailureHandlerUrl(String failureHandlerUrl) { this.failureHandlerUrl = failureHandlerUrl; } public String getProxyFailureHandlerUrl() { return proxyFailureHandlerUrl; } public void setProxyFailureHandlerUrl(String proxyFailureHandlerUrl) { this.proxyFailureHandlerUrl = proxyFailureHandlerUrl; } } public static class Provider { /** * Authentication provider key */ private String key; public String getKey() { return key; } public void setKey(String key) { this.key = key; } } public static class Saml { private String entityId; private String passphrase; private String privateKey; private String certificate; public String getPassphrase() { return passphrase; } public void setPassphrase(String passphrase) { this.passphrase = passphrase; } public String getPrivateKey() { return privateKey; } public void setPrivateKey(String privateKey) { this.privateKey = privateKey; } public String getCertificate() { return certificate; } public void setCertificate(String certificate) { this.certificate = certificate; } public String getEntityId() { return entityId; } public void setEntityId(String entityId) { this.entityId = entityId; } } public boolean isEnabled() { return enabled; } public void setEnabled(boolean enabled) { this.enabled = enabled; } public Service getService() { return service; } public void setService(Service service) { this.service = service; } public Provider getProvider() { return provider; } public void setProvider(Provider provider) { this.provider = provider; } public Saml getSaml() { return saml; } public void setSaml(Saml saml) { this.saml = saml; } public String getDisableSsoParameter() { return disableSsoParameter; } public void setDisableSsoParameter(String disableSsoParameter) { this.disableSsoParameter = disableSsoParameter; } } public static class Login { /** * ็™ปๅฝ•้กต้ข */ private String page = "/login"; /** * ็™ปๅฝ•ๆˆๅŠŸๅœฐๅ€ */ private String successUrl = "/"; /** * #็ฝ‘ๅ…ณๆ˜ฏๅฆๅฏ็”จhttps */ private boolean enableHttps; /** * ้ป˜่ฎค็š„ๅฎขๆˆท็ซฏ */ private String defaultClientId = "client"; public String getPage() { return page; } public void setPage(String page) { this.page = page; } public String getSuccessUrl() { return successUrl; } public void setSuccessUrl(String successUrl) { this.successUrl = successUrl; } public boolean isEnableHttps() { return enableHttps; } public void setEnableHttps(boolean enableHttps) { this.enableHttps = enableHttps; } public String getDefaultClientId() { return defaultClientId; } public void setDefaultClientId(String defaultClientId) { this.defaultClientId = defaultClientId; } } public Sso getSso() { return sso; } public void setSso(Sso sso) { this.sso = sso; } public Login getLogin() { return login; } public void setLogin(Login login) { this.login = login; } }
package com.hyperproteinenimia.qaservice.service; import com.hyperproteinenimia.qaservice.entity.Answer; import com.hyperproteinenimia.qaservice.exception.AnswerHaveNoFoundException; import com.hyperproteinenimia.qaservice.repository.AnswerRepository; import org.springframework.stereotype.Service; import java.util.List; @Service public class AnswerService { private final AnswerRepository answerRepository; public AnswerService(AnswerRepository answerRepository) { this.answerRepository = answerRepository; } public List<Answer> getAll() { return answerRepository.findAll(); } public Answer getById(Long id) { return answerRepository.findById(id).orElseThrow(AnswerHaveNoFoundException::new); } public void removeById(Long id) { answerRepository.deleteById(id); } }
#!/bin/bash cd "$(dirname "$0")" dotnet /Users/reapazor/Repositories/dotBunny/JARVIS.NET/JARVIS.Shard/bin/Debug/netcoreapp2.0/JARVIS.Shard.dll --host localhost --encrypt --wirecast --counters --output /Users/reapazor/Documents/StreamingData exit $?
package com.alipay.api.response; import com.alipay.api.internal.mapping.ApiField; import com.alipay.api.AlipayResponse; /** * ALIPAY API: alipay.commerce.educate.scene.user.query response. * * @author auto create * @since 1.0, 2021-12-24 18:02:55 */ public class AlipayCommerceEducateSceneUserQueryResponse extends AlipayResponse { private static final long serialVersionUID = 5196117734415635472L; /** * ๆ กๅ›ญไธ€่„ธ้€š่กŒๅผ€้€š็Šถๆ€ใ€‚OPEN๏ผšๅผ€้€š๏ผŒCLOSE๏ผšๅ…ณ้—ญ */ @ApiField("open_status") private String openStatus; public void setOpenStatus(String openStatus) { this.openStatus = openStatus; } public String getOpenStatus( ) { return this.openStatus; } }
#!/bin/bash # Source settings.conf file . ./settings.conf # Check for set settings if [[ -z "$vpnUser" ]]; then echo 'Error: No "$vpnUser" variable found' exit 1 fi if [[ -z "$vpnPass" ]]; then echo 'Error: No "$vpnPass" variable found' exit 1 fi # Count VPN tunnels to add echo "Attempting to add '${#piaNetworks[@]}' PrivateInternetAccess VPNs:" # For each network, execute addVPN.scpt for network in "${piaNetworks[@]}"; do printf "Processing \"${network}\"... " networkName=${network%%.*} osascript bin/addVPN.scpt "PIA (${networkName})" "${network}" "${vpnUser}" "${vpnPass}" printf "done\n" done exit 0
package ochk import ( "fmt" "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" "testing" ) func TestAccSecurityGroupDataSource_read(t *testing.T) { resourceName := "data.ochk_security_group.one_member" displayName := generateRandName() resource.ParallelTest(t, resource.TestCase{ ProviderFactories: testAccProviderFactories, Steps: []resource.TestStep{ { Config: testAccSecurityGroupDataSourceConfig(displayName), Check: resource.ComposeTestCheckFunc( resource.TestCheckResourceAttr(resourceName, "display_name", displayName), resource.TestCheckResourceAttrSet(resourceName, "created_by"), resource.TestCheckResourceAttrSet(resourceName, "created_at"), resource.TestCheckResourceAttrSet(resourceName, "modified_by"), resource.TestCheckResourceAttrSet(resourceName, "modified_at"), resource.TestCheckResourceAttrPair(resourceName, "members.0.id", "data.ochk_virtual_machine.default", "id"), resource.TestCheckResourceAttr(resourceName, "members.0.type", "VIRTUAL_MACHINE"), resource.TestCheckResourceAttrSet(resourceName, "members.0.display_name"), ), }, }, }) } func testAccSecurityGroupDataSourceConfig(displayName string) string { return fmt.Sprintf(` data "ochk_virtual_machine" "default" { display_name = %[2]q } resource "ochk_security_group" "one_member" { display_name = %[1]q members { id = data.ochk_virtual_machine.default.id type = "VIRTUAL_MACHINE" } } data "ochk_security_group" "one_member" { display_name = ochk_security_group.one_member.display_name depends_on = [ochk_security_group.one_member] } `, displayName, testData.LegacyVirtualMachineDisplayName) }
#include <stdio.h> void swapWithoutTemp(int *x, int *y) { // Code to swap 'x' and 'y' *x = *x + *y; *y = *x - *y; *x = *x - *y; } // Driver code int main() { int x = 5, y = 3; printf("Before Swap\nx = %d\ny = %d\n", x, y); // Calling swap function swapWithoutTemp(&x, &y); printf("After Swap\nx = %d\ny = %d", x, y); return 0; }
const sinon = require('sinon'); const expect = require('expect'); const flat = require('flat'); const { ObjectId } = require('mongodb'); const { fn: momentProto } = require('moment'); const Customer = require('../../../src/models/Customer'); const Drive = require('../../../src/models/Google/Drive'); const ESign = require('../../../src/models/ESign'); const GDriveStorageHelper = require('../../../src/helpers/gDriveStorage'); const MandatesHelper = require('../../../src/helpers/mandates'); const ESignHelper = require('../../../src/helpers/eSign'); const FileHelper = require('../../../src/helpers/file'); const SinonMongoose = require('../sinonMongoose'); describe('getMandates', () => { let findOneCustomer; beforeEach(() => { findOneCustomer = sinon.stub(Customer, 'findOne'); }); afterEach(() => { findOneCustomer.restore(); }); it('should return customer mandates', async () => { const customerId = (new ObjectId()).toHexString(); const mandate = { _id: new ObjectId() }; findOneCustomer.returns(SinonMongoose.stubChainedQueries(mandate, ['lean'])); const result = await MandatesHelper.getMandates(customerId); expect(result).toMatchObject(mandate); SinonMongoose.calledOnceWithExactly( findOneCustomer, [ { query: 'findOne', args: [ { _id: customerId, 'payment.mandates': { $exists: true } }, { identity: 1, 'payment.mandates': 1 }, { autopopulate: false }, ], }, { query: 'lean' }, ] ); }); }); describe('updateMandate', () => { let findOneAndUpdateCustomer; beforeEach(() => { findOneAndUpdateCustomer = sinon.stub(Customer, 'findOneAndUpdate'); }); afterEach(() => { findOneAndUpdateCustomer.restore(); }); it('should update customer mandates', async () => { const customerId = (new ObjectId()).toHexString(); const mandateId = '1234567890'; const payload = { startDate: '2019-12-12T00:00:00' }; findOneAndUpdateCustomer.returns(SinonMongoose.stubChainedQueries({ ...payload, _id: mandateId }, ['lean'])); const result = await MandatesHelper.updateMandate(customerId, mandateId, payload); expect(result).toMatchObject({ ...payload, _id: mandateId }); SinonMongoose.calledOnceWithExactly( findOneAndUpdateCustomer, [ { query: 'findOneAndUpdate', args: [ { _id: customerId, 'payment.mandates._id': mandateId }, { $set: flat({ 'payment.mandates.$': { ...payload } }) }, { new: true, select: { identity: 1, 'payment.mandates': 1 }, autopopulate: false }, ], }, { query: 'lean' }, ] ); }); }); describe('getSignatureRequest', () => { let findOneCustomer; let updateOneCustomer; let generateSignatureRequest; beforeEach(() => { findOneCustomer = sinon.stub(Customer, 'findOne'); updateOneCustomer = sinon.stub(Customer, 'updateOne'); generateSignatureRequest = sinon.stub(ESignHelper, 'generateSignatureRequest'); }); afterEach(() => { findOneCustomer.restore(); updateOneCustomer.restore(); generateSignatureRequest.restore(); }); it('should generate signature request', async () => { const customerId = (new ObjectId()).toHexString(); const mandateId = new ObjectId(); const payload = { fileId: 'fileId', fields: 'fields', title: 'MANDAT SEPA rum', customer: { name: 'qwertyuiop', email: '<EMAIL>' }, redirect: 'redirect', redirectDecline: 'redirectDecline', }; const customer = { _id: customerId, payment: { mandates: [{ _id: new ObjectId() }, { _id: mandateId, rum: 'rum' }] }, }; findOneCustomer.returns(SinonMongoose.stubChainedQueries(customer, ['lean'])); generateSignatureRequest.returns({ data: { document_hash: 'document_hash', signers: [{ embedded_signing_url: 'embedded_signing_url' }] }, }); const result = await MandatesHelper.getSignatureRequest(customerId, mandateId.toHexString(), payload); expect(result).toEqual({ embeddedUrl: 'embedded_signing_url' }); sinon.assert.calledOnceWithExactly( updateOneCustomer, { _id: customerId, 'payment.mandates._id': mandateId.toHexString() }, { $set: flat({ 'payment.mandates.$.everSignId': 'document_hash' }) } ); SinonMongoose.calledOnceWithExactly( findOneCustomer, [ { query: 'findOne', args: [{ _id: customerId, 'payment.mandates._id': mandateId.toHexString() }, { payment: 1 }], }, { query: 'lean' }, ] ); }); it('should throw error if error on generate', async () => { const customerId = (new ObjectId()).toHexString(); const mandateId = new ObjectId(); try { const payload = { fileId: 'fileId', fields: 'fields', title: 'MANDAT SEPA rum', customer: { name: 'qwertyuiop', email: '<EMAIL>' }, redirect: 'redirect', redirectDecline: 'redirectDecline', }; const customer = { _id: customerId, payment: { mandates: [{ _id: new ObjectId() }, { _id: mandateId, rum: 'rum' }] }, }; findOneCustomer.returns(SinonMongoose.stubChainedQueries(customer, ['lean'])); generateSignatureRequest.returns({ data: { error: 'error' } }); await MandatesHelper.getSignatureRequest(customerId, mandateId.toHexString(), payload); } catch (e) { expect(e.output.statusCode).toEqual(400); } finally { sinon.assert.notCalled(updateOneCustomer); SinonMongoose.calledOnceWithExactly( findOneCustomer, [ { query: 'findOne', args: [{ _id: customerId, 'payment.mandates._id': mandateId.toHexString() }, { payment: 1 }], }, { query: 'lean' }, ] ); } }); }); describe('saveSignedMandate', () => { let findOneCustomer; let findOneAndUpdateCustomer; let getDocument; let downloadFinalDocument; let createAndReadFile; let addFile; let getFileById; let momentToDate; beforeEach(() => { findOneCustomer = sinon.stub(Customer, 'findOne'); findOneAndUpdateCustomer = sinon.stub(Customer, 'findOneAndUpdate'); getDocument = sinon.stub(ESign, 'getDocument'); downloadFinalDocument = sinon.stub(ESign, 'downloadFinalDocument'); createAndReadFile = sinon.stub(FileHelper, 'createAndReadFile'); addFile = sinon.stub(GDriveStorageHelper, 'addFile'); getFileById = sinon.stub(Drive, 'getFileById'); momentToDate = sinon.stub(momentProto, 'toDate'); }); afterEach(() => { findOneCustomer.restore(); findOneAndUpdateCustomer.restore(); getDocument.restore(); downloadFinalDocument.restore(); createAndReadFile.restore(); addFile.restore(); getFileById.restore(); momentToDate.restore(); }); it('should save signed mandate', async () => { const customerId = '1234567890'; const mandateId = new ObjectId(); const customer = { _id: customerId, payment: { mandates: [{ _id: mandateId, everSignId: 'everSignId', rum: 'rum' }] }, driveFolder: { driveId: 'driveFolder' }, }; const drive = { driveId: 'fileId', link: 'webViewLink' }; findOneCustomer.returns(SinonMongoose.stubChainedQueries(customer, ['lean'])); findOneAndUpdateCustomer.returns(SinonMongoose.stubChainedQueries(null, ['lean'])); getDocument.returns({ data: { log: [{ event: 'document_signed' }] } }); downloadFinalDocument.returns({ data: 'data' }); createAndReadFile.returns('file'); addFile.returns({ id: 'fileId' }); getFileById.returns({ webViewLink: 'webViewLink' }); momentToDate.returns('2020-12-08T13:45:25.437Z'); await MandatesHelper.saveSignedMandate(customerId, mandateId.toHexString()); sinon.assert.calledWithExactly(getDocument, 'everSignId'); sinon.assert.calledWithExactly(downloadFinalDocument, 'everSignId'); sinon.assert.called(createAndReadFile); sinon.assert.calledWithExactly( addFile, { driveFolderId: 'driveFolder', name: 'rum', type: 'application/pdf', body: 'file' } ); sinon.assert.calledWithExactly(getFileById, { fileId: 'fileId' }); SinonMongoose.calledOnceWithExactly( findOneCustomer, [{ query: 'findOne', args: [{ _id: customerId }] }, { query: 'lean' }] ); SinonMongoose.calledOnceWithExactly( findOneAndUpdateCustomer, [ { query: 'findOneAndUpdate', args: [ { _id: customerId, 'payment.mandates._id': mandateId.toHexString() }, { $set: flat({ 'payment.mandates.$': { drive, signedAt: '2020-12-08T13:45:25.437Z' } }) }, ], }, { query: 'lean' }, ] ); }); it('should throw an error if esign returns an error', async () => { const customerId = '1234567890'; try { const mandateId = new ObjectId(); const customer = { _id: customerId, payment: { mandates: [{ _id: mandateId, everSignId: 'everSignId', rum: 'rum' }] }, driveFolder: { driveId: 'driveFolder' }, }; findOneCustomer.returns(SinonMongoose.stubChainedQueries(customer, ['lean'])); getDocument.returns({ data: { error: 'error', log: [{ event: 'document_signed' }] } }); await MandatesHelper.saveSignedMandate(customerId, mandateId.toHexString()); } catch (e) { expect(e.output.statusCode).toEqual(404); } finally { sinon.assert.calledWithExactly(getDocument, 'everSignId'); sinon.assert.notCalled(downloadFinalDocument); sinon.assert.notCalled(createAndReadFile); sinon.assert.notCalled(addFile); sinon.assert.notCalled(getFileById); sinon.assert.notCalled(findOneAndUpdateCustomer); SinonMongoose.calledOnceWithExactly( findOneCustomer, [{ query: 'findOne', args: [{ _id: customerId }] }, { query: 'lean' }] ); } }); it('should throw an error if no signed doc in esign response', async () => { const customerId = '1234567890'; try { const mandateId = new ObjectId(); const customer = { _id: customerId, payment: { mandates: [{ _id: mandateId, everSignId: 'everSignId', rum: 'rum' }] }, driveFolder: { driveId: 'driveFolder' }, }; findOneCustomer.returns(SinonMongoose.stubChainedQueries(customer, ['lean'])); getDocument.returns({ data: { log: [{ event: 'document_not_signed' }] } }); await MandatesHelper.saveSignedMandate(customerId, mandateId.toHexString()); } catch (e) { expect(e.output.statusCode).toEqual(503); } finally { sinon.assert.calledWithExactly(getDocument, 'everSignId'); sinon.assert.notCalled(downloadFinalDocument); sinon.assert.notCalled(createAndReadFile); sinon.assert.notCalled(addFile); sinon.assert.notCalled(getFileById); sinon.assert.notCalled(findOneAndUpdateCustomer); SinonMongoose.calledOnceWithExactly( findOneCustomer, [{ query: 'findOne', args: [{ _id: customerId }] }, { query: 'lean' }] ); } }); });
#/bin/bash CUDA_HOME=/opt/cuda TF_CFLAGS=$(python -c 'import tensorflow as tf; print(" ".join(tf.sysconfig.get_compile_flags()))') TF_LFLAGS=$(python -c 'import tensorflow as tf; print(" ".join(tf.sysconfig.get_link_flags()))') nvcc tf_sampling_g.cu -o tf_sampling_g.cu.o -c -O2 -DGOOGLE_CUDA=1 -x cu -Xcompiler -fPIC g++ -std=c++11 tf_sampling.cpp tf_sampling_g.cu.o -o tf_sampling_so.so -shared -fPIC -I$CUDA_HOME/include -L $CUDA_HOME/lib64 -lcudart $TF_CFLAGS $TF_LFLAGS -O2