text
stringlengths 1
1.05M
|
|---|
#!/bin/bash
# Find linting errors in Synapse's default config file.
# Exits with 0 if there are no problems, or another code otherwise.
# Fix non-lowercase true/false values
sed -i.bak -E "s/: +True/: true/g; s/: +False/: false/g;" docs/sample_config.yaml
rm docs/sample_config.yaml.bak
# Check if anything changed
git diff --exit-code docs/sample_config.yaml
|
<reponame>jresendiz27/personal_blog<filename>poorman_system_monitoring/push_metrics_to_prometheus.py<gh_stars>0
import asyncio
import csv
import logging
import os
import aiohttp
MEMORY_COMMAND = 'head -n 1 /proc/meminfo | awk \'{print $2}\''
PROCESS_INFORMATION = 'ps -o pid,uid,%mem,command ax'
SSH_COMMAND_TO_RETRIEVE = "ssh " \
"-o UserKnownHostsFile=/dev/null " \
"-o StrictHostKeyChecking=no " \
"-i %s %s@%s "
PUSHGATEWAY_URL = os.getenv('PUSHGATEWAY_URL', 'http://localhost:9091')
async def memory_retrieval(params):
command = base_ssh_command(params)
logging.info(f"Getting information from host: {params['host']}")
memory_process = await asyncio.create_subprocess_shell(
f"{command} {MEMORY_COMMAND}",
stdout=asyncio.subprocess.PIPE,
stderr=asyncio.subprocess.PIPE
)
memory_stdout, memory_stderr = await memory_process.communicate()
current_server_memory = -1
if memory_stdout:
current_server_memory = int(memory_stdout.decode())
logging.info(f"Server: {params['host']}, Memory: {current_server_memory}")
return current_server_memory
def base_ssh_command(params):
return SSH_COMMAND_TO_RETRIEVE % (params['key_location'], params['user'], params['host'])
def escape_label_chars(param: str):
return param \
.replace("\\", "\\\\") \
.replace("\n", "\\n") \
.replace("\"", "\\""")
def camelize_string(param: str):
return param \
.replace("\\", "_") \
.replace(" ", "_") \
.replace(":", "_") \
.replace("-", "_") \
.replace("[", "_") \
.replace("]", "_") \
.replace("/", "_") \
.replace("=", "_") \
.replace("(", "") \
.replace(")", "")
def parse_to_open_metrics_format(host_information, columns, current_server_memory):
return f'''
# TYPE process_{camelize_string(columns[3])}_id gauge
process_{camelize_string(columns[3])}_id{{instance=\"{host_information['host']}\",command=\"{escape_label_chars(
" ".join(columns[3:]))}\"}} {int(columns[0])}
# TYPE process_{camelize_string(columns[3])}_uid gauge
process_{camelize_string(columns[3])}_uid{{instance=\"{host_information['host']}\"}} {columns[1]}
# TYPE total_memory gauge
total_memory{{instance=\"{host_information['host']}\"}} {current_server_memory}
# TYPE process_{camelize_string(columns[3])}_memory_percentage gauge
process_{camelize_string(columns[3])}_memory_percentage{{instance=\"{host_information['host']}\"}} {float(
columns[2])}
# TYPE process_{camelize_string(columns[3])}_memory_usage gauge
process_{camelize_string(columns[3])}_memory_usage{{instance=\"{host_information[
'host']}\"}} {current_server_memory * float(
columns[2]) / 100}
'''
async def processes_information(host_information, current_server_memory):
logging.info(f"Getting processes information from host: {host_information['host']}")
ps_process = await asyncio.create_subprocess_shell(
f"{base_ssh_command(host_information)} {PROCESS_INFORMATION}",
stdout=asyncio.subprocess.PIPE,
stderr=asyncio.subprocess.PIPE
)
process_list = []
ps_process_stdout, ps_process_stderr = await ps_process.communicate()
logging.info("Transforming result into OpenMetrics standard")
if ps_process_stdout:
lines = ps_process_stdout.decode().splitlines()
for i in range(1, len(lines)):
columns = lines[i].split()
result = parse_to_open_metrics_format(host_information, columns, current_server_memory)
process_list.append(result)
logging.info(result)
logging.info(process_list)
logging.info("Finished parsing information from host")
return process_list
async def push_to_prometheus(host_info, list_processes):
host = f"{PUSHGATEWAY_URL}/metrics/job/metrics_collection/instance/{host_info['host']}"
logging.info(f"Pushing information to prometheus push gateway: {host}")
results = []
for process_info in list_processes:
async with aiohttp.ClientSession(headers={'Content-Type': 'text/plain'}).post(host, data=process_info) as resp:
response_text = await resp.text()
response_code = resp.status
logging.info(process_info)
formatted_response = f"{response_code} - {response_text} - \n {process_info}"
logging.info(f"Result from request: \n host: {host}, \n response: {formatted_response}")
results.append(formatted_response)
resp.close()
return results
async def main():
server_list = []
logging.info("Reading hosts inventory from csv")
with open("./servers_inventory.csv", "+r") as csv_file:
csv_reader = csv.DictReader(csv_file)
for row in csv_reader:
server_list.append(row)
logging.info("Getting memory information from each server")
memory_results = [asyncio.ensure_future(memory_retrieval(values)) for values in server_list]
await asyncio.wait(memory_results)
logging.info("Getting information per process from each server")
processes_results = [asyncio.ensure_future(processes_information(server_list[i], memory_results[i].result())) for i
in
range(0, len(server_list))]
await asyncio.wait(processes_results)
logging.info("Pushing information to prometheus")
prometheus_push_results = [
asyncio.ensure_future(
push_to_prometheus(server_list[i], processes_results[i].result())
) for i in range(0, len(processes_results))]
await asyncio.wait(prometheus_push_results)
logging.info("Finished sending information to prometheus")
if __name__ == '__main__':
logging.basicConfig(level=logging.INFO)
loop = asyncio.get_event_loop()
loop.run_until_complete(main())
loop.close()
|
#ifndef STUDENTCOURSELINK_H
#define STUDENTCOURSELINK_H
#include <QDate>
#include "student.h"
#include "course.h"
namespace slink //student links to courses and degrees and other files..
{
class StudentCourseLink
{
public:
StudentCourseLink();
StudentCourseLink(Student &student, program::Course &course, QDate dateEnrolled)
{
this->student = &student;
this->course = &course;
this->dateEnrolled = dateEnrolled;
this->TotalMark = 0;
this->Grade = '_';
}
~StudentCourseLink();
void enroll(Student &student, program::Course &course, QDate dateEnrolled);
void writeToFile(std::string filename);
void setStudent(Student *s) {this->student = s;}
void setCourse(program::Course *c) {this->course = c;}
void setDate(QDate d) {this->dateEnrolled = d;}
void setMark(int d) {this->TotalMark = d;}
void setGrade(char grade) {this->Grade = grade;}
Student* getStudent() {return this->student;}
program::Course* getCourse() {return this->course;}
QDate getDate() {return this->dateEnrolled;}
int getMark() {return this->TotalMark;}
char getGrade() {return this->Grade;}
int findLink(Student &student, program::Course &course, StudentCourseLink scLink[], int N); //find a matching object given student and course, in array. returns index if found, else -1.
int getCourseList(Student &student, StudentCourseLink scLink[], int N, int index[]); //returns an array of indexes for course where a student match was found
int getStudentList(program::Course &course, StudentCourseLink scLink[], int N, int index[]); //returns an array of indexes for student where a course match was found
//copies links to array and returns number found
size_t copyFromFile(std::string filename, StudentCourseLink link[], size_t N, std::vector<Student> &sList, size_t sN, std::vector<program::Course> &cList, size_t cN);
void removeFromFile(std::string filename);
private:
Student *student; //storing pointers to memory of where the actual student is stored, saves on memory as opposed to copying the entire student.
program::Course *course; //same for course, pointers.
QDate dateEnrolled;
int TotalMark;
char Grade;
};
class StudentDegreeLink
{
public:
StudentDegreeLink();
Student* getStudent() {return this->student;}
program::Degree* getDegree() {return this->degree;}
QDate getDate() {return this->dateEnrolled;}
int getFinalMark() {return this->FinalMark;}
void setStudent(Student *student) {this->student = student;}
void setDegree(program::Degree *d) {this->degree = d;}
void setDate(QDate date) {this->dateEnrolled = date;}
void setFinalMark(int mark) {this->FinalMark = mark;}
//copies links to array and returns number found
size_t copyFromFile(std::string filename, StudentDegreeLink link[], size_t N, std::vector<program::Degree> &dlist, size_t dN, std::vector<Student> &slist, size_t cN);
void writeToFile(std::string filename);
private:
Student *student;
program::Degree *degree;
QDate dateEnrolled;
int FinalMark;
};
} //namespace
#endif // STUDENTCOURSELINK_H
|
#!/bin/bash
echo "Adding Frameworks @rpath to binary ..."
install_name_tool -add_rpath @loader_path/../Frameworks out/a-simple-triangle-console
|
#!/usr/bin/env bash
THIS_DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" >/dev/null 2>&1 && pwd )"
ROOT_DIR="$THIS_DIR/../../.."
SCRIPTS_DIR="$ROOT_DIR/scripts"
source "$SCRIPTS_DIR/lib/common.sh"
source "$SCRIPTS_DIR/lib/k8s.sh"
source "$SCRIPTS_DIR/lib/testutil.sh"
wait_seconds=5
test_name="$( filenoext "${BASH_SOURCE[0]}" )"
service_name="ecr"
ack_ctrl_pod_id=$( controller_pod_id "$service_name")
debug_msg "executing test: $service_name/$test_name"
# This smoke test creates and deletes a set of ECR repositories. It creates
# more than 1 repository in order to ensure that the ReadMany code paths and
# the associated generated code that do object lookups for a single object work
# when >1 object are returned in various List operations.
# PRE-CHECKS
for x in a b c; do
repo_name="ack-test-smoke-$service_name-$x"
resource_name="repositories/$repo_name"
aws ecr describe-repositories --repository-names "$repo_name" --output json >/dev/null 2>&1
if [[ $? -ne 255 && $? -ne 254 ]]; then
echo "FAIL: expected $repo_name to not exist in ECR. Did previous test run cleanup?"
exit 1
fi
if k8s_resource_exists "$resource_name"; then
echo "FAIL: expected $resource_name to not exist. Did previous test run cleanup?"
exit 1
fi
done
# TEST ACTIONS and ASSERTIONS
for x in a b c; do
repo_name="ack-test-smoke-$service_name-$x"
cat <<EOF | kubectl apply -f -
apiVersion: ecr.services.k8s.aws/v1alpha1
kind: Repository
metadata:
name: $repo_name
spec:
repositoryName: $repo_name
EOF
done
sleep $wait_seconds
for x in a b c; do
repo_name="ack-test-smoke-$service_name-$x"
resource_name="repositories/$repo_name"
debug_msg "checking repository $repo_name created in ECR"
aws ecr describe-repositories --repository-names "$repo_name" --output json >/dev/null 2>&1
if [[ $? -eq 255 || $? -eq 254 ]]; then
echo "FAIL: expected $repo_name to have been created in ECR"
kubectl logs -n ack-system "$ack_ctrl_pod_id"
exit 1
fi
kubectl delete "$resource_name" 2>/dev/null
assert_equal "0" "$?" "Expected success from kubectl delete but got $?" || exit 1
done
sleep $wait_seconds
for x in a b c; do
repo_name="ack-test-smoke-$service_name-$x"
aws ecr describe-repositories --repository-names "$repo_name" --output json >/dev/null 2>&1
if [[ $? -ne 255 && $? -ne 254 ]]; then
echo "FAIL: expected $repo_name to be deleted in ECR"
kubectl logs -n ack-system "$ack_ctrl_pod_id"
exit 1
fi
done
|
#!/bin/bash
set -e
SOURCE="${BASH_SOURCE[0]}"
while [ -h "$SOURCE" ]; do # resolve $SOURCE until the file is no longer a symlink
DIR="$( cd -P "$( dirname "$SOURCE" )" && pwd )"
SOURCE="$(readlink "$SOURCE")"
[[ $SOURCE != /* ]] && SOURCE="$DIR/$SOURCE" # if $SOURCE was a relative symlink, we need to resolve it relative to the path where the symlink file was located
done
SCRIPTS_DIR="$( cd -P "$( dirname "$SOURCE" )" && pwd )"
CPP_SRC_DIR="${SCRIPTS_DIR}/../../cpp"
CPP_BUILD_DIR="${CPP_SRC_DIR}/cmake_build"
BUILD_TYPE="Debug"
BUILD_UNITTEST="OFF"
INSTALL_PREFIX="/var/lib/arctern"
RUN_LINT="OFF";
COMPILE_BUILD="ON"
USE_GPU="OFF"
CUDA_COMPILER=/usr/local/cuda/bin/nvcc
PRIVILEGES="OFF"
while getopts "o:t:d:e:lnguph" arg
do
case $arg in
o)
INSTALL_PREFIX=$OPTARG
;;
t)
BUILD_TYPE=$OPTARG # BUILD TYPE
;;
d)
CPP_BUILD_DIR=$OPTARG # CPP BUILD DIRCETORY
;;
e)
CONDA_ENV=$OPTARG # CONDA ENVIRONMENT
;;
l)
RUN_LINT="ON";
;;
n)
COMPILE_BUILD="OFF";
;;
g)
USE_GPU="ON";
;;
u)
echo "Build unittest cases" ;
BUILD_UNITTEST="ON";
;;
p)
PRIVILEGES="ON" # ELEVATED PRIVILEGES
;;
h) # help
echo "
parameter:
-o: install prefix(default: /var/lib/arctern)
-t: build type(default: Debug)
-d: cpp code build directory
-e: set conda activate environment
-l: run cpplint & check clang-format
-n: no execute make and make install
-g: gpu version
-u: building unit test options(default: OFF)
-p: install command with elevated privileges
-h: help
usage:
./cpp_build.sh -o \${INSTALL_PREFIX} -t \${BUILD_TYPE} -d \${CPP_BUILD_DIR} -e \${CONDA_ENV} [-l] [-n] [-g] [-u] [-p] [-h]
"
exit 0
;;
?)
echo "ERROR! unknown argument"
exit 1
;;
esac
done
if [[ -n ${CONDA_ENV} ]]; then
eval "$(conda shell.bash hook)"
conda activate ${CONDA_ENV}
fi
if [[ ! -d ${CPP_BUILD_DIR} ]]; then
mkdir ${CPP_BUILD_DIR}
fi
cd ${CPP_BUILD_DIR}
# CMAKE_CMD="cmake \
# -DCMAKE_INSTALL_PREFIX=${INSTALL_PREFIX} \
# -DCMAKE_BUILD_TYPE=${BUILD_TYPE} \
# -DUSE_GPU=${USE_GPU} \
# -DBUILD_UNITTEST=${BUILD_UNITTEST} \
# -DCMAKE_CUDA_COMPILER=${CUDA_COMPILER} \
# ${CPP_SRC_DIR}
# "
CMAKE_CMD="cmake \
-DCMAKE_INSTALL_PREFIX=${CONDA_PREFIX} \
-DCMAKE_BUILD_TYPE=${BUILD_TYPE} \
-DUSE_GPU=${USE_GPU} \
-DBUILD_UNITTEST=${BUILD_UNITTEST} \
-DCMAKE_CUDA_COMPILER=${CUDA_COMPILER} \
${CPP_SRC_DIR}
"
echo ${CMAKE_CMD}
${CMAKE_CMD}
if [[ ${RUN_LINT} == "ON" ]];then
make lint || exit 1
make check-clang-format || exit 1
fi
if [[ ${COMPILE_BUILD} == "ON" ]];then
# compile and build
make -j8 || exit 1
if [[ ${PRIVILEGES} == "ON" ]];then
sudo make install || exit 1
else
make install || exit 1
fi
fi
|
#!/bin/sh -e
my_file="$(readlink -e "$0")"
my_dir="$(dirname $my_file)"
juju deploy "$my_dir/contrail-docker-bundle-ha-trusty.yaml"
BUILD="3065"
juju attach contrail-controller contrail-controller="/home/ubuntu/contrail-controller-ubuntu14.04-4.0.0.0-$BUILD.tar.gz"
juju attach contrail-analytics contrail-analytics="/home/ubuntu/contrail-analytics-ubuntu14.04-4.0.0.0-$BUILD.tar.gz"
juju attach contrail-analyticsdb contrail-analyticsdb="/home/ubuntu/contrail-analyticsdb-ubuntu14.04-4.0.0.0-$BUILD.tar.gz"
|
import json
import time
import requests
from logger import other
# http云打码的client
class YDMHttp:
apiurl = 'http://api.yundama.com/api.php'
username = ''
password = ''
appid = ''
appkey = ''
# 初始化,
# 获取用户名、密码,appid,appkey等
def __init__(self, name, passwd, app_id, app_key):
self.username = name
self.password = <PASSWORD>
self.appid = str(app_id)
self.appkey = app_key
def request(self, fields, files=[]):
# post请求url
response = self.post_url(self.apiurl, fields, files)
# 返回的是一个json
response = json.loads(response)
# 返回json数据
return response
# 获取账户的余额
def balance(self):
data = {
'method': 'balance',
'username': self.username,
'password': <PASSWORD>,
'appid': self.appid,
'appkey': self.appkey
}
response = self.request(data)
if response:
if response['ret'] and response['ret'] < 0:
return response['ret']
else:
return response['balance']
else:
return -9001
# 登录云打码
def login(self):
data = {'method': 'login', 'username': self.username, 'password': self.password, 'appid': self.appid,
'appkey': self.appkey}
response = self.request(data)
if response:
# 返回return的数据
if response['ret'] and response['ret'] < 0:
return response['ret']
else:
return response['uid']
else:
return -9001
def upload(self, filename, codetype, timeout):
# 上传文件,要是通过post请求的形式
data = {'method': 'upload', 'username': self.username, 'password': <PASSWORD>, 'appid': self.appid,
'appkey': self.appkey, 'codetype': str(codetype), 'timeout': str(timeout)}
file = {'file': filename}
response = self.request(data, file)
if response:
if response['ret'] and response['ret'] < 0:
return response['ret']
else:
return response['cid']
else:
return -9001
def result(self, cid):
data = {'method': 'result', 'username': self.username, 'password': self.password, 'appid': self.appid,
'appkey': self.appkey, 'cid': str(cid)}
# 请求返回结果
response = self.request(data)
return response and response['text'] or ''
def decode(self, file_name, code_type, time_out):
# 长传文件,获得一个返回值
cid = self.upload(file_name, code_type, time_out)
if cid > 0:
# 循环请求结果
for i in range(0, time_out):
result = self.result(cid)
if result != '':
return cid, result
else:
time.sleep(1)
return -3003, ''
else:
return cid, ''
def post_url(self, url, fields, files=[]):
for key in files:
files[key] = open(files[key], 'rb')
res = requests.post(url, files=files, data=fields)
return res.text
def report_error(self, cid):
data = {
'method': 'report',
'username': self.username,
'password': self.password,
'appid': self.appid,
'appkey': self.appkey,
'flag': 0,
'cid': cid
}
response = self.request(data)
if response:
if response['ret']:
return response['ret']
else:
return -9001
# 使用云打码来识别
def code_verificate(name, passwd, file_name, code_type=1005, app_id=3510, app_key='7281f8452aa559cdad6673684aa8f575',
time_out=60):
"""
:param name: 云打码注册用户名,这是普通用户注册,而非开发者用户注册名
:param passwd: <PASSWORD>
:param file_name: 需要识别的图片名
:param app_id: 软件ID,这里默认是填的我的,如果需要,可以自行注册一个开发者账号,填自己的。
软件开发者会有少额提成,希望大家支持weibospider的发展(提成的20%会给celery项目以支持其发展)
:param app_key: 软件key,这里默认是填的我的,如果需要,可以自行注册一个开发者账号,填自己的
:param code_type: 1005表示五位字符验证码。价格和验证码类别,详细请看http://www.yundama.com/price.html
:param time_out: 超时时间
:return: 验证码结果
"""
yundama_obj = YDMHttp(name, passwd, app_id, app_key)
yundama_obj.login()
# 查询账户余额
rest = yundama_obj.balance()
if rest <= 0:
raise Exception('云打码已经欠费了,请及时充值')
if rest <= 100:
other.warning('云打码余额已不多,请注意及时充值')
# 开始识别,图片路径,验证码类型ID,超时时间(秒),识别结果
cid, result = yundama_obj.decode(file_name, code_type, time_out)
return result, yundama_obj, cid
|
<gh_stars>0
import React from "react";
import { Container, Row, Col, Button } from "reactstrap";
import imgCard1 from "./risen-christ/img1.jpg";
import imgCard2 from "./risen-christ/img2.jpg";
import imgCard3 from "./risen-christ/img3.jpg";
import imgCard4 from "./risen-christ/img4.jpg";
import Review from "./Review";
const RisenCrist = () => (
<div className="subComponent">
<Container>
<section className="tour-cover item-center">
<img src={imgCard1} alt="The Shrine of the Risen Christ" />
<h1>The Shrine of the Risen Christ</h1>
<h4>Brgy. Balicuatro</h4>
</section>
<section className="tour-info">
<Row>
<Col sm="8">
<div className="tour-desc">
<p>
Shrine of the Risen Christ in Brgy. Balicuatro are inspiring in
their splendor and compelling in their significance as places of
worship, meditation, and spiritually, located on a rock hill
overlooking Lavezares Bay, was similarly chiseled by de los
Reyes and funded by the Cuycos.
</p>
<p>
Believer swear that the number and strength of raging storms
that frequently battered the province in the past had been
greatly reduced and weakened because of the giant religious
sculptures that guard their shores, they may yet – spiritually
and realistic.
</p>
<h5>Contact</h5>
<p>
For more information please contact the Municipal Tourism
Officer – <NAME> at 09282972948
</p>
</div>
</Col>
<Col sm="4">
<div className="tour-gallery">
<a href={imgCard1}>
<img src={imgCard1} alt="" />
</a>
<a href={imgCard2}>
<img src={imgCard2} alt="" />
</a>
<a href={imgCard3}>
<img src={imgCard3} alt="" />
</a>
<a href={imgCard4}>
<img src={imgCard4} alt="" />
</a>
</div>
</Col>
</Row>
</section>
</Container>
<section>
<iframe
title="Risen Christ map"
src="https://www.google.com/maps/embed?pb=!1m18!1m12!1m3!1d3893.680052559179!2d124.31599931442825!3d12.549966991133484!2m3!1f0!2f0!3f0!3m2!1i1024!2i768!4f13.1!3m3!1m2!1s0x0%3A0x0!2zMTLCsDMyJzU5LjkiTiAxMjTCsDE5JzA1LjUiRQ!5e0!3m2!1sen!2sph!4v1549940395418"
/>
</section>
<Review />
</div>
);
export default RisenCrist;
|
<gh_stars>1-10
module Fog
module Compute
class Ecloud
module Shared
def validate_node_service_data(service_data)
required_opts = [:name, :port, :enabled, :ip_address]
unless required_opts.all? { |opt| service_data.has_key?(opt) }
raise ArgumentError.new("Required Internet Service data missing: #{(required_opts - service_data.keys).map(&:inspect).join(", ")}")
end
end
end
class Real
include Shared
def node_service_create(service_data)
validate_node_service_data(service_data)
request(
:body => generate_node_service_request(service_data),
:expects => 201,
:method => "POST",
:headers => {},
:uri => service_data[:uri],
:parse => true
)
end
private
def generate_node_service_request(service_data)
xml = Builder::XmlMarkup.new
xml.CreateNodeService(:name => service_data[:name]) do
xml.IpAddress(:href => service_data[:ip_address], :name => service_data[:ip_address].scan(/\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}/)[0])
xml.Port service_data[:port]
xml.Enabled service_data[:enabled]
if service_data[:description]
xml.Description service_data[:description]
end
end
end
end
end
end
end
|
#!/usr/bin/env bash
cd $(dirname $0)
docker build -t madar15/cassandra .
|
<gh_stars>1-10
//// react
import React, {useState, useEffect, useContext} from 'react';
//// react native
import {StyleSheet, Dimensions, Image, TouchableOpacity} from 'react-native';
//// config
//// language
import {useIntl} from 'react-intl';
//// ui
import {Block, Button, Input, Text, theme, Icon} from 'galio-framework';
import Modal from 'react-native-modal';
import {argonTheme} from '~/constants';
const {width, height} = Dimensions.get('window');
//// coponents
interface Props {
title: string;
showModal: boolean;
username: string;
balance: string;
loading: boolean;
userAvatar: string;
amount: number;
amountMessage: string;
errorMessage: string;
showConfirm: boolean;
handleAmountChange: (amount: string) => void;
handleAmountFocus: () => void;
onPressProceedButton: () => void;
hanldePowerup: (amount: number) => void;
cancelModal: () => void;
}
const PowerupView = (props: Props): JSX.Element => {
//// props
const {
showModal,
title,
username,
balance,
loading,
userAvatar,
amount,
amountMessage,
showConfirm,
errorMessage,
} = props;
//// language
const intl = useIntl();
const _renderForms = () => {
return (
<Block center card>
<Block center style={{margin: 10}}>
<Block row center space="between">
<Text style={styles.text}>
{intl.formatMessage({id: 'Wallet.from'})}
</Text>
<Input
style={styles.input}
bgColor="lightgray"
editable={false}
defaultValue={username}
autoCapitalize="none"
left
icon="at"
family="font-awesome"
/>
<Image
source={{
uri: userAvatar || null,
}}
style={styles.avatar}
/>
</Block>
<Block>
<Block row center space="between">
<Text style={styles.text}>
{intl.formatMessage({id: 'TokenTransfer.amount'})}
</Text>
<Block>
<Input
editable={!showConfirm}
bgColor={showConfirm ? 'lightgray' : null}
right
type="number-pad"
style={[styles.input, {marginRight: 30}]}
defaultValue={amount.toString()}
placeholder={intl.formatMessage({
id: 'TokenTransfer.amount_placeholder',
})}
onFocus={props.handleAmountFocus}
onChangeText={props.handleAmountChange}
/>
</Block>
</Block>
<TouchableOpacity onPress={() => props.handleAmountChange(balance)}>
<Text color={argonTheme.COLORS.FACEBOOK} style={{left: 80}}>
{intl.formatMessage(
{id: 'TokenTransfer.steem_balance'},
{what: balance},
)}
</Text>
</TouchableOpacity>
<Text color="red">{amountMessage}</Text>
</Block>
</Block>
</Block>
);
};
const _renderFooter = () => (
<Block>
<Block row center>
<Button
size="small"
shadowless
color={argonTheme.COLORS.STEEM}
onPress={props.onPressProceedButton}
loading={loading}>
{showConfirm || loading
? intl.formatMessage({id: 'Powerup.button'})
: intl.formatMessage({id: 'TokenTransfer.next_button'})}
</Button>
</Block>
<Block center>
<Text size={16} color="red">
{errorMessage}
</Text>
</Block>
</Block>
);
return (
<Modal
isVisible={showModal}
animationIn="zoomIn"
animationOut="zoomOut"
onBackdropPress={props.cancelModal}>
<Block style={styles.listContainer}>
<Block center>
<Text
h5
style={{
borderBottomColor: 'red',
borderBottomWidth: 5,
marginBottom: 10,
}}>
{title}
</Text>
</Block>
<Text
style={{
margin: 3,
}}>
{intl.formatMessage({id: 'Powerup.description'})}
</Text>
{_renderForms()}
{_renderFooter()}
</Block>
</Modal>
);
};
export {PowerupView};
const styles = StyleSheet.create({
modalContainer: {
width: '100%',
height: 'auto',
backgroundColor: theme.COLORS.WHITE,
paddingVertical: 10,
},
listContainer: {
marginHorizontal: 10,
backgroundColor: theme.COLORS.WHITE,
paddingVertical: 10,
},
text: {
width: 70,
textAlign: 'left',
marginRight: 10,
},
input: {
width: width * 0.5,
marginRight: 10,
},
autocompleteContainer: {
flex: 1,
left: 0,
position: 'absolute',
right: 0,
top: 0,
zIndex: 1,
},
list: {
width: '100%',
paddingHorizontal: theme.SIZES.BASE,
paddingVertical: theme.SIZES.BASE * 1,
},
avatar: {
width: 24,
height: 24,
borderRadius: 24 / 2,
},
});
|
def intersectSets(arr1, arr2) {
return new Set([...arr1].filter(el => arr2.includes(el)));
}
const result = intersectSets([1, 2, 4, 5], [4, 5, 6, 7]);
console.log(result);
|
package com.yoga.content.template.vo;
import com.fasterxml.jackson.annotation.JsonInclude;
import io.swagger.annotations.ApiModelProperty;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
@Getter
@Setter
@NoArgsConstructor
@JsonInclude(JsonInclude.Include.NON_EMPTY)
public class TemplateVo {
@ApiModelProperty(value = "模板ID")
private Long id;
@ApiModelProperty(value = "模板名称")
private String name;
@ApiModelProperty(value = "模板编码")
private String code;
@ApiModelProperty(value = "是否启用")
private Boolean enabled;
@ApiModelProperty(value = "字段数量")
private Integer fieldCount;
@ApiModelProperty(value = "模板备注")
private String remark;
}
|
# Import the preprocess module and call the preprocess_data function
from . import preprocess
def perform_preprocessing(data: list) -> list:
preprocessed_data = preprocess.preprocess_data(data)
return preprocessed_data
|
#!/bin/bash
set -e
source $(dirname $0)/lib.sh
req_env_var "
SRC $SRC
CRIO_SRC $CRIO_SRC
OS_RELEASE_ID $OS_RELEASE_ID
OS_RELEASE_VER $OS_RELEASE_VER
"
cd "$CRIO_SRC"
case "$OS_REL_VER" in
fedora-29)
PATCH="$SRC/$SCRIPT_BASE/network_bats.patch"
cd "$CRIO_SRC"
echo "WARNING: Applying $PATCH"
git apply --index --apply --ignore-space-change --recount "$PATCH"
;;
*) bad_os_id_ver ;;
esac
# Assume cri-o and all dependencies are installed from packages
# and conmon installed using build_and_replace_conmon()
export CRIO_BINARY=/usr/bin/crio
export CONMON_BINARY=/usr/libexec/crio/conmon
export PAUSE_BINARY=/usr/libexec/crio/pause
export CRIO_CNI_PLUGIN=/usr/libexec/cni
echo "Executing cri-o integration tests (typical 10 - 20 min)"
cd "$CRIO_SRC"
timeout --foreground --kill-after=5m 60m ./test/test_runner.sh
|
#!/bin/sh
set -e
RESOURCES_TO_COPY=${PODS_ROOT}/resources-to-copy-${TARGETNAME}.txt
> "$RESOURCES_TO_COPY"
install_resource()
{
case $1 in
*.storyboard)
echo "ibtool --reference-external-strings-file --errors --warnings --notices --output-format human-readable-text --compile ${CONFIGURATION_BUILD_DIR}/${UNLOCALIZED_RESOURCES_FOLDER_PATH}/`basename \"$1\" .storyboard`.storyboardc ${PODS_ROOT}/$1 --sdk ${SDKROOT}"
ibtool --reference-external-strings-file --errors --warnings --notices --output-format human-readable-text --compile "${CONFIGURATION_BUILD_DIR}/${UNLOCALIZED_RESOURCES_FOLDER_PATH}/`basename \"$1\" .storyboard`.storyboardc" "${PODS_ROOT}/$1" --sdk "${SDKROOT}"
;;
*.xib)
echo "ibtool --reference-external-strings-file --errors --warnings --notices --output-format human-readable-text --compile ${CONFIGURATION_BUILD_DIR}/${UNLOCALIZED_RESOURCES_FOLDER_PATH}/`basename \"$1\" .xib`.nib ${PODS_ROOT}/$1 --sdk ${SDKROOT}"
ibtool --reference-external-strings-file --errors --warnings --notices --output-format human-readable-text --compile "${CONFIGURATION_BUILD_DIR}/${UNLOCALIZED_RESOURCES_FOLDER_PATH}/`basename \"$1\" .xib`.nib" "${PODS_ROOT}/$1" --sdk "${SDKROOT}"
;;
*.framework)
echo "mkdir -p ${CONFIGURATION_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}"
mkdir -p "${CONFIGURATION_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}"
echo "rsync -av ${PODS_ROOT}/$1 ${CONFIGURATION_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}"
rsync -av "${PODS_ROOT}/$1" "${CONFIGURATION_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}"
;;
*.xcdatamodel)
echo "xcrun momc \"${PODS_ROOT}/$1\" \"${CONFIGURATION_BUILD_DIR}/${UNLOCALIZED_RESOURCES_FOLDER_PATH}/`basename "$1"`.mom\""
xcrun momc "${PODS_ROOT}/$1" "${CONFIGURATION_BUILD_DIR}/${UNLOCALIZED_RESOURCES_FOLDER_PATH}/`basename "$1" .xcdatamodel`.mom"
;;
*.xcdatamodeld)
echo "xcrun momc \"${PODS_ROOT}/$1\" \"${CONFIGURATION_BUILD_DIR}/${UNLOCALIZED_RESOURCES_FOLDER_PATH}/`basename "$1" .xcdatamodeld`.momd\""
xcrun momc "${PODS_ROOT}/$1" "${CONFIGURATION_BUILD_DIR}/${UNLOCALIZED_RESOURCES_FOLDER_PATH}/`basename "$1" .xcdatamodeld`.momd"
;;
*.xcassets)
;;
/*)
echo "$1"
echo "$1" >> "$RESOURCES_TO_COPY"
;;
*)
echo "${PODS_ROOT}/$1"
echo "${PODS_ROOT}/$1" >> "$RESOURCES_TO_COPY"
;;
esac
}
install_resource "${BUILT_PRODUCTS_DIR}/DKFilterView.bundle"
rsync -avr --copy-links --no-relative --exclude '*/.svn/*' --files-from="$RESOURCES_TO_COPY" / "${CONFIGURATION_BUILD_DIR}/${UNLOCALIZED_RESOURCES_FOLDER_PATH}"
if [[ "${ACTION}" == "install" ]]; then
rsync -avr --copy-links --no-relative --exclude '*/.svn/*' --files-from="$RESOURCES_TO_COPY" / "${INSTALL_DIR}/${UNLOCALIZED_RESOURCES_FOLDER_PATH}"
fi
rm -f "$RESOURCES_TO_COPY"
if [[ -n "${WRAPPER_EXTENSION}" ]] && [ `xcrun --find actool` ] && [ `find . -name '*.xcassets' | wc -l` -ne 0 ]
then
case "${TARGETED_DEVICE_FAMILY}" in
1,2)
TARGET_DEVICE_ARGS="--target-device ipad --target-device iphone"
;;
1)
TARGET_DEVICE_ARGS="--target-device iphone"
;;
2)
TARGET_DEVICE_ARGS="--target-device ipad"
;;
*)
TARGET_DEVICE_ARGS="--target-device mac"
;;
esac
find "${PWD}" -name "*.xcassets" -print0 | xargs -0 actool --output-format human-readable-text --notices --warnings --platform "${PLATFORM_NAME}" --minimum-deployment-target "${IPHONEOS_DEPLOYMENT_TARGET}" ${TARGET_DEVICE_ARGS} --compress-pngs --compile "${BUILT_PRODUCTS_DIR}/${UNLOCALIZED_RESOURCES_FOLDER_PATH}"
fi
|
#!/bin/bash
# Copyright (c) 2019-2020 P3TERX <https://p3terx.com>
#
# 修改openwrt登陆地址,把下面的192.168.2.2修改成你想要的就可以了
sed -i 's/192.168.1.1/192.168.3.1/g' package/base-files/files/bin/config_generate
# 修改主机名字,把OpenWrt-123修改你喜欢的就行(不能纯数字或者使用中文)
sed -i '/uci commit system/i\uci set system.@system[0].hostname='Newifi'' package/lean/default-settings/files/zzz-default-settings
# 版本号里显示一个自己的名字(281677160 build $(TZ=UTC-8 date "+%Y.%m.%d") @ 这些都是后增加的)
sed -i "s/OpenWrt /10vice build $(TZ=UTC-8 date "+%Y.%m.%d") @ OpenWrt /g" package/lean/default-settings/files/zzz-default-settings
# 修改 argon 为默认主题,可根据你喜欢的修改成其他的(不选择那些会自动改变为默认主题的主题才有效果)
sed -i 's/luci-theme-bootstrap/luci-theme-argon/g' feeds/luci/collections/luci/Makefile
# 设置密码为空(安装固件时无需密码登陆,然后自己修改想要的密码)
sed -i 's@.*CYXluq4wUazHjmCDBCqXF*@#&@g' package/lean/default-settings/files/zzz-default-settings
# 修改插件名字(修改名字后不知道会不会对插件功能有影响,自己多测试)
sed -i 's/"BaiduPCS Web"/"百度网盘"/g' package/lean/luci-app-baidupcs-web/luasrc/controller/baidupcs-web.lua
sed -i 's/cbi("qbittorrent"),_("qBittorrent")/cbi("qbittorrent"),_("BT下载")/g' package/lean/luci-app-qbittorrent/luasrc/controller/qbittorrent.lua
sed -i 's/"aMule设置"/"电驴下载"/g' package/lean/luci-app-amule/po/zh-cn/amule.po
sed -i 's/"网络存储"/"存储"/g' package/lean/luci-app-amule/po/zh-cn/amule.po
sed -i 's/"网络存储"/"存储"/g' package/lean/luci-app-vsftpd/po/zh-cn/vsftpd.po
sed -i 's/"Turbo ACC 网络加速"/"网络加速"/g' package/lean/luci-app-flowoffload/po/zh-cn/flowoffload.po
sed -i 's/"Turbo ACC 网络加速"/"网络加速"/g' package/lean/luci-app-sfe/po/zh-cn/sfe.po
sed -i 's/"实时流量监测"/"流量"/g' package/lean/luci-app-wrtbwmon/po/zh-cn/wrtbwmon.po
sed -i 's/"KMS 服务器"/"KMS激活"/g' package/lean/luci-app-vlmcsd/po/zh-cn/vlmcsd.zh-cn.po
sed -i 's/"TTYD 终端"/"命令窗"/g' package/lean/luci-app-ttyd/po/zh-cn/terminal.po
sed -i 's/"USB 打印服务器"/"打印服务"/g' package/lean/luci-app-usb-printer/po/zh-cn/usb-printer.po
sed -i 's/"网络存储"/"存储"/g' package/lean/luci-app-usb-printer/po/zh-cn/usb-printer.po
sed -i 's/"Web 管理"/"Web"/g' package/lean/luci-app-webadmin/po/zh-cn/webadmin.po
sed -i 's/"管理权"/"改密码"/g' feeds/luci/modules/luci-base/po/zh-cn/base.po
sed -i 's/"带宽监控"/"监视"/g' feeds/luci/applications/luci-app-nlbwmon/po/zh-cn/nlbwmon.po
|
<reponame>luanlazz/barbecue-app-back
import { makeSaveParticipantValidation } from './save-participant-validation-factory'
import { makeLogControllerDecorator } from '@/main/factories/decorators'
import { makeDbLoadBarbecueById, makeDbSaveParticipant } from '@/main/factories/usecases'
import { SaveParticipantController } from '@/presentation/controllers'
import { Controller } from '@/presentation/protocols'
export const makeSaveParticipantController = (): Controller => {
const controller = new SaveParticipantController(makeSaveParticipantValidation(), makeDbLoadBarbecueById(), makeDbSaveParticipant())
return makeLogControllerDecorator(controller)
}
|
import { JSONRPCRequestPayload } from '@0xproject/types';
import { Callback, ErrorCallback } from '../types';
import { Subprovider } from './subprovider';
// HACK: We need this so that our tests don't use testrpc gas estimation which sometimes kills the node.
// Source: https://github.com/trufflesuite/ganache-cli/issues/417
// Source: https://github.com/trufflesuite/ganache-cli/issues/437
// Source: https://github.com/MetaMask/provider-engine/blob/master/subproviders/subprovider.js
/**
* This class implements the [web3-provider-engine](https://github.com/MetaMask/provider-engine) subprovider interface.
* It intercepts the `eth_estimateGas` JSON RPC call and always returns a constant gas amount when queried.
*/
export class FakeGasEstimateSubprovider extends Subprovider {
private _constantGasAmount: number;
/**
* Instantiates an instance of the FakeGasEstimateSubprovider
* @param constantGasAmount The constant gas amount you want returned
*/
constructor(constantGasAmount: number) {
super();
this._constantGasAmount = constantGasAmount;
}
/**
* This method conforms to the web3-provider-engine interface.
* It is called internally by the ProviderEngine when it is this subproviders
* turn to handle a JSON RPC request.
* @param payload JSON RPC payload
* @param next Callback to call if this subprovider decides not to handle the request
* @param end Callback to call if subprovider handled the request and wants to pass back the request.
*/
// tslint:disable-next-line:prefer-function-over-method async-suffix
public async handleRequest(payload: JSONRPCRequestPayload, next: Callback, end: ErrorCallback) {
switch (payload.method) {
case 'eth_estimateGas':
end(null, this._constantGasAmount);
return;
default:
next();
return;
}
}
}
|
#!/bin/bash
set -e
if [ -z "$1" ]; then
echo "Need a commit ID!"
exit 1
fi
if [ -z "$2" ]; then
echo "Need a kernel version!"
exit 1
fi
sed -i "s/BR2_LINUX_KERNEL_CUSTOM_VERSION_VALUE=\".*\"/BR2_LINUX_KERNEL_CUSTOM_VERSION_VALUE=\"$1\"/g" buildroot-external/configs/odroid_*
sed -i "s/| Odroid\(.*\) | .* |/| Odroid\1 | $2 |/g" Documentation/kernel.md
git commit -m "Odroid: Update kernel $2 - $1" buildroot-external/configs/* Documentation/kernel.md
|
#include "lic.hpp"
std::array<void*, lic::LIC_MAX_COMPONENT> lic::components;
std::array<std::vector<std::size_t>, lic::LIC_MAX_COMPONENT> lic::destroyed_components;
std::array<std::vector<std::vector<std::function<void()>>>, lic::LIC_MAX_COMPONENT> lic::on_component_removals;
std::vector<lic::EntityInfo> lic::entities;
std::vector<lic::EntityID> lic::destroyed_entities;
lic::ComponentID lic::next_component_id;
lic::EntityID lic::next_entity_id;
void lic::Entity::RemoveComponent(ComponentID cid) const
{
return lic::RemoveComponent(this->id, cid);
}
bool lic::Entity::HasComponent(ComponentID cid) const
{
return lic::HasComponent(this->id, cid);
}
void lic::Entity::OnComponentRemoval(ComponentID cid, const std::function<void()>& callback) const
{
lic::OnComponentRemoval(id, cid, callback);
}
void lic::Entity::RaiseComponentRemoval(ComponentID cid) const
{
lic::RaiseComponentRemoval(id, cid);
}
lic::Entity lic::AddEntity()
{
if (destroyed_entities.empty())
{
EntityID eid = next_entity_id++;
entities.emplace_back(eid, false);
return Entity(entities.back().id);
}
else
{
EntityID eid = destroyed_entities.back();
entities.at(eid) = EntityInfo(eid, false);
destroyed_entities.pop_back();
return Entity(entities.at(eid).id);
}
}
void lic::DestroyEntity(EntityID eid)
{
if (!HasEntity(eid))
return;
for (ComponentID cid = 0u; cid < LIC_MAX_COMPONENT; ++cid)
{
if (HasComponent(eid, cid))
RemoveComponent(eid, cid);
}
entities.at(eid).component_field.reset();
destroyed_entities.push_back(eid);
}
bool lic::HasEntity(EntityID eid)
{
return eid < next_entity_id && std::find(destroyed_entities.begin(), destroyed_entities.end(), eid) == destroyed_entities.end();
}
lic::Entity lic::GetEntity(EntityID eid)
{
return Entity(entities.at(eid).id);
}
void lic::RemoveComponent(EntityID eid, ComponentID cid)
{
if (!HasComponent(eid, cid))
{
return;
}
RaiseComponentRemoval(eid, cid);
destroyed_components.at(cid).push_back(entities.at(eid).component_indices.at(cid));
entities.at(eid).component_field.set(cid, false);
}
bool lic::HasComponent(EntityID eid, ComponentID cid)
{
return entities.at(eid).component_field.test(cid);
}
void lic::OnComponentRemoval(EntityID eid, ComponentID cid, const std::function<void()>& callback)
{
if (!HasComponent(eid, cid))
{
return;
}
auto cind = entities.at(eid).component_indices.at(cid);
on_component_removals.at(cid).at(cind).push_back(callback);
}
void lic::RaiseComponentRemoval(EntityID eid, ComponentID cid)
{
auto cind = entities.at(eid).component_indices.at(cid);
for (auto callback : on_component_removals.at(cid).at(cind))
{
callback();
}
on_component_removals.at(cid).at(cind).clear();
}
lic::Entity lic::EntityContainer::Iterator::operator*() const
{
return Entity(entities.at(VecIterator::operator*()).id);
}
lic::EntityContainer::Iterator lic::EntityContainer::begin() const
{
return Iterator(std::vector<EntityID>::cbegin());
}
lic::EntityContainer::Iterator lic::EntityContainer::end() const
{
return Iterator(std::vector<EntityID>::cend());
}
lic::EntityContainer::Iterator lic::EntityContainer::cbegin() const
{
return Iterator(std::vector<EntityID>::cbegin());
}
lic::EntityContainer::Iterator lic::EntityContainer::cend() const
{
return Iterator(std::vector<EntityID>::cend());
}
|
<reponame>marcpursals/i18n_yaml_editor
# frozen_string_literal: true
require 'test_helper'
require 'i18n_yaml_editor/app'
class TestApp < Minitest::Test
def test_new_no_path_given
assert_raises(ArgumentError) { App.new }
end
def test_new_given_path
app = App.new('my_path')
assert_match(/my_path\z/, app.instance_variable_get(:@path))
end
def test_new_default_port
app = App.new('')
assert_equal 5050, app.instance_variable_get(:@port)
end
def test_new_given_port
app = App.new('', 3333)
assert_equal 3333, app.instance_variable_get(:@port)
end
def test_new_store
app = App.new('')
refute_nil app.instance_variable_get(:@store)
end
def test_new_store_accessor
app = App.new('')
assert_equal app.store, app.instance_variable_get(:@store)
end
def test_new_exposure
app = App.new('')
assert_equal(I18nYamlEditor.app, app)
end
end
|
<filename>src/pages/journal/living-abroad.tsx
import React, { useContext } from "react"
import SEO from "../../components/layout/seo"
import { ArticlesContainer } from "../../components/layout/layout"
import { getArticles } from "../../components/core/links/links.utils"
import { ApplicationContext } from "../../components/application"
import { Divider } from "../../components/core/divider"
import { PageQuote } from "../../components/core/quote"
import { HomeSection, HomeSubSection, MainTitleSection, SectionContent } from "../../components/core/section"
import { PrimaryBlogLayoutWithDrawer } from "../../components/layout/main-layout"
import { useCustomTranslation } from "../../i18n-hook"
import i18n from "i18next"
import indexFr from "../../locales/fr/journal/living-abroad.json"
import indexEn from "../../locales/en/journal/living-abroad.json"
import { PageProps } from "gatsby"
const namespace = "journal/living-abroad"
const id = "living-abroad"
i18n.addResourceBundle("fr", namespace, indexFr)
i18n.addResourceBundle("en", namespace, indexEn)
const IndexPage: React.FunctionComponent<PageProps> = ({ location }) => {
const { development } = useContext(ApplicationContext)
const articles = getArticles({ kind: "other", tags: ["living-abroad"], development })
const { t } = useCustomTranslation([namespace, "common"])
return (
<>
<SEO
title={t("common:link.journal.living-abroad")}
fullTitle={t("full-title")}
location={location}
socialNetworkDescription={t("meta-description")}
googleDescription={t("meta-description")}
/>
<PrimaryBlogLayoutWithDrawer page={id} location={location}>
<MainTitleSection>{t("common:link.journal.living-abroad")}</MainTitleSection>
<Divider />
<SectionContent>
<PageQuote>{t("quote.part1")}</PageQuote>
<PageQuote position="none">{t("quote.part2")}</PageQuote>
<PageQuote position="none">{t("quote.part3")}</PageQuote>
</SectionContent>
<Divider />
<HomeSection>{t("inform.title")}</HomeSection>
<HomeSubSection>{t("inform.subtitle")}</HomeSubSection>
<ArticlesContainer>
{articles.map(({ card: Card }, index) =>
Card ? <Card key={index} fluidObject={{ aspectRatio: 4 / 3 }} /> : null
)}
</ArticlesContainer>
</PrimaryBlogLayoutWithDrawer>
</>
)
}
export default IndexPage
|
package repository
import (
"testing"
"github.com/stretchr/testify/assert"
)
func testRepository(repo Repository) error {
return nil
}
func TestMock(t *testing.T) {
mock := NewMock()
assert := assert.New(t)
assert.NotNil(mock)
assert.Nil(testRepository(mock))
}
|
# test_module.py
import pytest
from your_module import create_linear_param_dae, LinearParameterDAE
def test_create_linear_param_dae():
# Define input parameters
param_vars = ['param1', 'param2']
e_lin_param_dae = 0.5
a_lin_param_dae = 1.5
f_lin_param_dae = 2.5
# Call the function under test
result_dae = create_linear_param_dae(param_vars, e_lin_param_dae, a_lin_param_dae, f_lin_param_dae)
# Verify the result
assert isinstance(result_dae, LinearParameterDAE)
assert result_dae.param_vars == param_vars
assert result_dae.e_lin_param_dae == e_lin_param_dae
assert result_dae.a_lin_param_dae == a_lin_param_dae
assert result_dae.f_lin_param_dae == f_lin_param_dae
assert result_dae.constant_value == 2
|
func test01() {
var instance = S(a: 1, b: 2, 3) // Initializing the struct using the first initializer
var inoutParam = 0 // Creating an inout parameter
instance.foo1(4, 5, 6, 7, 8, 9, &inoutParam) // Calling the foo1 method with appropriate arguments
}
|
<gh_stars>0
/*
* Copyright (C) 2009-2016 Typesafe Inc. <http://www.typesafe.com>
*/
package scalaguide.tests.scalatest.oneserverpertest
import play.api.test._
import org.scalatest._
import org.scalatestplus.play._
import play.api.test.Helpers._
import play.api.libs.ws._
import play.api.mvc._
import Results._
// #scalafunctionaltest-oneserverpertest
class ExampleSpec extends PlaySpec with OneServerPerTest {
// Override newAppForTest if you need a FakeApplication with other than
// default parameters.
override def newAppForTest(testData: TestData): FakeApplication =
new FakeApplication(
additionalConfiguration = Map("ehcacheplugin" -> "disabled"),
withRoutes = {
case ("GET", "/") => Action { Ok("ok") }
}
)
"The OneServerPerTest trait" must {
"test server logic" in {
val myPublicAddress = s"localhost:$port"
val testPaymentGatewayURL = s"http://$myPublicAddress"
// The test payment gateway requires a callback to this server before it returns a result...
val callbackURL = s"http://$myPublicAddress/callback"
// await is from play.api.test.FutureAwaits
val response = await(WS.url(testPaymentGatewayURL).withQueryString("callbackURL" -> callbackURL).get())
response.status mustBe (OK)
}
}
}
// #scalafunctionaltest-oneserverpertest
|
<reponame>GuusSeldenthuis/core
// Copyright (c) 2014 The Bitcoin developers
// Copyright (c) 2017-2018 The PIVX developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include "networkstyle.h"
#include "guiconstants.h"
#include <QApplication>
#include <utility>
static const struct {
const char* networkId;
const char* appName;
const char* appIcon;
const char* titleAddText;
const char* splashImage;
} network_styles[] = {
{"main", QAPP_APP_NAME_DEFAULT, ":/icons/bitcoin", "", ":/images/splash"},
{"test", QAPP_APP_NAME_TESTNET, ":/icons/bitcoin_testnet", QT_TRANSLATE_NOOP("SplashScreen", "[testnet]"), ":/images/splash_testnet"},
{"regtest", QAPP_APP_NAME_TESTNET, ":/icons/bitcoin_regtest", "[regtest]", ":/images/splash_regtest"}};
static const unsigned network_styles_count = sizeof(network_styles) / sizeof(*network_styles);
// titleAddText needs to be const char* for tr()
NetworkStyle::NetworkStyle(QString appName, const QString& appIcon, const char* titleAddText, const QString& splashImage) : appName(std::move(appName)),
appIcon(appIcon),
titleAddText(qApp->translate("SplashScreen", titleAddText)),
splashImage(splashImage)
{
}
const NetworkStyle* NetworkStyle::instantiate(const QString& networkId)
{
for (const auto & network_style : network_styles) {
if (networkId == network_style.networkId) {
return new NetworkStyle(
network_style.appName,
network_style.appIcon,
network_style.titleAddText,
network_style.splashImage);
}
}
return nullptr;
}
|
#!/bin/bash
# Creates tgz file from chroot directory
# Example: create_tgz '32bit-debian-stretch-min-BLAH.tgz' '/var/chroot/stretch/min'
create_tgz ()
{
TGZ_FILE=$1
DIR_CHROOT=$2
echo '----------------------------------'
echo "tar cfz $TGZ_FILE -C $DIR_CHROOT ."
tar cfz $TGZ_FILE -C $DIR_CHROOT .
echo '----------------------'
echo 'Recording md5sum value'
MD5SUM1=$(md5sum $TGZ_FILE)
echo $MD5SUM1 > "$TGZ_FILE.md5sum"
}
# Imports image from *.tgz file
# Example: import_local_image '32bit-debian-stretch-min.tgz' 'rubyonracetracks/32bit-debian-stretch-min'
import_local_image ()
{
echo '---------------------------------------'
echo "Removing old containers ($DOCKER_IMAGE)"
for i in $(docker ps -a | grep $DOCKER_IMAGE | awk '{print $1}')
do
docker kill $i; wait;
docker rm $i; wait;
done;
echo '---------------------------------'
echo "docker ps -a | grep $DOCKER_IMAGE"
docker ps -a | grep $DOCKER_IMAGE
echo '--------------------------------'
echo "Removing images of $DOCKER_IMAGE"
for i in $(docker images -a | grep $DOCKER_IMAGE | awk '{print $3}')
do
docker kill $i; wait;
docker rmi $i; wait;
done;
echo '-------------------------------------'
echo "docker images -a | grep $DOCKER_IMAGE"
docker images -a | grep $DOCKER_IMAGE
TGZ_FILE=$1
DOCKER_IMAGE=$2
echo '---------------------------------------------'
echo "cat $TGZ_FILE | docker import - $DOCKER_IMAGE"
cat $TGZ_FILE | docker import - $DOCKER_IMAGE
}
|
rsync -avz -e ssh --exclude=.gitignore accessibility@accessibility.kr:public_html/nia/logs/ ./www/logs/
|
<filename>src/dns_poller.c<gh_stars>100-1000
#include <math.h> // NOLINT(llvmlibc-restrict-system-libc-headers)
#include <netdb.h> // NOLINT(llvmlibc-restrict-system-libc-headers)
#include <string.h> // NOLINT(llvmlibc-restrict-system-libc-headers)
#include "dns_poller.h"
#include "logging.h"
static void sock_cb(struct ev_loop __attribute__((unused)) *loop,
ev_io *w, int revents) {
dns_poller_t *d = (dns_poller_t *)w->data;
ares_process_fd(d->ares, (revents & EV_READ) ? w->fd : ARES_SOCKET_BAD,
(revents & EV_WRITE) ? w->fd : ARES_SOCKET_BAD);
}
static struct ev_io * get_io_event(dns_poller_t *d, int sock) {
for (int i = 0; i < d->io_events_count; i++) {
if (d->io_events[i].fd == sock) {
return &d->io_events[i];
}
}
return NULL;
}
static void sock_state_cb(void *data, int fd, int read, int write) {
dns_poller_t *d = (dns_poller_t *)data;
// stop and release used event
struct ev_io *io_event_ptr = get_io_event(d, fd);
if (io_event_ptr) {
ev_io_stop(d->loop, io_event_ptr);
io_event_ptr->fd = 0;
DLOG("Released used io event: %p", io_event_ptr);
}
if (!read && !write) {
return;
}
// reserve and start new event on unused slot
io_event_ptr = get_io_event(d, 0);
if (!io_event_ptr) {
FLOG("c-ares needed more event, than nameservers count: %d", d->io_events_count);
}
DLOG("Reserved new io event: %p", io_event_ptr);
// NOLINTNEXTLINE(clang-analyzer-security.insecureAPI.DeprecatedOrUnsafeBufferHandling)
ev_io_init(io_event_ptr, sock_cb, fd,
(read ? EV_READ : 0) | (write ? EV_WRITE : 0));
ev_io_start(d->loop, io_event_ptr);
}
static char *get_addr_listing(char** addr_list, const int af) {
char *list = (char *)calloc(1, POLLER_ADDR_LIST_SIZE);
char *pos = list;
if (list == NULL) {
FLOG("Out of mem");
}
for (int i = 0; addr_list[i]; i++) {
const char *res = ares_inet_ntop(af, addr_list[i], pos,
list + POLLER_ADDR_LIST_SIZE - 1 - pos);
if (res != NULL) {
pos += strlen(pos);
*pos = ',';
pos++;
}
}
if (pos == list) {
free((void*)list);
list = NULL;
} else {
*(pos-1) = '\0';
}
return list;
}
static void ares_cb(void *arg, int status, int __attribute__((unused)) timeouts,
struct hostent *h) {
dns_poller_t *d = (dns_poller_t *)arg;
d->request_ongoing = 0;
ev_tstamp interval = 5; // retry by default after some time
if (status != ARES_SUCCESS) {
WLOG("DNS lookup failed: %s", ares_strerror(status));
} else if (!h || h->h_length < 1) {
WLOG("No hosts.");
} else {
interval = d->polling_interval;
d->cb(d->hostname, d->cb_data, get_addr_listing(h->h_addr_list, h->h_addrtype));
}
if (status != ARES_EDESTRUCTION) {
DLOG("DNS poll interval changed to: %.0lf", interval);
ev_timer_stop(d->loop, &d->timer);
ev_timer_set(&d->timer, interval, 0);
ev_timer_start(d->loop, &d->timer);
}
}
static ev_tstamp get_timeout(dns_poller_t *d)
{
static struct timeval max_tv = {.tv_sec = 5, .tv_usec = 0};
struct timeval tv;
struct timeval *tvp = ares_timeout(d->ares, &max_tv, &tv);
// NOLINTNEXTLINE(bugprone-narrowing-conversions,cppcoreguidelines-narrowing-conversions)
ev_tstamp after = tvp->tv_sec + tvp->tv_usec * 1e-6;
return after ? after : 0.1;
}
static void timer_cb(struct ev_loop __attribute__((unused)) *loop,
ev_timer *w, int __attribute__((unused)) revents) {
dns_poller_t *d = (dns_poller_t *)w->data;
if (d->request_ongoing) {
// process query timeouts
DLOG("Processing DNS queries");
ares_process(d->ares, NULL, NULL);
} else {
DLOG("Starting DNS query");
// Cancel any pending queries before making new ones. c-ares can't be depended on to
// execute ares_cb() even after the specified query timeout has been reached, e.g. if
// the packet was dropped without any response from the network. This also serves to
// free memory tied up by any "zombie" queries.
ares_cancel(d->ares);
d->request_ongoing = 1;
ares_gethostbyname(d->ares, d->hostname, d->family, ares_cb, d);
}
if (d->request_ongoing) { // need to re-check, it might change!
const ev_tstamp interval = get_timeout(d);
DLOG("DNS poll interval changed to: %.03f", interval);
ev_timer_stop(d->loop, &d->timer);
ev_timer_set(&d->timer, interval, 0);
ev_timer_start(d->loop, &d->timer);
}
}
void dns_poller_init(dns_poller_t *d, struct ev_loop *loop,
const char *bootstrap_dns,
int bootstrap_dns_polling_interval,
const char *hostname,
int family, dns_poller_cb cb, void *cb_data) {
int r = 0;
if ((r = ares_library_init(ARES_LIB_INIT_ALL)) != ARES_SUCCESS) {
FLOG("ares_library_init error: %s", ares_strerror(r));
}
struct ares_options options = {
.timeout = POLLER_QUERY_TIMEOUT_MS,
.tries = POLLER_QUERY_TRIES,
.sock_state_cb = sock_state_cb,
.sock_state_cb_data = d
};
int optmask = ARES_OPT_TIMEOUTMS | ARES_OPT_TRIES | ARES_OPT_SOCK_STATE_CB;
if ((r = ares_init_options(&d->ares, &options, optmask)) != ARES_SUCCESS) {
FLOG("ares_init_options error: %s", ares_strerror(r));
}
if((r = ares_set_servers_ports_csv(d->ares, bootstrap_dns)) != ARES_SUCCESS) {
FLOG("ares_set_servers_ports_csv error: %s", ares_strerror(r));
}
d->loop = loop;
d->hostname = hostname;
d->family = family;
d->cb = cb;
d->polling_interval = bootstrap_dns_polling_interval;
d->request_ongoing = 0;
d->cb_data = cb_data;
// NOLINTNEXTLINE(clang-analyzer-security.insecureAPI.DeprecatedOrUnsafeBufferHandling)
ev_timer_init(&d->timer, timer_cb, 0, 0);
d->timer.data = d;
ev_timer_start(d->loop, &d->timer);
int nameservers = 1;
for (int i = 0; bootstrap_dns[i]; i++) {
if (bootstrap_dns[i] == ',') {
nameservers++;
}
}
DLOG("Nameservers count: %d", nameservers);
d->io_events = (ev_io *)calloc(nameservers, sizeof(ev_io)); // zeroed!
if (!d->io_events) {
FLOG("Out of mem");
}
for (int i = 0; i < nameservers; i++) {
d->io_events[i].data = d;
}
d->io_events_count = nameservers;
}
void dns_poller_cleanup(dns_poller_t *d) {
ares_destroy(d->ares);
ev_timer_stop(d->loop, &d->timer);
ares_library_cleanup();
free(d->io_events);
}
|
<reponame>neuling/fso-livetest-chrome-extension
function(page, done) {
var t = page.getWindowPerformanceNavigation();
var p = page.getLocation().protocol;
var is_https = false;
if(p == "https:"){ is_https = true; }
if (t) {
var prot = t.nextHopProtocol
var is_h2 = false;
if(['h2', 'hq'].includes(prot)) { is_h2 = true; }
if(is_https == true && is_h2 == false)
{
return done(this.createResult('HTTP', "Network protocol: "+prot+" (but https protocol)", 'warning'));
}
return done(this.createResult('HTTP', "Network protocol: "+prot, 'info', null, 400));
}
}
|
<filename>src/components/Styled/Footer/index.js
import styled from 'styled-components';
export const Footer = styled.footer`
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
background: #090909;
color: #fff;
height: 300px;
font-size: 1.1rem;
letter-spacing: 1px;
.footer__more {
display: block;
margin-top: 5px;
font-size: 0.9rem;
text-align: center;
}
.footer__changelog a {
font-weight: normal;
color: rgba(255, 255, 255, 0.2);
font-size: 1rem;
}
a {
text-transform: none;
font-weight: bold;
color: #fff;
}
@media only screen and (max-width: 1200px) {
font-size: 1rem;
}
`;
export const FooterFinePrint = styled.div`
color: #fff;
text-align: center;
margin: 30px 0px;
font-size: 0.8rem;
p {
margin: 0.3rem 0;
padding: 0;
}
@media only screen and (max-width: 1200px) {
font-size: 0.7rem;
}
`;
|
#!/bin/sh -k
#
# Re-order arguments so that -L comes first
#
opts=""
lopts=""
for arg in $* ; do
case $arg in
-L*) lopts="$lopts $arg" ;;
*) opts="$opts $arg" ;;
esac
done
c89 $lopts $opts
|
<filename>vuu-ui/scripts/publish-local.js
(async function () {
try {
// const yargs = require('yargs');
const { exec } = require('./utils');
console.log('[PUBLISHING]');
const currentPath = process.cwd();
const PACKAGE_PATH = `${currentPath}/packages`;
await Promise.all([
exec(
`cd ${PACKAGE_PATH}/utils && npm publish --registry http://localhost:4873 --access public`
),
exec(
`cd ${PACKAGE_PATH}/react-utils && npm publish --registry http://localhost:4873 --access public`
),
exec(
`cd ${PACKAGE_PATH}/theme && npm publish --registry http://localhost:4873 --access public`
),
exec(
`cd ${PACKAGE_PATH}/data-remote && npm publish --registry http://localhost:4873 --access public`
),
exec(
`cd ${PACKAGE_PATH}/data-store && npm publish --registry http://localhost:4873 --access public`
),
exec(
`cd ${PACKAGE_PATH}/data-worker && npm publish --registry http://localhost:4873 --access public`
),
exec(
`cd ${PACKAGE_PATH}/ui-controls && npm publish --registry http://localhost:4873 --access public`
),
exec(
`cd ${PACKAGE_PATH}/datagrid-parsers && npm publish --registry http://localhost:4873 --access public`
),
exec(
`cd ${PACKAGE_PATH}/data-grid && npm publish --registry http://localhost:4873 --access public`
),
exec(
`cd ${PACKAGE_PATH}/layout && npm publish --registry http://localhost:4873 --access public`
),
exec(
`cd ${PACKAGE_PATH}/parsed-input && npm publish --registry http://localhost:4873 --access public`
),
exec(
`cd ${PACKAGE_PATH}/shell && npm publish --registry http://localhost:4873 --access public`
)
]);
} catch (error) {
console.error(error);
process.exit((error && error.code) || 1); // properly exit with error code (useful for CI or chaining)
}
})();
|
<reponame>briankaney/retired<filename>qvs_c++/2021-11-extract_change_map_json.pre_arg_overhaul.pre_no_hard_paths.cc
//######################################################################################
// extract_change_map_json.cc
// by <NAME>, 2018
//######################################################################################
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <cmath>
#include <iostream>
#include <zlib.h>
#include "../../c++_library/general/library_json_output.h"
#include "../../c++_library/general/library_time.epoch1960.h"
#include "../../c++_library/general/library_read_text_place_list.h"
#include "../../c++_library/binary_array/library_place_binary_array.h"
#define NUM_PAIRS 587
#define MAX_PATH_FILENAME_LEN 256
#define DEBUG 0
using namespace std;
int main(int argc, char *argv[])
{
char data_type[32];
int before_end_hour,before_end_day,before_end_month,before_end_year,before_num_hours;
int after_end_hour,after_end_day,after_end_month,after_end_year,after_num_hours;
int start_hour_block,end_hour_block;
float min_dbz,max_dbz,max_dbz_diff;
int min_bin_count;
//--------------------------------------------------------------------------------------
// If in debug mode, dump out all command line args.
//--------------------------------------------------------------------------------------
if(DEBUG==1) {
cout<<"Command Line: ";
for(int i=0;i<argc;++i) cout<<argv[i]<<" ";
cout<<"<br>"<<endl;
}
//--------------------------------------------------------------------------------------
// Usage message if run with no command line args
//--------------------------------------------------------------------------------------
if(argc<2) {
cout<<endl<<endl;
cout<<"Usage:"<<endl;
cout<<" ./extract_change_map_json data_type before_end_year before_end_month before_end_day before_end_hour before_num_hours after_end_year after_end_month after_end_day after_end_hour after_num_hours start_hour_block end_hour_block min_dbz max_dbz max_dbz_diff min_bin_count"<<endl<<endl;
cout<<"Example:"<<endl;
cout<<" ./extract_change_map_json Refl 2018 7 15 0 240 2018 7 5 0 240 0 0 10 70 60 0"<<endl;
cout<<" ./extract_change_map_json ZDR 2018 7 15 0 240 2018 7 5 0 240 0 0 10 70 60 0"<<endl<<endl;
return -1;
}
//--------------------------------------------------------------------------------------
// Read in command line args.
// No use of argc or argv beyond this block.
//--------------------------------------------------------------------------------------
strcpy(data_type,argv[1]);
sscanf(argv[2],"%d",&before_end_year);
sscanf(argv[3],"%d",&before_end_month);
sscanf(argv[4],"%d",&before_end_day);
sscanf(argv[5],"%d",&before_end_hour);
sscanf(argv[6],"%d",&before_num_hours);
sscanf(argv[7],"%d",&after_end_year);
sscanf(argv[8],"%d",&after_end_month);
sscanf(argv[9],"%d",&after_end_day);
sscanf(argv[10],"%d",&after_end_hour);
sscanf(argv[11],"%d",&after_num_hours);
sscanf(argv[12],"%d",&start_hour_block);
sscanf(argv[13],"%d",&end_hour_block);
sscanf(argv[14],"%f",&min_dbz);
sscanf(argv[15],"%f",&max_dbz);
sscanf(argv[16],"%f",&max_dbz_diff);
sscanf(argv[17],"%d",&min_bin_count);
/* changes to back propogate to rrct version.
* added memory clean up for dbz1, dbz2, and files. */
//--------------------------------------------------------------------------------------
// Read placelist file
//--------------------------------------------------------------------------------------
char radar_list[MAX_PATH_FILENAME_LEN];
strcpy(radar_list,"/web_data/qvs/ref_data/rrct/RRCT_Radar_List.txt");
PlaceList *pt;
pt = LoadPlaceListFromFile(radar_list,LON_LAT,0);
//--------------------------------------------------------------------------------------
// Set up array for json output fields that need to be calculated from stored data.
// Use of 'NUM_PAIRS' not ideal, weird mix of hard-coded values and values read from
// config list (pt->num_list).
//--------------------------------------------------------------------------------------
float *before_pair_diff,*after_pair_diff;
before_pair_diff = new float [NUM_PAIRS];
after_pair_diff = new float [NUM_PAIRS];
for(int i=0;i<NUM_PAIRS;++i) {
before_pair_diff[i] = -99;
after_pair_diff[i] = -99;
}
//--------------------------------------------------------------------------------------
if(before_num_hours<1 || after_num_hours<1) {
printf("{\"site_count\":0,\"pair_count\":0}");
return -1;
}
int before_start_hour,before_start_day,before_start_month,before_start_year;
AddHoursToTimeStamp(before_end_hour,before_end_day,before_end_month,before_end_year,
-1*before_num_hours,&before_start_hour,&before_start_day,&before_start_month,&before_start_year);
int num_files = NumberMonthsInYYYYMMSequence(before_start_month,before_start_year,before_end_month,before_end_year);
int file_year,file_month;
char **files;
files = new char* [num_files];
for(int i=0;i<num_files;++i) {
files[i] = new char [MAX_PATH_FILENAME_LEN];
AddMonthsToYYYYMM(before_start_month,before_start_year,i,&file_month,&file_year);
if(strcmp(data_type,"Refl")==0) sprintf(files[i],"/web_data/qvs_data/rrct/%4d/%02d/RRCT_Refl.%d%02d.gz",file_year,file_month,file_year,file_month);
if(strcmp(data_type,"ZDR")==0) sprintf(files[i],"/web_data/qvs_data/rrct/%4d/%02d/RRCT_ZDR.%d%02d.gz",file_year,file_month,file_year,file_month);
}
//--------------------------------------------------------------------------------------
int num_times = 12*(HoursSince1960(before_end_hour,before_end_day,before_end_month,before_end_year) -
HoursSince1960(before_start_hour,before_start_day,before_start_month,before_start_year));
float **dbz1,**dbz2;
dbz1 = new float* [NUM_PAIRS];
dbz2 = new float* [NUM_PAIRS];
for(int i=0;i<NUM_PAIRS;++i) {
dbz1[i] = new float [num_times];
dbz2[i] = new float [num_times];
for(int j=0;j<num_times;++j) {
dbz1[i][j] = -99;
dbz2[i][j] = -99;
}
}
//--------------------------------------------------------------------------------------
PlaceBinaryArray *dat;
int t=0;
for(int f=0;f<num_files;++f) {
if( (dat = CreatePlaceBinaryArrayFromFile(files[f]))==NULL ) {
printf("{\"site_count\":0,\"pair_count\":0}");
return -1;
}
int start_index = 0;
int end_index = dat->number_values[0];
if(f==0) start_index = (before_start_day-1)*288 + before_start_hour*12;
if(f==num_files-1) end_index = (before_end_day-1)*288 + before_end_hour*12;
int *var_offset;
var_offset = GetOffsetsToAllVariableBlocks(dat);
int read_hr_of_day;
float read_dbz1,read_dbz2;
for(int i=0;i<dat->number_list;++i) {
for(int j=start_index;j<end_index;++j) {
read_hr_of_day = (j/12)%24;
if(start_hour_block>end_hour_block) {
if(read_hr_of_day>=start_hour_block || read_hr_of_day<end_hour_block) continue;
}
if(end_hour_block>start_hour_block) {
if(read_hr_of_day>=start_hour_block && read_hr_of_day<end_hour_block) continue;
}
read_dbz1 = ((float)(dat->data[var_offset[1] + dat->number_values[1]*i + j]))/dat->variable_scales[1];
read_dbz2 = ((float)(dat->data[var_offset[2] + dat->number_values[2]*i + j]))/dat->variable_scales[2];
if(strcmp(data_type,"Refl")==0 && (read_dbz1<min_dbz || read_dbz2<min_dbz || read_dbz1>max_dbz || read_dbz2>max_dbz)) continue;
if(strcmp(data_type,"Refl")==0 && abs(read_dbz1-read_dbz2) > max_dbz_diff) continue;
if(dat->data[var_offset[3] + dat->number_values[3]*i + j] < min_bin_count) continue;
dbz1[i][t+j-start_index] = read_dbz1;
dbz2[i][t+j-start_index] = read_dbz2;
}
}
t = t + end_index - start_index;
DestroyPlaceBinaryArray(dat);
}
int count;
float sum;
for(int i=0;i<NUM_PAIRS;++i) {
count = 0;
sum = 0.0;
for(int j=0;j<num_times;++j) {
if(dbz1[i][j]<-90 || dbz2[i][j]<-90) continue;
sum = sum + dbz1[i][j] - dbz2[i][j];
++count;
}
if(count>0) before_pair_diff[i] = sum/(float)(count);
}
//--------------------------------------------------------------------------------------
for(int i=0;i<num_files;++i) delete [] files[i];
delete [] files;
for(int i=0;i<NUM_PAIRS;++i) {
delete [] dbz1[i];
delete [] dbz2[i];
}
delete [] dbz1;
delete [] dbz2;
//--------------------------------------------------------------------------------------
//--------------------------------------------------------------------------------------
int after_start_hour,after_start_day,after_start_month,after_start_year;
AddHoursToTimeStamp(after_end_hour,after_end_day,after_end_month,after_end_year,
-1*after_num_hours,&after_start_hour,&after_start_day,&after_start_month,&after_start_year);
num_files = NumberMonthsInYYYYMMSequence(after_start_month,after_start_year,after_end_month,after_end_year);
files = new char* [num_files];
for(int i=0;i<num_files;++i) {
files[i] = new char [MAX_PATH_FILENAME_LEN];
AddMonthsToYYYYMM(after_start_month,after_start_year,i,&file_month,&file_year);
if(strcmp(data_type,"Refl")==0) sprintf(files[i],"/web_data/qvs_data/rrct/%4d/%02d/RRCT_Refl.%d%02d.gz",file_year,file_month,file_year,file_month);
if(strcmp(data_type,"ZDR")==0) sprintf(files[i],"/web_data/qvs_data/rrct/%4d/%02d/RRCT_ZDR.%d%02d.gz",file_year,file_month,file_year,file_month);
}
//--------------------------------------------------------------------------------------
num_times = 12*(HoursSince1960(after_end_hour,after_end_day,after_end_month,after_end_year) -
HoursSince1960(after_start_hour,after_start_day,after_start_month,after_start_year));
dbz1 = new float* [NUM_PAIRS];
dbz2 = new float* [NUM_PAIRS];
for(int i=0;i<NUM_PAIRS;++i) {
dbz1[i] = new float [num_times];
dbz2[i] = new float [num_times];
for(int j=0;j<num_times;++j) {
dbz1[i][j] = -99;
dbz2[i][j] = -99;
}
}
//--------------------------------------------------------------------------------------
// PlaceBinaryArray *dat;
t=0;
for(int f=0;f<num_files;++f) {
if( (dat = CreatePlaceBinaryArrayFromFile(files[f]))==NULL ) {
printf("{\"site_count\":0,\"pair_count\":0}");
return -1;
}
int start_index = 0;
int end_index = dat->number_values[0];
if(f==0) start_index = (after_start_day-1)*288 + after_start_hour*12;
if(f==num_files-1) end_index = (after_end_day-1)*288 + after_end_hour*12;
int *var_offset;
var_offset = GetOffsetsToAllVariableBlocks(dat);
int read_hr_of_day;
float read_dbz1,read_dbz2;
for(int i=0;i<dat->number_list;++i) {
for(int j=start_index;j<end_index;++j) {
read_hr_of_day = (j/12)%24;
if(start_hour_block>end_hour_block) {
if(read_hr_of_day>=start_hour_block || read_hr_of_day<end_hour_block) continue;
}
if(end_hour_block>start_hour_block) {
if(read_hr_of_day>=start_hour_block && read_hr_of_day<end_hour_block) continue;
}
read_dbz1 = ((float)(dat->data[var_offset[1] + dat->number_values[1]*i + j]))/dat->variable_scales[1];
read_dbz2 = ((float)(dat->data[var_offset[2] + dat->number_values[2]*i + j]))/dat->variable_scales[2];
if(strcmp(data_type,"Refl")==0 && (read_dbz1<min_dbz || read_dbz2<min_dbz || read_dbz1>max_dbz || read_dbz2>max_dbz)) continue;
if(strcmp(data_type,"Refl")==0 && abs(read_dbz1-read_dbz2) > max_dbz_diff) continue;
if(dat->data[var_offset[3] + dat->number_values[3]*i + j] < min_bin_count) continue;
dbz1[i][t+j-start_index] = read_dbz1;
dbz2[i][t+j-start_index] = read_dbz2;
}
}
t = t + end_index - start_index;
DestroyPlaceBinaryArray(dat);
}
for(int i=0;i<NUM_PAIRS;++i) {
count = 0;
sum = 0.0;
for(int j=0;j<num_times;++j) {
if(dbz1[i][j]<-90 || dbz2[i][j]<-90) continue;
sum = sum + dbz1[i][j] - dbz2[i][j];
++count;
}
if(count>0) after_pair_diff[i] = sum/(float)(count);
}
//--------------------------------------------------------------------------------------
// Print out outputs to json
//--------------------------------------------------------------------------------------
printf("{");
WriteJSONBlock_1D_FloatArray("before_pair_diff",NUM_PAIRS,before_pair_diff,1);
printf(",");
WriteJSONBlock_1D_FloatArray("after_pair_diff",NUM_PAIRS,after_pair_diff,1);
printf("}");
}
|
import winston, { format } from 'winston';
const {combine} = format;
const logger = winston.createLogger({
format: combine(
winston.format.colorize(),
winston.format.timestamp(),
winston.format.align(),
winston.format.printf((info) => {
const {timestamp, level, message, ...args} = info;
const ts = timestamp.slice(0, 19).replace('T', ' ');
return `${ts} [${level}]: ${message} ${Object.keys(args).length ? JSON.stringify(args, undefined, 2) : ''}`;
}),
),
transports: [
new (winston.transports.Console)({level: process.env.NODE_ENV === 'production' ? 'error' : 'debug'})
]
});
export default logger;
|
package com.example.beans;
import java.util.ArrayList;
import java.util.List;
/*
* 封装一个对象所有的PropertyValue,相对于对象的成员列表
*
*/
public class PropertyValues {
private final List<PropertyValue> propertyValueList=new ArrayList<PropertyValue>();
public PropertyValues() {}
public void addPropertyValue(PropertyValue pv) {
propertyValueList.add(pv);
}
public List<PropertyValue> getPropertyValueList(){
return propertyValueList;
}
}
|
fn main() {
// Define build options
println!("cargo:rustc-cfg=BUILD_GNUABI_LIBS=\"FALSE\"");
println!("cargo:rustc-cfg=CMAKE_INSTALL_LIBDIR=\"lib\"");
// Set build profile
println!("cargo:profile=release");
// Trigger the build process
// (Assuming the build process is triggered by cargo build command)
// Emit signal for rerun if "sleef" library is changed
println!("cargo:rerun-if-changed=sleef");
}
|
package com.cyosp.mpa.api.rest.homebank.v1dot2.response;
import lombok.Getter;
import lombok.Setter;
import lombok.ToString;
import java.math.BigDecimal;
/**
* Created by CYOSP on 2017-07-14.
*/
@Getter
@Setter
@ToString
public class AccountResponse extends RootResponse {
private OptionsResponse options;
private Integer pos;
private Integer type;
private CurrencyResponse currency;
private String name;
private BigDecimal initial;
private BigDecimal minimum;
private Long cheque1;
private Long cheque2;
private String balance;
}
|
import * as Yup from 'yup';
const AchievementSchema = Yup.object().shape({
name: Yup.string().required('Digite o nome da conquista.'),
description: Yup.string().required('Explique como ganhar a conquista.'),
title: Yup.string(),
image: Yup.mixed(),
});
export default AchievementSchema;
|
package cfg.source;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import org.apache.poi.EncryptedDocumentException;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import code.file.FileUtils;
public class WorkbookUtil {
private static final String EXTENSION_XLS = "xls";
private static final String EXTENSION_XLSX = "xlsx";
/**
* 取得Workbook对象(xls,xlsx)
*
* @param filePath
* 文件路径
* @return 一个Excel文件对应的数据对象 (Workbook)
*/
public static Workbook getWorkbook(String filePath) {
if (FileUtils.isExists(filePath) && !FileUtils.isFolder(filePath)) {
return loadWorkbook(filePath);
} else {
return null;
}
}
/**
* 取得Workbook对象(xls,xlsx)
*
* @param file
* 文件
* @return 一个Excel文件对应的数据对象 (Workbook)
*/
public static Workbook getWorkbook(File file) {
if (file.isFile()) {
return loadWorkbook(file.getAbsolutePath());
} else {
return null;
}
}
/**
* 读取一行数据
*
* @param sheet
* Excel中的一个Sheet表
* @param rowNum
* 行索引
* @param len
* 长度
* @return 一行数据的文本数组
*/
public static String[] getContentArray(Sheet sheet, int rowNum, int len) {
Row row = sheet.getRow(rowNum);
if (null == row) {
return null;
}
String[] contentArray = new String[len];
int rowLen = row.getLastCellNum();
// System.out.println(rowNum + ": " + rowLen + ": " + len);
Cell cell;
for (int index = 0; index < len; index++) {
if (index < rowLen) {
cell = row.getCell(index);
// System.out.println(index + "\t" + (null != cell));
// System.out.println("\t\t" + CellUtil.toStringValue(cell));
contentArray[index] = CellUtil.toStringValue(cell);
} else {
contentArray[index] = "";
}
}
// System.out.println("WorkbookUtil.getContentArray(" + rowNum + "):" +
// Arrays.toString(contentArray));
return contentArray;
}
/**
* 读取一个数据
*
* @param sheet
* Excel中的一个Sheet表
* @param rowNum
* 行索引
* @param colNum
* 列索引
* @return 一个数据的文本数组
*/
public static String getContent(Sheet sheet, int rowNum, int colNum) {
Row row = sheet.getRow(rowNum);
if (null == row) {
return null;
}
return CellUtil.toStringValue(row.getCell(colNum));
}
/**
* 取得Workbook对象(xls和xlsx对象不同,不过都是Workbook的实现类) <br>
* xls:HSSFWorkbook<br>
* xlsx:XSSFWorkbook<br>
*
* @param filePath
* 文件路径
* @return 一个Excel文件对应的数据对象 (Workbook)
*/
private static Workbook loadWorkbook(String filePath) {
Workbook workbook = null;
InputStream is;
try {
is = new FileInputStream(filePath);
if (filePath.endsWith(EXTENSION_XLS)) {
workbook = new HSSFWorkbook(is);
} else if (filePath.endsWith(EXTENSION_XLSX)) {
workbook = new XSSFWorkbook(is);
}
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (EncryptedDocumentException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return workbook;
}
}
|
import argparse
import json
import matplotlib.pyplot as plt
# Define the command-line arguments
parser = argparse.ArgumentParser()
parser.add_argument('-in', dest="INPUT_FILE", default="data/still_i_rise_sound.json", help="Path to input sound analysis json file")
parser.add_argument('-key', dest="KEY", default="intensity", help="Key to output, e.g. intensity, frequency, duration")
# Parse the command-line arguments
args = parser.parse_args()
INPUT_FILE = args.INPUT_FILE
KEY = args.KEY
# Read the JSON file and extract the data for the specified key
with open(INPUT_FILE, 'r') as file:
sound_data = json.load(file)
data = sound_data[KEY]
# Generate the plot based on the extracted data
plt.plot(data)
plt.title(f"Sound Analysis - {KEY}")
plt.xlabel("Time")
plt.ylabel(KEY.capitalize())
plt.show()
|
<filename>patientdashboard/src/app/vitals/vitals.component.ts
import { Component, OnDestroy, OnInit } from '@angular/core';
import { ActivatedRoute } from '@angular/router';
import { VitalsService } from '../services/vitals.service';
@Component({
selector: 'app-vitals',
templateUrl: './vitals.component.html',
styleUrls: ['./vitals.component.css']
})
export class VitalsComponent implements OnInit {
vitals: any;
ngOnInit(): void {
this.activeRoute.parent.params.subscribe(params => {
if (params.patient_uuid) {
console.log('Fetch Vitals for patient', params.patient_uuid);
this.vitalsService.fetchVitals(params.patient_uuid).subscribe((res: any) => {
console.log('Vitals', res);
this.vitals = res.result;
});
}
});
}
constructor(private activeRoute: ActivatedRoute, private vitalsService: VitalsService) {
}
}
|
#!/bin/bash -f
#*********************************************************************************************************
# Vivado (TM) v2020.2 (64-bit)
#
# Filename : pixsimFifo.sh
# Simulator : Aldec Riviera-PRO Simulator
# Description : Simulation script for compiling, elaborating and verifying the project source files.
# The script will automatically create the design libraries sub-directories in the run
# directory, add the library logical mappings in the simulator setup file, create default
# 'do/prj' file, execute compilation, elaboration and simulation steps.
#
# Generated by Vivado on Sun May 15 16:50:34 +0200 2022
# SW Build 3064766 on Wed Nov 18 09:12:45 MST 2020
#
# Copyright 1986-2020 Xilinx, Inc. All Rights Reserved.
#
# usage: pixsimFifo.sh [-help]
# usage: pixsimFifo.sh [-lib_map_path]
# usage: pixsimFifo.sh [-noclean_files]
# usage: pixsimFifo.sh [-reset_run]
#
# Prerequisite:- To compile and run simulation, you must compile the Xilinx simulation libraries using the
# 'compile_simlib' TCL command. For more information about this command, run 'compile_simlib -help' in the
# Vivado Tcl Shell. Once the libraries have been compiled successfully, specify the -lib_map_path switch
# that points to these libraries and rerun export_simulation. For more information about this switch please
# type 'export_simulation -help' in the Tcl shell.
#
# You can also point to the simulation libraries by either replacing the <SPECIFY_COMPILED_LIB_PATH> in this
# script with the compiled library directory path or specify this path with the '-lib_map_path' switch when
# executing this script. Please type 'pixsimFifo.sh -help' for more information.
#
# Additional references - 'Xilinx Vivado Design Suite User Guide:Logic simulation (UG900)'
#
#*********************************************************************************************************
# Script info
echo -e "pixsimFifo.sh - Script generated by export_simulation (Vivado v2020.2 (64-bit)-id)\n"
# Main steps
run()
{
check_args $# $1
setup $1 $2
compile
simulate
}
# RUN_STEP: <compile>
compile()
{
# Compile design files
source compile.do 2>&1 | tee -a compile.log
}
# RUN_STEP: <simulate>
simulate()
{
runvsimsa -l simulate.log -do "do {simulate.do}"
}
# STEP: setup
setup()
{
case $1 in
"-lib_map_path" )
if [[ ($2 == "") ]]; then
echo -e "ERROR: Simulation library directory path not specified (type \"./pixsimFifo.sh -help\" for more information)\n"
exit 1
fi
map_setup_file $2
;;
"-reset_run" )
reset_run
echo -e "INFO: Simulation run files deleted.\n"
exit 0
;;
"-noclean_files" )
# do not remove previous data
;;
* )
map_setup_file $2
esac
# Add any setup/initialization commands here:-
# <user specific commands>
}
# Map library.cfg file
map_setup_file()
{
file="library.cfg"
lib_map_path="<SPECIFY_COMPILED_LIB_PATH>"
if [[ ($1 != "" && -e $1) ]]; then
lib_map_path="$1"
else
echo -e "ERROR: Compiled simulation library directory path not specified or does not exist (type "./top.sh -help" for more information)\n"
fi
if [[ ($lib_map_path != "") ]]; then
src_file="$lib_map_path/$file"
if [[ -e $src_file ]]; then
vmap -link $lib_map_path
fi
fi
}
# Delete generated data from the previous run
reset_run()
{
files_to_remove=(compile.log elaboration.log simulate.log dataset.asdb work riviera)
for (( i=0; i<${#files_to_remove[*]}; i++ )); do
file="${files_to_remove[i]}"
if [[ -e $file ]]; then
rm -rf $file
fi
done
}
# Check command line arguments
check_args()
{
if [[ ($1 == 1 ) && ($2 != "-lib_map_path" && $2 != "-noclean_files" && $2 != "-reset_run" && $2 != "-help" && $2 != "-h") ]]; then
echo -e "ERROR: Unknown option specified '$2' (type \"./pixsimFifo.sh -help\" for more information)\n"
exit 1
fi
if [[ ($2 == "-help" || $2 == "-h") ]]; then
usage
fi
}
# Script usage
usage()
{
msg="Usage: pixsimFifo.sh [-help]\n\
Usage: pixsimFifo.sh [-lib_map_path]\n\
Usage: pixsimFifo.sh [-reset_run]\n\
Usage: pixsimFifo.sh [-noclean_files]\n\n\
[-help] -- Print help information for this script\n\n\
[-lib_map_path <path>] -- Compiled simulation library directory path. The simulation library is compiled\n\
using the compile_simlib tcl command. Please see 'compile_simlib -help' for more information.\n\n\
[-reset_run] -- Recreate simulator setup files and library mappings for a clean run. The generated files\n\
from the previous run will be removed. If you don't want to remove the simulator generated files, use the\n\
-noclean_files switch.\n\n\
[-noclean_files] -- Reset previous run, but do not remove simulator generated files from the previous run.\n\n"
echo -e $msg
exit 1
}
# Launch script
run $1 $2
|
def normalize(nums):
normalized = []
min_value = min(nums)
max_value = max(nums)
for value in nums:
normalized.append((value - min_value) / (max_value - min_value))
return normalized
if __name__ == '__main__':
nums = [2, 3, 5, 8]
normalized_nums = normalize(nums)
print("Normalized array:", normalized_nums)
|
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.jena.graph;
import java.util.Iterator ;
import java.util.List ;
import java.util.Set ;
import org.apache.jena.graph.impl.GraphWithPerform ;
import org.apache.jena.util.IteratorCollection ;
import org.apache.jena.util.iterator.ExtendedIterator ;
import org.apache.jena.util.iterator.WrappedIterator ;
/**
An ad-hoc collection of useful code for graphs
*/
public class GraphUtil
{
/**
* Only static methods here - the class cannot be instantiated.
*/
private GraphUtil()
{}
/** Return an iterator over the unique subjects with predciate p and object o.
* p and o can be wildcards (Node.ANY)
* @param g Graph
* @param p Predicate - may be Node.ANY
* @param o Object - may be Node.ANY
* @return ExtendedIterator
*/
public static ExtendedIterator<Node> listSubjects(Graph g, Node p, Node o) {
// Restore a minimal QueryHandler?
ExtendedIterator<Triple> iter = g.find(Node.ANY, p, o) ;
Set<Node> nodes = iter.mapWith(t -> t.getSubject()).toSet() ;
return WrappedIterator.createNoRemove(nodes.iterator()) ;
}
/** Return an iterator over the unique predicate between s and o.
* s and o can be wildcards (Node.ANY)
* @param g Graph
* @param s Subject - may be Node.ANY
* @param o Object - may be Node.ANY
* @return ExtendedIterator
*/
public static ExtendedIterator<Node> listPredicates(Graph g, Node s, Node o) {
ExtendedIterator<Triple> iter = g.find(s,Node.ANY, o) ;
Set<Node> nodes = iter.mapWith(t -> t.getPredicate()).toSet() ;
return WrappedIterator.createNoRemove(nodes.iterator()) ;
}
/** Return an iterator over the unique objects with a given subject and object.
* s and p can be wildcards (Node.ANY)
* @param g Graph
* @param s Subject - may be Node.ANY
* @param p Predicate - may be Node.ANY
* @return ExtendedIterator
*/
public static ExtendedIterator<Node> listObjects(Graph g, Node s, Node p) {
ExtendedIterator<Triple> iter = g.find(s, p, Node.ANY) ;
Set<Node> nodes = iter.mapWith(t -> t.getObject()).toSet() ;
return WrappedIterator.createNoRemove(nodes.iterator()) ;
}
/** Does the graph use the node anywhere as a subject, predciate or object? */
public static boolean containsNode(Graph graph, Node node) {
return
graph.contains(node, Node.ANY, Node.ANY) ||
graph.contains(Node.ANY, Node.ANY, node) ||
graph.contains(Node.ANY, node, Node.ANY) ;
}
/* Control how events are dealt with in bulk */
private static final boolean OldStyle = true ;
/**
* Answer an iterator covering all the triples in the specified graph.
*
* @param g
* the graph from which to extract triples
* @return an iterator over all the graph's triples
*/
public static ExtendedIterator<Triple> findAll(Graph g) {
return g.find(Triple.ANY) ;
}
public static void add(Graph graph, Triple[] triples) {
if ( OldStyle && graph instanceof GraphWithPerform )
{
GraphWithPerform g = (GraphWithPerform)graph ;
for (Triple t : triples )
g.performAdd(t) ;
graph.getEventManager().notifyAddArray(graph, triples) ;
}
else
{
for (Triple t : triples )
graph.add(t) ;
}
}
public static void add(Graph graph, List<Triple> triples) {
if ( OldStyle && graph instanceof GraphWithPerform )
{
GraphWithPerform g = (GraphWithPerform)graph ;
for (Triple t : triples)
g.performAdd(t) ;
graph.getEventManager().notifyAddList(graph, triples) ;
} else
{
for (Triple t : triples)
graph.add(t) ;
}
}
public static void add(Graph graph, Iterator<Triple> it) {
// Materialize to avoid ConcurrentModificationException.
List<Triple> s = IteratorCollection.iteratorToList(it) ;
if ( OldStyle && graph instanceof GraphWithPerform )
{
GraphWithPerform g = (GraphWithPerform)graph ;
for (Triple t : s)
g.performAdd(t) ;
graph.getEventManager().notifyAddIterator(graph, s) ;
}
else
{
for (Triple t : s)
graph.add(t) ;
}
}
/** Add triples into the destination (arg 1) from the source (arg 2)*/
public static void addInto(Graph dstGraph, Graph srcGraph ) {
dstGraph.getPrefixMapping().setNsPrefixes(srcGraph.getPrefixMapping()) ;
addIteratorWorker(dstGraph, GraphUtil.findAll( srcGraph ));
dstGraph.getEventManager().notifyAddGraph( dstGraph, srcGraph );
}
private static void addIteratorWorker( Graph graph, Iterator<Triple> it ) {
List<Triple> s = IteratorCollection.iteratorToList( it );
if ( OldStyle && graph instanceof GraphWithPerform )
{
GraphWithPerform g = (GraphWithPerform)graph ;
for (Triple t : s )
g.performAdd(t) ;
}
else
{
for (Triple t : s )
graph.add(t) ;
}
}
public static void delete(Graph graph, Triple[] triples) {
if ( OldStyle && graph instanceof GraphWithPerform ) {
GraphWithPerform g = (GraphWithPerform)graph ;
for ( Triple t : triples )
g.performDelete(t) ;
graph.getEventManager().notifyDeleteArray(graph, triples) ;
} else {
for ( Triple t : triples )
graph.delete(t) ;
}
}
public static void delete(Graph graph, List<Triple> triples)
{
if ( OldStyle && graph instanceof GraphWithPerform ) {
GraphWithPerform g = (GraphWithPerform)graph ;
for ( Triple t : triples )
g.performDelete(t) ;
graph.getEventManager().notifyDeleteList(graph, triples) ;
} else {
for ( Triple t : triples )
graph.delete(t) ;
}
}
public static void delete(Graph graph, Iterator<Triple> it)
{
// Materialize to avoid ConcurrentModificationException.
List<Triple> s = IteratorCollection.iteratorToList(it) ;
if ( OldStyle && graph instanceof GraphWithPerform ) {
GraphWithPerform g = (GraphWithPerform)graph ;
for ( Triple t : s )
g.performDelete(t) ;
graph.getEventManager().notifyDeleteIterator(graph, s) ;
} else {
for ( Triple t : s )
graph.delete(t) ;
}
}
/** Delete triples the destination (arg 1) as given in the source (arg 2) */
public static void deleteFrom(Graph dstGraph, Graph srcGraph) {
deleteIteratorWorker(dstGraph, GraphUtil.findAll(srcGraph)) ;
dstGraph.getEventManager().notifyDeleteGraph(dstGraph, srcGraph) ;
}
private static void deleteIteratorWorker(Graph graph, Iterator<Triple> it) {
List<Triple> s = IteratorCollection.iteratorToList(it) ;
if ( OldStyle && graph instanceof GraphWithPerform ) {
GraphWithPerform g = (GraphWithPerform)graph ;
for ( Triple t : s )
g.performDelete(t) ;
} else {
for ( Triple t : s )
graph.delete(t) ;
}
}
private static final int sliceSize = 1000 ;
/** A safe and cautious remve() function.
* To avoid any possible ConcurrentModificationExceptions,
* it finds batches of triples, deletes them and tries again until
* no change occurs.
*/
public static void remove(Graph g, Node s, Node p, Node o) {
// Beware of ConcurrentModificationExceptions.
// Delete in batches.
// That way, there is no active iterator when a delete
// from the indexes happens.
Triple[] array = new Triple[sliceSize] ;
while (true) {
// Convert/cache s,p,o?
// The Node Cache will catch these so don't worry unduely.
ExtendedIterator<Triple> iter = g.find(s, p, o) ;
// Get a slice
int len = 0 ;
for ( ; len < sliceSize ; len++ ) {
if ( !iter.hasNext() )
break ;
array[len] = iter.next() ;
}
// Delete them.
for ( int i = 0 ; i < len ; i++ ) {
g.delete(array[i]) ;
array[i] = null ;
}
// Finished?
if ( len < sliceSize )
break ;
}
}
}
|
set -e
# Install gcloud
curl -sSL https://raw.githubusercontent.com/CommercialTribe/travis-scripts/master/gcloud.sh | bash
NAMESPACE_PROVISIONER_VERSION=${NAMESPACE_PROVISIONER_VERSION:-v6.0.0}
echo "#####################################################################"
echo "# Installing namespace provisioner ${NAMESPACE_PROVISIONER_VERSION} #"
echo "#####################################################################"
# Install the provisioning script
AUTHORIZATION_HEADER="Authorization: token ${GITHUB_API_TOKEN}"
ACCEPT_HEADER="Accept: application/octet-stream"
NAMESPACE_PROVISIONER_RELEASE_URL=https://api.github.com/repos/commercialtribe/kube-namespace-provisioner/releases/tags/${NAMESPACE_PROVISIONER_VERSION}
NAMESPACE_PROVISIONER_DOWNLOAD_URL=`curl -sSL -H "${AUTHORIZATION_HEADER}" ${NAMESPACE_PROVISIONER_RELEASE_URL} | jq -r '.assets[] | select(.name | contains("linux")).url'`
curl -L -H "${ACCEPT_HEADER}" -H "${AUTHORIZATION_HEADER}" -o kube-namespace-provisioner ${NAMESPACE_PROVISIONER_DOWNLOAD_URL}
chmod +x ./kube-namespace-provisioner
sudo mv ./kube-namespace-provisioner /usr/local/bin/kube-namespace-provisioner
|
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
class CreateHosollvtTable extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('hosollvt', function (Blueprint $table) {
$table->increments('id');
$table->string('macanbo', 50);
$table->date('ngaytu')->nullable();
$table->date('ngayden')->nullable();
$table->string('quanham', 100)->nullable();
$table->string('chucvu', 100)->nullable();
$table->boolean('qhcn')->default(0);
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::dropIfExists('hosollvt');
}
}
|
import sys
from phonemizer import phonemize
def convert_to_phonetic(text: str, language: str, accent: str) -> str:
phonetic_representation = phonemize(text, language=language, accent=accent)
return phonetic_representation
|
# Shell library to run an HTTP server for use in tests.
# Ends the test early if httpd tests should not be run,
# for example because the user has not enabled them.
#
# Usage:
#
# . ./test-lib.sh
# . "$TEST_DIRECTORY"/lib-httpd.sh
# start_httpd
#
# test_expect_success '...' '
# ...
# '
#
# test_expect_success ...
#
# stop_httpd
# test_done
#
# Can be configured using the following variables.
#
# GIT_TEST_HTTPD enable HTTPD tests
# LIB_HTTPD_PATH web server path
# LIB_HTTPD_MODULE_PATH web server modules path
# LIB_HTTPD_PORT listening port
# LIB_HTTPD_DAV enable DAV
# LIB_HTTPD_SVN enable SVN
# LIB_HTTPD_SSL enable SSL
#
# Copyright (c) 2008 Clemens Buchacher <drizzd@aon.at>
#
if test -n "$NO_CURL"
then
skip_all='skipping test, git built without http support'
test_done
fi
if test -n "$NO_EXPAT" && test -n "$LIB_HTTPD_DAV"
then
skip_all='skipping test, git built without expat support'
test_done
fi
test_tristate GIT_TEST_HTTPD
if test "$GIT_TEST_HTTPD" = false
then
skip_all="Network testing disabled (unset GIT_TEST_HTTPD to enable)"
test_done
fi
if ! test_have_prereq NOT_ROOT; then
test_skip_or_die $GIT_TEST_HTTPD \
"Cannot run httpd tests as root"
fi
HTTPD_PARA=""
for DEFAULT_HTTPD_PATH in '/usr/sbin/httpd' '/usr/sbin/apache2'
do
if test -x "$DEFAULT_HTTPD_PATH"
then
break
fi
done
for DEFAULT_HTTPD_MODULE_PATH in '/usr/libexec/apache2' \
'/usr/lib/apache2/modules' \
'/usr/lib64/httpd/modules' \
'/usr/lib/httpd/modules'
do
if test -d "$DEFAULT_HTTPD_MODULE_PATH"
then
break
fi
done
case $(uname) in
Darwin)
HTTPD_PARA="$HTTPD_PARA -DDarwin"
;;
esac
LIB_HTTPD_PATH=${LIB_HTTPD_PATH-"$DEFAULT_HTTPD_PATH"}
LIB_HTTPD_PORT=${LIB_HTTPD_PORT-${this_test#t}}
TEST_PATH="$TEST_DIRECTORY"/lib-httpd
HTTPD_ROOT_PATH="$PWD"/httpd
HTTPD_DOCUMENT_ROOT_PATH=$HTTPD_ROOT_PATH/www
# hack to suppress apache PassEnv warnings
GIT_VALGRIND=$GIT_VALGRIND; export GIT_VALGRIND
GIT_VALGRIND_OPTIONS=$GIT_VALGRIND_OPTIONS; export GIT_VALGRIND_OPTIONS
GIT_TRACE=$GIT_TRACE; export GIT_TRACE
if ! test -x "$LIB_HTTPD_PATH"
then
test_skip_or_die $GIT_TEST_HTTPD "no web server found at '$LIB_HTTPD_PATH'"
fi
HTTPD_VERSION=`$LIB_HTTPD_PATH -v | \
sed -n 's/^Server version: Apache\/\([0-9]*\)\..*$/\1/p; q'`
if test -n "$HTTPD_VERSION"
then
if test -z "$LIB_HTTPD_MODULE_PATH"
then
if ! test $HTTPD_VERSION -ge 2
then
test_skip_or_die $GIT_TEST_HTTPD \
"at least Apache version 2 is required"
fi
if ! test -d "$DEFAULT_HTTPD_MODULE_PATH"
then
test_skip_or_die $GIT_TEST_HTTPD \
"Apache module directory not found"
fi
LIB_HTTPD_MODULE_PATH="$DEFAULT_HTTPD_MODULE_PATH"
fi
else
test_skip_or_die $GIT_TEST_HTTPD \
"Could not identify web server at '$LIB_HTTPD_PATH'"
fi
install_script () {
write_script "$HTTPD_ROOT_PATH/$1" <"$TEST_PATH/$1"
}
prepare_httpd() {
mkdir -p "$HTTPD_DOCUMENT_ROOT_PATH"
cp "$TEST_PATH"/passwd "$HTTPD_ROOT_PATH"
install_script broken-smart-http.sh
install_script error.sh
ln -s "$LIB_HTTPD_MODULE_PATH" "$HTTPD_ROOT_PATH/modules"
if test -n "$LIB_HTTPD_SSL"
then
HTTPD_PROTO=https
RANDFILE_PATH="$HTTPD_ROOT_PATH"/.rnd openssl req \
-config "$TEST_PATH/ssl.cnf" \
-new -x509 -nodes \
-out "$HTTPD_ROOT_PATH/httpd.pem" \
-keyout "$HTTPD_ROOT_PATH/httpd.pem"
GIT_SSL_NO_VERIFY=t
export GIT_SSL_NO_VERIFY
HTTPD_PARA="$HTTPD_PARA -DSSL"
else
HTTPD_PROTO=http
fi
HTTPD_DEST=127.0.0.1:$LIB_HTTPD_PORT
HTTPD_URL=$HTTPD_PROTO://$HTTPD_DEST
HTTPD_URL_USER=$HTTPD_PROTO://user%40host@$HTTPD_DEST
HTTPD_URL_USER_PASS=$HTTPD_PROTO://user%40host:pass%40host@$HTTPD_DEST
if test -n "$LIB_HTTPD_DAV" || test -n "$LIB_HTTPD_SVN"
then
HTTPD_PARA="$HTTPD_PARA -DDAV"
if test -n "$LIB_HTTPD_SVN"
then
HTTPD_PARA="$HTTPD_PARA -DSVN"
rawsvnrepo="$HTTPD_ROOT_PATH/svnrepo"
svnrepo="http://127.0.0.1:$LIB_HTTPD_PORT/svn"
fi
fi
}
start_httpd() {
prepare_httpd >&3 2>&4
trap 'code=$?; stop_httpd; (exit $code); die' EXIT
"$LIB_HTTPD_PATH" -d "$HTTPD_ROOT_PATH" \
-f "$TEST_PATH/apache.conf" $HTTPD_PARA \
-c "Listen 127.0.0.1:$LIB_HTTPD_PORT" -k start \
>&3 2>&4
if test $? -ne 0
then
trap 'die' EXIT
test_skip_or_die $GIT_TEST_HTTPD "web server setup failed"
fi
}
stop_httpd() {
trap 'die' EXIT
"$LIB_HTTPD_PATH" -d "$HTTPD_ROOT_PATH" \
-f "$TEST_PATH/apache.conf" $HTTPD_PARA -k stop
}
test_http_push_nonff () {
REMOTE_REPO=$1
LOCAL_REPO=$2
BRANCH=$3
EXPECT_CAS_RESULT=${4-failure}
test_expect_success 'non-fast-forward push fails' '
cd "$REMOTE_REPO" &&
HEAD=$(git rev-parse --verify HEAD) &&
cd "$LOCAL_REPO" &&
git checkout $BRANCH &&
echo "changed" > path2 &&
git commit -a -m path2 --amend &&
test_must_fail git push -v origin >output 2>&1 &&
(cd "$REMOTE_REPO" &&
test $HEAD = $(git rev-parse --verify HEAD))
'
test_expect_success 'non-fast-forward push show ref status' '
grep "^ ! \[rejected\][ ]*$BRANCH -> $BRANCH (non-fast-forward)$" output
'
test_expect_success 'non-fast-forward push shows help message' '
test_i18ngrep "Updates were rejected because" output
'
test_expect_${EXPECT_CAS_RESULT} 'force with lease aka cas' '
HEAD=$( cd "$REMOTE_REPO" && git rev-parse --verify HEAD ) &&
test_when_finished '\''
(cd "$REMOTE_REPO" && git update-ref HEAD "$HEAD")
'\'' &&
(
cd "$LOCAL_REPO" &&
git push -v --force-with-lease=$BRANCH:$HEAD origin
) &&
git rev-parse --verify "$BRANCH" >expect &&
(
cd "$REMOTE_REPO" && git rev-parse --verify HEAD
) >actual &&
test_cmp expect actual
'
}
setup_askpass_helper() {
test_expect_success 'setup askpass helper' '
write_script "$TRASH_DIRECTORY/askpass" <<-\EOF &&
echo >>"$TRASH_DIRECTORY/askpass-query" "askpass: $*" &&
case "$*" in
*Username*)
what=user
;;
*Password*)
what=pass
;;
esac &&
cat "$TRASH_DIRECTORY/askpass-$what"
EOF
GIT_ASKPASS="$TRASH_DIRECTORY/askpass" &&
export GIT_ASKPASS &&
export TRASH_DIRECTORY
'
}
set_askpass() {
>"$TRASH_DIRECTORY/askpass-query" &&
echo "$1" >"$TRASH_DIRECTORY/askpass-user" &&
echo "$2" >"$TRASH_DIRECTORY/askpass-pass"
}
expect_askpass() {
dest=$HTTPD_DEST${3+/$3}
{
case "$1" in
none)
;;
pass)
echo "askpass: Password for 'http://$2@$dest': "
;;
both)
echo "askpass: Username for 'http://$dest': "
echo "askpass: Password for 'http://$2@$dest': "
;;
*)
false
;;
esac
} >"$TRASH_DIRECTORY/askpass-expect" &&
test_cmp "$TRASH_DIRECTORY/askpass-expect" \
"$TRASH_DIRECTORY/askpass-query"
}
|
package io.github.brightloong.spring.cloud.learn.eureka.consumer.hystrix.controller;
import io.github.brightloong.spring.cloud.learn.eureka.consumer.hystrix.feign.HelloRemote;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
/**
* @author BrightLoong
* @date 2019-02-01 15:19
* @description
*/
@RestController
public class ConsumerController {
@Autowired
private HelloRemote helloRemote;
@RequestMapping("/hello/{name}")
public String index(@PathVariable("name") String name) {
return helloRemote.hello(name);
}
}
|
package me.minidigger.minicraft.protocol.client;
import com.google.common.base.MoreObjects;
import net.kyori.text.Component;
import net.kyori.text.serializer.gson.GsonComponentSerializer;
import io.netty.buffer.ByteBuf;
import me.minidigger.minicraft.model.ChatPosition;
import me.minidigger.minicraft.protocol.MiniPacket;
import me.minidigger.minicraft.protocol.DataTypes;
public class ClientPlayChatMessage extends MiniPacket {
private Component component;
private ChatPosition position;
public Component getComponent() {
return component;
}
public void setComponent(Component component) {
this.component = component;
}
public ChatPosition getPosition() {
return position;
}
public void setPosition(ChatPosition position) {
this.position = position;
}
@Override
public void toWire(ByteBuf buf) {
DataTypes.writeString(GsonComponentSerializer.INSTANCE.serialize(component),buf);
buf.writeByte(position.getId());
}
@Override
public void fromWire(ByteBuf buf) {
}
@Override
public String toString() {
return MoreObjects.toStringHelper(this)
.add("component", component)
.add("position", position)
.toString();
}
}
|
// Copyright (c) 2015-2016, ETH Zurich, <NAME>, Zurich Eye
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
// * Neither the name of the ETH Zurich, Wyss Zurich, Zurich Eye nor the
// names of its contributors may be used to endorse or promote products
// derived from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
// ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
// DISCLAIMED. IN NO EVENT SHALL ETH Zurich, Wyss Zurich, Zurich Eye BE LIABLE FOR ANY
// DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
// ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#include <ze/imu/imu_buffer.hpp>
namespace ze {
template<int BufferSize, typename GyroInterp, typename AccelInterp>
ImuBuffer<BufferSize, GyroInterp, AccelInterp>::ImuBuffer(ImuModel::Ptr imu_model)
: imu_model_(imu_model)
, gyro_delay_(secToNanosec(imu_model->gyroscopeModel()->intrinsicModel()->delay()))
, accel_delay_(secToNanosec(imu_model->accelerometerModel()->intrinsicModel()->delay()))
{
}
template<int BufferSize, typename GyroInterp, typename AccelInterp>
void ImuBuffer<BufferSize, GyroInterp, AccelInterp>::insertImuMeasurement(
int64_t time, const ImuAccGyr value)
{
acc_buffer_.insert(correctStampAccel(time), value.head<3>(3));
gyr_buffer_.insert(correctStampGyro(time), value.tail<3>(3));
}
template<int BufferSize, typename GyroInterp, typename AccelInterp>
void ImuBuffer<BufferSize, GyroInterp, AccelInterp>::insertGyroscopeMeasurement(
int64_t time, const Vector3 value)
{
gyr_buffer_.insert(correctStampGyro(time), value);
}
template<int BufferSize, typename GyroInterp, typename AccelInterp>
void ImuBuffer<BufferSize, GyroInterp, AccelInterp>::insertAccelerometerMeasurement(
int64_t time, const Vector3 value)
{
acc_buffer_.insert(correctStampAccel(time), value);
}
template<int BufferSize, typename GyroInterp, typename AccelInterp>
bool ImuBuffer<BufferSize, GyroInterp, AccelInterp>::get(int64_t time,
Eigen::Ref<ImuAccGyr> out)
{
std::lock_guard<std::mutex> gyr_lock(gyr_buffer_.mutex());
std::lock_guard<std::mutex> acc_lock(acc_buffer_.mutex());
if (time > gyr_buffer_.times().back()
|| time > acc_buffer_.times().back())
{
return false;
}
const auto gyro_before = gyr_buffer_.iterator_equal_or_before(time);
const auto acc_before = acc_buffer_.iterator_equal_or_before(time);
if (gyro_before == gyr_buffer_.times().end()
|| acc_before == acc_buffer_.times().end()) {
return false;
}
VectorX w = GyroInterp::interpolate(&gyr_buffer_, time, gyro_before);
VectorX a = AccelInterp::interpolate(&acc_buffer_, time, acc_before);
out = imu_model_->undistort(a, w);
return true;
}
template<int BufferSize, typename GyroInterp, typename AccelInterp>
bool ImuBuffer<BufferSize, GyroInterp, AccelInterp>::getAccelerometerDistorted(
int64_t time,
Eigen::Ref<Vector3> out)
{
return acc_buffer_.getValueInterpolated(time, out);
}
template<int BufferSize, typename GyroInterp, typename AccelInterp>
bool ImuBuffer<BufferSize, GyroInterp, AccelInterp>::getGyroscopeDistorted(
int64_t time,
Eigen::Ref<Vector3> out)
{
return gyr_buffer_.getValueInterpolated(time, out);
}
template<int BufferSize, typename GyroInterp, typename AccelInterp>
std::pair<ImuStamps, ImuAccGyrContainer>
ImuBuffer<BufferSize, GyroInterp, AccelInterp>::getBetweenValuesInterpolated(
int64_t stamp_from, int64_t stamp_to)
{
//Takes gyroscope timestamps and interpolates accelerometer measurements at
// same times. Rectifies all measurements.
CHECK_GE(stamp_from, 0u);
CHECK_LT(stamp_from, stamp_to);
ImuAccGyrContainer rectified_measurements;
ImuStamps stamps;
std::lock_guard<std::mutex> gyr_lock(gyr_buffer_.mutex());
std::lock_guard<std::mutex> acc_lock(acc_buffer_.mutex());
if(gyr_buffer_.times().size() < 2)
{
LOG(WARNING) << "Buffer has less than 2 entries.";
// return empty means unsuccessful.
return std::make_pair(stamps, rectified_measurements);
}
const time_t oldest_stamp = gyr_buffer_.times().front();
const time_t newest_stamp = gyr_buffer_.times().back();
if (stamp_from < oldest_stamp)
{
LOG(WARNING) << "Requests older timestamp than in buffer.";
// return empty means unsuccessful.
return std::make_pair(stamps, rectified_measurements);
}
if (stamp_to > newest_stamp)
{
LOG(WARNING) << "Requests newer timestamp than in buffer.";
// return empty means unsuccessful.
return std::make_pair(stamps, rectified_measurements);
}
const auto it_from_before = gyr_buffer_.iterator_equal_or_before(stamp_from);
const auto it_to_after = gyr_buffer_.iterator_equal_or_after(stamp_to);
CHECK(it_from_before != gyr_buffer_.times().end());
CHECK(it_to_after != gyr_buffer_.times().end());
const auto it_from_after = it_from_before + 1;
const auto it_to_before = it_to_after - 1;
if (it_from_after == it_to_before)
{
LOG(WARNING) << "Not enough data for interpolation";
// return empty means unsuccessful.
return std::make_pair(stamps, rectified_measurements);
}
// resize containers
const size_t range = it_to_before.index() - it_from_after.index() + 3;
rectified_measurements.resize(Eigen::NoChange, range);
stamps.resize(range);
// first element
VectorX w = GyroInterp::interpolate(&gyr_buffer_, stamp_from, it_from_before);
VectorX a = AccelInterp::interpolate(&acc_buffer_, stamp_from);
stamps(0) = stamp_from;
rectified_measurements.col(0) = imu_model_->undistort(a, w);
// this is a real edge case where we hit the two consecutive timestamps
// with from and to.
size_t col = 1;
if (range > 2)
{
for (auto it=it_from_before+1; it!=it_to_after; ++it) {
w = GyroInterp::interpolate(&gyr_buffer_, (*it), it);
a = AccelInterp::interpolate(&acc_buffer_, (*it));
stamps(col) = (*it);
rectified_measurements.col(col) = imu_model_->undistort(a, w);
++col;
}
}
// last element
w = GyroInterp::interpolate(&gyr_buffer_, stamp_to, it_to_before);
a = AccelInterp::interpolate(&acc_buffer_, stamp_to);
stamps(range - 1) = stamp_to;
rectified_measurements.col(range - 1) = imu_model_->undistort(a, w);
return std::make_pair(stamps, rectified_measurements);
}
template<int BufferSize, typename GyroInterp, typename AccelInterp>
std::tuple<int64_t, int64_t, bool>
ImuBuffer<BufferSize, GyroInterp, AccelInterp>::getOldestAndNewestStamp() const
{
std::tuple<int64_t, int64_t, bool> accel =
acc_buffer_.getOldestAndNewestStamp();
std::tuple<int64_t, int64_t, bool> gyro =
gyr_buffer_.getOldestAndNewestStamp();
if (!std::get<2>(accel) || !std::get<2>(gyro))
{
return std::make_tuple(-1, -1, false);
}
int64_t oldest = std::get<0>(accel) < std::get<0>(gyro) ?
std::get<0>(gyro) : std::get<0>(accel);
int64_t newest = std::get<1>(accel) < std::get<1>(gyro) ?
std::get<1>(accel) : std::get<1>(gyro);
// This is an extreme edge case where the accel and gyro measurements
// do not overlap at all.
if (oldest > newest)
{
return std::make_tuple(-1, -1, false);
}
return std::make_tuple(oldest, newest, true);
}
// A set of explicit declarations
template class ImuBuffer<2000, InterpolatorLinear>;
template class ImuBuffer<5000, InterpolatorLinear>;
template class ImuBuffer<2000, InterpolatorNearest>;
template class ImuBuffer<5000, InterpolatorNearest>;
template class ImuBuffer<2000, InterpolatorDifferentiatorLinear,
InterpolatorLinear>;
template class ImuBuffer<5000, InterpolatorDifferentiatorLinear,
InterpolatorLinear>;
} // namespace ze
|
<reponame>smagill/opensphere-desktop<gh_stars>10-100
package io.opensphere.controlpanels.layers.base;
import java.util.Collection;
import java.util.Enumeration;
import java.util.Set;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.regex.Pattern;
import javax.swing.tree.DefaultMutableTreeNode;
import javax.swing.tree.TreeNode;
import org.apache.commons.lang3.StringUtils;
import org.apache.log4j.Logger;
import io.opensphere.core.Toolbox;
import io.opensphere.core.datafilter.DataFilter;
import io.opensphere.core.datafilter.DataFilterRegistryListener;
import io.opensphere.core.datafilter.impl.DataFilterRegistryAdapter;
import io.opensphere.core.event.EventListener;
import io.opensphere.core.preferences.PreferenceChangeListener;
import io.opensphere.core.quantify.Quantify;
import io.opensphere.core.util.ChangeSupport;
import io.opensphere.core.util.WeakChangeSupport;
import io.opensphere.core.util.concurrent.ProcrastinatingExecutor;
import io.opensphere.core.util.lang.StringUtilities;
import io.opensphere.core.util.lang.ThreadUtilities;
import io.opensphere.core.util.swing.tree.DirectionalTransferHandler;
import io.opensphere.core.util.swing.tree.OrderTreeEventController;
import io.opensphere.mantle.controller.DataGroupController;
import io.opensphere.mantle.controller.event.AbstractRootDataGroupControllerEvent;
import io.opensphere.mantle.controller.event.impl.RootDataGroupAddedEvent;
import io.opensphere.mantle.controller.event.impl.RootDataGroupRemovedEvent;
import io.opensphere.mantle.data.DataGroupInfo;
import io.opensphere.mantle.data.event.DataGroupInfoChildAddedEvent;
import io.opensphere.mantle.data.event.DataGroupInfoChildRemovedEvent;
import io.opensphere.mantle.data.event.DataGroupInfoMemberAddedEvent;
import io.opensphere.mantle.data.event.DataGroupInfoMemberRemovedEvent;
import io.opensphere.mantle.data.event.DataTypeInfoTagsChangeEvent;
import io.opensphere.mantle.data.event.DataTypeVisibilityChangeEvent;
import io.opensphere.mantle.data.impl.DataGroupInfoGroupByUtility;
import io.opensphere.mantle.data.impl.DefaultDataGroupActivator;
import io.opensphere.mantle.data.impl.GroupByNodeUserObject;
import io.opensphere.mantle.data.impl.GroupByTreeBuilder;
import io.opensphere.mantle.data.impl.GroupKeywordUtilities;
import io.opensphere.mantle.data.impl.NodeUserObjectGenerator;
import io.opensphere.mantle.util.MantleToolboxUtils;
/**
* The Class AbstractDiscoveryDataLayerController.
*/
@SuppressWarnings("PMD.GodClass")
public abstract class AbstractDiscoveryDataLayerController implements EventListener<AbstractRootDataGroupControllerEvent>
{
/** The logger. */
private static final Logger LOGGER = Logger.getLogger(AbstractDiscoveryDataLayerController.class);
/** The activation listener. */
private final Runnable myActivationListener = this::handleActiveGroupsChanged;
/** The Change executor service. */
private final ScheduledExecutorService myChangeExecutorService = Executors.newScheduledThreadPool(1);
/** The change support that handles my listeners. */
private final ChangeSupport<DiscoveryDataLayerChangeListener> myChangeSupport = new WeakChangeSupport<>();
/**
* Asks the user yes no questions.
*/
private final UserConfirmer myConfirmer;
/** The Data filter registry listener. */
private final DataFilterRegistryListener myDataFilterRegistryListener;
/** The data group controller. */
private final DataGroupController myDataGroupController;
/** The Data groups changed executor. */
private final ProcrastinatingExecutor myDataGroupsChangedExecutor = new ProcrastinatingExecutor(myChangeExecutorService, 300,
500);
/** The Data type info tags change event listener. */
private final EventListener<DataTypeInfoTagsChangeEvent> myDataTypeInfoTagsChangeEventListener;
/** The filtered tree. */
private TreeNode myFilteredTree;
/**
* Activates/deactivates data groups.
*/
private final GroupActivator myGroupActivator;
/** The Group vis changed executor. */
private final ProcrastinatingExecutor myGroupVisChangedExecutor = new ProcrastinatingExecutor(myChangeExecutorService, 300,
500);
/** The Repaint tree executor. */
private final ProcrastinatingExecutor myRepaintTreeExecutor = new ProcrastinatingExecutor(myChangeExecutorService, 300, 500);
/** The toolbox. */
private final Toolbox myToolbox;
/** The tree needs rebuild. */
private boolean myTreeNeedsRebuild = true;
/** The unfiltered tree. */
private TreeNode myUnfilteredTree;
/** The Update labels executor. */
private final ProcrastinatingExecutor myUpdateLabelsExecutor = new ProcrastinatingExecutor(myChangeExecutorService, 300, 500);
/** The view filter. */
private String myViewFilter;
/**
* Filter node.
*
* @param nodeToAddTo the node to add to
* @param nodeToFilter the node to filter
* @param searchPattern the search pattern
* @return true, if successful
*/
public static boolean filterNode(DefaultMutableTreeNode nodeToAddTo, TreeNode nodeToFilter, Pattern searchPattern)
{
boolean passedNode = false;
if (nodeToFilter instanceof DefaultMutableTreeNode)
{
Object userObject = ((DefaultMutableTreeNode)nodeToFilter).getUserObject();
DefaultMutableTreeNode node = userObject == null ? new DefaultMutableTreeNode()
: new DefaultMutableTreeNode(userObject);
if (userObject instanceof GroupByNodeUserObject)
{
GroupByNodeUserObject uo = (GroupByNodeUserObject)userObject;
passedNode = uo.matchesPattern(searchPattern);
}
boolean passedAny = false;
if (nodeToFilter.getChildCount() >= 0)
{
for (Enumeration<?> e = nodeToFilter.children(); e.hasMoreElements();)
{
TreeNode n = (TreeNode)e.nextElement();
if (filterNode(node, n, searchPattern))
{
passedAny = true;
}
}
}
if (passedNode || passedAny)
{
passedNode = true;
nodeToAddTo.add(node);
}
}
return passedNode;
}
/**
* Filter tree.
*
* @param treeToFilter the tree to filter
* @param viewFilter the view filter
* @return the tree node
*/
public static TreeNode filterTree(TreeNode treeToFilter, String viewFilter)
{
Object userObject = ((DefaultMutableTreeNode)treeToFilter).getUserObject();
DefaultMutableTreeNode fRootNode = userObject == null ? new DefaultMutableTreeNode()
: new DefaultMutableTreeNode(userObject);
Pattern p = GroupKeywordUtilities.getSearchPattern(viewFilter);
if (LOGGER.isTraceEnabled())
{
LOGGER.trace("Filter Tree With Regex [" + p.pattern() + "]");
}
if (treeToFilter.getChildCount() >= 0)
{
for (Enumeration<?> e = treeToFilter.children(); e.hasMoreElements();)
{
TreeNode n = (TreeNode)e.nextElement();
filterNode(fRootNode, n, p);
}
}
return fRootNode;
}
/**
* Instantiates a new abstract discovery data layer controller.
*
* @param pBox the box
* @param confirmer Asks the user yes no questions.
*/
@SuppressWarnings("PMD.ConstructorCallsOverridableMethod")
public AbstractDiscoveryDataLayerController(Toolbox pBox, UserConfirmer confirmer)
{
myToolbox = pBox;
myConfirmer = confirmer;
myToolbox.getEventManager().subscribe(AbstractRootDataGroupControllerEvent.class, this);
MantleToolboxUtils.getMantleToolbox(myToolbox).getDataGroupController().addActivationListener(myActivationListener);
myDataTypeInfoTagsChangeEventListener = createDataTypeTagsChangedEventListener();
myToolbox.getEventManager().subscribe(DataTypeInfoTagsChangeEvent.class, myDataTypeInfoTagsChangeEventListener);
myDataGroupController = MantleToolboxUtils.getMantleToolbox(getToolbox()).getDataGroupController();
myDataFilterRegistryListener = createDataFilterRegistryListener();
myToolbox.getDataFilterRegistry().addListener(myDataFilterRegistryListener);
myViewFilter = null;
myGroupActivator = new GroupActivator(new DefaultDataGroupActivator(pBox.getEventManager()));
}
/**
* Adds the {@link DiscoveryDataLayerChangeListener}.
*
* @param listener the listener
*/
public void addListener(DiscoveryDataLayerChangeListener listener)
{
myChangeSupport.addListener(listener);
}
/**
* Change the activation state for the groups.
*
* @param groups the groups whose state should be changed.
* @param active when true the groups will be made active, when false the
* will be made inactive.
*/
public void changeActivation(Collection<DataGroupInfo> groups, boolean active)
{
Quantify.collectEnableDisableMetric("mist3d.add-data-panel.activation", active);
ThreadUtilities.runBackground(() -> groups.parallelStream().filter(g -> g.userActivationStateControl())
.forEach(g -> myGroupActivator.activateDeactivateGroup(active, g, myConfirmer)));
}
/**
* Change the activation state for the groups.
*
* @param groups the groups whose state should be changed.
*/
public void deleteDataGroups(Collection<DataGroupInfo> groups)
{
// Filter out any groups that don't allow user activation/de-activation
// control.
for (DataGroupInfo dgi : groups)
{
if (dgi.userDeleteControl())
{
getDataGroupController().removeDataGroupInfo(dgi, this);
}
}
}
/**
* Gets the data group controller.
*
* @return the data group controller
*/
public DataGroupController getDataGroupController()
{
return myDataGroupController;
}
/**
* Gets the drag and drop transfer handler.
*
* @return The drag and drop transfer handler.
*/
public DirectionalTransferHandler getDragAndDropHandler()
{
return null;
}
/**
* Gets the group by tree builder.
*
* @return the group by tree builder
*/
public abstract GroupByTreeBuilder getGroupByTreeBuilder();
/**
* Gets the group tree with the given filter.
*
* @return the group tree
*/
public TreeNode getGroupTree()
{
if (myTreeNeedsRebuild)
{
if (LOGGER.isTraceEnabled())
{
LOGGER.trace("Rebuild Tree");
}
Set<DataGroupInfo> dgiSet = getDataGroupInfoSet();
GroupByTreeBuilder builder = getGroupByTreeBuilder();
long start = System.nanoTime();
myUnfilteredTree = DataGroupInfoGroupByUtility.createGroupByTree(builder, getNodeUserObjectGenerator(), dgiSet);
if (LOGGER.isTraceEnabled())
{
LOGGER.trace(StringUtilities.formatTimingMessage("Built Tree In: ", System.nanoTime() - start));
}
myTreeNeedsRebuild = false;
}
if (StringUtils.isBlank(myViewFilter))
{
myFilteredTree = myUnfilteredTree;
}
else
{
if (LOGGER.isTraceEnabled())
{
LOGGER.trace("Filter Tree");
}
long start = System.nanoTime();
myFilteredTree = filterTree(myUnfilteredTree, myViewFilter);
if (LOGGER.isTraceEnabled())
{
LOGGER.trace(StringUtilities.formatTimingMessage("Filtered Tree In: ", System.nanoTime() - start));
}
}
return myFilteredTree;
}
/**
* Gets the node user object generator.
*
* @return the node user object generator
*/
public abstract NodeUserObjectGenerator getNodeUserObjectGenerator();
/**
* Get the orderTreeEventController.
*
* @return the orderTreeEventController
*/
public OrderTreeEventController getOrderTreeEventController()
{
return null;
}
/**
* Gets the toolbox.
*
* @return the toolbox
*/
public Toolbox getToolbox()
{
return myToolbox;
}
/**
* Gets the view by type string.
*
* @return the view by type string
*/
public abstract String getViewByTypeString();
@Override
public void notify(AbstractRootDataGroupControllerEvent event)
{
if (event instanceof RootDataGroupRemovedEvent || event instanceof RootDataGroupAddedEvent
|| event.getOriginEvent() instanceof DataGroupInfoChildAddedEvent
|| event.getOriginEvent() instanceof DataGroupInfoChildRemovedEvent
|| event.getOriginEvent() instanceof DataGroupInfoMemberAddedEvent
|| event.getOriginEvent() instanceof DataGroupInfoMemberRemovedEvent)
{
myTreeNeedsRebuild = true;
notifyDataGroupsChanged();
}
}
/**
* Removes the {@link DiscoveryDataLayerChangeListener}.
*
* @param listener the listener
*/
public void removeListener(DiscoveryDataLayerChangeListener listener)
{
myChangeSupport.removeListener(listener);
}
/**
* Sets the tree filter.
*
* @param filter the new tree filter
*/
public void setTreeFilter(String filter)
{
myViewFilter = filter;
notifyDataGroupsChanged();
}
/**
* Sets the tree needs rebuild.
*
* @param rebuild the new tree needs rebuild
*/
public void setTreeNeedsRebuild(boolean rebuild)
{
myTreeNeedsRebuild = rebuild;
}
/**
* Gets the value of the treeNeedsRebuild ({@link #myTreeNeedsRebuild})
* field.
*
* @return the value stored in the {@link #myTreeNeedsRebuild} field.
*/
protected boolean isTreeNeedsRebuild()
{
return myTreeNeedsRebuild;
}
/**
* Gets the value of the viewFilter ({@link #myViewFilter}) field.
*
* @return the value stored in the {@link #myViewFilter} field.
*/
protected String getViewFilter()
{
return myViewFilter;
}
/**
* Sets the view by type from string.
*
* @param vbt the new view by type from string
*/
public abstract void setViewByTypeFromString(String vbt);
/**
* Update group node user object labels.
*/
public void updateGroupNodeUserObjectLabels()
{
if (myUnfilteredTree != null)
{
updateGroupNodeUserObjectLabels((DefaultMutableTreeNode)myUnfilteredTree);
}
}
/**
* Sets the value of the unfilteredTree ({@link #myUnfilteredTree}) field.
*
* @param unfilteredTree the value to store in the {@link #myUnfilteredTree}
* field.
*/
protected void setUnfilteredTree(TreeNode unfilteredTree)
{
myUnfilteredTree = unfilteredTree;
}
/**
* Gets the value of the unfilteredTree ({@link #myUnfilteredTree}) field.
*
* @return the value stored in the {@link #myUnfilteredTree} field.
*/
protected TreeNode getUnfilteredTree()
{
return myUnfilteredTree;
}
/**
* Sets the value of the filteredTree ({@link #myFilteredTree}) field.
*
* @param filteredTree the value to store in the {@link #myFilteredTree}
* field.
*/
protected void setFilteredTree(TreeNode filteredTree)
{
myFilteredTree = filteredTree;
}
/**
* Gets the value of the filteredTree ({@link #myFilteredTree}) field.
*
* @return the value stored in the {@link #myFilteredTree} field.
*/
protected TreeNode getFilteredTree()
{
return myFilteredTree;
}
/**
* Gets the set of data groups to display in the tree with the given filter.
*
* @return The set of data groups to display in tree.
*/
protected Set<DataGroupInfo> getDataGroupInfoSet()
{
return MantleToolboxUtils.getMantleToolbox(getToolbox()).getDataGroupController().getDataGroupInfoSet();
}
/**
* Get the preferences change listener for showing layer type labels.
*
* @return The change listener.
*/
protected PreferenceChangeListener getShowLayerTypeLabelsPreferencesChangeListener()
{
return (evt) ->
{
updateGroupNodeUserObjectLabels();
notifyUpdateTreeLabelsRequest();
};
}
/**
* Handle tags changed.
*
* @param event the event
*/
protected abstract void handleTagsChanged(DataTypeInfoTagsChangeEvent event);
/**
* Notify data groups changed.
*/
protected void notifyDataGroupsChanged()
{
myChangeSupport.notifyListeners(listener -> listener.dataGroupsChanged(), myDataGroupsChangedExecutor);
}
/**
* Notify groups visibility changed.
*
* @param event the event
*/
protected void notifyGroupsVisibilityChanged(final DataTypeVisibilityChangeEvent event)
{
myChangeSupport.notifyListeners(listener -> listener.dataGroupVisibilityChanged(event), myGroupVisChangedExecutor);
}
/**
* Notify data groups changed.
*/
protected void notifyRepaintTreeRequest()
{
myChangeSupport.notifyListeners(listener -> listener.treeRepaintRequest(), myRepaintTreeExecutor);
}
/**
* Notify data groups changed.
*/
protected void notifyUpdateTreeLabelsRequest()
{
myChangeSupport.notifyListeners(listener -> listener.refreshTreeLabelRequest(), myUpdateLabelsExecutor);
}
/**
* Update group node user object labels.
*
* @param node the node
*/
protected void updateGroupNodeUserObjectLabels(DefaultMutableTreeNode node)
{
if (node != null)
{
if (node.getUserObject() instanceof GroupByNodeUserObject)
{
((GroupByNodeUserObject)node.getUserObject()).generateLabel();
}
if (node.getChildCount() > 0)
{
for (int i = 0; i < node.getChildCount(); i++)
{
updateGroupNodeUserObjectLabels((DefaultMutableTreeNode)node.getChildAt(i));
}
}
}
}
/**
* Creates the data filter registry listener.
*
* @return the data filter registry listener
*/
private DataFilterRegistryListener createDataFilterRegistryListener()
{
DataFilterRegistryListener listener = new DataFilterRegistryAdapter()
{
@Override
public void loadFilterAdded(String typeKey, DataFilter filter, Object source)
{
notifyUpdateTreeLabelsRequest();
}
@Override
public void loadFiltersRemoved(Set<? extends DataFilter> removedFilters, Object source)
{
notifyUpdateTreeLabelsRequest();
}
@Override
public void viewFilterAdded(String typeKey, DataFilter filter, Object source)
{
notifyUpdateTreeLabelsRequest();
}
@Override
public void viewFiltersRemoved(Set<? extends DataFilter> removedFilters, Object source)
{
notifyUpdateTreeLabelsRequest();
}
};
return listener;
}
/**
* Creates the data type tags changed event listener.
*
* @return the event listener
*/
private EventListener<DataTypeInfoTagsChangeEvent> createDataTypeTagsChangedEventListener()
{
return event -> handleTagsChanged(event);
}
/**
* Handle active groups changed.
*/
private void handleActiveGroupsChanged()
{
myTreeNeedsRebuild = true;
}
}
|
# src/bash/aspark-starter/funcs/change-env-type.test.sh
# v1.0.9
# ---------------------------------------------------------
# todo: add doTestChangeEnvType comments ...
# ---------------------------------------------------------
doTestChangeEnvType(){
doLog "DEBUG START doTestChangeEnvType"
cat doc/txt/aspark-starter/tests/change-env-type.test.txt
sleep 2
# add your action implementation code here ...
doLog "DEBUG STOP doTestChangeEnvType"
}
# eof func doTestChangeEnvType
# eof file: src/bash/aspark-starter/funcs/change-env-type.test.sh
|
nasm -f elf32 ../asm/kernel.asm -o kasm.o
gcc -m32 -fno-builtin -fno-stack-protector -c ../src/kernel.c -o kmain.o
gcc -m32 -fno-builtin -fno-stack-protector -c ../src/screen.c -o screen.o
gcc -m32 -fno-builtin -fno-stack-protector -c ../src/interupt_handler.c -o int_handler.o
gcc -m32 -fno-builtin -fno-stack-protector -c ../src/keyboard_handler.c -o key_handler.o
gcc -m32 -fno-builtin -fno-stack-protector -c ../src/input.c -o input.o
ld -m elf_i386 -T link.ld -o kernel kasm.o screen.o int_handler.o key_handler.o input.o kmain.o
rm -f *.o
|
<filename>tailwind.config.js<gh_stars>0
module.exports = {
purge: ["./src/**/*.html", "./src/**/*.js"],
darkMode: false, // or 'media' or 'class'
theme: {
extend: {
colors: {
one: {
lt: "#EF6B81",
md: "#E83151",
dk: "#B4142F",
},
two: {
lt: "#0BC2FF",
md: "#007EA7",
dk: "#005A78",
},
three: {
lt: "#FFBF49",
md: "#FFA400",
dk: "#B67600",
},
neutral: {
lt: "#FFFFFF",
dk: "#242424",
},
},
},
},
variants: {
extend: {
backgroundColor: ["active"],
textColor: ["active"],
},
},
plugins: [],
};
|
class PayloadManager: NSObject, NSCoding {
var payloadString: String
init(payload: String) {
self.payloadString = payload
super.init()
}
required init?(coder: NSCoder) {
if let data = coder.decodeObject(forKey: "payloadString") as? Data {
payloadString = String(data: data, encoding: .utf8) ?? ""
} else {
payloadString = ""
}
}
func encode(with coder: NSCoder) {
if let data = payloadString.data(using: .utf8) {
coder.encode(data, forKey: "payloadString")
}
}
}
|
/*
* Copyright 2014-2019 michael-simons.eu.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package ac.simons.biking2.bikes;
import ac.simons.biking2.bikes.BikeEntity.Link;
import java.time.LocalDate;
import java.time.Month;
import org.junit.jupiter.api.Test;
import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotEquals;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertNull;
/**
* @author <NAME>
*/
class BikeEntityTest {
private final BikeEntity defaultTestBike;
BikeEntityTest() {
this.defaultTestBike = new BikeEntity()
.addMilage(LocalDate.of(2014, 1, 1), 0).getBike()
.addMilage(LocalDate.of(2014, 2, 1), 20).getBike()
.addMilage(LocalDate.of(2014, 3, 1), 50).getBike();
}
@Test
void linkBeanShouldWorkAsExpected() {
Link l1 = new Link();
Link l2 = new Link("http://heise.de", "h");
Link l3 = new Link("http://heise.de", "H");
assertEquals(l2, l3);
assertEquals(l2.hashCode(), l3.hashCode());
assertNotEquals(l2, l1);
assertNotEquals(l2.hashCode(), l1.hashCode());
assertNotEquals(l2, null);
assertNotEquals(l2, "asds");
assertEquals("http://heise.de", l2.getUrl());
assertEquals("h", l2.getLabel());
l2.setLabel("H");
assertEquals("H", l2.getLabel());
}
@Test
void beanShouldWorkAsExpected() {
final LocalDate now = LocalDate.now();
BikeEntity bike = new BikeEntity("poef", now.withDayOfMonth(1));
BikeEntity same = new BikeEntity("poef", now.withDayOfMonth(1));
BikeEntity other = new BikeEntity("other", now.withDayOfMonth(1));
other.decommission(null);
assertNull(other.getDecommissionedOn());
other.decommission(now);
assertNotNull(other.getDecommissionedOn());
assertNull(bike.getStory());
assertNull(bike.getId());
assertNotNull(bike.getCreatedAt());
assertEquals(bike, same);
assertNotEquals(bike, other);
assertNotEquals(bike, null);
assertNotEquals(bike, "somethingElse");
assertNull(bike.getDecommissionedOn());
assertEquals(now.withDayOfMonth(1), bike.getBoughtOn());
assertEquals(now.withDayOfMonth(1), other.getBoughtOn());
assertEquals(now, other.getDecommissionedOn());
final BikeEntity.Link story = new BikeEntity.Link("http://planet-punk.de/2015/08/11/nie-wieder-stadtschlampe/", "Nie wieder Stadtschlampe");
bike.setStory(story);
assertEquals(story, bike.getStory());
}
@Test
void testGetLastMilage() {
assertEquals(50, defaultTestBike.getLastMilage());
assertEquals(0, new BikeEntity("test", LocalDate.now()).getLastMilage());
}
@Test
void testAddMilageInvalidDate() {
assertThatIllegalArgumentException()
.isThrownBy(() -> this.defaultTestBike.addMilage(LocalDate.of(2015, Month.JANUARY, 1), 23))
.withMessage("Next valid date for milage is " + LocalDate.of(2014, 4, 1));
;
}
@Test
void testAddMilageInvalidAmount() {
assertThatIllegalArgumentException()
.isThrownBy(() -> this.defaultTestBike.addMilage(LocalDate.of(2014, Month.APRIL, 1), 23))
.withMessage("New amount must be greater than or equal 50.0");
}
}
|
package com.github.robindevilliers.cascade.modules;
import com.github.robindevilliers.cascade.Scope;
import com.github.robindevilliers.cascade.model.Journey;
import org.junit.runner.Description;
import org.junit.runner.notification.RunNotifier;
import java.util.List;
import java.util.Map;
public interface TestExecutor {
void init(Class<?> controlClass, Map<String, Scope> globalScope);
void executeTest(RunNotifier notifier, Description description, List<Object> steps, Journey journey, TestReport reporter, Map<String, Scope> scope);
}
|
<filename>lib/quickbooks/model/sales_item_line_detail.rb
module Quickbooks
module Model
class SalesItemLineDetail < BaseModel
xml_accessor :item_ref, :from => 'ItemRef', :as => Integer
xml_accessor :class_ref, :from => 'ClassRef', :as => Integer
xml_accessor :unit_price, :from => 'UnitPrice', :as => Float
xml_accessor :rate_percent, :from => 'RatePercent', :as => Float
xml_accessor :price_level_ref, :from => 'PriceLevelRef', :as => Integer
xml_accessor :quantity, :from => 'Qty', :as => Float
xml_accessor :tax_code_ref, :from => 'TaxCodeRef'
xml_accessor :service_date, :from => 'ServiceDate', :as => Date
end
end
end
|
def search(target, elements):
start = 0
end = len(elements) - 1
while start <= end:
mid = (start + end) // 2
if target == elements[mid]:
return True
elif target < elements[mid]:
end = mid - 1
else:
start = mid + 1
return False
|
/* See LICENSE file for copyright and license details. */
#include <X11/XF86keysym.h>
/* appearance */
static const unsigned int borderpx = 0; /* border pixel of windows */
static const unsigned int snap = 32; /* snap pixel */
static const unsigned int systraypinning = 0; /* 0: sloppy systray follows selected monitor, >0: pin systray to monitor X */
static const unsigned int systrayspacing = 2; /* systray spacing */
static const int systraypinningfailfirst = 1; /* 1: if pinning fails, display systray on the first monitor, False: display systray on the last monitor*/
static const int showsystray = 1; /* 0 means no systray */
static const int showbar = 1; /* 0 means no bar */
static const int topbar = 1; /* 0 means bottom bar */
static const char *fonts[] = { "terminus:size=10" };
static const char dmenufont[] = "terminus:size=10";
static const char col_gray1[] = "#222222";
static const char col_gray2[] = "#444444";
static const char col_gray3[] = "#bbbbbb";
static const char col_gray4[] = "#eeeeee";
static const char col_cyan[] = "#005577";
static const char *colors[][3] = {
/* fg bg border */
[SchemeNorm] = { col_gray3, col_gray1, col_gray2 },
[SchemeSel] = { col_gray4, col_cyan, col_cyan },
};
/* False means using the scroll wheel on a window will not change focus */
static const Bool focusonwheelscroll = False;
/* tagging */
static const char *tags[] = { "W1", "D2", "M3", "F4", "5", "6", "M7", "E8", "9" };
static const Rule rules[] = {
/* xprop(1):
* WM_CLASS(STRING) = instance, class
* WM_NAME(STRING) = title
*/
/* class instance title tags mask isfloating monitor */
{ "Tilda", NULL, NULL, 0, True, -1 },
{ "Chromium", NULL, NULL, 1, False, -1 },
{ "Thunar", NULL, NULL, 1 << 3, False, -1 },
{ "Thunderbird",NULL, NULL, 1 << 7, False, -1 },
{ "Geany", NULL, NULL, 1 << 1, False, -1 },
{ "MATLAB R2016a - academic use",NULL, NULL, 1 << 1, False, -1 },
{ "Spotify", NULL, NULL, 1 << 6, False, -1 },
{ "Audacious", NULL, NULL, 1 << 6, False, -1 },
{ "QtCreator", NULL, NULL, 1 << 1, False, -1 },
{ "TeXstudio", NULL, NULL, 1 << 1, False, -1 },
{ "Franz", NULL, NULL, 1 << 2, False, -1 },
};
/* layout(s) */
static const float mfact = 0.5; /* factor of master area size [0.05..0.95] */
static const int nmaster = 1; /* number of clients in master area */
static const int resizehints = 0; /* 1 means respect size hints in tiled resizals */
static const Layout layouts[] = {
/* symbol arrange function */
{ "[M]", monocle },
{ "[]=", tile }, /* first entry is default */
{ "><>", NULL }, /* no layout function means floating behavior */
};
/* custom functions declarations */
static void rotatewindows(const Arg *arg);
static void tag_view(const Arg *arg);
/* key definitions */
#define MODKEY Mod1Mask
#define TAGKEYS(KEY,TAG) \
{ MODKEY, KEY, view, {.ui = 1 << TAG} }, \
{ MODKEY|ControlMask, KEY, toggleview, {.ui = 1 << TAG} }, \
{ MODKEY|ShiftMask, KEY, tag_view, {.ui = 1 << TAG} }, \
{ MODKEY|ControlMask|ShiftMask, KEY, toggletag, {.ui = 1 << TAG} },
/* helper for spawning shell commands in the pre dwm-5.0 fashion */
#define SHCMD(cmd) { .v = (const char*[]){ "/bin/sh", "-c", cmd, NULL } }
/* commands */
static char dmenumon[2] = "0"; /* component of dmenucmd, manipulated in spawn() */
static const char *dmenucmd[] = { "dmenu_run", "-m", dmenumon, "-fn", dmenufont, "-nb", col_gray1, "-nf", col_gray3, "-sb", col_cyan, "-sf", col_gray4, NULL };
static const char *termcmd[] = { "st", NULL };
static const char *browsercmd[] = { "chromium", NULL };
static const char *mailcmd[] = { "thunderbird", NULL };
static const char *messagecmd[] = { "franz-bin", NULL };
static const char *filecmd[] = { "thunar", NULL };
static const char *spotifycmd[] = { "spotify", NULL };
static const char *calcmd[] = { "gsimplecal_de", NULL };
static const char *taskcmd[] = { "st", "-e", "htop", NULL };
static const char *runcmd[] = { "gmrun", NULL };
static const char *lockcmd[] = { "slock", NULL };
static const char *killcmd[] = { "xkill", NULL };
static const char *sleepcmd[] = { "sleep_custom", NULL };
static const char *mediastopcmd[] = { "mediakeyscript", "stop", NULL };
static const char *mediaplaycmd[] = { "mediakeyscript", "playpause", NULL };
static const char *medianextcmd[] = { "mediakeyscript", "next", NULL };
static const char *mediaprevcmd[] = { "mediakeyscript", "prev", NULL };
static const char *audiotoggle[] = { "pacon_custom", "togglemute", NULL };
static const char *audioplus[] = { "pacon_custom", "plus", NULL };
static const char *audiominus[] = { "pacon_custom", "minus", NULL };
//static const char *setmonitor[] = { "setmonitor", "rotate", NULL };
static const char *wallpaper[] = { "changewallpaper", "random", NULL };
static const char *screenshotcmd[] = { "tscreenshot", NULL };
static Key keys[] = {
/* modifier key function argument */
{ MODKEY, XK_p, spawn, {.v = dmenucmd } },
{ MODKEY|ShiftMask, XK_Return, spawn, {.v = termcmd } },
//starter
{ Mod4Mask, XK_w, spawn, {.v = browsercmd } },
{ Mod4Mask, XK_f, spawn, {.v = filecmd } },
{ Mod4Mask, XK_t, spawn, {.v = termcmd } },
{ Mod4Mask, XK_m, spawn, {.v = mailcmd } },
{ Mod4Mask, XK_c, spawn, {.v = messagecmd } },
{ Mod4Mask, XK_s, spawn, {.v = spotifycmd } },
{ Mod4Mask, XK_l, spawn, {.v = lockcmd } },
{ Mod4Mask, XK_k, spawn, {.v = killcmd } },
{ Mod1Mask, XK_F2, spawn, {.v = runcmd } },
{ Mod4Mask, XK_r, spawn, {.v = wallpaper } },
{ ControlMask|Mod1Mask, XK_Delete, spawn, {.v = taskcmd } },
{ Mod1Mask, XK_F4, killclient, {0} },
//direct XF86
{ 0, XF86XK_Sleep, spawn, {.v = sleepcmd } },
{ 0, XF86XK_AudioStop, spawn, {.v = mediastopcmd } },
{ 0, XF86XK_AudioPlay, spawn, {.v = mediaplaycmd } },
{ 0, XF86XK_AudioNext, spawn, {.v = medianextcmd } },
{ 0, XF86XK_AudioPrev, spawn, {.v = mediaprevcmd } },
{ 0, XF86XK_AudioMute, spawn, {.v = audiotoggle } },
{ 0, XF86XK_AudioRaiseVolume, spawn, {.v = audioplus } },
{ 0, XF86XK_AudioLowerVolume, spawn, {.v = audiominus } },
// { 0, XF86XK_Display, spawn, {.v = setmonitor } },
{ 0, XK_Print, spawn, {.v = screenshotcmd } },
{ MODKEY, XK_b, togglebar, {0} },
{ MODKEY, XK_j, focusstack, {.i = +1 } },
{ MODKEY, XK_k, focusstack, {.i = -1 } },
{ MODKEY, XK_i, incnmaster, {.i = +1 } },
{ MODKEY, XK_d, incnmaster, {.i = -1 } },
{ MODKEY, XK_h, setmfact, {.f = -0.05} },
{ MODKEY, XK_l, setmfact, {.f = +0.05} },
{ MODKEY, XK_Return, zoom, {0} },
//{ MODKEY, XK_Tab, view, {0} },
{ MODKEY, XK_Tab, rotatewindows, {0} },
{ MODKEY|ShiftMask, XK_c, killclient, {0} },
{ MODKEY, XK_m, setlayout, {.v = &layouts[0]} },
{ MODKEY, XK_t, setlayout, {.v = &layouts[1]} },
{ MODKEY, XK_f, setlayout, {.v = &layouts[2]} },
{ MODKEY, XK_space, setlayout, {0} },
{ MODKEY|ShiftMask, XK_space, togglefloating, {0} },
{ MODKEY, XK_0, view, {.ui = ~0 } },
{ MODKEY|ShiftMask, XK_0, tag, {.ui = ~0 } },
{ MODKEY, XK_comma, focusmon, {.i = -1 } },
{ MODKEY, XK_period, focusmon, {.i = +1 } },
{ MODKEY|ShiftMask, XK_comma, tagmon, {.i = -1 } },
{ MODKEY|ShiftMask, XK_period, tagmon, {.i = +1 } },
TAGKEYS( XK_1, 0)
TAGKEYS( XK_2, 1)
TAGKEYS( XK_3, 2)
TAGKEYS( XK_4, 3)
TAGKEYS( XK_5, 4)
TAGKEYS( XK_6, 5)
TAGKEYS( XK_7, 6)
TAGKEYS( XK_8, 7)
TAGKEYS( XK_9, 8)
{ MODKEY|ShiftMask, XK_q, quit, {0} },
};
/* button definitions */
/* click can be ClkLtSymbol, ClkStatusText, ClkWinTitle, ClkClientWin, or ClkRootWin */
static Button buttons[] = {
/* click event mask button function argument */
{ ClkLtSymbol, 0, Button1, setlayout, {0} },
{ ClkLtSymbol, 0, Button3, setlayout, {.v = &layouts[2]} },
{ ClkWinTitle, 0, Button2, zoom, {0} },
{ ClkStatusText, 0, Button2, spawn, {.v = calcmd } },
{ ClkClientWin, MODKEY, Button1, movemouse, {0} },
{ ClkClientWin, MODKEY, Button2, togglefloating, {0} },
{ ClkClientWin, MODKEY, Button3, resizemouse, {0} },
{ ClkTagBar, 0, Button1, view, {0} },
{ ClkTagBar, 0, Button3, toggleview, {0} },
{ ClkTagBar, MODKEY, Button1, tag, {0} },
{ ClkTagBar, MODKEY, Button3, toggletag, {0} },
};
/* custom functions */
void
rotatewindows(const Arg *arg) {
Arg arg1;
arg1.i = -1;
focusstack(&arg1);
if(selmon->lt[selmon->sellt] != &layouts[2])
zoom(0);
}
void
tag_view(const Arg *arg)
{
if (selmon->sel && arg->ui & TAGMASK) {
selmon->sel->tags = arg->ui & TAGMASK;
focus(NULL);
arrange(selmon);
view(arg);
}
}
|
#
# Copyright (c) 2020 Seagate Technology LLC and/or its Affiliates
#
# 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.
#
# For any questions about this software or licensing,
# please email opensource@seagate.com or cortx-questions@seagate.com.
#
#!/bin/sh -e
# Script to start S3 server in dev environment.
# Usage: sudo ./dev-starts3-noauth.sh [<Number of S3 sever instances>]
# Optional argument is:
# Number of S3 server instances to start.
# Max number of instances allowed = 20
# Default number of instances = 1
MAX_S3_INSTANCES_NUM=20
if [ $# -gt 1 ]
then
echo "Invalid number of arguments passed to the script"
echo "Usage: sudo ./dev-starts3-noauth.sh [<Number of S3 server instances>]"
exit 1
fi
set +e
tmp=$(systemctl status rsyslog)
res=$?
if [ "$res" -eq "4" ]
then
echo "Rsyslog service not found. Exiting..."
exit -1
fi
if [ "$res" -ne "0" ]
then
echo "Starting Rsyslog..."
tmp=$(systemctl start rsyslog)
res=$?
if [ "$res" -ne "0" ]
then
echo "Rsyslog service start failed. Exiting..."
exit -1
fi
fi
echo "rsyslog started"
set -e
num_instances=1
if [ $# -eq 1 ]
then
if [[ $1 =~ ^[0-9]+$ ]] && [ $1 -le $MAX_S3_INSTANCES_NUM ]
then
num_instances=$1
else
echo "Invalid argument [$1], needs to be an integer <= $MAX_S3_INSTANCES_NUM"
exit 1
fi
fi
set -x
export LD_LIBRARY_PATH="$(pwd)/third_party/motr/motr/.libs/:"\
"$(pwd)/third_party/motr/helpers/.libs/:"\
"$(pwd)/third_party/motr/extra-libs/gf-complete/src/.libs/"
# Get local address
modprobe lnet
lctl network up &>> /dev/null
local_nid=`lctl list_nids | head -1`
local_ep=$local_nid:12345:33
ha_ep=$local_nid:12345:34:1
# Ensure default working dir is present
s3_working_dir="/var/seagate/s3/"
mkdir -p $s3_working_dir
s3_log_dir="/var/log/cortx/s3/"
mkdir -p $s3_log_dir
# Start the s3server
export PATH=$PATH:/opt/seagate/cortx/s3/bin
counter=1
while [[ $counter -le $num_instances ]]
do
motr_local_port=`expr 100 + $counter`
s3port=`expr 8080 + $counter`
pid_filename='/var/run/s3server.'$s3port'.pid'
echo "Starting S3Server in authentication disabled mode.."
s3server --s3pidfile $pid_filename \
--motrlocal $local_ep:${motr_local_port} --motrha $ha_ep \
--s3port $s3port --fault_injection true --disable_auth true
((counter++))
done
|
import time
class Stopwatch:
def __init__(self):
self._is_running = False
self._start_time = 0
self._elapsed_time = 0
def start(self):
if not self._is_running:
self._is_running = True
self._start_time = time.time()
def stop(self):
if self._is_running:
self._is_running = False
self._elapsed_time += time.time() - self._start_time
def reset(self):
self._is_running = False
self._start_time = 0
self._elapsed_time = 0
def elapsed_time(self):
if self._is_running:
return self._elapsed_time + (time.time() - self._start_time)
else:
return self._elapsed_time
|
class Card():
def __init__(self, suite, rank, value):
self.suite = suite
self.rank = rank
self.value = value
def get_value(self):
return self.value
card = Card(suite='diamonds', rank='ace', value=11)
print(card.get_value())
|
package ru.skarpushin.swingpm.bindings;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import javax.swing.JToggleButton;
import org.apache.log4j.Logger;
import ru.skarpushin.swingpm.modelprops.ModelPropertyAccessor;
import ru.skarpushin.swingpm.tools.SwingPmSettings;
public class ToggleButtonBinding implements Binding {
private static Logger log = Logger.getLogger(ToggleButtonBinding.class);
private JToggleButton toggleButton;
private ModelPropertyAccessor<Boolean> booleanProperty;
public ToggleButtonBinding(ModelPropertyAccessor<Boolean> booleanProperty, JToggleButton toggleButton) {
this.booleanProperty = booleanProperty;
this.toggleButton = toggleButton;
toggleButton.setSelected(booleanProperty.getValue());
toggleButton.setText(SwingPmSettings.getMessages().get(getActionMessageCode()));
toggleButton.getModel().addItemListener(toggleButtonChangeListener);
booleanProperty.addPropertyChangeListener(propertyChangeListener);
}
private final PropertyChangeListener propertyChangeListener = new PropertyChangeListener() {
@Override
public void propertyChange(PropertyChangeEvent evt) {
log.debug(booleanProperty.getPropertyName() + ": onChange from PM = " + evt.getNewValue());
toggleButton.getModel().setSelected((Boolean) evt.getNewValue());
}
};
private ItemListener toggleButtonChangeListener = new ItemListener() {
@Override
public void itemStateChanged(ItemEvent e) {
boolean isSelected = toggleButton.getModel().isSelected();
log.debug(booleanProperty.getPropertyName() + ": onChanged from UI, stateId = " + isSelected);
booleanProperty.setValue(isSelected);
}
};
private String getActionMessageCode() {
// NOTE: Not sure that this is clean solution. Probably we should
// have separate ModelProperty which will explicitly provide check
// box title
String propName = booleanProperty.getPropertyName();
String alternatePropName = "term." + propName;
String actionTitle = SwingPmSettings.getMessages().get(alternatePropName);
if (!actionTitle.equals(alternatePropName)) {
return alternatePropName;
}
actionTitle = SwingPmSettings.getMessages().get(propName);
if (!actionTitle.equals(propName)) {
return propName;
}
log.error("No message code defined for property name: " + propName);
return propName;
}
@Override
public boolean isBound() {
return toggleButton != null;
}
@Override
public void unbind() {
toggleButton.setText("");
toggleButton.getModel().removeItemListener(toggleButtonChangeListener);
booleanProperty.removePropertyChangeListener(propertyChangeListener);
toggleButton = null;
}
}
|
<reponame>petersamokhin/markdown-site
import { Router } from 'express'
import { renderHtmlFromString } from '../utils/kramdown'
import { isLoggedInAndHaveAccess } from '../config/access-configurator'
import codeMirrorConfig from '../config/codemirror-mime-mapping'
import cheerio from 'cheerio'
const router = Router()
export default () => {
router.route('/preview').post(isLoggedInAndHaveAccess, (req, res) => {
renderHtmlFromString(req.body.markdown, (err, html) => {
res.send({
markdown: req.body.markdown,
error: err || undefined,
html: html ? prettifyHtml(html) : undefined
})
})
})
return router
}
function prettifyHtml (html) {
let $ = cheerio.load(html)
/* Add code highlight by codemirror */
$('code').each((i, el) => {
let element = $(el)
let c = element.attr('class') ? element.attr('class').replace('language-', '') : ''
let datalang = codeMirrorConfig.mimeMap[c]
element.attr('data-lang', datalang)
element.addClass('code _highlighted')
})
/* Fix cyrillic header ids for links */
let h = []
const hs = $('h1,h2,h3,h4,h5,h6')
const cyrillicPattern = /[\u0400-\u04FF]/
hs.each((i, item) => {
if (cyrillicPattern.test($(item).text())) {
$(item).attr('id', 'header-' + i)
}
})
hs.each((index, item) => {
return h.push($(item).attr('id'))
})
h = h.map(x => `#${x}`)
/* Make links for headers */
h.forEach(item => {
let el = $(item)
el.append(`<a class="anchor" href="${item}"></a>`)
let ind = el.parent().children().index(el) + 1
let pre = el.parent().children()[ind]
if (pre && pre.name === 'pre') {
el.append(`<a class="ctrlc" onclick="M.toast({html: 'Copied to clipboard', displayLength: 800})"></a>`)
let aEl = el.find('a.ctrlc')
let codeEl = $(pre).find('code')
let dct = el.attr('id') + '-code'
codeEl.attr('id', dct)
aEl.attr('data-clipboard-target', '#' + dct)
}
})
return $.html()
}
|
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="WebForm1.aspx.cs" Inherits="WebApplication1.WebForm1" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
<script type="text/javascript">
var interval;
function startTime() {
interval = setInterval(displayTime, 1000);
}
function displayTime() {
var div = document.getElementById("dvTime");
div.innerHTML = Date().toString();
}
window.onload = startTime;
</script>
</head>
<body>
<form id="form1" runat="server">
<div id="dvTime" style="margin-left:30%;padding-top:100px;font-size:3em;font-weight:bold;" >
</div>
</form>
</body>
</html>
|
/* printf( const char *, ... )
This file is part of the Public Domain C Library (PDCLib).
Permission is granted to use, modify, and / or redistribute at will.
*/
#include <stdio.h>
#include <stdarg.h>
int printf( const char * restrict format, ... )
{
int rc;
va_list ap;
va_start( ap, format );
rc = vfprintf( stdout, format, ap );
va_end( ap );
return rc;
}
|
append_path_if_exists() {
if [[ -d $1 ]]
then
export PATH="$PATH:$1"
return 0
else
return 1
fi
}
prepend_path_if_exists() {
if [[ -d $1 ]]
then
export PATH="$1:$PATH"
return 0
else
return 1
fi
}
|
<gh_stars>1-10
#include "BMP.h"
#include <cassert>
#include "../../File/FileStream.h"
#include "../../Math/Math.h"
BF::BMP::BMP()
{
Type = BMPType::UnkownOrInavlid;
InfoHeaderType = BMPInfoHeaderType::UnkownOrInvalid;
PixelDataSize = 0;
PixelData = 0;
}
BF::BMP::~BMP()
{
free(PixelData);
}
BF::FileActionResult BF::BMP::Load(const wchar_t* filePath)
{
FileStream file;
FileActionResult FileActionResult = file.ReadFromDisk(filePath);
if (FileActionResult != FileActionResult::Successful)
{
return FileActionResult;
}
//---[ Parsing Header ]----------------------------------------------------
{
Byte type[2];
unsigned int sizeOfFile = 0;
unsigned int reservedBlock = 0;
unsigned int dataOffset = 0;
file.Read(type, 2u);
file.Read(sizeOfFile, Endian::Little);
file.Read(reservedBlock, Endian::Little);
file.Read(dataOffset, Endian::Little);
Type = ConvertBMPType(type);
}
//-------------------------------------------------------------------------
//---[ DIP ]---------------------------------------------------------------
{
file.Read(InfoHeader.HeaderSize, Endian::Little);
InfoHeaderType = ConvertBMPInfoHeaderType(InfoHeader.HeaderSize);
switch (InfoHeaderType)
{
case BMPInfoHeaderType::BitMapInfoHeader:
{
file.Read(InfoHeader.Width, Endian::Little);
file.Read(InfoHeader.Height, Endian::Little);
file.Read(InfoHeader.NumberOfColorPlanes, Endian::Little);
file.Read(InfoHeader.NumberOfBitsPerPixel, Endian::Little);
file.Read(InfoHeader.CompressionMethod, Endian::Little);
file.Read(InfoHeader.ImageSize, Endian::Little);
file.Read(InfoHeader.HorizontalResolution, Endian::Little);
file.Read(InfoHeader.VerticalResolution, Endian::Little);
file.Read(InfoHeader.NumberOfColorsInTheColorPalette, Endian::Little);
file.Read(InfoHeader.NumberOfImportantColorsUsed, Endian::Little);
break;
}
case BMPInfoHeaderType::OS21XBitMapHeader:
case BMPInfoHeaderType::OS22XBitMapHeader:
{
file.Read((unsigned short&)InfoHeader.Width, Endian::Little);
file.Read((unsigned short&)InfoHeader.Height, Endian::Little);
file.Read(InfoHeader.NumberOfColorPlanes, Endian::Little);
file.Read(InfoHeader.NumberOfBitsPerPixel, Endian::Little);
if (InfoHeaderType == BMPInfoHeaderType::OS22XBitMapHeader)
{
unsigned short paddingBytes = 0; // Padding.Ignored and should be zero
file.Read(InfoHeader.HorizontalandVerticalResolutions, Endian::Little);
file.Read(paddingBytes, Endian::Little);
file.Read(InfoHeader.DirectionOfBits, Endian::Little);
file.Read(InfoHeader.halftoningAlgorithm, Endian::Little);
file.Read(InfoHeader.HalftoningParameterA, Endian::Little);
file.Read(InfoHeader.HalftoningParameterB, Endian::Little);
file.Read(InfoHeader.ColorEncoding, Endian::Little);
file.Read(InfoHeader.ApplicationDefinedByte, Endian::Little);
}
break;
}
default:
{
// Unkown Header
return FileActionResult::FormatNotSupported;
}
}
}
//-----------------------------------------------------------
PixelDataSize = InfoHeader.Width * InfoHeader.Height * (InfoHeader.NumberOfBitsPerPixel / 8);
PixelData = (Byte*)malloc(PixelDataSize * sizeof(Byte));
//---[ Pixel Data ]--------------------------------------------------------
size_t dataRowSize = InfoHeader.Width * (InfoHeader.NumberOfBitsPerPixel / 8);
size_t fullRowSize = Math::Floor((InfoHeader.NumberOfBitsPerPixel * InfoHeader.Width + 31) / 32.0f) * 4;
size_t padding = Math::Absolute((int)fullRowSize - (int)dataRowSize);
size_t amountOfRows = PixelDataSize / fullRowSize;
size_t pixelDataOffset = 0;
while (amountOfRows-- > 0)
{
assert(pixelDataOffset <= PixelDataSize);
file.Read(PixelData + pixelDataOffset, dataRowSize);
pixelDataOffset += dataRowSize;
file.DataCursorPosition += padding; // Move data, row + padding(padding can be 0)
}
return FileActionResult::Successful;
}
BF::FileActionResult BF::BMP::Save(const wchar_t* filePath)
{
unsigned int fileSize = InfoHeader.Width * InfoHeader.Height * 3 + 54u;
FileStream file(fileSize);
file.Write("BM", 2u);
file.Write(fileSize, Endian::Little);
file.Write(0u, Endian::Little);
file.Write(54u, Endian::Little);
//------<Windows-Header>-----------
file.Write(InfoHeader.HeaderSize, Endian::Little);
file.Write(InfoHeader.Width, Endian::Little);
file.Write(InfoHeader.Height, Endian::Little);
file.Write(InfoHeader.NumberOfColorPlanes, Endian::Little);
file.Write(InfoHeader.NumberOfBitsPerPixel, Endian::Little);
file.Write(InfoHeader.CompressionMethod, Endian::Little);
file.Write(InfoHeader.ImageSize, Endian::Little);
file.Write(InfoHeader.HorizontalResolution, Endian::Little);
file.Write(InfoHeader.VerticalResolution, Endian::Little);
file.Write(InfoHeader.NumberOfColorsInTheColorPalette, Endian::Little);
file.Write(InfoHeader.NumberOfImportantColorsUsed, Endian::Little);
file.Write(PixelData, PixelDataSize);
file.WriteToDisk(filePath);
return FileActionResult::Successful;
}
BF::FileActionResult BF::BMP::ConvertFrom(Image& image)
{
PixelData = (unsigned char*)malloc(image.PixelDataSize);
if (!PixelData)
{
return FileActionResult::OutOfMemory;
}
PixelDataSize = image.PixelDataSize;
InfoHeader.Width = image.Width;
InfoHeader.Height = image.Height;
InfoHeader.ImageSize = PixelDataSize;
memcpy(PixelData, image.PixelData, PixelDataSize);
return FileActionResult::Successful;
}
BF::FileActionResult BF::BMP::ConvertTo(Image& image)
{
unsigned char* pixelData = (unsigned char*)malloc(PixelDataSize * sizeof(unsigned char));
if (!pixelData)
{
return FileActionResult::OutOfMemory;
}
image.Format = ImageDataFormat::BGR;
image.Height = InfoHeader.Height;
image.Width = InfoHeader.Width;
image.PixelDataSize = PixelDataSize;
image.PixelData = pixelData;
memcpy(image.PixelData, PixelData, image.PixelDataSize);
//image.FlipHorizontal(); ??
//image.RemoveColor(0,0,0);
return FileActionResult::Successful;
}
BF::FileActionResult BF::BMP::ConvertTo(Image& image, BMP& alphaMap)
{
size_t pixelDataSize = (PixelDataSize / 3) * 4;
unsigned char* pixelData = (unsigned char*)malloc(pixelDataSize * sizeof(unsigned char));
if (!pixelData)
{
return FileActionResult::OutOfMemory;
}
image.Format = ImageDataFormat::BGRA;
image.Height = InfoHeader.Height;
image.Width = InfoHeader.Width;
image.PixelDataSize = pixelDataSize;
image.PixelData = pixelData;
size_t imageDataIndex = 0;
size_t alphaDataIndex = 0;
for (size_t i = 0; i < pixelDataSize; )
{
unsigned char blue = PixelData[imageDataIndex++];
unsigned char green = PixelData[imageDataIndex++];
unsigned char red = PixelData[imageDataIndex++];
unsigned char alpha = alphaMap.PixelData[alphaDataIndex++];
bool isTansparanetColor = blue == 0xFF && green == 0xFF && red == 0xFF;
pixelData[i++] = blue;
pixelData[i++] = green;
pixelData[i++] = red;
pixelData[i++] = isTansparanetColor ? 0x00 : 0xFF;
}
image.FlipHorizontal();
return FileActionResult::Successful;
}
|
<reponame>shermainelim/QuizReactNativeAWS<gh_stars>0
import React, { useState } from "react";
import { View, Text, TextInput, Button, TouchableOpacity } from "react-native";
import { MaterialCommunityIcons } from "@expo/vector-icons";
interface Props {
setPlayerName: (e: string) => void;
}
const Player: React.FC<Props> = ({ setPlayerName }) => {
const [text, setText] = useState("");
return (
<View style={{ alignItems: "center" }}>
<Text style={{ fontSize: 24 }}>Player Name</Text>
<View style={{ flexDirection: "row", margin: 20 }}>
<TextInput
style={{ borderWidth: 1, borderColor: "black", width: "50%" }}
placeholder="Input Player Name"
onChangeText={(text) => setText(text)}
value={text}
/>
<TouchableOpacity
disabled={text.length === 0 ? true : false}
onPress={() => {
setText("");
}}
>
<MaterialCommunityIcons
style={{ marginLeft: 25 }}
name="backspace-outline"
size={24}
color={text.length === 0 ? "grey" : "black"}
/>
</TouchableOpacity>
</View>
<View>
<Button
title="Start"
color="green"
onPress={() => setPlayerName(text)}
/>
</View>
</View>
);
};
export default Player;
|
#include<iostream>
int findSmallestElement(int arr[], int n){
int smallest = arr[0]; // assume arr[0] is the smallest
for(int i=0; i < n; i++){
if(arr[i] < smallest){
smallest = arr[i];
}
}
return smallest;
}
int main()
{
int arr[] = {10, 20, 15, 0, 17};
int n = sizeof(arr)/sizeof(arr[0]);
std::cout << "Smallest element: " << findSmallestElement(arr, n);
return 0;
}
|
# https://blackfire.io/docs/up-and-running/installation?action=install&mode=full&location=local&os=debian&language=php&agent=f6f50a71-079e-463b-a2f8-04abd913f50e
|
#!/usr/bin/env python3
import numpy as np
import tensorflow as tf
class Network:
HEIGHT, WIDTH = 28, 28
def __init__(self, threads, seed=42):
# Create an empty graph and a session
graph = tf.Graph()
graph.seed = seed
self.session = tf.Session(graph = graph, config=tf.ConfigProto(inter_op_parallelism_threads=threads,
intra_op_parallelism_threads=threads))
def construct(self, args):
self.z_dim = args.z_dim
with self.session.graph.as_default():
if args.recodex:
tf.get_variable_scope().set_initializer(tf.glorot_uniform_initializer(seed=42))
# Inputs
self.images = tf.placeholder(tf.float32, [None, self.HEIGHT, self.WIDTH, 1])
# Encoder
def encoder(image):
# Define an encoder as a sequence of:
# - flattening layer
# - dense layer with 500 neurons and ReLU activation
# - dense layer with 500 neurons and ReLU activation
#
# Using the last hidden layer output, produce two vectors of size self.z_dim,
# using two dense layers without activation, the first being `z_mean` and the second
# `z_log_variance`.
x = tf.layers.flatten(image)
x = tf.layers.dense(x, 500, activation=tf.nn.relu)
x = tf.layers.dense(x, 500, activation=tf.nn.relu)
z_mean = tf.layers.dense(x, self.z_dim)
z_log_variance = tf.layers.dense(x, self.z_dim)
return z_mean, z_log_variance
z_mean, z_log_variance = encoder(self.images)
# Compute `z_sd` as a standard deviation from `z_log_variance`, by passing
# `z_log_variance` / 2 to an exponential function.
z_sd = tf.exp(z_log_variance / 2)
# Compute `epsilon` as a random normal noise, with a shape of `z_mean`.
epsilon = tf.random_normal(tf.shape(z_mean), dtype=tf.float32)
# Compute `self.z` by drawing from normal distribution with
# mean `z_mean` and standard deviation `z_sd` (utilizing the `epsilon` noise).
self.z = z_mean + z_sd * epsilon
# Decoder
def decoder(z):
# Define a decoder as a sequence of:
# - dense layer with 500 neurons and ReLU activation
# - dense layer with 500 neurons and ReLU activation
# - dense layer with as many neurons as there are pixels in an image
#
# Consider the output of the last hidden layer to be the logits of
# individual pixels. Reshape them into a correct shape for a grayscale
# image of size self.WIDTH x self.HEIGHT and return them.
x = tf.layers.dense(z, 500, activation=tf.nn.relu)
x = tf.layers.dense(x, 500, activation=tf.nn.relu)
x = tf.layers.dense(x, self.HEIGHT * self.WIDTH)
return tf.reshape(x, [-1, self.HEIGHT, self.WIDTH, 1])
generated_logits = decoder(self.z)
# Define `self.generated_images` as generated_logits passed through a sigmoid.
self.generated_images = tf.sigmoid(generated_logits)
# Loss and training
# Define `reconstruction_loss` as a sigmoid cross entropy
# loss of `self.images` and `generated_logits`.
reconstruction_loss = tf.losses.sigmoid_cross_entropy(self.images, generated_logits)
# Define `latent_loss` as a mean of KL-divergences of normal distributions
# N(z_mean, z_sd) and N(0, 1), utilizing `tf.distributions.kl_divergence`
# and `tf.distributions.Normal`.
latent_loss = tf.reduce_mean(tf.distributions.kl_divergence(tf.distributions.Normal(z_mean, z_sd),
tf.distributions.Normal(0., 1.)))
# Define `self.loss` as a weighted combination of
# reconstruction_loss (weight is the number of pixels in an image)
# and latent_loss (weight is the dimensionality of the latent variable z).
self.loss = (self.HEIGHT * self.WIDTH) * reconstruction_loss + self.z_dim * latent_loss
global_step = tf.train.create_global_step()
self.training = tf.train.AdamOptimizer().minimize(self.loss, global_step=global_step, name="training")
# Summaries
summary_writer = tf.contrib.summary.create_file_writer(args.logdir, flush_millis=10 * 1000)
with summary_writer.as_default(), tf.contrib.summary.record_summaries_every_n_global_steps(100):
self.summaries = [tf.contrib.summary.scalar("vae/loss", self.loss),
tf.contrib.summary.scalar("vae/reconstruction_loss", reconstruction_loss),
tf.contrib.summary.scalar("vae/latent_loss", latent_loss)]
self.generated_image_data = tf.placeholder(tf.float32, [None, None, 1])
with summary_writer.as_default(), tf.contrib.summary.always_record_summaries():
self.generated_image_summary = tf.contrib.summary.image("vae/generated_image",
tf.expand_dims(self.generated_image_data, axis=0))
# Initialize variables
self.session.run(tf.global_variables_initializer())
with summary_writer.as_default():
tf.contrib.summary.initialize(session=self.session, graph=self.session.graph)
def train(self, images):
return self.session.run([self.training, self.summaries, self.loss], {self.images: images})[-1]
def generate(self):
GRID = 20
def sample_z(batch_size):
return np.random.normal(size=[batch_size, self.z_dim])
# Generate GRIDxGRID images
random_images = self.session.run(self.generated_images, {self.z: sample_z(GRID * GRID)})
# Generate GRIDxGRID interpolated images
if self.z_dim == 2:
# Use 2D grid for sampled Z
starts = np.stack([-2 * np.ones(GRID), np.linspace(-2, 2, GRID)], -1)
ends = np.stack([2 * np.ones(GRID), np.linspace(-2, 2, GRID)], -1)
else:
# Generate random Z
starts, ends = sample_z(GRID), sample_z(GRID)
interpolated_z = []
for i in range(GRID):
interpolated_z.extend(starts[i] + (ends[i] - starts[i]) * np.expand_dims(np.linspace(0, 1, GRID), -1))
interpolated_images = self.session.run(self.generated_images, {self.z: interpolated_z})
# Stack the random images, then an empty row, and finally interpolated imates
image = np.concatenate(
[np.concatenate(list(images), axis=1) for images in np.split(random_images, GRID)] +
[np.zeros([self.HEIGHT, self.WIDTH * GRID, 1])] +
[np.concatenate(list(images), axis=1) for images in np.split(interpolated_images, GRID)], axis=0)
self.session.run(self.generated_image_summary, {self.generated_image_data: image})
if __name__ == "__main__":
import argparse
import datetime
import os
import re
# Fix random seed
np.random.seed(42)
# Parse arguments
parser = argparse.ArgumentParser()
parser.add_argument("--batch_size", default=50, type=int, help="Batch size.")
parser.add_argument("--dataset", default="mnist-data", type=str, help="Dataset [fasion|cifar-cars|mnist-data].")
parser.add_argument("--epochs", default=100, type=int, help="Number of epochs.")
parser.add_argument("--recodex", default=False, action="store_true", help="ReCodEx mode.")
parser.add_argument("--recodex_validation_size", default=None, type=int, help="Validation size in ReCodEx mode.")
parser.add_argument("--threads", default=1, type=int, help="Maximum number of threads to use.")
parser.add_argument("--z_dim", default=100, type=int, help="Dimension of Z.")
args = parser.parse_args()
# Create logdir name
args.logdir = "logs/{}-{}-{}".format(
os.path.basename(__file__),
datetime.datetime.now().strftime("%Y-%m-%d_%H%M%S"),
",".join(("{}={}".format(re.sub("(.)[^_]*_?", r"\1", key), value) for key, value in sorted(vars(args).items())))
)
if not os.path.exists("logs"): os.mkdir("logs") # TF 1.6 will do this by itself
# Load the data
from tensorflow.examples.tutorials import mnist
if args.recodex:
data = mnist.input_data.read_data_sets(".", reshape=False, validation_size=args.recodex_validation_size, seed=42)
elif args.dataset == "fashion":
data = mnist.input_data.read_data_sets("fashion", reshape=False, validation_size=0, seed=42,
source_url="http://fashion-mnist.s3-website.eu-central-1.amazonaws.com/")
elif args.dataset == "cifar-cars":
data = mnist.input_data.read_data_sets("cifar-cars", reshape=False, validation_size=0, seed=42,
source_url="https://ufal.mff.cuni.cz/~straka/courses/npfl114/1718/cifar-cars/")
else:
data = mnist.input_data.read_data_sets(args.dataset, reshape=False, validation_size=0, seed=42)
# Construct the network
network = Network(threads=args.threads)
network.construct(args)
# Train
for i in range(args.epochs):
loss = 0
while data.train.epochs_completed == i:
images, _ = data.train.next_batch(args.batch_size)
loss += network.train(images)
print("{:.2f}".format(loss))
network.generate()
|
import java.util.Random;
public class GenerateRandom {
public static void main(String[] args) {
Random rand = new Random();
// specify the lower and upper bounds of the range
int lower = 10;
int upper = 100;
// generate random numbers
int random = rand.nextInt(upper - lower) + lower ;
System.out.println(random);
}
}
|
#!/bin/bash
# Set the maximum heap size for the JVM
JAVA_XMX=4G # Example value, can be set according to requirements
# Execute the Java class with specified memory constraints and classpath
java -Xmx$JAVA_XMX -cp index-06.jar org.dbpedia.spotlight.lucene.index.external.utils.SSEUriDecoder $INDEX_CONFIG_FILE > out_SSEUriDecoder.log 2>&1
|
/*
File: Grafic.java ; This file is part of Twister.
Version: 3.0036
Copyright (C) 2012-2013 , Luxoft
Authors: <NAME> <<EMAIL>>
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
import java.awt.FontMetrics;
import javax.swing.JPanel;
import java.awt.Color;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.Rectangle;
import java.awt.Graphics;
import javax.swing.JPopupMenu;
import javax.swing.JMenuItem;
import java.util.ArrayList;
import java.util.Arrays;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import javax.swing.JOptionPane;
import javax.swing.JFrame;
import javax.swing.JButton;
import javax.swing.JLabel;
import java.io.File;
import java.awt.Font;
import javax.swing.JTextField;
import java.io.InputStreamReader;
import java.io.InputStream;
import java.io.BufferedReader;
import javax.swing.JComboBox;
import java.awt.event.KeyListener;
import java.awt.event.WindowAdapter;
import javax.swing.SwingUtilities;
import java.awt.FontMetrics;
import java.awt.dnd.DropTarget;
import javax.swing.tree.TreeNode;
import javax.swing.tree.TreePath;
import java.awt.Dimension;
import javax.swing.filechooser.FileFilter;
import javax.swing.InputMap;
import javax.swing.ComponentInputMap;
import javax.swing.KeyStroke;
import javax.swing.ActionMap;
import javax.swing.plaf.ActionMapUIResource;
import javax.swing.Action;
import javax.swing.AbstractAction;
import javax.swing.JComponent;
import java.awt.Cursor;
import java.awt.dnd.DragSource;
import java.awt.event.KeyEvent;
import java.util.Collections;
import java.awt.event.WindowFocusListener;
import java.awt.event.WindowEvent;
import java.util.Comparator;
import java.awt.event.InputEvent;
import java.awt.event.MouseMotionAdapter;
import javax.swing.JFileChooser;
import javax.swing.BoxLayout;
import java.awt.BorderLayout;
import com.twister.Item;
import javax.swing.JList;
import javax.swing.JScrollPane;
import com.twister.CustomDialog;
import com.twister.Configuration;
import java.util.HashMap;
import java.util.Set;
import java.util.Iterator;
import java.io.BufferedWriter;
import java.io.FileWriter;
import javax.swing.DefaultComboBoxModel;
import javax.swing.tree.DefaultMutableTreeNode;
import javax.swing.GroupLayout;
import javax.swing.LayoutStyle;
import javax.swing.tree.DefaultTreeCellRenderer;
public class Grafic extends JPanel{
private static final long serialVersionUID = 1L;
private ArrayList <Integer> selected;
public ArrayList <int []> selectedcollection = new ArrayList<int []>();
private byte keypress;
private JPopupMenu p = new JPopupMenu();
private boolean foundfirstitem;
private int y = 5;
private String user;
private boolean dragging=false;
private ArrayList<Item>clone = new ArrayList<Item>();
private int dragammount = 0;
private boolean clearedSelection = false;
private boolean dragscroll = true;
private boolean scrolldown = false;
private boolean scrollup = false;
private int[] line = {-1,-1,-1,-1,-1};
private boolean canrequestfocus = true;
private int xStart, yStart;
private boolean onlyOptionals;
public Grafic(TreeDropTargetListener tdtl, String user){
this.user=user;
setFocusable(true);
if(!user.equals("")){
RunnerRepository.window.mainpanel.setTitleAt(0,
(user.split("\\\\")[user.split("\\\\").length-1]).split("\\.")[0]);}
add(p);
DropTarget dropTarget = new DropTarget(this, tdtl);
new Thread(){
public void run(){
automaticScroll();}}.start();
addMouseMotionListener(new MouseMotionAdapter(){
public void mouseDragged(MouseEvent ev){
if(!onlyOptionals){
mouseIsDragged(ev);}}});
addMouseListener(new MouseAdapter(){
public void mousePressed(MouseEvent ev){}
public void mouseEntered(MouseEvent ev){
if(canrequestfocus)new Thread(){
public void run(){
try{Thread.sleep(300);
Grafic.this.requestFocus();}
catch(Exception e){e.printStackTrace();}}}.start();
dragscroll = true;}
public void mouseExited(MouseEvent ev){
dragscroll = false;
keypress = 0;}
public void mouseReleased(MouseEvent ev){
mouseIsReleased(ev);}});
addKeyListener(new KeyListener(){
public void keyPressed(KeyEvent ev){
if(ev.getKeyCode()==KeyEvent.VK_SHIFT){keypress=1;}
if(ev.getKeyCode()==KeyEvent.VK_CONTROL){keypress=2;}
if(ev.getKeyCode()==KeyEvent.VK_DELETE){removeSelected();}
if(ev.getKeyCode()==KeyEvent.VK_UP){keyUpPressed();}
if(ev.getKeyCode()==KeyEvent.VK_DOWN){keyDownPressed();}}
public void keyReleased(KeyEvent ev){
if(ev.getKeyCode()!=KeyEvent.VK_UP&&ev.getKeyCode()!=KeyEvent.VK_DOWN){
if(ev.getKeyCode()!=KeyEvent.VK_SHIFT)clearedSelection=false;
keypress=0;}}
public void keyTyped(KeyEvent ev){}});}
/*
* handle up down press
*/
public void keyDownPressed(){
ArrayList <Integer> temp = new ArrayList <Integer>();
int last = selectedcollection.size()-1;
if(last<0)return;
for(int j=0;j<selectedcollection.get(last).length;j++){
temp.add(new Integer(selectedcollection.get(last)[j]));}
Item next = nextItem(getItem(temp,false));
if(next!=null&&keypress!=2){
if(keypress!=1){
deselectAll();
selectItem(next.getPos());
if(next.getType()==2&&next.getPos().size()==1){
int userDefNr = next.getUserDefNr();
RunnerRepository.window.mainpanel.p1.suitaDetails.setParent(next);
RunnerRepository.window.mainpanel.p1.testconfigmngmnt.setParent(next);
if(userDefNr!=RunnerRepository.window.mainpanel.p1.suitaDetails.getDefsNr()){
System.out.println("Warning, suite "+next.getName()+
" has "+userDefNr+" fields while in database xml are defined "+
RunnerRepository.window.mainpanel.p1.suitaDetails.getDefsNr()+" fields");}
try{for(int i=0;i<userDefNr;i++){
RunnerRepository.window.mainpanel.p1.suitaDetails.
getDefPanel(i).setDescription(next.getUserDef(i)[1],true);}}
catch(Exception e){e.printStackTrace();}
} else{
RunnerRepository.window.mainpanel.p1.testconfigmngmnt.setParent(next);
RunnerRepository.window.mainpanel.p1.suitaDetails.setParent(next);
if(next.getType()==2)RunnerRepository.window.mainpanel.p1.suitaDetails.setSuiteDetails(false);
else RunnerRepository.window.mainpanel.p1.suitaDetails.setTCDetails();
}}
else{
RunnerRepository.window.mainpanel.p1.suitaDetails.setGlobalDetails();
RunnerRepository.window.mainpanel.p1.suitaDetails.clearDefs();
RunnerRepository.window.mainpanel.p1.suitaDetails.setParent(null);
RunnerRepository.window.mainpanel.p1.testconfigmngmnt.setParent(null);
if(!clearedSelection){
deselectAll();
clearedSelection = true;
selectItem(getItem(temp,false).getPos());}
if(next.isSelected()){
int [] itemselected = selectedcollection.get(selectedcollection.size()-1);
Item theone = RunnerRepository.getSuita(itemselected[0]);
for(int j=1;j<itemselected.length;j++){theone = theone.getSubItem(itemselected[j]);}
theone.select(false);
selectedcollection.remove(selectedcollection.size()-1);}
else selectItem(next.getPos());}
RunnerRepository.window.mainpanel.p1.remove.setEnabled(true);
repaint();}}
/*
* handle up key press
*/
public void keyUpPressed(){
ArrayList <Integer> temp = new ArrayList <Integer>();
int last = selectedcollection.size()-1;
if(last<0)return;
for(int j=0;j<selectedcollection.get(last).length;j++){
temp.add(new Integer(selectedcollection.get(last)[j]));}
Item next = previousItem(getItem(temp,false));
if(next!=null&&keypress!=2){
if(keypress!=1){
deselectAll();
selectItem(next.getPos());
if(next.getType()==2&&next.getPos().size()==1){
int userDefNr = next.getUserDefNr();
RunnerRepository.window.mainpanel.p1.suitaDetails.setParent(next);
RunnerRepository.window.mainpanel.p1.testconfigmngmnt.setParent(next);
if(userDefNr!=RunnerRepository.window.mainpanel.p1.suitaDetails.getDefsNr()){
System.out.println("Warning, suite "+next.getName()+" has "+
userDefNr+" fields while in bd.xml are defined "+
RunnerRepository.window.mainpanel.p1.suitaDetails.getDefsNr()+" fields");}
try{for(int i=0;i<userDefNr;i++){
RunnerRepository.window.mainpanel.p1.suitaDetails.getDefPanel(i).
setDescription(next.getUserDef(i)[1],true);}}
catch(Exception e){e.printStackTrace();}}
else {
RunnerRepository.window.mainpanel.p1.testconfigmngmnt.setParent(next);
RunnerRepository.window.mainpanel.p1.suitaDetails.setParent(next);
if(next.getType()==2)RunnerRepository.window.mainpanel.p1.suitaDetails.setSuiteDetails(false);
else RunnerRepository.window.mainpanel.p1.suitaDetails.setTCDetails();
}
} else{
RunnerRepository.window.mainpanel.p1.suitaDetails.setGlobalDetails();
RunnerRepository.window.mainpanel.p1.suitaDetails.clearDefs();
RunnerRepository.window.mainpanel.p1.suitaDetails.setParent(null);
RunnerRepository.window.mainpanel.p1.testconfigmngmnt.setParent(null);
if(!clearedSelection){
deselectAll();
clearedSelection = true;
selectItem(getItem(temp,false).getPos());}
if(next.isSelected()){
int [] itemselected = selectedcollection.get(selectedcollection.size()-1);
Item theone = RunnerRepository.getSuita(itemselected[0]);
for(int j=1;j<itemselected.length;j++){
theone = theone.getSubItem(itemselected[j]);}
theone.select(false);
selectedcollection.remove(selectedcollection.size()-1);}
else selectItem(next.getPos());}
RunnerRepository.window.mainpanel.p1.remove.setEnabled(true);
repaint();}}
/*
* handles mouse released
*/
public void mouseIsReleased(MouseEvent ev){
clearDraggingLine();
scrolldown = false;
scrollup = false;
RunnerRepository.window.mainpanel.p1.suitaDetails.setGlobalDetails();
RunnerRepository.window.mainpanel.p1.suitaDetails.clearDefs();
RunnerRepository.window.mainpanel.p1.suitaDetails.setParent(null);
RunnerRepository.window.mainpanel.p1.testconfigmngmnt.setParent(null);
dragammount=0;
if(dragging){handleMouseDroped(ev.getY());}
else handleClick(ev);}
/*
* handles mouse dragged
*/
public void mouseIsDragged(MouseEvent ev){
if((ev.getModifiers() & InputEvent.BUTTON1_MASK) != 0){
if(dragging){handleDraggingLine(ev.getX(),ev.getY());}
else{//first time
if(dragammount==0){
xStart = ev.getX();
yStart = ev.getY();}
if(dragammount<3)dragammount++;
else{dragammount=0;
getClickedItem(xStart,yStart);
if(selected.size()>0){
handleDraggedItems();}}}}}
/*
* Dragged items method
* handles dragged items
* and puts them in a clone array
*/
public void handleDraggedItems(){
if(getItem(selected,false).getType()!=0){
setCursor(DragSource.DefaultCopyDrop);
if(!getItem(selected,false).isSelected()){
deselectAll();
int [] temporary = new int[selected.size()];
for(int m=0;m<temporary.length;m++){
temporary[m]=selected.get(m).intValue();}
selectedcollection.add(temporary);}
ArrayList <Integer> temp = new ArrayList <Integer>();
for(int i=selectedcollection.size()-1;i>=0;i--){
for(int j=0;j<selectedcollection.get(i).length;j++){
temp.add(new Integer(selectedcollection.get(i)[j]));}
Item theone2 = getItem(temp,false);
clone.add(theone2);
temp.clear();}
removeSelected();
dragging = true;}
ArrayList<Item> unnecessary = new ArrayList<Item>();//remove from clone children of parents already selected
for(int i=0;i<clone.size();i++){
Item one = clone.get(i);
ArrayList<Integer>pos = (ArrayList<Integer>)one.getPos().clone();
while(pos.size()>1){
pos.remove(pos.size()-1);
boolean found = false;
for(int j=0;j<clone.size();j++){
Item one2 = clone.get(j);
ArrayList<Integer>pos2 = (ArrayList<Integer>)one2.getPos().clone();
if(compareArrays(pos,pos2)){
unnecessary.add(clone.get(i));
found = true;
break;}}
if(found)break;}}
for(int i=0;i<unnecessary.size();i++){clone.remove(unnecessary.get(i));}}
/*
* handle automatic scrolling
*/
public void automaticScroll(){
while(RunnerRepository.run){
if(scrolldown){
int scrollvalue = RunnerRepository.window.mainpanel.p1.sc.pane.
getVerticalScrollBar().getValue();
RunnerRepository.window.mainpanel.p1.sc.pane.
getVerticalScrollBar().setValue(scrollvalue-10);}
else if(scrollup){
int scrollvalue = RunnerRepository.window.mainpanel.p1.sc.pane.
getVerticalScrollBar().getValue();
RunnerRepository.window.mainpanel.p1.sc.pane.
getVerticalScrollBar().setValue(scrollvalue+10);}
try{Thread.sleep(60);}
catch(Exception e){e.printStackTrace();}}}
/*
* clears draggin line from screen
*/
public void clearDraggingLine(){
line[0] = -1;
line[1] = line[0];
line[2] = line[0];
line[3] = line[0];
line[4] = line[0];}
/*
* arrange all items according to
* tear/setup property
*/
public void sortTearSetup(Item i){
int size = i.getSubItemsNr();
ArrayList<Item> pretemp = new ArrayList();
ArrayList<Item> teartemp = new ArrayList();
Item subitem;
for(int j=0;j<size;j++){
subitem = i.getSubItem(j);
if(subitem.isPrerequisite()&&j!=0&&!i.getSubItem(j-1).isPrerequisite()){
for(int k=j;k<size;k++){
if(i.getSubItem(k).isPrerequisite())pretemp.add(i.getSubItem(k));
}
break;
}
}
for(int j=size-1;j>-1;j--){
subitem = i.getSubItem(j);
if(subitem.isTeardown()&&j!=size-1&&!i.getSubItem(j+1).isTeardown()){
for(int k = j;k>-1;k--){
if(i.getSubItem(k).isTeardown())teartemp.add(i.getSubItem(k));
}
break;
}
}
for(Item subitm:pretemp){
i.getSubItems().remove(subitm);
}
for(Item subitm:teartemp){
i.getSubItems().remove(subitm);
}
int arraysize = pretemp.size();
size = i.getSubItemsNr();
for(int j=0;j<size;j++){
if(!i.getSubItem(j).isPrerequisite()){
for(int k=arraysize-1;k>-1;k--){
i.insertSubItem(pretemp.get(k),j);
}
break;
}
if(j==(size-1)){
for(int k=arraysize-1;k>-1;k--){
i.insertSubItem(pretemp.get(k),j);
}
}
}
if(size==0){
for(int k=arraysize-1;k>-1;k--){
i.insertSubItem(pretemp.get(k),0);
}
}
arraysize = teartemp.size();
size = i.getSubItemsNr();
for(int j=size-1;j>-1;j--){
if(!i.getSubItem(j).isTeardown()){
for(int k=arraysize-1;k>-1;k--){
i.insertSubItem(teartemp.get(k),j+1);
}
break;
}
if(j==0){
for(int k=arraysize-1;k>-1;k--){
i.insertSubItem(teartemp.get(k),j+1);
}
}
}
if(size==0){
for(int k=arraysize-1;k>-1;k--){
i.insertSubItem(teartemp.get(k),0);
}
}
size = i.getSubItemsNr();
for(int j=0;j<size;j++){
subitem = i.getSubItem(j);
subitem.updatePos(subitem.getPos().size()-1, new Integer(j));
}
for(Item itm:i.getSubItems()){
if(i.getType()==2)sortTearSetup(itm);
}
}
public void handleMouseDroped(int mouseY){
Collections.sort(clone, new CompareItems());
dragging=false;
setCursor(Cursor.getPredefinedCursor(Cursor.DEFAULT_CURSOR));
int Xpos = 0;
while(Xpos<getWidth()){
getClickedItem(Xpos,mouseY);
Xpos+=5;
if(selected.size()!=0)break;}
if(selected.size()==0){//not inserted in element @@@@@@@@@@@
int y1 = mouseY;
Item upper=null;
while(y1>0){
y1-=5;
for(int x1=0;x1<getWidth();x1+=5){
getClickedItem(x1,y1);
if(selected.size()>0){
upper=getItem(selected,false);
if(upper!=null)break;}
if(upper!=null)break;}}
if(upper!=null){
if(upper.getType()==1){//inserted under tc
int index = upper.getPos().get(upper.getPos().size()-1).intValue();
int position = upper.getPos().size()-1;
ArrayList<Integer> temp = (ArrayList<Integer>)upper.getPos().clone();
if(temp.size()>1)temp.remove(temp.size()-1);
Item parent = getItem(temp,false);
if(parent.getType()==1){
dropOnFirstLevel(upper);} //if upper parent is tc=>is on level 0, will not have parent
else{ //parent is not tc=>is not on level 0, must insert to parent or after parent
if((parent.getSubItemsNr()-1==upper.getPos().get(upper.getPos().size()-1)) &&
!upper.getSubItem(0).isVisible()){//if tc is last in suite
int Y = mouseY;
if(Y<upper.getRectangle().y+upper.getRectangle().getHeight()+5){//Should be inserted in upper parent/next in line
dropNextInLine(upper,parent,index,position);}
else{//Should be inserted after upper parent; exit one level
upper = parent;
position = upper.getPos().size();
int temp1 = upper.getPos().get(position-1);
if(upper.getPos().size()==1){dropOnFirstLevel(upper);}//Suite on level 0
else{dropOnUpperLevel(upper);}}} //Suite with parent suite
else{dropNextInLine(upper, parent, index, position);}}}//tc is not last in suite, make drop after him
else if(upper.getType()==2){//inserted under suite
int Y = mouseY;
if((upper.getSubItemsNr()>0&&upper.getSubItem(0).isVisible())){//suite is expander||has no children,must insert into it
dropFirstInSuita(upper);}//Should be inserted in suita
else if(Y<upper.getRectangle().y+upper.getRectangle().getHeight()+5||//closer to upper half
(Y>upper.getRectangle().y+upper.getRectangle().getHeight()+5&&upper.getPos().size()>1 //farther from 5px half but suite is not last in parent
&&getFirstSuitaParent(upper,false).getSubItemsNr()-1>upper.getPos().get(upper.getPos().size()-1))){//must insert on same row after suite
int position = upper.getPos().size();
int temp1 = upper.getPos().get(position-1);
if(upper.getPos().size()==1){dropOnFirstLevel(upper);}//suite on level 0
else{int index = upper.getPos().get(upper.getPos().size()-1).intValue();//suite not on level 0
position = upper.getPos().size()-1;
ArrayList<Integer> temp = (ArrayList<Integer>)upper.getPos().clone();
if(temp.size()>1)temp.remove(temp.size()-1);
Item parent = getItem(temp,false);
dropNextInLine(upper, parent, index, position);}}
else{//suite is not expanded||has no children&¬ made drop close to it, Should be inserted after suita parent(exit one level)
if(upper.getPos().size()==1) dropOnFirstLevel(upper);//Suite on level 0
else{//Suite not on level 0
if(getFirstSuitaParent(upper,false).getPos().size()>1)
{dropOnUpperLevel(getFirstSuitaParent(upper,false));} //parent of suite not on level 0
else dropOnFirstLevel(getFirstSuitaParent(upper,false));}}} //parent on level 0
else if(upper.getType()==0){
int Y = mouseY;//upper is made parent of this prop and copy methods from drop under tc
Y-=upper.getRectangle().y+upper.getRectangle().getHeight();
ArrayList<Integer> temp = (ArrayList<Integer>)upper.getPos().clone();
temp.remove(temp.size()-1);
Item prop = upper;
upper = getItem(temp,false);
Y+=upper.getRectangle().y+upper.getRectangle().getHeight();
int index = upper.getPos().get(upper.getPos().size()-1).intValue();
int position = upper.getPos().size()-1;
temp = (ArrayList<Integer>)upper.getPos().clone();
if(temp.size()>1)temp.remove(temp.size()-1);
Item parent = getItem(temp,false);
if(parent.getType()==1){dropOnFirstLevel(upper);} //parent on level 0 because it is tc=>will not have paremt
else{ // parent is not tc=>not on level 0, must ad to parent or after parent
if(Grafic.getTcParent(prop,false).getSubItemsNr()-1==prop.getPos().get(prop.getPos().size()-1) &&
parent.getSubItemsNr()-1==upper.getPos().get(upper.getPos().size()-1)){//if prop is last in tc and tc is last in suite
if(Y<upper.getRectangle().y+upper.getRectangle().getHeight()+5){
dropNextInLine(upper, parent, index, position);}//Should be inserted in upper parent
else{//Should be inserted after upper parent
upper = parent;
position = upper.getPos().size();
int temp1 = upper.getPos().get(position-1);
if(upper.getPos().size()==1){dropOnFirstLevel(upper);}//suite on level 0
else{dropOnUpperLevel(upper);}}}//Suita with parent suita
else{dropNextInLine(upper, parent, index, position);}}}}//tc is not last in suite
else{dropFirstElement();}}//upper is null
else{//inserted in element
if(getItem(selected,false).getType()==2){//inserted in suita
dropFirstInSuita(getItem(selected,false));}//first element is not prerequisite, can insert on first level
else if(getItem(selected,false).getType()==1){//inserted in tc
Item item = getItem(selected,false);
boolean up = isUpperHalf(item, mouseY);
if(up){//in upper half of tc, tc is not prerequisite
Item upper = item; //tc the element in witch is made drop
int index = upper.getPos().get(upper.getPos().size()-1).intValue(); //last position value of tc
int position = upper.getPos().size()-1; //what nr is the element is the one from witch made drop
ArrayList<Integer> temp = (ArrayList<Integer>)upper.getPos().clone(); //clone position of the lement in that was made drop
if(temp.size()>1)temp.remove(temp.size()-1); //delete last pos to get parent
Item parent = getItem(temp,false); //upper item parentul
if(parent.getType()==2){dropPreviousInLine(upper,parent,index,position);}
else{
if(upper.getPos().get(0)>0){//must insert before upper, will not be first element
temp = (ArrayList<Integer>)upper.getPos().clone(); //clone position of the lement in that was made drop
temp.set(0,temp.get(0)-1);//the one before him
upper = getItem(temp,false);
dropOnFirstLevel(upper);}
else{dropFirstElement();}}}//will be first element
else{Item upper = item;//under tc
int index = upper.getPos().get(upper.getPos().size()-1).intValue();
int position = upper.getPos().size()-1;
ArrayList<Integer> temp = (ArrayList<Integer>)upper.getPos().clone();
if(temp.size()>1)temp.remove(temp.size()-1);
Item parent = getItem(temp,false);
if(parent.getType()==1)dropOnFirstLevel(upper);//parent is tc=>on level 0
else dropNextInLine(upper, parent, index, position);}}//parent is not tc>can be added in line after parent
else if(getItem(selected,false).getType()==0){//inserted in prop
ArrayList<Integer> temp = (ArrayList<Integer>)getItem(selected,false).getPos().clone();
temp.remove(temp.size()-1);
Item upper = getItem(temp,false);
int index = upper.getPos().get(upper.getPos().size()-1).intValue();
int position = upper.getPos().size()-1;
temp = (ArrayList<Integer>)upper.getPos().clone();
if(temp.size()>1)temp.remove(temp.size()-1);
Item parent = getItem(temp,false);
if(parent.getType()==1)dropOnFirstLevel(upper);//parent is tc=>on level 0
else dropNextInLine(upper, parent, index, position);}}
for(Item item:RunnerRepository.getSuite()){
if(item.getType()==2){
sortTearSetup(item);
}
}
updateLocations(RunnerRepository.getSuita(0));
repaint();
}
/*
* checks if y is in the upper half
* of item
*/
public boolean isUpperHalf(Item item, int Y){
int middle = item.getLocation()[1]+(int)item.getRectangle().getHeight()/2;
if(Y<=middle)return true;
return false;}
/*
* drops elements from clone
* as first lements in tree
*/
public void dropFirstElement(){
int temp1 = 0;
y=10;
foundfirstitem=true;
for(int i=0;i<clone.size();i++){
if(clone.get(i).getType()==1)continue;
ArrayList<Integer> selected2 = new ArrayList<Integer>();
selected2.add(new Integer(i));
clone.get(i).setPos(selected2);
for(int j = temp1;j<RunnerRepository.getSuiteNr();j++){
RunnerRepository.getSuita(j).updatePos(0,new Integer(RunnerRepository.getSuita(j).
getPos().get(0).intValue()+1));}
temp1++;
clone.get(i).select(false);
RunnerRepository.getSuite().add(clone.get(i).getPos().get(0), clone.get(i));}
deselectAll();
clone.clear();
updateLocations(RunnerRepository.getSuita(0));
repaint();}
/*
* drops elements from clone
* at first level under upper
*/
public void dropOnFirstLevel(Item upper){
int position = upper.getPos().size();
int temp1 = upper.getPos().get(position-1);
for(int i=0;i<clone.size();i++){
if(clone.get(i).getType()==1)continue;
ArrayList<Integer> selected2 = (ArrayList<Integer>)upper.getPos().clone();
selected2.set(0,new Integer(upper.getPos().get(0)+i+1));
clone.get(i).setPos(selected2);
for(int j = temp1+1;j<RunnerRepository.getSuiteNr();j++){
RunnerRepository.getSuita(j).updatePos(0,new Integer(RunnerRepository.getSuita(j).
getPos().get(0).intValue()+1));}
temp1++;
clone.get(i).select(false);
RunnerRepository.getSuite().add(clone.get(i).getPos().get(0), clone.get(i));}
deselectAll();
clone.clear();
updateLocations(RunnerRepository.getSuita(0));
repaint();}
/*
* drops elements from clone
* next in line after upper
*/
public void dropNextInLine(Item upper,Item parent,int index,int position){
int temp1 = index+1;
String [] ep = parent.getEpId();
for(int i=0;i<clone.size();i++){
ArrayList<Integer> selected2 = (ArrayList<Integer>)upper.getPos().clone();
selected2.set(selected2.size()-1,new Integer(selected2.get(selected2.size()-1).intValue()+(i+1)));
clone.get(i).setPos(selected2);
for(int j = temp1;j<parent.getSubItemsNr();j++){
parent.getSubItem(j).updatePos(position,new Integer(parent.getSubItem(j).
getPos().get(position).intValue()+1));}
temp1++;
if(clone.get(i).getType()==2)clone.get(i).setEpId(ep);
insertNewTC(clone.get(i).getName(),selected2,parent,clone.get(i));}
deselectAll();
clone.clear();}
/*
* drops elements from clone
* previous in line before upper
*/
public void dropPreviousInLine(Item upper, Item parent, int index, int position){
int temp1 = index; //value for last position of tc
ArrayList<Integer> selected2 = (ArrayList<Integer>)upper.getPos().clone();
String [] ep = parent.getEpId();
for(int i=0;i<clone.size();i++){//all elements from drag
ArrayList<Integer> selected3 = (ArrayList<Integer>)selected2.clone(); //clone position of the lement in that was made drop
selected3.set(selected3.size()-1,new Integer(selected3.get(selected3.size()-1).intValue()+i));
clone.get(i).setPos(selected3);
for(int j = temp1;j<parent.getSubItemsNr();j++){
parent.getSubItem(j).updatePos(position,new Integer(parent.getSubItem(j).
getPos().get(position).intValue()+1));}
temp1++;
if(clone.get(i).getType()==2)clone.get(i).setEpId(ep);
insertNewTC(clone.get(i).getName(),selected3,parent,clone.get(i));}
deselectAll();
clone.clear();}
/*
* drops elements from clone
* on upper level from upper
*/
public void dropOnUpperLevel(Item upper){
int index = upper.getPos().get(upper.getPos().size()-1).intValue();
int position = upper.getPos().size()-1;
ArrayList<Integer> temp = (ArrayList<Integer>)upper.getPos().clone();
if(temp.size()>1)temp.remove(temp.size()-1);
Item parent = getItem(temp,false);
String [] ep = parent.getEpId();
int temp1 = index+1;
for(int i=0;i<clone.size();i++){
ArrayList<Integer> selected2 = (ArrayList<Integer>)upper.getPos().clone();
selected2.set(selected2.size()-1,new Integer(selected2.get(selected2.size()-1).intValue()+(i+1)));
clone.get(i).setPos(selected2);
for(int j = temp1;j<parent.getSubItemsNr();j++){
parent.getSubItem(j).updatePos(position,new Integer(parent.getSubItem(j).
getPos().get(position).intValue()+1));}
temp1++;
if(clone.get(i).getType()==2)clone.get(i).setEpId(ep);
insertNewTC(clone.get(i).getName(),selected2,parent,clone.get(i));}
deselectAll();
clone.clear();}
/*
* drops elements from clone
* last in suite upper
*/
public void dropLastInSuita(Item upper){
int position = upper.getPos().size();
Item parent = upper;
String [] ep = upper.getEpId();
for(int i=0;i<clone.size();i++){
ArrayList<Integer> selected2 = (ArrayList<Integer>)upper.getPos().clone();
selected2.add(new Integer(upper.getSubItemsNr()+i));
clone.get(i).setPos(selected2);
insertNewTC(clone.get(i).getName(),selected2,parent,clone.get(i));
if(clone.get(i).getType()==2)clone.get(i).setEpId(ep);}
deselectAll();
clone.clear();}
/*
* drops elements from clone
* first in suite upper
*/
public void dropFirstInSuita(Item upper){
int position = upper.getPos().size();
Item parent = upper;
int temp1 = 0;
String [] ep = upper.getEpId();
for(int i=0;i<clone.size();i++){
ArrayList<Integer> selected2 = (ArrayList<Integer>)upper.getPos().clone();
selected2.add(new Integer(i));
clone.get(i).setPos(selected2);
for(int j = temp1;j<parent.getSubItemsNr();j++){
parent.getSubItem(j).updatePos(position,new Integer(parent.getSubItem(j).
getPos().get(position).intValue()+1));}
temp1++;
insertNewTC(clone.get(i).getName(),selected2,parent,clone.get(i));
if(clone.get(i).getType()==2)clone.get(i).setEpId(ep);}
deselectAll();
clone.clear();}
/*
* positions dragging line
* inside suite
*/
public void lineInsideSuita(Item item, int X){
// line[0] = (int)(item.getRectangle().x+item.getRectangle().getWidth()/2-55);
line[0] = (int)(item.getRectangle().x+item.getRectangle().getWidth()/2-5);
line[1] = (int)(item.getRectangle().y+item.getRectangle().getHeight()+5);
line[2] = X;
line[3] = line[1];
line[4] = (int)(item.getRectangle().y+item.getRectangle().getHeight()+5);}
/*
* positions dragging line
* on suite
*/
public void lineOnSuita(Item item, int X){
line[0] = (int)(item.getRectangle().x+item.getRectangle().getWidth()-40);
line[1] = (int)(item.getRectangle().y+item.getRectangle().getHeight()/2);
line[2] = X;
line[3] = line[1];
line[4] = line[3];}
/*
* positions dragging line
* under suite
*/
public void lineUnderSuita(Item item,int X){
line[0] = (int)(item.getRectangle().x-25);
line[1] = (int)(item.getRectangle().y+item.getRectangle().getHeight()+5);
line[2] = X;
line[3] = line[1];
if(getFirstSuitaParent(item,false)!=null)
{line[4] = (int)(getFirstSuitaParent(item,false).getRectangle().y+
getFirstSuitaParent(item,false).getRectangle().getHeight()+5);}
else line[4] = line[2];}
/*
* positions dragging line
* above tc
*/
public void lineAboveTc(Item item, int X){
line[0] = (int)(item.getRectangle().x-25);
line[1] = (int)(item.getRectangle().y-5);
line[2] = X;
line[3] = line[1];
line[4] = line[1];}
/*
* positions dragging line
* under item
*/
public void lineUnderItem(Item item, int X){
line[0] = (int)(item.getRectangle().x-25);
line[2] = X;
if(item.getType()==1&&itemIsExpanded(item)){
line[1] = (int)(item.getSubItem(item.getSubItemsNr()-1).getRectangle().y+
item.getSubItem(item.getSubItemsNr()-1).getRectangle().getHeight()+5);}
else{line[1] = (int)(item.getRectangle().y+item.getRectangle().getHeight()+5);}
line[3] = line[1];
line[4] = (int)(item.getRectangle().y+item.getRectangle().getHeight()/2);}
/*
* positions dragging line
* after upper parent
*/
public void lineAfterUpperParent(Item item, int X){
line[0] = (int)(getFirstSuitaParent(item,false).getRectangle().x-25);
line[2] = X;
if(item.getSubItemsNr()>0&&itemIsExpanded(item)){
line[1] = (int)(item.getSubItem(item.getSubItemsNr()-1).getRectangle().y+
item.getSubItem(item.getSubItemsNr()-1).getRectangle().getHeight()+5);}
else{line[1] = (int)(item.getRectangle().y+item.getRectangle().getHeight()+5);}
line[3] = line[1];
line[4] = (int)(getFirstSuitaParent(item,false).getRectangle().y+
getFirstSuitaParent(item,false).getRectangle().getHeight()/2);}
/*
* positions dragging line
* after suite parent
*/
public void lineAfterSuitaParent(Item item, int X){
line[0] = (int)(getFirstSuitaParent(getTcParent(item,false),false).getRectangle().x-25);
line[2] = X;
line[1] = (int)(item.getRectangle().y+item.getRectangle().getHeight()+5);
line[3] = line[1];
line[4] = (int)(getFirstSuitaParent(item,false).getRectangle().y+
getFirstSuitaParent(item,false).getRectangle().getHeight()/2);}
/*
* positions dragging line
* after tc parent
*/
public void lineAfterTcParent(Item item, int X){
line[0] = (int)(getTcParent(item,false).getRectangle().x-25);
line[1] = (int)(getTcParent(item,false).getSubItem(getTcParent(item,false).
getSubItemsNr()-1).getRectangle().y+getTcParent(item,false).
getSubItem(getTcParent(item,false).getSubItemsNr()-1).
getRectangle().getHeight()+5);
line[2] = X;
line[3] = line[1];
line[4] = (int)(getTcParent(item,false).getRectangle().y+getTcParent(item,false).getRectangle().getHeight()/2);}
/*
* position dragging line
* based on context
*/
public void handleDraggingLine(int X, int Y){
Item item = null;
item = getUpperItem(X,Y);
if(item==null){
line[0] = 0;
line[1] = 5;
line[2] = X;
line[3] = 5;}
else{
if(item.getType()==2){//it is suite
if(item.getRectangle().intersects(new Rectangle(0,Y-1,getWidth(),2))){//touches suite
if(item.getSubItemsNr()>0&&itemIsExpanded(item)){//it is expanded
// if(item.getSubItem(0).isPrerequisite()){//first element is prerequisite, must insert after
// lineUnderItem(item.getSubItem(0), X);}
// else{
lineInsideSuita(item,X);
// }
}
else{lineOnSuita(item,X);}}//it is not expanded
else if (item.getSubItemsNr()>0&&itemIsExpanded(item)){//not touching suite but suite is expanded
// if(item.getSubItem(0).isPrerequisite()){//first element is prerequisite, must insert after
// lineUnderItem(item.getSubItem(0), X);}
// else
lineInsideSuita(item,X);}
else if(item.getRectangle().y+item.getRectangle().getHeight()+5<=Y){//upper half, on level before suite
if(item.getPos().size()==1||
getFirstSuitaParent(item,false).getSubItemsNr()-1>
item.getPos().get(item.getPos().size()-1)){
lineUnderItem(item,X);}//on level 0
else lineAfterUpperParent(item, X);}//not on level 0
else{lineUnderSuita(item,X);}}//lower half insert after suite
else if(item.getType()==1){//it is tc
if(item.getRectangle().intersects(new Rectangle(0,Y-1,getWidth(),2))){//touches tc
// if(item.isPrerequisite()){//tc is prerequisite, must insert after
// lineUnderItem(item, X);}
// else{//tc is not prerequisite, must interpret pos
boolean up = isUpperHalf(item,Y);
if(up){lineAboveTc(item,X);}//touches and in upper half
else{lineUnderItem(item,X);}
// }
}//touches and in lower half
else{//didn't touch tc
if(getFirstSuitaParent(item,false)!=null&&
getFirstSuitaParent(item,false).getSubItemsNr()-1==item.getPos().get(item.getPos().size()-1)){//tc is last and has parent
if(Y<item.getRectangle().y+item.getRectangle().getHeight()+5){
lineUnderItem(item, X);}//Should be inserted in upper parent
else if(!itemIsExpanded(item)){lineAfterUpperParent(item,X);}}//must insert after tc parent
else{lineUnderItem(item,X);}}}//not last element or is on level 0, must insert on same level
else{//it is prop
if(getFirstSuitaParent(getTcParent(item,false),false)!=null &&
getTcParent(item,false).getSubItemsNr()-1==item.getPos().get(item.getPos().size()-1) &&
getFirstSuitaParent(getTcParent(item,false),false).getSubItemsNr()-1==getTcParent(item,false).
getPos().get(getTcParent(item,false).getPos().size()-1) &&
Y>item.getRectangle().y+item.getRectangle().getHeight()+5){//prop is last in tc, tc is last in suita, and mouse is in lower half
lineAfterSuitaParent(item,X);}
else{lineAfterTcParent(item,X);}}}//not last prop, can insert after tc with this prop
repaint();
if(dragscroll){
scrolldown = false;
scrollup = false;
if(Y-RunnerRepository.window.mainpanel.p1.sc.pane.getVerticalScrollBar().getValue()<10){
int scrollvalue = RunnerRepository.window.mainpanel.p1.sc.pane.getVerticalScrollBar().getValue();
scrolldown = true;
RunnerRepository.window.mainpanel.p1.sc.pane.getVerticalScrollBar().setValue(scrollvalue-10);}
else if(Y-RunnerRepository.window.mainpanel.p1.sc.pane.getVerticalScrollBar().getValue()>RunnerRepository.window.
mainpanel.p1.sc.pane.getSize().getHeight()-15){
int scrollvalue = RunnerRepository.window.mainpanel.p1.sc.pane.getVerticalScrollBar().getValue();
scrollup = true;
RunnerRepository.window.mainpanel.p1.sc.pane.getVerticalScrollBar().setValue(scrollvalue+10);}}}
public String getArrayString(ArrayList<Integer> selected2){
StringBuffer string = new StringBuffer();
for(Integer el:selected2){
string.append(el.toString()+" ");}
return string.toString();}
/*
* check if this item is expanded,
* has subelements that are visible
*/
public boolean itemIsExpanded(Item item){
for(Item i:item.getSubItems()){
if(i.isVisible())return true;
}
return false;
}
/*
* gets the item above
* X, Y position
*/
public Item getUpperItem(int X, int Y){
int y1 = Y;
Item upper=null;
while(y1>0){
for(int x1=0;x1<getWidth();x1+=5){
getClickedItem(x1,y1);
if(selected.size()>0){
upper=getItem(selected,false);
if(upper!=null)break;}
if(upper!=null)break;}
y1-=5;}
return upper;}
/*
* return next visible elment
*/
public Item nextItem(Item item){
if(item.getSubItemsNr()>0){
for(int i=0;i<item.getSubItemsNr();i++){
Item subitem = item.getSubItem(i);
if(subitem.isVisible()){
return subitem;}
}
Item parent;
if(item.getType()!=0)parent = getFirstSuitaParent(item, false);
else parent = getTcParent(item, false);
if(parent!=null){
return iterateBack(parent,item.getPos().get(item.getPos().size()-1));
}
return null;
}
Item parent;
if(item.getType()!=0)parent = getFirstSuitaParent(item, false);
else parent = getTcParent(item, false);
if(parent!=null){
return iterateBack(parent,item.getPos().get(item.getPos().size()-1));
}
return null;
}
/*
* item - parent of item
* index - the index of item in parent
*/
public Item iterateBack(Item item, int index){
if(item.getSubItemsNr()-1>index){
Item subitem = item.getSubItem(index+1);
if(subitem.isVisible())return subitem;
return iterateBack(item,index+1);
}
Item parent;
if(item.getType()!=0)parent = getFirstSuitaParent(item, false);
else parent = getTcParent(item, false);
if(parent!=null){
return iterateBack(parent,item.getPos().get(item.getPos().size()-1));
}
int nr = item.getPos().get(0);
if(RunnerRepository.getSuiteNr()-1>nr){
return RunnerRepository.getSuita(nr+1);
}
return null;
}
/*
* previous item on same line
* if none returns parent
*/
public Item prevInLine(Item item){
ArrayList <Integer> temp =(ArrayList <Integer>)item.getPos().clone();
if(temp.size()>1){
if(temp.get(temp.size()-1)>0){
temp.set(temp.size()-1, temp.get(temp.size()-1)-1);
Item previous = getItem(temp, false);
if(previous.isVisible()){
return previous;
}
return prevInLine(previous);
}
else{
temp.remove(temp.size()-1);
return getItem(temp, false);
}
}
else if(temp.get(0)>0){
return RunnerRepository.getSuita(temp.get(0)-1);
}
return item;
}
/*
* the item immediately befor item
*/
public Item previousItem(Item item){
ArrayList <Integer> temp =(ArrayList <Integer>)item.getPos().clone();
if(temp.size()>1){
if(temp.get(temp.size()-1)>0){
temp.set(temp.size()-1, temp.get(temp.size()-1)-1);
Item previous = getItem(temp, false);
if(previous.isVisible()){
return lastVisible(previous);
}
return previousItem(previous);
}
else{
//if(item.isVisible())return item;
temp.remove(temp.size()-1);
return getItem(temp, false);
}
}
else if(temp.get(0)>0){
return lastVisible(RunnerRepository.getSuita(temp.get(0)-1));
}
return item;
}
/*
* returns last visible element after
* element at pos
*/
public Item lastVisible(Item item){//last visible elem under pos
if(item.getSubItemsNr()>0){
for(int i=item.getSubItemsNr()-1;i>-1;i--){
Item subitem = item.getSubItem(i);
if(subitem.isVisible()){
return lastVisible(subitem);
}
}
return item;
}
return item;
}
/*
* prints this item and his
* subitems indices on screen
*/
public static void printPos(Item item){
if(item.getType()==0||item.getType()==1||item.getType()==2){
System.out.print(item.getName()+" - ");
for(int i=0;i<item.getPos().size();i++){
System.out.print(item.getPos().get(i));}
System.out.println();}
if(item.getType()==1||item.getType()==2){
for(int i=0;i<item.getSubItemsNr();i++){
printPos(item.getSubItem(i));}}}
public boolean compareArrays(ArrayList<Integer> one, ArrayList<Integer> two){
if(one.size()!=two.size())return false;
else{
for(int i=0;i<one.size();i++){
if(one.get(i)!=two.get(i))return false;}
return true;}}
public void handleClick(MouseEvent ev){
if(ev.getButton()==1){
if(RunnerRepository.getSuiteNr()==0)return;
if(keypress==0){
deselectAll();
getClickedItem(ev.getX(),ev.getY());
if(selected.size()>0){
selectItem(selected);
if(getItem(selected,false).getType()==2){
Item temp = getItem(selected,false);
int userDefNr = temp.getUserDefNr();
boolean root = false;
RunnerRepository.window.mainpanel.p1.suitaDetails.setParent(temp);
RunnerRepository.window.mainpanel.p1.testconfigmngmnt.setParent(temp);
if(temp.getPos().size()==1){
root = true;
if(userDefNr!=RunnerRepository.window.mainpanel.p1.suitaDetails.getDefsNr()){
System.out.println("Warning, suite "+
temp.getName()+" has "+userDefNr+" fields while in bd.xml are defined "+
RunnerRepository.window.mainpanel.p1.suitaDetails.getDefsNr()+" fields");
if(RunnerRepository.window.mainpanel.p1.suitaDetails.getDefsNr()<userDefNr){
temp.getUserDefs().subList(RunnerRepository.window.mainpanel.p1.suitaDetails.
getDefsNr(),userDefNr).clear();}}
try{
for(int i=0;i<RunnerRepository.window.mainpanel.p1.suitaDetails.getDefsNr();i++){
if(temp.getUserDefNr()==i)break;
RunnerRepository.window.mainpanel.p1.suitaDetails.getDefPanel(i).
setDescription(temp.getUserDef(i)[1],true);}}
catch(Exception e){e.printStackTrace();}
}
RunnerRepository.window.mainpanel.p1.suitaDetails.setSuiteDetails(root);
}
if(getItem(selected,false).getType()==1){
Item temp = getItem(selected,false);
RunnerRepository.window.mainpanel.p1.suitaDetails.setParent(temp);
RunnerRepository.window.mainpanel.p1.testconfigmngmnt.setParent(temp);
RunnerRepository.window.mainpanel.p1.suitaDetails.setTCDetails();
}
if(getItem(selected,false).getCheckRectangle().intersects(
new Rectangle(ev.getX()-1,ev.getY()-1,2,2))){
Item select = getItem(selected,false);
select.setCheck(!select.getCheck(),true);
if(select.getCheck()&&select.getType()==1){//if element is tc and selected, select all upper suites
Item suita = getFirstSuitaParent(select, false);
while(suita!=null){
suita.setCheck(true, false);
suita = getFirstSuitaParent(suita, false);
}
}
// getItem(selected,false).setCheck(!getItem(selected,false).getCheck());
}
else if(getItem(selected,false).getSubItemsNr()>0&&ev.getClickCount()==2 &&
getItem(selected,false).getType()!=1){
if(getItem(selected,false).getType()==2 &&
!itemIsExpanded(getItem(selected,false))){
if(!onlyOptionals)getItem(selected,false).setVisibleTC();
else{
Item parent = getItem(selected,false);
for(Item i:parent.getSubItems()){
if(i.isOptional()){
i.setSubItemVisible(true);
i.setSubItemVisible(true);
i.setVisible(false);
}
}
}
}
else getItem(selected,false).setVisible(
!itemIsExpanded(getItem(selected,false)));
}
updateLocations(getItem(selected,false));}
else{
RunnerRepository.window.mainpanel.p1.suitaDetails.setGlobalDetails();}
repaint();}
else if(keypress==2){
getClickedItem(ev.getX(),ev.getY());
if(selected.size()>0){
int [] theone = new int[selected.size()];
for(int i=0;i<selected.size();i++){theone[i]= selected.get(i).intValue();}
Item theone1 = getItem(selected,false);
theone1.select(!theone1.isSelected());
if(theone1.isSelected())selectedcollection.add(theone);
else{
for(int m=0;m<selectedcollection.size();m++){
if(Arrays.equals(selectedcollection.get(m),theone)){
selectedcollection.remove(m);
break;}}}
if(selectedcollection.size()==0){
RunnerRepository.window.mainpanel.p1.remove.setEnabled(false);}
repaint();}}
else{// selection with shift
if(selected.size()>0){
deselectAll();
int [] theone1 = new int[selected.size()];
for(int i=0;i<selected.size();i++){theone1[i]= selected.get(i).intValue();}
getClickedItem(ev.getX(),ev.getY());
int [] theone2 = new int[selected.size()];
for(int i=0;i<selected.size();i++){theone2[i]= selected.get(i).intValue();}
if(theone1.length==theone2.length){
if(theone1.length>1){
int [] temp1,temp2;
temp1 = Arrays.copyOfRange(theone1,0,theone1.length-1);
temp2 = Arrays.copyOfRange(theone2,0,theone2.length-1);
if(Arrays.equals(temp1,temp2)){
int [] first,second;
if(theone2[theone2.length-1]>=theone1[theone1.length-1]){
first = theone2;
second = theone1;}
else{
first = theone1;
second = theone2;}
ArrayList<Integer>temp11 = new ArrayList<Integer>();
for(int i=0;i<temp1.length;i++)temp11.add(new Integer(temp1[i]));
Item parent = getItem(temp11,false);
for(int i=second[second.length-1];i<first[first.length-1]+1;i++){
parent.getSubItem(i).select(true);
int [] temporary = new int[parent.getSubItem(i).getPos().size()];
for(int m=0;m<temporary.length;m++){
temporary[m]=parent.getSubItem(i).getPos().get(m).intValue();}
selectedcollection.add(temporary);}}}
else{
int first,second;
if(theone1[0]>=theone2[0]){
first = theone1[0];
second = theone2[0];}
else{
second = theone1[0];
first = theone2[0];}
for(int m=second;m<first+1;m++){
RunnerRepository.getSuita(m).select(true);
selectedcollection.add(new int[]{m});}}}
repaint();}}}
if(ev.getButton()==3){
getClickedItem(ev.getX(),ev.getY());
if((selected.size()==0)){
if(RunnerRepository.getSuiteNr()>0){
deselectAll();
repaint();}
noSelectionPopUp(ev);}
else{if(!getItem(selected,false).isSelected()){
deselectAll();
selectItem(selected);
repaint();
Item temp = getItem(selected,false);
if(temp.getType()==0) propertyPopUp(ev,getItem(selected,false));
else if(temp.getType()==1){
RunnerRepository.window.mainpanel.p1.suitaDetails.setParent(temp);
RunnerRepository.window.mainpanel.p1.testconfigmngmnt.setParent(temp);
RunnerRepository.window.mainpanel.p1.suitaDetails.setTCDetails();
tcPopUp(ev,getItem(selected,false));}
else{
boolean root = false;
RunnerRepository.window.mainpanel.p1.suitaDetails.setParent(temp);
RunnerRepository.window.mainpanel.p1.testconfigmngmnt.setParent(temp);
if(temp.getPos().size()==1){//if it is a root suite
root = true;
int userDefNr = temp.getUserDefNr();
if(userDefNr!=RunnerRepository.window.mainpanel.p1.suitaDetails.getDefsNr()){
System.out.println("Warning, suite "+
temp.getName()+" has "+userDefNr+" fields while in bd.xml are defined "+
RunnerRepository.window.mainpanel.p1.suitaDetails.getDefsNr()+" fields");
if(RunnerRepository.window.mainpanel.p1.suitaDetails.getDefsNr()<userDefNr){
temp.getUserDefs().subList(RunnerRepository.window.mainpanel.p1.suitaDetails.
getDefsNr(),userDefNr).clear();}}
try{
for(int i=0;i<RunnerRepository.window.mainpanel.p1.suitaDetails.getDefsNr();i++){
if(temp.getUserDefNr()==i)break;
RunnerRepository.window.mainpanel.p1.suitaDetails.getDefPanel(i).
setDescription(temp.getUserDef(i)[1],true);}}
catch(Exception e){e.printStackTrace();}
}
RunnerRepository.window.mainpanel.p1.suitaDetails.setSuiteDetails(root);
suitaPopUp(ev, temp);
}
}
else{if(selectedcollection.size()==1){
if(getItem(selected,false).getType()==0) propertyPopUp(ev,getItem(selected,false));
else if(getItem(selected,false).getType()==1){
Item temp = getItem(selected,false);
RunnerRepository.window.mainpanel.p1.testconfigmngmnt.setParent(temp);
RunnerRepository.window.mainpanel.p1.suitaDetails.setParent(temp);
RunnerRepository.window.mainpanel.p1.suitaDetails.setTCDetails();
tcPopUp(ev,getItem(selected,false));
}
else{
Item temp = getItem(selected,false);
boolean root = false;
RunnerRepository.window.mainpanel.p1.suitaDetails.setParent(temp);
RunnerRepository.window.mainpanel.p1.testconfigmngmnt.setParent(temp);
if(temp.getPos().size()==1){//if it is a root suite
root = true;
int userDefNr = temp.getUserDefNr();
if(userDefNr!=RunnerRepository.window.mainpanel.p1.suitaDetails.getDefsNr()){
System.out.println("Warning, suite "+
temp.getName()+" has "+userDefNr+" fields while in bd.xml are defined "+
RunnerRepository.window.mainpanel.p1.suitaDetails.getDefsNr()+" fields");
if(RunnerRepository.window.mainpanel.p1.suitaDetails.getDefsNr()<userDefNr){
temp.getUserDefs().subList(RunnerRepository.window.mainpanel.p1.suitaDetails.
getDefsNr(),userDefNr).clear();}}
try{
for(int i=0;i<RunnerRepository.window.mainpanel.p1.suitaDetails.getDefsNr();i++){
if(temp.getUserDefNr()==i)break;
RunnerRepository.window.mainpanel.p1.suitaDetails.getDefPanel(i).
setDescription(temp.getUserDef(i)[1],true);}}
catch(Exception e){e.printStackTrace();}}
RunnerRepository.window.mainpanel.p1.suitaDetails.setSuiteDetails(root);
suitaPopUp(ev,getItem(selected,false));
}
}
else{
multipleSelectionPopUp(ev);}}}}
if(selectedcollection.size()>0)RunnerRepository.window.mainpanel.p1.remove.setEnabled(true);}
/*
* popup in case nothing
* is selected
*/
public void noSelectionPopUp(final MouseEvent ev){
p.removeAll();
JMenuItem item = new JMenuItem("Add Suite");
p.add(item);
item.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent ev2){
int y1 = ev.getY();
Item upper=null;
while(y1>0){
y1-=5;
getClickedItem(ev.getX(),y1);
if(selected.size()>0){
upper=getItem(selected,false);
if(upper!=null){
break;}}}
if(upper!=null&&upper.getType()==1){
int index = upper.getPos().get(upper.getPos().size()-1).intValue();
int position = upper.getPos().size()-1;
ArrayList<Integer> temp = (ArrayList<Integer>)upper.getPos().clone();
if(temp.size()>1)temp.remove(temp.size()-1);
Item parent = getItem(temp,false);
int j = upper.getPos().get(upper.getPos().size()-1).intValue()+1;
for(;j<parent.getSubItemsNr();j++){
parent.getSubItem(j).updatePos(position,
new Integer(parent.getSubItem(j).getPos().get(position).intValue()+1));}
(new AddSuiteFrame(Grafic.this, parent,index+1)).setLocation(ev.getX()-50,ev.getY()-50);}
else{
(new AddSuiteFrame(Grafic.this, null,0)).setLocation((int)ev.getLocationOnScreen().getX()-50,
(int)ev.getLocationOnScreen().getY()-50);}}});//add suite
p.show(this,ev.getX(),ev.getY());}
/*
* popup in case property
* is selected
*/
public void propertyPopUp(MouseEvent ev,final Item prop){
if(prop.getPos().get(prop.getPos().size()-1)!=0){
p.removeAll();
JMenuItem item = new JMenuItem("Redefine");
p.add(item);
item.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent ev){redefineProp(prop);}});
item = new JMenuItem("Remove");
p.add(item);
item.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent ev){
removeSelected();
}});
p.show(this,ev.getX(),ev.getY());}}
/*
* prompt user to redefine property
*/
public void redefineProp(Item prop){
boolean found = true;
JTextField name = new JTextField(prop.getName());
if(prop.getName().equals("param"))name.setEnabled(false);
JTextField value = new JTextField(prop.getValue());
Object[] message = new Object[] {"Name", name, "Value", value};
while(found){
JPanel p = getPropPanel(name,value);
int resp = (Integer)CustomDialog.showDialog(p,JOptionPane.PLAIN_MESSAGE,
JOptionPane.OK_CANCEL_OPTION, Grafic.this, "Property: value",null);
if(resp == JOptionPane.OK_OPTION&&(!(name.getText()+value.getText()).equals(""))){
if(name.getText().equals("param")&&name.isEnabled()){
CustomDialog.showInfo(JOptionPane.WARNING_MESSAGE, Grafic.this,
"Warning", "'param' is used for parameters, please use a different name");
continue;}
else found = false;
FontMetrics metrics = getGraphics().getFontMetrics(new Font("TimesRoman", 0, 11));
int width = metrics.stringWidth(name.getText()+": "+value.getText()) + 40;
prop.setName(name.getText());
prop.setValue(value.getText());
prop.getRectangle().setSize(width, (int)(prop.getRectangle().getHeight()));
repaint();}
else found = false;}}
/*
* name value panel created
* for adding props
*/
public JPanel getPropPanel(JTextField name, JTextField value){
JPanel p = new JPanel();
p.setLayout(new BoxLayout(p, BoxLayout.Y_AXIS));
JPanel jPanel1 = new JPanel();
JLabel jLabel3 = new JLabel();
JPanel jPanel2 = new JPanel();
JLabel jLabel4 = new JLabel();
jPanel1.setLayout(new java.awt.BorderLayout());
jLabel3.setText("Name: ");
jPanel1.add(jLabel3, BorderLayout.CENTER);
p.add(jPanel1);
p.add(name);
jPanel2.setLayout(new BorderLayout());
jLabel4.setText("Value: ");
jPanel2.add(jLabel4, BorderLayout.CENTER);
p.add(jPanel2);
p.add(value);
return p;}
/*
* popup in case there
* are multiple items selected
*/
public void multipleSelectionPopUp(MouseEvent ev){
p.removeAll();
JMenuItem menuitem = new JMenuItem("Remove");
p.add(menuitem);
menuitem.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent ev){
removeSelected();}});
final int nr = selectedcollection.size();
final ArrayList<Integer>temp = new ArrayList<Integer>();
byte type = areTheSame(nr);
if(type!=-1){
if(type!=0){
menuitem = new JMenuItem("Switch Check");
p.add(menuitem);
menuitem.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent ev){
switchCheck();}});}
if(type==1){
menuitem = new JMenuItem("Add Configurations");
p.add(menuitem);
menuitem.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent ev){
addConfigurations(false);}});
menuitem = new JMenuItem("Switch Runnable");
p.add(menuitem);
menuitem.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent ev){
switchRunnable();}});
menuitem = new JMenuItem("Switch Optional");
p.add(menuitem);
menuitem.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent ev){
switchOptional();}});}}
p.show(this,ev.getX(),ev.getY());}
private void addConfigurations(boolean unitary){
JPanel p = new JPanel();
p.setLayout(null);
p.setPreferredSize(new Dimension(515,200));
JLabel ep = new JLabel("Configurations: ");
ep.setBounds(5,5,95,25);
JList tep = new JList();
JScrollPane scep = new JScrollPane(tep);
scep.setBounds(100,5,400,180);
p.add(ep);
p.add(scep);
String [] vecresult = RunnerRepository.window.mainpanel.p4.getTestConfig().tree.getFiles();
tep.setModel(new DefaultComboBoxModel(vecresult));
if(unitary){
Item item=null;
int nr = selectedcollection.size();
ArrayList<Integer>temp = new ArrayList<Integer>();
for(int i=0;i<nr;i++){
temp.clear();
int [] indices = selectedcollection.get(i);
for(int j=0;j<indices.length;j++)temp.add(new Integer(indices[j]));
item = getItem(temp,false);
}
ArrayList<String> array = new ArrayList<String>(Arrays.asList(vecresult));
ArrayList<String> torem = new ArrayList<String>();
for(int i=0;i<vecresult.length;i++){
for(Configuration conf:item.getConfigurations()){
if(conf.getFile().equals(vecresult[i])){
torem.add(vecresult[i]);
break;
}
}
}
for(String s:torem){
array.remove(s);
}
Object [] resultingarray = array.toArray();
tep.setModel(new DefaultComboBoxModel(resultingarray));
}
int resp = (Integer)CustomDialog.showDialog(p,JOptionPane.PLAIN_MESSAGE,
JOptionPane.OK_CANCEL_OPTION, Grafic.this, "Test Configurations Files",null);
if(resp == JOptionPane.OK_OPTION){
Item item=null;
int nr = selectedcollection.size();
ArrayList<Integer>temp = new ArrayList<Integer>();
for(int i=0;i<nr;i++){
temp.clear();
int [] indices = selectedcollection.get(i);
for(int j=0;j<indices.length;j++)temp.add(new Integer(indices[j]));
item = getItem(temp,false);
for(Object selection:tep.getSelectedValues()){
boolean goon = true;
for(Configuration config:item.getConfigurations()){//check for existing file in configuration
if(config.getFile().equals(selection.toString())){
goon = false;
break;
}
}
if(goon)item.getConfigurations().add(new Configuration(selection.toString()));
}
}
TestConfigManagement tcm = RunnerRepository.window.mainpanel.p1.testconfigmngmnt;
tcm.setParent(tcm.getConfigParent());
}
repaint();
}
public void switchOptional(){
Item item=null;
int nr = selectedcollection.size();
ArrayList<Integer>temp = new ArrayList<Integer>();
for(int i=0;i<nr;i++){
temp.clear();
int [] indices = selectedcollection.get(i);
for(int j=0;j<indices.length;j++)temp.add(new Integer(indices[j]));
item = getItem(temp,false);
if(!item.isPrerequisite()&&!item.isTeardown())item.setOptional(!item.isOptional());}
repaint();}
/*
* switch runnable for selected items
*/
public void switchRunnable(){
Item item=null;
int nr = selectedcollection.size();
ArrayList<Integer>temp = new ArrayList<Integer>();
for(int i=0;i<nr;i++){
temp.clear();
int [] indices = selectedcollection.get(i);
for(int j=0;j<indices.length;j++)temp.add(new Integer(indices[j]));
item = getItem(temp,false);
item.switchRunnable();}
repaint();}
/*
* switch check for selected items
*/
public void switchCheck(){
Item item=null;
int nr = selectedcollection.size();
ArrayList<Integer>temp = new ArrayList<Integer>();
for(int i=0;i<nr;i++){
temp.clear();
int [] indices = selectedcollection.get(i);
for(int j=0;j<indices.length;j++)temp.add(new Integer(indices[j]));
item = getItem(temp,false);
item.setCheck(!item.getCheck(),true);}
repaint();}
/*
* popup in case TC is selected
*/
public void tcPopUp(MouseEvent ev, final Item tc){
p.removeAll();
JMenuItem item;
item = new JMenuItem("Add Property");
p.add(item);
item.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent ev){
addTCProp(tc);}});
item = new JMenuItem("Set Parameters");
p.add(item);
item.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent ev){
setParam(tc);}});
item = new JMenuItem("Add Configurations");
p.add(item);
item.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent ev){
addConfigurations(true);}});
item = new JMenuItem("Repeat");
if(RunnerRepository.isMaster())p.add(item);
item.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent ev){
reapeatItem(tc);
}});
item = new JMenuItem("Remove");
p.add(item);
item.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent ev){
removeSelected();
}});
p.show(this,ev.getX(),ev.getY());}
/*
* popup in case suite is selected
*/
public void suitaPopUp(MouseEvent ev,final Item suita){
p.removeAll();
JMenuItem item ;
item = new JMenuItem("Add Suite");
item.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent ev){
new AddSuiteFrame(Grafic.this, suita,0);}});
p.add(item);
item = new JMenuItem("Expand");
p.add(item);
item.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent ev){
suita.setVisible(true);
updateLocations(suita);
repaint();}});
item = new JMenuItem("Contract");
p.add(item);
item.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent ev){
int nr = suita.getSubItemsNr();
for(int i=0;i<nr;i++){
suita.getSubItem(i).setVisible(false);}
suita.setVisible(false);
updateLocations(suita);
repaint();}});
item = new JMenuItem("Export");
p.add(item);
item.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent ev){
exportSuiteToPredefined(suita);
}});
item = new JMenuItem("Repeat");
if(RunnerRepository.isMaster())p.add(item);
item.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent ev){
reapeatItem(suita);
}});
item = new JMenuItem("Remove");
p.add(item);
item.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent ev){
if(suita.getPos().size()==1){//este pe nivelul 0
int index = suita.getPos().get(0).intValue();
RunnerRepository.getSuite().remove(suita);
if(RunnerRepository.getSuiteNr()>=index){
for(int i= index;i<RunnerRepository.getSuiteNr();i++){
RunnerRepository.getSuita(i).updatePos(0,new Integer(RunnerRepository.getSuita(i).
getPos().get(0).intValue()-1));}
if(RunnerRepository.getSuiteNr()>0){
RunnerRepository.getSuita(0).setLocation(new int[]{5,10});
updateLocations(RunnerRepository.getSuita(0));}
repaint();
selectedcollection.clear();}}
else{int index = suita.getPos().get(suita.getPos().size()-1).intValue();//not on level 0
int position = suita.getPos().size()-1;
ArrayList<Integer> temp = (ArrayList<Integer>)suita.getPos().clone();
temp.remove(temp.size()-1);
Item parent = getItem(temp,false);
parent.getSubItems().remove(suita);
if(parent.getSubItemsNr()>=index){
for(int i = index;i<parent.getSubItemsNr();i++){
parent.getSubItem(i).updatePos(position,new Integer(parent.getSubItem(i).getPos().
get(position).intValue()-1));}}
updateLocations(parent);
repaint();
selectedcollection.clear();}}});
p.show(this,ev.getX(),ev.getY());}
//repeat item window
public void reapeatItem(Item item){
String respons = CustomDialog.showInputDialog(JOptionPane.INFORMATION_MESSAGE,
JOptionPane.OK_CANCEL_OPTION,
Grafic.this, "", "Number of times:");
int times;
try{times = Integer.parseInt(respons);}//exit if respons is not integer
catch(Exception e){
return;
}
if(times==0)times=1;//cannot set 0 as repeat
item.setRepeat(times);
FontMetrics metrics = getGraphics().getFontMetrics(new Font("TimesRoman", Font.BOLD, 14));
int width = metrics.stringWidth(times+"X "+item.getName())+40;
item.getRectangle().setSize(width,(int)item.getRectangle().getHeight());
if(item.isVisible())updateLocations(item);
repaint();
}
/*
* export this suite in predefined suites
*/
public void exportSuiteToPredefined(Item suite){
String user = CustomDialog.showInputDialog(JOptionPane.QUESTION_MESSAGE,
JOptionPane.OK_CANCEL_OPTION, RunnerRepository.window,
"File Name","Please enter suite file name");
if(user!=null&&!user.equals("")){
ArrayList<Item>array = new ArrayList<Item>();
array.add(suite);
boolean cond;
if(RunnerRepository.isMaster()){
cond = printXML(RunnerRepository.temp+RunnerRepository.getBar()+"Twister"+RunnerRepository.getBar()+"Users"+RunnerRepository.getBar()+user+".xml",
false,false,
RunnerRepository.window.mainpanel.p1.suitaDetails.stopOnFail(),
RunnerRepository.window.mainpanel.p1.suitaDetails.preStopOnFail(),
RunnerRepository.window.mainpanel.p1.suitaDetails.saveDB(),
RunnerRepository.window.mainpanel.p1.suitaDetails.getDelay(),
true,array,RunnerRepository.window.mainpanel.p1.suitaDetails.getProjectDefs(),
RunnerRepository.window.mainpanel.p1.suitaDetails.getGlobalDownloadType());
} else {
cond = printXML(RunnerRepository.temp+RunnerRepository.getBar()+"Twister"+RunnerRepository.getBar()+"Users"+RunnerRepository.getBar()+user+".xml",
false,false,
RunnerRepository.window.mainpanel.p1.suitaDetails.stopOnFail(),
RunnerRepository.window.mainpanel.p1.suitaDetails.preStopOnFail(),
RunnerRepository.window.mainpanel.p1.suitaDetails.saveDB(),
RunnerRepository.window.mainpanel.p1.suitaDetails.getDelay(),
true,array,RunnerRepository.window.mainpanel.p1.suitaDetails.getProjectDefs(),null);
}
if(cond){
CustomDialog.showInfo(JOptionPane.PLAIN_MESSAGE,
RunnerRepository.window, "Success",
"File successfully saved");
RunnerRepository.window.mainpanel.p1.lp.refreshTree(100,100);
}
else CustomDialog.showInfo(JOptionPane.WARNING_MESSAGE,
RunnerRepository.window, "Warning",
"Warning, file not saved");}
}
/*
* set tc prerequisite
*/
public void setPreRequisites(Item tc){
Item i = getFirstSuitaParent(tc, false);
tc.setPrerequisite(true);
tc.setTeardown(false);
tc.setOptional(false);
sortTearSetup(i);
updateLocations(i);
deselectAll();
selectItem(tc.getPos());
RunnerRepository.window.mainpanel.p1.testconfigmngmnt.setParent(tc);
RunnerRepository.window.mainpanel.p1.suitaDetails.setParent(tc);
RunnerRepository.window.mainpanel.p1.suitaDetails.setTCDetails();
repaint();}
public void unsetPrerequisite(Item tc){
Item i = getFirstSuitaParent(tc, false);
tc.setPrerequisite(false);
sortTearSetup(i);
updateLocations(i);
deselectAll();
selectItem(tc.getPos());
repaint();
}
/*
* set tc teardown
*/
public void setTeardown(Item tc){
Item i = getFirstSuitaParent(tc, false);
tc.setTeardown(true);
tc.setPrerequisite(false);
sortTearSetup(i);
updateLocations(i);
deselectAll();
selectItem(tc.getPos());
RunnerRepository.window.mainpanel.p1.suitaDetails.setParent(tc);
RunnerRepository.window.mainpanel.p1.testconfigmngmnt.setParent(tc);
RunnerRepository.window.mainpanel.p1.suitaDetails.setTCDetails();
repaint();}
public void unsetTeardown(Item tc){
Item i = getFirstSuitaParent(tc, false);
tc.setTeardown(false);
sortTearSetup(i);
updateLocations(i);
deselectAll();
selectItem(tc.getPos());
repaint();
}
public void setOptional(Item tc){
if(tc.isOptional()){
tc.setOptional(false);
}
else{
tc.setOptional(true);
}
repaint();
}
/*
* prompt user to add
* prop to tc
*/
public void addTCProp(Item tc){
boolean found = true;
JTextField name = new JTextField();
JTextField value = new JTextField();
while(found){
JPanel p = getPropPanel(name,value);
int r = (Integer)CustomDialog.showDialog(p,JOptionPane.PLAIN_MESSAGE,
JOptionPane.OK_CANCEL_OPTION,
Grafic.this, "Property: value",null);
if(r == JOptionPane.OK_OPTION&&(!(name.getText()+value.getText()).equals(""))){
if(name.getText().equals("param")){
CustomDialog.showInfo(JOptionPane.WARNING_MESSAGE, Grafic.this,
"Warning", "'param' is used for parameters,"+
" please use a different name");
continue;}
else found = false;
ArrayList <Integer> indexpos3 = (ArrayList <Integer>)tc.getPos().clone();
indexpos3.add(new Integer(tc.getSubItemsNr()));
Item property = new Item(name.getText(),0,-1,-1,0,20,indexpos3);
property.setValue(value.getText());
property.setSubItemVisible(false);
tc.addSubItem(property);
RunnerRepository.window.mainpanel.p1.suitaDetails.setParent(tc);
RunnerRepository.window.mainpanel.p1.testconfigmngmnt.setParent(tc);
RunnerRepository.window.mainpanel.p1.suitaDetails.setTCDetails();
}
else found = false;}}
/*
* prompt user to add
* param to tc
*/
public void setParam(Item tc){
JTextField name = new JTextField();
name.setText("param");
name.setEnabled(false);
JTextField value = new JTextField();
Object[] message = new Object[] {"Name", name, "Value", value};
JPanel p = getParamPanel(name,value);
int resp = (Integer)CustomDialog.showDialog(p,JOptionPane.QUESTION_MESSAGE,
JOptionPane.OK_CANCEL_OPTION, Grafic.this,
"Property: value",null);
if(resp == JOptionPane.OK_OPTION){
ArrayList <Integer> indexpos3 = (ArrayList <Integer>)tc.getPos().clone();
indexpos3.add(new Integer(tc.getSubItemsNr()));
Item property = new Item(name.getText(),0,-1,-1,0,20,indexpos3);
property.setValue(value.getText());
if(!tc.getSubItem(0).isVisible())property.setSubItemVisible(false);
tc.addSubItem(property);
updateLocations(tc);
RunnerRepository.window.mainpanel.p1.suitaDetails.setParent(tc);
RunnerRepository.window.mainpanel.p1.testconfigmngmnt.setParent(tc);
RunnerRepository.window.mainpanel.p1.suitaDetails.setTCDetails();
}}
/*
* panel displayed on
* twister tc setParam
*/
public JPanel getParamPanel(JTextField name,JTextField value){
JPanel p = new JPanel();
p.setLayout(new BoxLayout(p, BoxLayout.Y_AXIS));
JPanel jPanel1 = new JPanel();
JLabel jLabel3 = new JLabel();
JPanel jPanel2 = new JPanel();
JLabel jLabel4 = new JLabel();
jPanel1.setLayout(new java.awt.BorderLayout());
jLabel3.setText("Name: ");
jPanel1.add(jLabel3, BorderLayout.CENTER);
p.add(jPanel1);
p.add(name);
jPanel2.setLayout(new BorderLayout());
jLabel4.setText("Value: ");
jPanel2.add(jLabel4, BorderLayout.CENTER);
p.add(jPanel2);
p.add(value);
return p;}
public void setCanRequestFocus(boolean canrequestfocus){
this.canrequestfocus = canrequestfocus;}
/*
* remove selected items from
* RunnerRepository suites array
* update indexes for next elements after removed
* update position in graph
*/
public void removeSelected(){
if(selectedcollection.size()>0){
ArrayList<Item> fordeletion = new ArrayList<Item>();
int selectednr = selectedcollection.size();
for(int i=0;i<selectednr;i++){
ArrayList<Integer> temp = new ArrayList<Integer>();
int indexsize = selectedcollection.get(i).length;
for(int j=0;j<indexsize;j++){
temp.add(new Integer(selectedcollection.get(i)[j]));}
Item theone = getItem(temp,false);
if(theone.getType()==0&&theone.getPos().get(theone.getPos().size()-1)==0){//must not delete prop on level 0
theone.select(false);}
else fordeletion.add(theone);}
ArrayList<Item> unnecessary = new ArrayList<Item>();
for(int i=0;i<fordeletion.size();i++){
Item one = fordeletion.get(i);
ArrayList<Integer>pos = (ArrayList<Integer>)one.getPos().clone();
if(pos.size()>1){
pos.remove(pos.size()-1);
Item parent = getItem(pos,false);
if(parent.isSelected()){unnecessary.add(fordeletion.get(i));}}}
for(int i=0;i<unnecessary.size();i++){fordeletion.remove(unnecessary.get(i));}
int deletenr = fordeletion.size();
for(int i=0;i<deletenr;i++){
Item theone = fordeletion.get(i);
if(theone.getPos().size()==1){
int index = theone.getPos().get(0).intValue();
RunnerRepository.getSuite().remove(theone);
if(RunnerRepository.getSuiteNr()>=index){
for(int k = index;k<RunnerRepository.getSuiteNr();k++){
RunnerRepository.getSuita(k).updatePos(0,new Integer(RunnerRepository.getSuita(k).
getPos().get(0).intValue()-1));}}}
else{
int index = theone.getPos().get(theone.getPos().size()-1).intValue();
int position = theone.getPos().size()-1;
ArrayList<Integer> temporary = (ArrayList<Integer>)theone.getPos().clone();
temporary.remove(temporary.size()-1);
Item parent = getItem(temporary,false);
parent.getSubItems().remove(theone);
if(parent.getSubItemsNr()>=index){
for(int k = index;k<parent.getSubItemsNr();k++){
parent.getSubItem(k).updatePos(position,new Integer(parent.getSubItem(k).
getPos().get(position).intValue()-1));}}}}
if(RunnerRepository.getSuiteNr()>0){
RunnerRepository.getSuita(0).setLocation(new int[]{5,10});
updateLocations(RunnerRepository.getSuita(0));}
selectedcollection.clear();
deselectAll();
RunnerRepository.window.mainpanel.p1.suitaDetails.setGlobalDetails();
RunnerRepository.window.mainpanel.p1.suitaDetails.clearDefs();
RunnerRepository.window.mainpanel.p1.suitaDetails.setParent(null);
RunnerRepository.window.mainpanel.p1.testconfigmngmnt.setParent(null);
repaint();}}
/*
* assign epid to item and its
* subsuites
*/
// public void assignEpID(Item item,String ID){
// if(item.getType()==2){
// item.setEpId(ID);
// for(int i=0;i<item.getSubItemsNr();i++){
// assignEpID(item.getSubItem(i),ID);}}}
/*
* remove tc
*/
public void removeTC(Item tc){
if(tc.getPos().size()>1){//tc nu e pe nivelul 0
int index = tc.getPos().get(tc.getPos().size()-1).intValue();
int position = tc.getPos().size()-1;
ArrayList<Integer> temp = (ArrayList<Integer>)tc.getPos().clone();
temp.remove(temp.size()-1);
Item parent = getItem(temp,false);
parent.getSubItems().remove(tc);
if(parent.getSubItemsNr()>=index){
for(int i = index;i<parent.getSubItemsNr();i++){
parent.getSubItem(i).updatePos(position,new Integer(parent.getSubItem(i).
getPos().get(position).intValue()-1));}}
updateLocations(parent);
repaint();}
else{//tc pe nivelul 0
int index = tc.getPos().get(0).intValue();
RunnerRepository.getSuite().remove(tc);
if(RunnerRepository.getSuiteNr()>=index){
for(int i= index;i<RunnerRepository.getSuiteNr();i++){
RunnerRepository.getSuita(i).updatePos(0,new Integer(RunnerRepository.getSuita(i).
getPos().get(0).intValue()-1));}
if(RunnerRepository.getSuiteNr()>0){
RunnerRepository.getSuita(0).setLocation(new int[]{5,10});
updateLocations(RunnerRepository.getSuita(0));}
repaint();
selectedcollection.clear();}}}
/*
* deselect all the items that are selected
*/
public void deselectAll(){
RunnerRepository.window.mainpanel.p1.remove.setEnabled(false);
int selectednr = selectedcollection.size()-1;
for(int i=selectednr ; i>=0 ; i--){
int [] itemselected = selectedcollection.get(i);
Item theone = RunnerRepository.getSuita(itemselected[0]);
for(int j=1;j<itemselected.length;j++){
theone = theone.getSubItem(itemselected[j]);}
theone.select(false);
selectedcollection.remove(i);}}
/*
* select item based on
* his pos indices
*/
public void selectItem(ArrayList <Integer> pos){
getItem(pos,false).select(true);
int [] theone1 = new int[pos.size()];
for(int i=0;i<pos.size();i++){
theone1[i]= pos.get(i).intValue();}
selectedcollection.add(theone1);}
/*
* get item at position x, y in suites frame
*/
public void getClickedItem(int x, int y){
Rectangle r = new Rectangle(x-1,y-1,2,2);
int suitenr = RunnerRepository.getSuiteNr();
selected = new ArrayList<Integer>();
for(int i=0;i<suitenr;i++){
if(handleClicked(r,RunnerRepository.getSuita(i))){
selected.add(i);
break;}}
if(selected.size()>0)Collections.reverse(selected);}
/*
* get item with pos indices
* test - from mastersuites or suites
*/
public static Item getItem(ArrayList <Integer> pos,boolean test){
Item theone1;
if(!test)theone1 = RunnerRepository.getSuita(pos.get(0));
else theone1 = RunnerRepository.getTestSuita(pos.get(0));
for(int j=1;j<pos.size();j++){
theone1 = theone1.getSubItem(pos.get(j));}
return theone1;}
/*
* return if item or its
* subitem have been clicked
*/
public boolean handleClicked(Rectangle r, Item item){
if(r.intersects(item.getRectangle())&&item.isVisible())return true;
else{int itemnr = item.getSubItemsNr();
for(int i=0;i<itemnr;i++){
if(handleClicked(r,item.getSubItem(i))){
selected.add(i);
return true;}}
return false;}}
/*
* handle update locations
* from suita on
*/
public void updateLocations(Item suita){
ArrayList <Integer> selected2 = (ArrayList <Integer>)suita.getPos().clone();
if(selected2.size()>1){
int index = selected2.get(0);
selected2.remove(0);
for(int i=index;i<RunnerRepository.getSuiteNr();i++){
iterateThrough(RunnerRepository.getSuita(i),selected2);
selected2 = null;}}
else if(selected2.size()==1){
for(int i=selected2.get(0);i<RunnerRepository.getSuiteNr();i++){
iterateThrough(RunnerRepository.getSuita(i),null);
}
}
y=10;
foundfirstitem=false;
updateScroll();}
/*
* returns previous item from item
* half width locatiuon
*/
public int calcPreviousPositions(Item item){
ArrayList <Integer> pos = (ArrayList <Integer>)item.getPos().clone();
if(pos.size()>1){
pos.remove(pos.size()-1);
Item temp = getItem(pos,false);
if(temp.getType()==2){
return temp.getLocation()[0]+(int)((temp.getRectangle().getWidth())/2+20);}
return temp.getLocation()[0]+(int)(temp.getRectangle().getWidth()/2+20);}
else{return 5;}}
/*
* positions item based on
* previous postion
*/
public void positionItem(Item item){
int x = calcPreviousPositions(item);
item.setLocation(new int[]{x,y});
y+=(int)(10+item.getRectangle().getHeight());}
/*
* used for calculating items positions
* iterates through subitems and positions them
* based previous location
*/
public void iterateThrough(Item item, ArrayList <Integer> theone){
int subitemsnr = item.getSubItemsNr();
if(theone==null){
if(item.isVisible()){
if(!foundfirstitem)y=item.getLocation()[1];
foundfirstitem = true;
positionItem(item);}
for(int i=0;i<subitemsnr;i++){
iterateThrough(item.getSubItem(i),null);}}
else if(theone.size()>1){
int index = theone.get(0);
theone.remove(0);
for(int i=index;i<subitemsnr;i++){
iterateThrough(item.getSubItem(i),theone);
theone=null;}}
else if(theone.size()==1){
int index = theone.get(0);
for(int i=index;i<subitemsnr;i++){
iterateThrough(item.getSubItem(i),null);}}}
public void paint(Graphics g){
g.setColor(Color.WHITE);
g.fillRect(0,0,getWidth(),getHeight());
drawDraggingLine(g);
g.setColor(Color.BLACK);
int suitenr = RunnerRepository.getSuiteNr();
for(int i=0;i<suitenr;i++){
handlePaintItem(RunnerRepository.getSuita(i),g);}}
/*
* actual drawing of dragging line
*/
public void drawDraggingLine(Graphics g){
if(line[0]!=-1){
g.setColor(new Color(150,150,150));
g.drawLine(line[0],line[1],line[2],line[3]);
g.drawLine(line[0],line[3],line[0],line[4]);}}
/*
* handle paint item
* and subitems
*/
public void handlePaintItem(Item item, Graphics g){
drawItem(item,g);
int subitemnr = item.getSubItemsNr();
if(subitemnr>0){
for(int i=0;i<subitemnr;i++){
if(!item.getSubItem(i).isVisible())continue;
handlePaintItem(item.getSubItem(i),g);}}}
/*
* handles drawing item based
* on item type
*/
public void drawItem(Item item,Graphics g){
Font font = ((DefaultTreeCellRenderer)RunnerRepository.window.mainpanel.p1.ep.tree.getCellRenderer()).getFont();
font = font.deriveFont(12);
g.setFont(font);
g.setColor(Color.BLACK);
if(item.isSelected()){
g.setColor(new Color(220,220,220));
g.fillRect((int)item.getRectangle().getX(),(int)item.getRectangle().getY(),
(int)item.getRectangle().getWidth(),(int)item.getRectangle().getHeight());
g.setColor(Color.BLACK);
g.drawRect((int)item.getRectangle().getX(),(int)item.getRectangle().getY(),
(int)item.getRectangle().getWidth(),(int)item.getRectangle().getHeight());}
if(item.getType()==2){
//draw repeat
if(item.getRepeat()>1){
g.drawString(item.getRepeat()+"X "+item.getName(),(int)item.getRectangle().getX()+45,
(int)item.getRectangle().getY()+18);
} else {
g.drawString(item.getName(),(int)item.getRectangle().getX()+45,
(int)item.getRectangle().getY()+18);
}
g.drawImage(RunnerRepository.getSuitaIcon(),(int)item.getRectangle().getX()+25,
(int)item.getRectangle().getY()+1,null);
//draw dependency icon if necesary
if(item.getDependencies().size()>0){
g.drawImage(RunnerRepository.getDependencyIcon(),(int)item.getRectangle().getX()+28,
(int)item.getRectangle().getY()+4,null);
}
}
else if(item.getType()==1){
if(item.isPrerequisite()||item.isTeardown())g.setColor(Color.RED);
else if(!item.isRunnable())g.setColor(Color.GRAY);
//draw repeat
if(item.getRepeat()>1){
g.drawString(item.getRepeat()+"X "+item.getName(),(int)item.getRectangle().getX()+50,
(int)item.getRectangle().getY()+15);
} else {
g.drawString(item.getName(),(int)item.getRectangle().getX()+50,
(int)item.getRectangle().getY()+15);
}
g.setColor(Color.BLACK);
g.drawImage(RunnerRepository.getTCIcon(),(int)item.getRectangle().getX()+25,
(int)item.getRectangle().getY()+2,null);
if(item.isOptional()){
g.drawImage(RunnerRepository.optional,(int)item.getRectangle().getX()+43,
(int)item.getRectangle().getY()+1,null);
}
//draw dependency icon if necesary
if(item.getDependencies().size()>0){
g.drawImage(RunnerRepository.getDependencyIcon(),(int)item.getRectangle().getX()+28,
(int)item.getRectangle().getY()+2,null);
}
StringBuilder sb = new StringBuilder();
sb.append("- ");
for(Configuration st:item.getConfigurations()){
if(st.isEnabled()){
sb.append(st.getFile());
sb.append("; ");
}
}
if(sb.length()>0) sb.deleteCharAt(sb.length()-2);
g.drawString(sb.toString(),(int)(item.getRectangle().getX()+item.getRectangle().getWidth()),
(int)(item.getRectangle().getY()+15));
}
else{if(item.getPos().get(item.getPos().size()-1).intValue()==0){
g.drawImage(RunnerRepository.getPropertyIcon(),
(int)item.getRectangle().getX()+2,
(int)item.getRectangle().getY()+1,null);}
g.drawString(item.getName()+" : "+item.getValue(),
(int)item.getRectangle().getX()+25,
(int)item.getRectangle().getY()+15);}
if((item.getPos().size()!=1)){
if(item.getType()==0 &&
item.getPos().get(item.getPos().size()-1).intValue()!=0){}
else{g.setColor(new Color(180,180,180));
g.drawLine((int)item.getRectangle().getX()-25,
(int)(item.getRectangle().getY()+item.getRectangle().getHeight()/2),
(int)item.getRectangle().getX(),
(int)(item.getRectangle().getY()+item.getRectangle().getHeight()/2));
ArrayList<Integer> temp = (ArrayList<Integer>)item.getPos().clone();
if(temp.get(temp.size()-1)==0){
g.drawLine((int)item.getRectangle().getX()-25,
(int)(item.getRectangle().getY()+item.getRectangle().getHeight()/2),
(int)item.getRectangle().getX()-25,(int)(item.getRectangle().getY())-5);}
else{temp.set(temp.size()-1,new Integer(temp.get(temp.size()-1).intValue()-1));
Item theone = prevInLine(item);
g.drawLine((int)item.getRectangle().getX()-25,
(int)(item.getRectangle().getY()+item.getRectangle().getHeight()/2),
(int)item.getRectangle().getX()-25,
(int)(theone.getRectangle().getY()+theone.getRectangle().getHeight()/2));}
g.setColor(Color.BLACK);}}
if(item.getType()!=0){
g.drawRect((int)item.getCheckRectangle().getX(),
(int)item.getCheckRectangle().getY(),
(int)item.getCheckRectangle().getWidth(),
(int)item.getCheckRectangle().getHeight());
if(item.getCheck()){
Rectangle r = item.getCheckRectangle();
int x2[] = {(int)r.getX(),(int)r.getX()+(int)r.getWidth()/2,
(int)r.getX()+(int)r.getWidth(),
(int)r.getX()+(int)r.getWidth()/2};
int y2[] = {(int)r.getY()+(int)r.getHeight()/2,
(int)r.getY()+(int)r.getHeight(),
(int)r.getY(),(int)r.getY()+(int)r.getHeight()-5};
g.fillPolygon(x2,y2,4);}}
if(item.getType()==2){
int x = (int)(item.getRectangle().getX()+item.getRectangle().getWidth());
if(item.getEpId()!=null && item.getEpId().length>0){
font = font.deriveFont(11);
g.setFont(font);
StringBuilder EP = new StringBuilder();
for(String s:item.getEpId()){
EP.append(s+";");
}
EP.deleteCharAt(EP.length()-1);
g.drawString(" - "+EP.toString(),(int)(item.getRectangle().getX()+item.getRectangle().getWidth()),
(int)(item.getRectangle().getY()+18));
FontMetrics metrics = g.getFontMetrics(font);
int adv = metrics.stringWidth(" - "+EP.toString());
x += adv+2;}
StringBuilder sb = new StringBuilder();
sb.append("- ");
for(Configuration st:item.getConfigurations()){
if(st.isEnabled()){
sb.append(st.getFile());
sb.append("; ");
}
}
if(sb.length()>0) sb.deleteCharAt(sb.length()-2);
g.drawString(sb.toString(),x,
(int)(item.getRectangle().getY()+18));
}
}
/*
* changes suites file name and sets
* name accordingly on tab
*/
public void setUser(String user){
if(user!=null){
RunnerRepository.window.mainpanel.p1.setOpenedfile(new File(user).getName());
} else {
RunnerRepository.window.mainpanel.p1.setOpenedfile("");
}
RunnerRepository.window.mainpanel.p1.suitaDetails.setGlobalDetails();
RunnerRepository.window.mainpanel.p1.suitaDetails.clearDefs();
RunnerRepository.window.mainpanel.p1.suitaDetails.setParent(null);
RunnerRepository.window.mainpanel.p1.testconfigmngmnt.setParent(null);
this.user = user;}
/*
* returns file name and path
*/
public String getUser(){
return user;}
/*
* parses xml and represents in grafic
*/
public void parseXML(File file){
// new XMLReader(file).parseXML(getGraphics(),false);
new XMLReader(file).parseXML(getGraphics(),false,RunnerRepository.getSuite(),true);
}
/*
* writes xml on file
* if skip => master xml
*/
public boolean printXML(String user, boolean skip,
boolean local, boolean stoponfail,boolean prestoponfail,
String savedb, String delay,boolean lib, ArrayList<Item> array,
String [][] projdefined,String downloadlibraryoption){
//skip = true
try{if(array==null)array = RunnerRepository.getSuite();
XMLBuilder xml = new XMLBuilder(array);
boolean cond;
if(RunnerRepository.isMaster()){
cond = xml.createXML(skip,stoponfail,prestoponfail,false,
RunnerRepository.window.mainpanel.p1.suitaDetails.getPreScript(),
RunnerRepository.window.mainpanel.p1.suitaDetails.getPostScript(),
savedb,delay,RunnerRepository.window.mainpanel.p1.suitaDetails.getGlobalLibs(),
projdefined,downloadlibraryoption);
} else {
cond = xml.createXML(skip,stoponfail,prestoponfail,false,
RunnerRepository.window.mainpanel.p1.suitaDetails.getPreScript(),
RunnerRepository.window.mainpanel.p1.suitaDetails.getPostScript(),
savedb,delay,
RunnerRepository.window.mainpanel.p1.suitaDetails.getGlobalLibs(),
projdefined,null);
}
if(!cond){
return false;
}
return xml.writeXMLFile(user,local,false,lib);}
catch(Exception e){
e.printStackTrace();
return false;}}
public int countSubtreeNr(int nr, Object child){
boolean cond; //if it is directory or file
cond = RunnerRepository.window.mainpanel.p1.ep.tree.getModel().isLeaf((TreeNode)child);
ArrayList <TreeNode>list = new ArrayList<TreeNode>();
while ((TreeNode)child != null) {
list.add((TreeNode)child);
child = ((TreeNode)child).getParent();}
Collections.reverse(list);
child = new TreePath(list.toArray());
if(cond){return nr+1;}
else{int nr1 = RunnerRepository.window.mainpanel.p1.ep.tree.getModel().
getChildCount(((TreePath)child).getLastPathComponent());
for(int j=0;j<nr1;j++){
nr = countSubtreeNr(nr,RunnerRepository.window.mainpanel.p1.ep.tree.
getModel().getChild((TreeNode)((TreePath)child).getLastPathComponent(),j));}
return nr;}}
public void drop(int x, int y,String source){
if(source.equals("tc")){
deselectAll();
requestFocus();
int max = RunnerRepository.window.mainpanel.p1.ep.getSelected().length;
if(max>0){
for(int i=0;i<max;i++){
boolean cond = RunnerRepository.window.mainpanel.p1.ep.tree.getModel().
isLeaf((TreeNode)RunnerRepository.window.mainpanel.p1.
ep.getSelected()[i].getLastPathComponent());//has no children
if(cond){
String name = RunnerRepository.window.mainpanel.p1.ep.
getSelected()[i].getPath()[RunnerRepository.window.mainpanel.p1.ep.getSelected()[i].
getPathCount()-2]+"/"+RunnerRepository.window.mainpanel.p1.
ep.getSelected()[i].getPath()[RunnerRepository.window.
mainpanel.p1.ep.getSelected()[i].getPathCount()-1];
try{name = name.split(RunnerRepository.getTestSuitePath())[1];}
catch(Exception e){
System.out.println("Could not find projects path:"+RunnerRepository.getTestSuitePath()+" in filename:"+name);
e.printStackTrace();}
FontMetrics metrics = getGraphics().getFontMetrics(new Font("TimesRoman", Font.PLAIN, 13));
Item newItem = new Item(name,1, -1, -1, metrics.stringWidth(name)+48, 20, null);
ArrayList<Integer> pos = new ArrayList <Integer>();
pos.add(new Integer(0));
ArrayList<Integer> pos2 = (ArrayList <Integer>)pos.clone();
pos2.add(new Integer(0));
Item property = new Item("Running",0,-1,-1,(metrics.stringWidth("Running: true"))+28,20,pos2);
property.setValue("true");
property.setSubItemVisible(false);
newItem.addSubItem(property);
newItem.setVisible(false);
clone.add(newItem);}
else{
subtreeTC((TreeNode)RunnerRepository.window.mainpanel.p1.ep.getSelected()[i].getLastPathComponent(),null,0,"tc");}}
handleMouseDroped(y);
}
} else if(source.equals("lib")){
deselectAll();
requestFocus();
int max = RunnerRepository.window.mainpanel.p1.lp.getSelected().length;
if(max>0){
ArrayList<Item>list = new ArrayList();
for(int i=0;i<max;i++){
boolean cond = RunnerRepository.window.mainpanel.p1.lp.tree.getModel().
isLeaf((TreeNode)RunnerRepository.window.mainpanel.p1.
lp.getSelected()[i].getLastPathComponent());//has no children
if(cond){
String name = RunnerRepository.window.mainpanel.p1.lp.
getSelected()[i].getPath()[RunnerRepository.window.mainpanel.p1.lp.getSelected()[i].
getPathCount()-2]+"/"+RunnerRepository.window.mainpanel.p1.
lp.getSelected()[i].getPath()[RunnerRepository.window.
mainpanel.p1.lp.getSelected()[i].getPathCount()-1];
try{
String path = RunnerRepository.getPredefinedSuitesPath();
String content = RunnerRepository.readPredefinedProjectFile(name);
File file = new File(RunnerRepository.temp+RunnerRepository.getBar()+"Twister"+
RunnerRepository.getBar()+"Users"+RunnerRepository.getBar()+name.replace(path, ""));
BufferedWriter writer = new BufferedWriter(new FileWriter(file));
writer.write(content);
writer.close();
new XMLReader(file).parseXML(getGraphics(), false, list, false);
for(Item itm :list){
clone.add(itm);
}
} catch (Exception e){
e.printStackTrace();
}
}
}
handleMouseDroped(y);
Item parent = getFirstSuitaParent(list.get(0), false);
if(parent!=null)checkSameName(parent);
}
}else if(source.equals("clearcase")){
deselectAll();
requestFocus();
int max = RunnerRepository.window.mainpanel.p1.cp.getSelected().length;
if(max>0){
for(int i=0;i<max;i++){
boolean cond = RunnerRepository.window.mainpanel.p1.cp.tree.getModel().
isLeaf((TreeNode)RunnerRepository.window.mainpanel.p1.
cp.getSelected()[i].getLastPathComponent());//has no children
if(cond){
String name = RunnerRepository.window.mainpanel.p1.cp.
getSelected()[i].getPath()[RunnerRepository.window.mainpanel.p1.cp.getSelected()[i].
getPathCount()-2]+"/"+RunnerRepository.window.mainpanel.p1.
cp.getSelected()[i].getPath()[RunnerRepository.window.
mainpanel.p1.cp.getSelected()[i].getPathCount()-1];
FontMetrics metrics = getGraphics().getFontMetrics(new Font("TimesRoman", Font.PLAIN, 13));
Item newItem = new Item(name,1, -1, -1, metrics.stringWidth(name)+48, 20, null);
newItem.setClearcase(true);
ArrayList<Integer> pos = new ArrayList <Integer>();
pos.add(new Integer(0));
ArrayList<Integer> pos2 = (ArrayList <Integer>)pos.clone();
pos2.add(new Integer(0));
Item property = new Item("Running",0,-1,-1,(metrics.stringWidth("Running: true"))+28,20,pos2);
property.setValue("true");
property.setSubItemVisible(false);
newItem.addSubItem(property);
newItem.setVisible(false);
clone.add(newItem);}
else{
subtreeTC((TreeNode)RunnerRepository.window.mainpanel.p1.cp.getSelected()[i].getLastPathComponent(),null,0,"clearcase");}}
handleMouseDroped(y);
}
}
}
/*
* check if this item has children
* with same name and prompt to rename
*/
private void checkSameName(Item item){
for(Item i:item.getSubItems()){
for(Item j:item.getSubItems()){
if(j.getType()!=2)continue;
if(i.getName().equals(j.getName())&&i!=j){
if(i.getType()!=2)continue;
deselectAll();
selectItem(j.getPos());
RunnerRepository.window.mainpanel.p1.remove.setEnabled(true);
RunnerRepository.window.mainpanel.p1.sc.pane.getVerticalScrollBar().setValue((int)j.getCheckRectangle().getCenterY());
String name = "";
while(name==null||name.equals("")||name.equals(j.getName())){
name = CustomDialog.showInputDialog(JOptionPane.WARNING_MESSAGE,
JOptionPane.OK_CANCEL_OPTION,
Grafic.this, "Warning",
"There is a suite with the same name, please rename.");
for(Item k:item.getSubItems()){
if(name.equals(k.getName())){
name = "";
}
}
}
j.setName(name);
RunnerRepository.window.mainpanel.p1.suitaDetails.setParent(j);
RunnerRepository.window.mainpanel.p1.testconfigmngmnt.setParent(j);
RunnerRepository.window.mainpanel.p1.suitaDetails.setSuiteDetails(false);
repaint();
}
}
}
}
public ArrayList<int []> getSelectedCollection(){
return selectedcollection;}
public int subtreeTC(Object child, Item parent, int location, String source){
if(source.equals("tc")){
boolean cond; //if it is directory or file
cond = RunnerRepository.window.mainpanel.p1.ep.tree.getModel().isLeaf((TreeNode)child);
ArrayList <TreeNode>list = new ArrayList<TreeNode>();
while ((TreeNode)child != null){
list.add((TreeNode)child);
child = ((TreeNode)child).getParent();}
Collections.reverse(list);
child = new TreePath(list.toArray());
if(cond){
if(parent==null){//called from jtree drop
String name = ((TreePath)child).getPath()[((TreePath)child).getPathCount()-2]+
"/"+((TreePath)child).getPath()[((TreePath)child).
getPathCount()-1];
name = name.split(RunnerRepository.getTestSuitePath())[1];
FontMetrics metrics = getGraphics().getFontMetrics(new Font("TimesRoman", Font.PLAIN, 13));
Item newItem = new Item(name,1, -1, -1, metrics.stringWidth(name)+48, 20, null);
ArrayList<Integer> pos = new ArrayList <Integer>();
pos.add(new Integer(0));
ArrayList<Integer> pos2 = (ArrayList <Integer>)pos.clone();
pos2.add(new Integer(0));
Item property = new Item("Running",0,-1,-1,(metrics.stringWidth("Running: true"))+28,20,pos2);
property.setValue("true");
property.setSubItemVisible(false);
newItem.addSubItem(property);
newItem.setVisible(false);
clone.add(newItem);
return 0;}
addNewTC(((TreePath)child).getPath()[((TreePath)child).getPathCount()-2]+
"/"+((TreePath)child).getPath()[((TreePath)child).
getPathCount()-1],parent,location,source);
return location+1;}
else{int nr = RunnerRepository.window.mainpanel.p1.ep.tree.getModel().
getChildCount(((TreePath)child).getLastPathComponent());
for(int j=0;j<nr;j++){
location = subtreeTC(RunnerRepository.window.mainpanel.p1.ep.tree.getModel().
getChild((TreeNode)((TreePath)child).getLastPathComponent(),j),
parent,location,source);}
return location;}
} else if(source.equals("clearcase")){
boolean cond; //if it is directory or file
cond = RunnerRepository.window.mainpanel.p1.cp.tree.getModel().isLeaf((TreeNode)child);
ArrayList <TreeNode>list = new ArrayList<TreeNode>();
while ((TreeNode)child != null){
list.add((TreeNode)child);
child = ((TreeNode)child).getParent();}
Collections.reverse(list);
child = new TreePath(list.toArray());
if(cond){
if(parent==null){//called from jtree drop
String name = ((TreePath)child).getPath()[((TreePath)child).getPathCount()-2]+
"/"+((TreePath)child).getPath()[((TreePath)child).
getPathCount()-1];
//name = name.split(RunnerRepository.window.mainpanel.getP5().root)[1];
FontMetrics metrics = getGraphics().getFontMetrics(new Font("TimesRoman", Font.PLAIN, 13));
Item newItem = new Item(name,1, -1, -1, metrics.stringWidth(name)+48, 20, null);
newItem.setClearcase(true);
ArrayList<Integer> pos = new ArrayList <Integer>();
pos.add(new Integer(0));
ArrayList<Integer> pos2 = (ArrayList <Integer>)pos.clone();
pos2.add(new Integer(0));
Item property = new Item("Running",0,-1,-1,(metrics.stringWidth("Running: true"))+28,20,pos2);
property.setValue("true");
property.setSubItemVisible(false);
newItem.addSubItem(property);
newItem.setVisible(false);
clone.add(newItem);
return 0;}
addNewTC(((TreePath)child).getPath()[((TreePath)child).getPathCount()-2]+
"/"+((TreePath)child).getPath()[((TreePath)child).
getPathCount()-1],parent,location,source);
return location+1;}
else{int nr = RunnerRepository.window.mainpanel.p1.cp.tree.getModel().
getChildCount(((TreePath)child).getLastPathComponent());
for(int j=0;j<nr;j++){
location = subtreeTC(RunnerRepository.window.mainpanel.p1.cp.tree.getModel().
getChild((TreeNode)((TreePath)child).getLastPathComponent(),j),
parent,location,source);}
return location;}
}
return -1;
}
/*
* adds new tc, accepts a file that is tc and suite pos in vector
*/
public void addNewTC(String file,Item parent,int location,String source){
if(source.equals("tc")){
file = file.split(RunnerRepository.getTestSuitePath())[1];
FontMetrics metrics = getGraphics().getFontMetrics(new Font("TimesRoman", Font.PLAIN, 13));
ArrayList <Integer> indexpos = (ArrayList <Integer>)parent.getPos().clone();
indexpos.add(new Integer(location));
Item tc = new Item(file,1,-1,-1,metrics.stringWidth(file)+48,20,indexpos);
ArrayList <Integer> indexpos2 = (ArrayList <Integer>)indexpos.clone();
indexpos2.add(new Integer(0));
Item property = new Item("Running",0,-1,-1,(metrics.stringWidth("Running: true"))+28,20,indexpos2);
property.setSubItemVisible(false);
property.setValue("true");
tc.addSubItem(property);
if(parent.getSubItemsNr()>0){if(!parent.getSubItem(0).isVisible())tc.setSubItemVisible(false);}
tc.setVisible(false);
parent.insertSubItem(tc,location);
} else if(source.equals("clearcase")){
//file = file.split(RunnerRepository.window.mainpanel.getP5().root)[1];
FontMetrics metrics = getGraphics().getFontMetrics(new Font("TimesRoman", Font.PLAIN, 13));
ArrayList <Integer> indexpos = (ArrayList <Integer>)parent.getPos().clone();
indexpos.add(new Integer(location));
Item tc = new Item(file,1,-1,-1,metrics.stringWidth(file)+48,20,indexpos);
tc.setClearcase(true);
ArrayList <Integer> indexpos2 = (ArrayList <Integer>)indexpos.clone();
indexpos2.add(new Integer(0));
Item property = new Item("Running",0,-1,-1,(metrics.stringWidth("Running: true"))+28,20,indexpos2);
property.setSubItemVisible(false);
property.setValue("true");
tc.addSubItem(property);
if(parent.getSubItemsNr()>0){if(!parent.getSubItem(0).isVisible())tc.setSubItemVisible(false);}
tc.setVisible(false);
parent.insertSubItem(tc,location);
}
}
/*
* inserts new tc, accepts a file that is tc and suite pos in vector
*/
public void insertNewTC(String file,ArrayList <Integer> pos,Item parent,Item item){
Item tc = null;
if(item==null){
file = file.split(RunnerRepository.getTestSuitePath())[1];
FontMetrics metrics = getGraphics().getFontMetrics(new Font("TimesRoman", Font.PLAIN, 13));
tc = new Item(file,1,-1,-1,metrics.stringWidth(file)+48,20,pos);
ArrayList<Integer>pos2 = (ArrayList <Integer>)pos.clone();
pos2.add(new Integer(0));
Item property = new Item("Running",0,-1,-1,(metrics.stringWidth("Running: true"))+28,20,pos2);
property.setSubItemVisible(false);
property.setValue("true");
tc.addSubItem(property);
tc.setVisible(false);}
else{tc=item;
tc.selectAll(tc, false);}
if(parent.getSubItemsNr()>0)if(!parent.getSubItem(0).isVisible())tc.setSubItemVisible(false);
parent.insertSubItem(tc,pos.get(pos.size()-1));
updateLocations(parent);
repaint();}
public byte areTheSame(int nr){
final ArrayList<Integer>temp = new ArrayList<Integer>();
Item item;
boolean same = true;
byte type = 3;
for(int i=0;i<nr;i++){
temp.clear();
int [] indices = selectedcollection.get(i);
for(int j=0;j<indices.length;j++)temp.add(new Integer(indices[j]));
item = getItem(temp,false);
if(type!=3&&type!=item.getType()){
same = false;
break;}
else if(type==3)type = (byte)item.getType();}
if(same)return type;
else return -1;}
public int getLastY(Item item, int height){
if(height<=(item.getRectangle().getY()+item.getRectangle().getHeight())){
height=(int)(item.getRectangle().getY()+item.getRectangle().getHeight());
int nr = item.getSubItemsNr()-1;
for(int i=nr;i>=0;i--){
if(item.getSubItem(i).isVisible()){height = getLastY(item.getSubItem(i),height);}}
return height;}
else return height;}
/*
* scroll update method
*/
public void updateScroll(){
int y1=0;
for(int i=0;i<RunnerRepository.getSuiteNr();i++){
if(RunnerRepository.getSuita(i).isVisible())y1 = getLastY(RunnerRepository.getSuita(i),y1);}
if(y1>getHeight()){
setPreferredSize(new Dimension(425,y1+10));
revalidate();}
if(getHeight()>595){
if(y1<getHeight()-10){
setPreferredSize(new Dimension(425,y1+10));
revalidate();}
if(y1<595){
setPreferredSize(new Dimension(445,595));
revalidate();}}}
public void addSuiteFromButton(){
if(selectedcollection.size()==0)new AddSuiteFrame(Grafic.this, null,0);
else{
ArrayList <Integer> temp = new ArrayList <Integer>();
for(int j=0;j<selectedcollection.get(0).length;j++){
temp.add(new Integer(selectedcollection.get(0)[j]));}
if(selectedcollection.size()>1||getItem(temp,false).getType()!=2){
CustomDialog.showInfo(JOptionPane.WARNING_MESSAGE, Grafic.this,
"Warning", "Please select only one suite.");}
else new AddSuiteFrame(Grafic.this, getItem(temp,false),0);}}
public void setOnlyOptionals(boolean value){
onlyOptionals = value;
}
public boolean getOnlyOptionals(){
return onlyOptionals;
}
public void showOptionals(Item item){
if(item==null){
for(Item i:RunnerRepository.getSuite()){
showOptionals(i);
}
}
else if(item.getType()==1){
if(!onlyOptionals){
item.setSubItemVisible(true);
item.setVisible(false);
}
else if(!item.isOptional()){
item.setSubItemVisible(false);
}
}
else if(item.getType()==2){
for(int i=0;i<item.getSubItemsNr();i++){
showOptionals(item.getSubItem(i));}}}
/*
* gets the first upper suite parent
*/
public static Item getFirstSuitaParent(Item item, boolean test){
ArrayList <Integer> temp = (ArrayList <Integer>)item.getPos().clone();
if(temp.size()==1)return null;
if(item.getType()!=0){
temp.remove(temp.size()-1);
return getItem(temp,test);}
else{
temp.remove(temp.size()-1);
temp.remove(temp.size()-1);
return getItem(temp,test);}}
public static Item getTcParent(Item item, boolean test){
ArrayList <Integer> temp = (ArrayList <Integer>)item.getPos().clone();
if(item.getType()==0){
temp.remove(temp.size()-1);
return getItem(temp,test);}
return null;}
/*
* gets the first suite parent
* at the head of the Hierarchy
*/
public static Item getParent(Item item, boolean test){
if(item.getPos().size()>1){
ArrayList <Integer> temp = new ArrayList <Integer>();
temp.add(item.getPos().get(0));
return getItem(temp,test);}
else return null;}
/*
* check if item is available in suites array(maybe it was deleted)
*/
public static boolean chekItemInArray(Item item, boolean test){
ArrayList <Integer> temp = (ArrayList <Integer>)item.getPos().clone();
Item suiteitem;
if(temp.size()==1){
if(test){
suiteitem = RunnerRepository.getTestSuite().get(temp.get(0));
} else {
suiteitem = RunnerRepository.getSuita(temp.get(0));
}
} else {
if(item.getType()==0){//property
temp.remove(temp.size()-1);
temp.remove(temp.size()-1);
suiteitem = getItem(temp,test);
suiteitem = suiteitem.getSubItem(item.getPos().get(item.getPos().size()-2));
suiteitem = suiteitem.getSubItem(item.getPos().get(item.getPos().size()-1));
} else if(item.getType()==1){//tc
temp.remove(temp.size()-1);
suiteitem = getItem(temp,test);
if(suiteitem!=null){
if(suiteitem.getSubItemsNr()>item.getPos().get(item.getPos().size()-1)){
suiteitem = suiteitem.getSubItem(item.getPos().get(item.getPos().size()-1));
} else {
suiteitem = null;
}
}
} else {//suite
suiteitem = getItem(temp,test);
}
}
return suiteitem==item;
}
class AddSuiteFrame extends JFrame{
private static final long serialVersionUID = 1L;
JButton ok ;
JTextField namefield;
JList <String>epidfield;
JComponent mainwindow;
public void okAction(Item suita,int pos){
if(namefield.getText().equals("")){//don't allow empty names
CustomDialog.showInfo(JOptionPane.WARNING_MESSAGE, Grafic.this,
"Error", "SUT name must not be empty!");
return;
}
FontMetrics metrics = getGraphics().getFontMetrics(new Font("TimesRoman", Font.BOLD, 14));
int width = metrics.stringWidth(namefield.getText());
if(suita!=null){
if(pos==0){
for(int j = 0;j<suita.getSubItemsNr();j++){
suita.getSubItem(j).updatePos(suita.getPos().size(),
new Integer(suita.getSubItem(j).getPos().
get(suita.getPos().size()).intValue()+1));}
ArrayList <Integer> indexpos = (ArrayList <Integer>)suita.getPos().clone();
indexpos.add(new Integer(0));
Item item = new Item(namefield.getText(),2, -1,5, width+40,25 , indexpos);
if(suita.getSubItemsNr()>0&&!suita.getSubItem(0).isVisible())item.setSubItemVisible(false);
item.setEpId(suita.getEpId());
suita.insertSubItem(item,0);
Grafic.this.updateLocations(suita);}
else{ArrayList <Integer> indexpos = (ArrayList <Integer>)suita.getPos().clone();
indexpos.add(new Integer(pos));
Item item = new Item(namefield.getText(),2, -1,5, width+40,25 , indexpos);
if(suita.getSubItemsNr()>0&&!suita.getSubItem(0).isVisible())item.setSubItemVisible(false);
item.setEpId(suita.getEpId());
suita.insertSubItem(item,pos);
Grafic.this.updateLocations(suita);}}
else{ArrayList <Integer> indexpos = new ArrayList <Integer>();
indexpos.add(new Integer(RunnerRepository.getSuiteNr()));
Item item = new Item(namefield.getText(),2, -1, 5, width+40,25 , indexpos);
String [] selected = new String[epidfield.getSelectedValuesList().size()];
for(int i=0;i<epidfield.getSelectedValuesList().size();i++){
selected[i] = epidfield.getSelectedValuesList().get(i).toString();
}
item.setEpId(selected);
RunnerRepository.addSuita(item);
if(RunnerRepository.getSuiteNr()>1)Grafic.this.updateLocations(RunnerRepository.getSuita(RunnerRepository.getSuiteNr()-2));
else Grafic.this.updateLocations(RunnerRepository.getSuita(0));}
Grafic.this.setCanRequestFocus(true);
(SwingUtilities.getWindowAncestor(ok)).dispose();
Grafic.this.repaint();}
public AddSuiteFrame(final JComponent mainwindow,final Item suita,final int pos){
JLabel name = new JLabel();
JLabel EPId = new JLabel();
namefield = new JTextField();
JScrollPane jScrollPane1 = new JScrollPane();
String [] vecresult = RunnerRepository.window.mainpanel.p4.getSut().sut.getSutTree().getSutsName();
if(vecresult!=null){
int size = vecresult.length;
for(int i=0;i<size;i++){
vecresult[i] = vecresult[i].replace(".user", "(user)");
vecresult[i] = vecresult[i].replace(".system", "(system)");
}
}
epidfield = new JList<String>(vecresult);
try{epidfield.setSelectedIndex(0);}
catch(Exception e){e.printStackTrace();}
ok = new JButton();
name.setText("Suite Name:");
EPId.setText("SUT Name:");
jScrollPane1.setViewportView(epidfield);
ok.setText("OK");
JPanel main = new JPanel();
GroupLayout layout = new GroupLayout(main);
main.setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addGroup(layout.createParallelGroup(GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addComponent(name)
.addPreferredGap(LayoutStyle.ComponentPlacement.RELATED)
.addComponent(namefield))
.addGroup(layout.createSequentialGroup()
.addComponent(EPId)
.addPreferredGap(LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 375, Short.MAX_VALUE))
.addGroup(GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
.addGap(0, 0, Short.MAX_VALUE)
.addComponent(ok, GroupLayout.PREFERRED_SIZE, 80, GroupLayout.PREFERRED_SIZE)))
.addContainerGap())
);
layout.setVerticalGroup(
layout.createParallelGroup(GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addGroup(layout.createParallelGroup(GroupLayout.Alignment.BASELINE)
.addComponent(name)
.addComponent(namefield, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE))
.addPreferredGap(LayoutStyle.ComponentPlacement.RELATED)
.addGroup(layout.createParallelGroup(GroupLayout.Alignment.LEADING)
.addComponent(EPId)
.addComponent(jScrollPane1, GroupLayout.DEFAULT_SIZE, 260, Short.MAX_VALUE))
.addPreferredGap(LayoutStyle.ComponentPlacement.RELATED)
.addComponent(ok)
.addContainerGap())
);
add(main);
addWindowFocusListener(new WindowFocusListener(){
public void windowLostFocus(WindowEvent ev){
toFront();}
public void windowGainedFocus(WindowEvent ev){}});
setAlwaysOnTop(true);
Grafic.this.setCanRequestFocus(false);
ok.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent ev){
okAction(suita,pos);}});
addWindowListener(new WindowAdapter(){
public void windowClosing(WindowEvent e){
Grafic.this.setCanRequestFocus(true);
(SwingUtilities.getWindowAncestor(ok)).dispose();}});
Action actionListener = new AbstractAction(){
public void actionPerformed(ActionEvent actionEvent){
JButton source = (JButton) actionEvent.getSource();
okAction(suita,pos);}};
InputMap keyMap = new ComponentInputMap(ok);
keyMap.put(KeyStroke.getKeyStroke(KeyEvent.VK_ENTER, 0), "action");
ActionMap actionMap = new ActionMapUIResource();
actionMap.put("action", actionListener);
SwingUtilities.replaceUIActionMap(ok, actionMap);
SwingUtilities.replaceUIInputMap(ok, JComponent.WHEN_IN_FOCUSED_WINDOW, keyMap);
setBounds(400,300,300,400);
setVisible(true);
namefield.requestFocus();
}
}
}
class CompareItems implements Comparator{
public int compare(Object emp1, Object emp2){
return ((Item)emp1).getName().compareToIgnoreCase(((Item)emp2).getName());}}
class XMLFilter extends FileFilter {
public boolean accept(File f) {
return f.isDirectory() || f.getName().toLowerCase().endsWith(".xml");}
public String getDescription() {return ".xml files";}}
|
#!/bin/bash
. ./defaults.sh
. ../../include/common.sh
. .envrc
curl http://"$EKCP_HOST"/kubeconfig/"${CLUSTER_NAME}" > kubeconfig
ok "Kubeconfig for $BACKEND correctly imported"
|
#!/bin/bash
if [ -z "$1" ]; then
echo 'Usage: rs-auth-github.sh <Access Key>'
exit 1
fi
echo -e '\n\n'
echo 'Executing using Token in Query:'
echo ''
curl -X GET --header 'Accept: application/json' 'http://localhost:3000/api/vPassenger'?access_token=$1
echo -e '\n\n'
echo 'Executing using Token in Header:'
echo -e '\n\n'
curl -X GET --header 'Accept: application/json' --header "x-access-token: $1" 'http://localhost:3000/api/vPassenger'
echo -e '\n\n'
|
var user = user || {};
user.login_form = {
LoginForm: function () {
var self = this;
self.email = ko.observable("");
self.password = ko.observable("");
self.submitForm = function (form) {
$.ajax({
url: "/api/login",
type: 'POST',
contentType: 'application/json; charset=utf-8',
data: JSON.stringify({
email: self.email(),
password: <PASSWORD>.password()
}),
error: function (jqXHR) {
user.errorUtils.setErrorsToForm($(form), JSON.parse(jqXHR.responseText));
}
}).done(function () {
window.location.replace("/login");
});
};
}
};
$(function() {
var model = document.getElementById("login-form");
if (model) {
ko.applyBindings(new user.login_form.LoginForm(), model);
}
});
|
<reponame>godbobo/Admin<filename>spring-boot/src/main/java/com/aqzscn/www/weixin/domain/vo/UserOption.java
package com.aqzscn.www.weixin.domain.vo;
import lombok.Data;
/**
* 记录用户当前操作
* @author Godbobo
* @version 1.0
* @date 2019/9/7 9:23
*/
@Data
public class UserOption {
// 功能编号
private String menuId;
// 功能名称
private String menuName;
}
|
package com.carson.cloud.business.controller;
import com.carson.cloud.business.common.Result;
import com.carson.cloud.business.entity.UserEntity;
import com.carson.cloud.business.service.UserService;
import com.carson.cloud.business.viewmodel.LoginByPasswordIVO;
import com.carson.cloud.business.viewmodel.LoginByPasswordOVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class LoginController {
// @PostMapping(value = "/login/loginByPassword")
// Result<LoginByPasswordOVO> loginByPassword(@RequestBody LoginByPasswordIVO ivo) {
// LoginByPasswordOVO ovo = new LoginByPasswordOVO();
// ovo.setPassword(<PASSWORD>());
// ovo.setUserName(ivo.getUserName());
// ovo.setTelephone("180****0000");
// ovo.setUserId("1001");
// Result<LoginByPasswordOVO> result = new Result<>();
// result.setData(ovo);
// return result;
// }
@Autowired
private UserService userService;
//ok
@PostMapping(value = "/login/loginByPassword")
Result<UserEntity> loginByPassword(@RequestBody LoginByPasswordIVO ivo) {
// UserEntity user = new UserEntity();
UserEntity user = userService.findUserByName(ivo.getUserName());
String password = user.getPassword();
Result<UserEntity> result = new Result<>();
if(ivo.getPassword().equals(password)) {
result.setData(user);
}else {
result.setData(null);
result.setCode(510);
}
return result;
}
}
|
void selectionSort(int arr[], int n)
{
int i, j, min_idx;
// One by one move boundary of unsorted subarray
for (i = 0; i < n-1; i++)
{
// Find the minimum element in unsorted array
min_idx = i;
for (j = i+1; j < n; j++)
if (arr[j] < arr[min_idx])
min_idx = j;
// Swap the found minimum element with the first element
swap(arr[min_idx], arr[i]);
}
}
|
class Api::V4::Games::RunnersController < Api::V4::ApplicationController
before_action :set_game, only: [:index]
def index
render json: Api::V4::UserBlueprint.render(@game.users, root: :runners)
end
end
|
<gh_stars>10-100
//
// LiveDataExample.h
// Examples
//
// Created by <NAME> on 6/7/17.
// Copyright © 2017 Mapbox. All rights reserved.
//
#import <UIKit/UIKit.h>
@interface LiveDataExample : UIViewController
@end
|
<filename>Plugins/UnrealDotNet/Source/UnrealDotNetRuntime/Public/Generate/Export/UVectorFieldComponent.h
#pragma once
// This file was created automatically, do not modify the contents of this file.
PRAGMA_DISABLE_DEPRECATION_WARNINGS
#include "CoreMinimal.h"
#include "ManageEventSender.h"
#include "Runtime/Engine/Classes/Components/VectorFieldComponent.h"
// Source file C:\Program Files\Epic Games\UE_4.22\Engine\Source\Runtime\Engine\Classes\Components\VectorFieldComponent.h:18
extern "C"
{
DOTNET_EXPORT auto E_PROP_UVectorFieldComponent_Intensity_GET(UVectorFieldComponent* Ptr) { return Ptr->Intensity; }
DOTNET_EXPORT void E_PROP_UVectorFieldComponent_Intensity_SET(UVectorFieldComponent* Ptr, float Value) { Ptr->Intensity = Value; }
DOTNET_EXPORT auto E_PROP_UVectorFieldComponent_Tightness_GET(UVectorFieldComponent* Ptr) { return Ptr->Tightness; }
DOTNET_EXPORT void E_PROP_UVectorFieldComponent_Tightness_SET(UVectorFieldComponent* Ptr, float Value) { Ptr->Tightness = Value; }
DOTNET_EXPORT INT_PTR E_NewObject_UVectorFieldComponent(UObject* Parent, char* Name)
{
return (INT_PTR)NewObject<UVectorFieldComponent>(Parent, FName(UTF8_TO_TCHAR(Name)));
}
DOTNET_EXPORT auto E_UVectorFieldComponent_SetIntensity(UVectorFieldComponent* Self, float NewIntensity)
{
auto _p0 = NewIntensity;
Self->SetIntensity(_p0);
}
}
PRAGMA_ENABLE_DEPRECATION_WARNINGS
|
package Combination_Sum_IV;
import java.util.HashMap;
public class Solution {
public int combinationSum4(int[] nums, int target) {
if (nums == null || nums.length == 0) return 0;
// HashMap<Integer, Integer> map = new HashMap<>();
// return generate(target, nums, map);
/**
* DP solution
* From bottom to up, calculate the possible result for every number in [0, target]
* 5ms
*/
int[] dp = new int[target + 1];
dp[0] = 1;
for (int curTarget = 1; curTarget < dp.length; curTarget++) {
for (int i = 0; i < nums.length; i++) {
if (curTarget >= nums[i]) {
dp[curTarget] += dp[curTarget - nums[i]];
}
}
}
return dp[target];
}
private int generate(int target, int[] nums, HashMap<Integer, Integer> map){
if (target == 0) return 1;
if (map.containsKey(target)) return map.get(target);
int res = 0;
for (int i = 0; i < nums.length; i++) {
if (nums[i] <= target) {
int subRes = generate(target - nums[i], nums, map);
res += subRes;
}
}
map.put(target, res);
return res;
}
public static void main(String[] args) {
Solution s = new Solution();
System.out.println(s.combinationSum4(new int[]{1, 2, 3}, 4));
System.out.println(s.combinationSum4(new int[]{9}, 3));
System.out.println(s.combinationSum4(new int[]{}, 3));
System.out.println(s.combinationSum4(new int[]{3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25}, 10));
}
}
|
#!/bin/bash
# ========== Experiment Seq. Idx. 3137 / 61.2.5.0 / N. 0 - _S=61.2.5.0 D1_N=43 a=-1 b=1 c=1 d=-1 e=1 f=-1 D3_N=4 g=1 h=-1 i=-1 D4_N=4 j=4 D5_N=0 ==========
set -u
# Prints header
echo -e '\n\n========== Experiment Seq. Idx. 3137 / 61.2.5.0 / N. 0 - _S=61.2.5.0 D1_N=43 a=-1 b=1 c=1 d=-1 e=1 f=-1 D3_N=4 g=1 h=-1 i=-1 D4_N=4 j=4 D5_N=0 ==========\n\n'
# Prepares all environment variables
JBHI_DIR="$HOME/jbhi-special-issue"
RESULTS_DIR="$JBHI_DIR/results"
if [[ "No" == "Yes" ]]; then
SVM_SUFFIX="svm"
PREDICTIONS_FORMAT="isbi"
else
SVM_SUFFIX="nosvm"
PREDICTIONS_FORMAT="titans"
fi
RESULTS_PREFIX="$RESULTS_DIR/deep.43.layer.4.test.4.index.3137.$SVM_SUFFIX"
RESULTS_PATH="$RESULTS_PREFIX.results.txt"
# ...variables expected by jbhi-checks.include.sh and jbhi-footer.include.sh
SOURCES_GIT_DIR="$JBHI_DIR/jbhi-special-issue"
LIST_OF_INPUTS="$RESULTS_PREFIX.finish.txt"
# ...this experiment is a little different --- only one master procedure should run, so there's only a master lock file
METRICS_TEMP_PATH="$RESULTS_DIR/this_results.anova.txt"
METRICS_PATH="$RESULTS_DIR/all_results.anova.txt"
START_PATH="$METRICS_PATH.start.txt"
FINISH_PATH="-"
LOCK_PATH="$METRICS_PATH.running.lock"
LAST_OUTPUT="$METRICS_PATH"
mkdir -p "$RESULTS_DIR"
#
# Assumes that the following environment variables where initialized
# SOURCES_GIT_DIR="$JBHI_DIR/jbhi-special-issue"
# LIST_OF_INPUTS="$DATASET_DIR/finish.txt:$MODELS_DIR/finish.txt:"
# START_PATH="$OUTPUT_DIR/start.txt"
# FINISH_PATH="$OUTPUT_DIR/finish.txt"
# LOCK_PATH="$OUTPUT_DIR/running.lock"
# LAST_OUTPUT="$MODEL_DIR/[[[:D1_MAX_NUMBER_OF_STEPS:]]].meta"
EXPERIMENT_STATUS=1
STARTED_BEFORE=No
# Checks if code is stable, otherwise alerts scheduler
pushd "$SOURCES_GIT_DIR" >/dev/null
GIT_STATUS=$(git status --porcelain)
GIT_COMMIT=$(git log | head -n 1)
popd >/dev/null
if [ "$GIT_STATUS" != "" ]; then
echo 'FATAL: there are uncommitted changes in your git sources file' >&2
echo ' for reproducibility, experiments only run on committed changes' >&2
echo >&2
echo ' Git status returned:'>&2
echo "$GIT_STATUS" >&2
exit 162
fi
# The experiment is already finished - exits with special code so scheduler won't retry
if [[ "$FINISH_PATH" != "-" ]]; then
if [[ -e "$FINISH_PATH" ]]; then
echo 'INFO: this experiment has already finished' >&2
exit 163
fi
fi
# The experiment is not ready to run due to dependencies - alerts scheduler
if [[ "$LIST_OF_INPUTS" != "" ]]; then
IFS=':' tokens_of_input=( $LIST_OF_INPUTS )
input_missing=No
for input_to_check in ${tokens_of_input[*]}; do
if [[ ! -e "$input_to_check" ]]; then
echo "ERROR: input $input_to_check missing for this experiment" >&2
input_missing=Yes
fi
done
if [[ "$input_missing" != No ]]; then
exit 164
fi
fi
# Sets trap to return error code if script is interrupted before successful finish
LOCK_SUCCESS=No
FINISH_STATUS=161
function finish_trap {
if [[ "$LOCK_SUCCESS" == "Yes" ]]; then
rmdir "$LOCK_PATH" &> /dev/null
fi
if [[ "$FINISH_STATUS" == "165" ]]; then
echo 'WARNING: experiment discontinued because other process holds its lock' >&2
else
if [[ "$FINISH_STATUS" == "160" ]]; then
echo 'INFO: experiment finished successfully' >&2
else
[[ "$FINISH_PATH" != "-" ]] && rm -f "$FINISH_PATH"
echo 'ERROR: an error occurred while executing the experiment' >&2
fi
fi
exit "$FINISH_STATUS"
}
trap finish_trap EXIT
# While running, locks experiment so other parallel threads won't attempt to run it too
if mkdir "$LOCK_PATH" --mode=u=rwx,g=rx,o=rx &>/dev/null; then
LOCK_SUCCESS=Yes
else
echo 'WARNING: this experiment is already being executed elsewhere' >&2
FINISH_STATUS="165"
exit
fi
# If the experiment was started before, do any cleanup necessary
if [[ "$START_PATH" != "-" ]]; then
if [[ -e "$START_PATH" ]]; then
echo 'WARNING: this experiment is being restarted' >&2
STARTED_BEFORE=Yes
fi
#...marks start
date -u >> "$START_PATH"
echo GIT "$GIT_COMMIT" >> "$START_PATH"
fi
if [[ "$STARTED_BEFORE" == "Yes" ]]; then
# If the experiment was started before, do any cleanup necessary
echo -n
else
echo "D1_N;D3_N;D4_N;a;b;c;d;e;f;g;h;i;j;m_ap;m_auc;m_tn;m_fp;m_fn;m_tp;m_tpr;m_fpr;k_ap;k_auc;k_tn;k_fp;k_fn;k_tp;k_tpr;k_fpr;isbi_auc" > "$METRICS_PATH"
fi
python \
"$SOURCES_GIT_DIR/etc/compute_metrics.py" \
--metadata_file "$SOURCES_GIT_DIR/data/all-metadata.csv" \
--predictions_format "$PREDICTIONS_FORMAT" \
--metrics_file "$METRICS_TEMP_PATH" \
--predictions_file "$RESULTS_PATH"
EXPERIMENT_STATUS="$?"
echo -n "43;4;4;" >> "$METRICS_PATH"
echo -n "-1;1;1;-1;1;-1;1;-1;-1;4;" >> "$METRICS_PATH"
tail "$METRICS_TEMP_PATH" -n 1 >> "$METRICS_PATH"
#
#...starts training
if [[ "$EXPERIMENT_STATUS" == "0" ]]; then
if [[ "$LAST_OUTPUT" == "" || -e "$LAST_OUTPUT" ]]; then
if [[ "$FINISH_PATH" != "-" ]]; then
date -u >> "$FINISH_PATH"
echo GIT "$GIT_COMMIT" >> "$FINISH_PATH"
fi
FINISH_STATUS="160"
fi
fi
|
# python workflows/rivm/data_rivm_download.py
# python workflows/rivm/merge_data.py
# python workflows/rivm/data_rivm_geo.py
# python workflows/json/json-api.py
# Grafieken pagina on website RIVM
python workflows/rivm/merge_website_charts.py
# National Dashboard
# python workflows/rivm/data_rivm_dashboard.py
# python workflows/nice/nice_download_merge.py
# python workflows/nice/data-ic_nice.py
# Parse reports
d=`date +%Y%m%d`
pdftotext reports/COVID-19_epidemiological_report_${d}.pdf
# python workflows/rivm_pdf/parse_pdf_table.py
# python workflows/rivm_pdf/data_rivm_pdf_misc.py
# python workflows/rivm/data_rivm_desc.py
# python tests.py
|
#!/bin/bash
set -exu
python3 /mysite/manage.py makemigrations
python3 /mysite/manage.py migrate
export DJANGO_SUPERUSER_PASSWORD=$DJANGO_PASSWORD
python3 /mysite/manage.py createsuperuser \
--no-input \
--username=$DJANGO_NAME \
--email=$DJANGO_NAME@example.com
|
<gh_stars>0
/**
* Adjacent Replacements
* https://codeforces.com/problemset/problem/1006/A
*/
var elements = readline();
elements = readline().split(' ').map(e => e % 2 === 0 ? e - 1 : e).join(' ');
print(elements);
|
import mitt, { Emitter } from 'mitt';
// eslint-disable-next-line @typescript-eslint/consistent-type-definitions
type ImageEvents = {
load: {
imageId: string;
};
loaded: {
imageId: string;
};
error: {
imageId: string;
};
};
const imageEventEmitter: Emitter<ImageEvents> = mitt();
export default imageEventEmitter;
|
#!/usr/bin/env bash
set -ue
NEXUS_VERSION=3.22.0
function usage {
printf "Test Nexus setup.\n\n"
printf "\t-h|--help\t\tPrint usage\n"
printf "\t-v|--verbose\t\tEnable verbose mode\n"
printf "\t-s|--nexus-version\t\tNexus version, e.g. '3.22.0' (defaults to ${NEXUS_VERSION})\n"
}
while [[ "$#" -gt 0 ]]; do
case $1 in
-v|--verbose) set -x;;
-h|--help) usage; exit 0;;
-s|--nexus-version) NEXUS_VERSION="$2"; shift;;
-s=*|--nexus-version=*) NEXUS_VERSION="${1#*=}";;
*) echo_error "Unknown parameter passed: $1"; exit 1;;
esac; shift; done
CONTAINER_IMAGE="sonatype/nexus3:${NEXUS_VERSION}"
HOST_PORT="8081"
echo "Run container using image ${CONTAINER_IMAGE}"
containerId=$(docker run -d -p ${HOST_PORT}:8081 ${CONTAINER_IMAGE})
function cleanup {
echo "Cleanup"
docker rm -f ${containerId}
}
trap cleanup EXIT
NEXUS_URL="http://localhost:${HOST_PORT}"
ADMIN_USER_NAME=admin
ADMIN_USER_PWD=s3cr3t
DEV_USER_NAME=developer
DEV_USER_PWD=geHeim
echo "Run ./configure.sh"
./configure.sh \
--admin-password=${ADMIN_USER_PWD} \
--developer-password=${DEV_USER_PWD} \
--nexus=${NEXUS_URL} \
--local-container-id=${containerId}
echo "Check for blobstores"
expectedBlobstores=( "candidates"
"releases"
"atlassian_public"
"npm-private"
"pypi-private"
"leva-documentation" )
actualBlobstores=$(curl \
--fail \
--silent \
--user ${ADMIN_USER_NAME}:${ADMIN_USER_PWD} \
${NEXUS_URL}/service/rest/beta/blobstores)
for blobstore in "${expectedBlobstores[@]}"; do
if echo ${actualBlobstores} | jq -e ".[] | select(.name == \"${blobstore}\")" > /dev/null; then
echo "Blobstore '${blobstore}' is available"
else
echo "Blobstore '${blobstore}' is missing"
exit 1
fi
done
echo "Check for repositories"
expectedRepos=( "candidates:hosted"
"releases:hosted"
"atlassian_public:proxy"
"jcenter:proxy"
"jenkins-ci-releases:proxy"
"sbt-plugins:proxy"
"sbt-releases:proxy"
"typesafe-ivy-releases:proxy"
"ivy-releases:group"
"npm-registry:proxy"
"npm-private:hosted"
"npm-all:group"
"pypi-registry:proxy"
"pypi-private:hosted"
"pypi-all:group"
"leva-documentation:hosted")
actualRepos=$(curl \
--fail \
--silent \
--user ${ADMIN_USER_NAME}:${ADMIN_USER_PWD} \
${NEXUS_URL}/service/rest/v1/repositories)
for repo in "${expectedRepos[@]}"; do
repoName=${repo%%:*}
repoType=${repo#*:}
if echo ${actualRepos} | jq -e ".[] | select(.name == \"${repoName}\")" > /dev/null; then
actualType=$(echo ${actualRepos} | jq -r ".[] | select(.name == \"${repoName}\") | .type")
if [ "${actualType}" == "${repoType}" ]; then
echo "Repo '${repoName}' is available and has expected type '${repoType}'"
else
echo "Repo '${repoName}' is available, but has wrong type. Want: '${repoType}', got: '${actualType}'"
exit 1
fi
else
echo "Repo '${repoName}' is missing"
exit 1
fi
done
echo "Check if anonymous access is still possible"
if curl --fail --silent \
${NEXUS_URL}/service/rest/v1/repositories | jq -e "length > 0" > /dev/null; then
echo "Anonymous access still possible"
exit 1
else
echo "Anonymous access is disabled"
fi
echo "Check developer access"
if curl --fail --silent \
-u ${DEV_USER_NAME}:${DEV_USER_PWD} \
${NEXUS_URL}/service/rest/v1/repositories | jq -e "length == 0" > /dev/null; then
echo "Developer access not possible"
exit 1
else
echo "Developer access possible"
fi
echo "Success"
|
<filename>src/main/java/com/challenge/service/dto/LogEventPostResponseDto.java
package com.challenge.service.dto;
import com.challenge.entity.LogEvent;
import com.fasterxml.jackson.annotation.JsonFormat;
import com.fasterxml.jackson.databind.annotation.JsonDeserialize;
import lombok.Data;
import lombok.NoArgsConstructor;
import java.time.LocalDateTime;
@Data
@NoArgsConstructor
public class LogEventPostResponseDto {
private Long id;
private LevelErrorEnum levelErrorEnum;
private String eventDescription;
private String eventLog;
private String origin;
private LocalDateTime eventDate;
private Long eventCount;
private String status;
@JsonDeserialize
@JsonFormat(pattern = "yyyy-MM-dd HH:mm")
private LocalDateTime createdAt;
private String clientId;
public LogEventPostResponseDto(LogEvent logEvent) {
this.id = logEvent.getId();
this.levelErrorEnum = logEvent.getLevelErrorEnum();
this.eventDescription = logEvent.getEventDescription();
this.eventLog = logEvent.getEventLog();
this.origin = logEvent.getOrigin();
this.eventDate = logEvent.getEventDate();
this.eventCount = logEvent.getEventCount();
this.status = logEvent.getStatus();
this.createdAt = logEvent.getCreatedAt();
}
}
|
#!/bin/bash
# Git pre-commit hook to check staged Python files for formatting issues with
# yapf.
#
# INSTALLING: Copy this script into `.git/hooks/pre-commit`, and mark it as
# executable.
#
# This requires that yapf is installed and runnable in the environment running
# the pre-commit hook.
#
# When running, this first checks for unstaged changes to staged files, and if
# there are any, it will exit with an error. Files with unstaged changes will be
# printed.
#
# If all staged files have no unstaged changes, it will run yapf against them,
# leaving the formatting changes unstaged. Changed files will be printed.
#
# BUGS: This does not leave staged changes alone when used with the -a flag to
# git commit, due to the fact that git stages ALL unstaged files when that flag
# is used.
# Find all staged Python files, and exit early if there aren't any.
PYTHON_FILES=(`git diff --name-only --cached --diff-filter=AM ':(exclude)setup.py' | \
grep --color=never '.py$'`)
if [ ! "$PYTHON_FILES" ]; then
exit 0
fi
# Verify that yapf is installed; if not, warn and exit.
if [ -z $(which yapf) ]; then
echo 'yapf not on path; can not format. Please install yapf:'
echo ' pip install yapf'
exit 2
fi
# Check for unstaged changes to files in the index.
CHANGED_FILES=(`git diff --name-only ${PYTHON_FILES[@]}`)
if [ "$CHANGED_FILES" ]; then
echo 'You have unstaged changes to some files in your commit; skipping '
echo 'auto-format. Please stage, stash, or revert these changes. You may '
echo 'find `git stash -k` helpful here.'
echo
echo 'Files with unstaged changes:'
for file in ${CHANGED_FILES[@]}; do
echo " $file"
done
exit 1
fi
# Format all staged files, then exit with an error code if any have uncommitted
# changes.
echo 'Formatting staged Python files . . .'
yapf -i -r ${PYTHON_FILES[@]}
CHANGED_FILES=(`git diff --name-only ${PYTHON_FILES[@]}`)
if [ "$CHANGED_FILES" ]; then
echo 'Reformatted staged files. Please review and stage the changes.'
echo
echo 'Files updated:'
for file in ${CHANGED_FILES[@]}; do
echo " $file"
done
exit 1
else
exit 0
fi
|
import nltk
from nltk.sentiment.vader import SentimentIntensityAnalyzer
def sentiment_classifier(sentence):
sid = SentimentIntensityAnalyzer()
sentiment_scores = sid.polarity_scores(sentence)
if sentiment_scores['compound'] > 0.5:
sentiment_class = 'positive'
elif sentiment_scores['compound'] == 0.0:
sentiment_class = 'neutral'
else:
sentiment_class = 'negative'
return sentiment_class
if __name__ == '__main__':
sentence = 'This is a great movie!'
print(sentiment_classifier(sentence))
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.