content
stringlengths 7
2.61M
|
---|
/**
* Read given bytes from device.
* @param number How many bytes do you want to read?
* @return Read bytes
* @throws FTD2XXException If something goes wrong.
*/
public byte[] read(int number)
throws FTD2XXException {
byte[] ret = new byte[number];
int actually = read(ret);
if (actually != number) {
byte[] shrink = new byte[actually];
System.arraycopy(ret, 0, shrink, 0, actually);
return shrink;
} else {
return ret;
}
}
|
import errno
import binascii
import json
import os
import socket
import time
import datetime
import sys
sys.path.insert(1, '/home/pi/lora_gateway')
try:
import key_TTN as key_LoRaWAN
try:
key_LoRaWAN.lorawan_server
except AttributeError:
key_LoRaWAN.lorawan_server="router.eu.thethings.network"
try:
key_LoRaWAN.lorawan_port
except AttributeError:
key_LoRaWAN.lorawan_port=1700
lorawan_server=key_LoRaWAN.lorawan_server
lorawan_port=key_LoRaWAN.lorawan_port
except ImportError:
lorawan_server="router.eu.thethings.network"
lorawan_port=1700
PROTOCOL_VERSION = 2
PUSH_DATA = 0
PUSH_ACK = 1
PULL_DATA = 2
PULL_ACK = 4
PULL_RESP = 3
STAT_PK = {
'stat': {
'time': '',
'lati': 0,
'long': 0,
'alti': 0,
'rxnb': 0,
'rxok': 0,
'rxfw': 0,
'ackr': 100.0,
'dwnb': 0,
'txnb': 0
}
}
class TTN_stats:
def __init__(self, id, lati, long, rxnb, rxok, rxfw, ackr, dwnb, txnb, server, port):
self.id = id
self.lati = lati
self.long = long
self.rxnb = rxnb
self.rxok = rxok
self.rxfw = rxfw
self.ackr = ackr
self.dwnb = dwnb
self.txnb = txnb
self.server = server
self.port = port
self.server_ip = None
self.sock = None
def start(self):
self._log('ttn_stats: gw id {}', self.id)
# get the server IP and create an UDP socket
self.server_ip = socket.getaddrinfo(self.server, self.port)[0][-1]
self._log('ttn_stats: Opening UDP socket to {} ({}) port {}...', self.server, self.server_ip[0], self.server_ip[1])
self.sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM, socket.IPPROTO_UDP)
self.sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
self.sock.setblocking(False)
# push the first time immediatelly
self._push_data(self._make_stat_packet())
def _make_stat_packet(self):
now = time.strftime('%Y-%m-%d %H:%M:%S GMT')
STAT_PK["stat"]["time"] = now
if self.lati!="undef":
STAT_PK["stat"]["lati"] = self.lati
if self.long!="undef":
STAT_PK["stat"]["long"] = self.long
STAT_PK["stat"]["rxnb"] = self.rxnb
STAT_PK["stat"]["rxok"] = self.rxok
STAT_PK["stat"]["rxfw"] = self.rxfw
STAT_PK["stat"]["ackr"] = self.ackr
STAT_PK["stat"]["dwnb"] = self.dwnb
STAT_PK["stat"]["txnb"] = self.txnb
return json.dumps(STAT_PK)
def _push_data(self, data):
token = os.urandom(2)
packet = bytearray([PROTOCOL_VERSION]) + token + bytearray([PUSH_DATA]) + binascii.unhexlify(self.id) + data
#print ''.join('{:02x}'.format(x) for x in packet)
self._log('ttn_stats: Try to send UDP packet: {}', packet)
try:
self.sock.sendto(packet, self.server_ip)
self.sock.close()
except Exception as ex:
self._log('ttn_stats: Failed to push uplink packet to server: {}', ex)
def _log(self, message, *args):
print('{}'.format(str(message).format(*args)))
# python ttn_stats.py "0,0,0,0,0,0" "0.0,0.0" "B827EBFFFFD1B236"
# replace "0,0,0,0,0,0" by "rxnb,rxok,rxfw,ackr,dwnb,txnb"
# replace "0.0,0.0" by "lati,long"
def main(stats_str, gps_str, gwid):
arr = map(int,stats_str.split(','))
rxnb=arr[0]
rxok=arr[1]
rxfw=arr[2]
ackr=arr[3]
dwnb=arr[4]
txnb=arr[5]
try:
arr = map(float,gps_str.split(','))
lati=arr[0]
long=arr[1]
except ValueError:
lati="undef"
long="undef"
ttn = TTN_stats(
id=gwid,
lati=lati,
long=long,
rxnb=rxnb,
rxok=rxok,
rxfw=rxfw,
ackr=ackr,
dwnb=dwnb,
txnb=txnb,
server=lorawan_server,
port=lorawan_port)
ttn.start()
if __name__ == "__main__":
main(sys.argv[1], sys.argv[2], sys.argv[3])
|
<reponame>collects/udt<gh_stars>100-1000
#ifndef UDT_CONNECTED_PROTOCOL_STATE_BASE_STATE_H_
#define UDT_CONNECTED_PROTOCOL_STATE_BASE_STATE_H_
#include <memory>
#include <boost/chrono.hpp>
#include "udt/common/error/error.h"
#include "udt/connected_protocol/io/write_op.h"
#include "udt/connected_protocol/io/read_op.h"
#include "udt/connected_protocol/logger/log_entry.h"
namespace connected_protocol {
namespace state {
template <class Protocol>
class BaseState {
public:
using Ptr = std::shared_ptr<BaseState>;
using ConnectionDatagram = typename Protocol::ConnectionDatagram;
using ConnectionDatagramPtr = std::shared_ptr<ConnectionDatagram>;
using ControlDatagram = typename Protocol::GenericControlDatagram;
using SendDatagram = typename Protocol::SendDatagram;
using DataDatagram = typename Protocol::DataDatagram;
using Clock = typename Protocol::clock;
using TimePoint = typename Protocol::time_point;
using Timer = typename Protocol::timer;
public:
enum type { CLOSED, CONNECTING, ACCEPTING, CONNECTED, TIMEOUT };
public:
virtual type GetType() = 0;
boost::asio::io_service& get_io_service() { return io_service_; }
virtual void Init() {}
virtual ~BaseState() {}
virtual void Stop() {}
virtual void Close() {}
virtual void PushReadOp(
io::basic_pending_stream_read_operation<Protocol>* read_op) {
// Drop op
auto do_complete = [read_op]() {
read_op->complete(
boost::system::error_code(::common::error::not_connected,
::common::error::get_error_category()),
0);
};
io_service_.post(do_complete);
}
virtual void PushWriteOp(io::basic_pending_write_operation* write_op) {
// Drop op
auto do_complete = [write_op]() {
write_op->complete(
boost::system::error_code(::common::error::not_connected,
::common::error::get_error_category()),
0);
};
io_service_.post(do_complete);
}
virtual bool HasPacketToSend() { return false; }
virtual SendDatagram* NextScheduledPacket() { return nullptr; }
virtual void OnConnectionDgr(ConnectionDatagramPtr p_connection_dgr) {
// Drop dgr
}
virtual void OnControlDgr(ControlDatagram* p_control_dgr) {
// Drop dgr
}
virtual void OnDataDgr(DataDatagram* p_datagram) {
// Drop dgr
}
virtual void Log(connected_protocol::logger::LogEntry* p_log) {}
virtual void ResetLog() {}
virtual double PacketArrivalSpeed() { return 0.0; }
virtual double EstimatedLinkCapacity() { return 0.0; }
virtual boost::chrono::nanoseconds NextScheduledPacketTime() {
return boost::chrono::nanoseconds(0);
}
protected:
BaseState(boost::asio::io_service& io_service) : io_service_(io_service) {}
private:
boost::asio::io_service& io_service_;
};
} // state
} // connected_protocol
#endif // UDT_CONNECTED_PROTOCOL_STATE_BASE_STATE_H_
|
from __future__ import print_function
import os
import numpy as np
import tensorflow as tf
from PIL import Image
import urllib
import redis
import json
import logging
from threading import Timer
import time
import signal
import stylelens_index
from stylelens_index.rest import ApiException
from bluelens_spawning_pool import spawning_pool
from pprint import pprint
from util import label_map_util
from object_detection.utils import visualization_utils as vis_util
from util import s3
try:
from StringIO import StringIO
except ImportError:
from io import StringIO
AWS_BUCKET = 'bluelens-style-object'
REDIS_IMAGE_INDEX_QUEUE = 'bl:image:index:queue'
TMP_CROP_IMG_FILE = './tmp.jpg'
CWD_PATH = os.getcwd()
AWS_ACCESS_KEY = os.environ['AWS_ACCESS_KEY'].replace('"', '')
AWS_SECRET_ACCESS_KEY = os.environ['AWS_SECRET_ACCESS_KEY'].replace('"', '')
OD_MODEL = os.environ['OD_MODEL']
OD_LABELS = os.environ['OD_LABELS']
SPAWN_ID = os.environ['SPAWN_ID']
NUM_CLASSES = 89
HOST_URL = 'host_url'
TAGS = 'tags'
SUB_CATEGORY = 'sub_category'
PRODUCT_NAME = 'product_name'
IMAGE = 'image'
PRODUCT_PRICE = 'product_price'
CURRENCY_UNIT = 'currency_unit'
PRODUCT_URL = 'product_url'
PRODUCT_NO = 'product_no'
MAIN = 'main'
NATION = 'nation'
REDIS_IMAGE_CROP_QUEUE = 'bl:image:crop:queue'
STR_BUCKET = "bucket"
STR_STORAGE = "storage"
STR_CLASS_CODE = "class_code"
STR_NAME = "name"
STR_FORMAT = "format"
# Loading label map
label_map = label_map_util.load_labelmap(OD_LABELS)
categories = label_map_util.convert_label_map_to_categories(label_map, max_num_classes=NUM_CLASSES,
use_display_name=True)
category_index = label_map_util.create_category_index(categories)
api_instance = stylelens_index.ImageApi()
REDIS_SERVER = os.environ['REDIS_SERVER']
rconn = redis.StrictRedis(REDIS_SERVER)
logging.basicConfig(filename='./log/main.log', level=logging.DEBUG)
heart_bit = True
def job():
redis_pub('START')
detection_graph = tf.Graph()
with detection_graph.as_default():
od_graph_def = tf.GraphDef()
with tf.gfile.GFile(OD_MODEL, 'rb') as fid:
serialized_graph = fid.read()
od_graph_def.ParseFromString(serialized_graph)
tf.import_graph_def(od_graph_def, name='')
sess = tf.Session(graph=detection_graph)
def items():
while True:
yield rconn.blpop([REDIS_IMAGE_CROP_QUEUE])
def request_stop(signum, frame):
print('stopping')
stop_requested = True
rconn.connection_pool.disconnect()
print('connection closed')
signal.signal(signal.SIGINT, request_stop)
signal.signal(signal.SIGTERM, request_stop)
for item in items():
key, image_data = item
if type(image_data) is str:
image_info = json.loads(image_data)
elif type(image_data) is bytes:
image_info = json.loads(image_data.decode('utf-8'))
image = stylelens_index.Image()
image.name = image_info['name']
image.host_url = image_info['host_url']
image.host_code = image_info['host_code']
image.tags = image_info['tags']
image.format = image_info['format']
image.product_name = image_info['product_name']
image.parent_image_raw = image_info['parent_image_raw']
image.parent_image_mobile = image_info['parent_image_mobile']
image.parent_image_mobile_thumb = image_info['parent_image_mobile_thumb']
image.image = image_info['image']
image.class_code = image_info['class_code']
image.bucket = image_info['bucket']
image.storage = image_info['storage']
image.product_price = image_info['product_price']
image.currency_unit = image_info['currency_unit']
image.product_url = image_info['product_url']
image.product_no = image_info['product_no']
image.main = image_info['main']
image.nation = image_info['nation']
f = urllib.request.urlopen(image.image)
img = Image.open(f)
image_np = load_image_into_numpy_array(img)
show_box = False
out_image, boxes, scores, classes, num_detections = detect_objects(image_np, sess, detection_graph, show_box)
take_object(image,
out_image,
np.squeeze(boxes),
np.squeeze(scores),
np.squeeze(classes).astype(np.int32))
if show_box:
img = Image.fromarray(out_image, 'RGB')
img.show()
global heart_bit
heart_bit = True
def check_health():
print('check_health: ' + str(heart_bit))
logging.debug('check_health: ' + str(heart_bit))
global heart_bit
if heart_bit == True:
heart_bit = False
Timer(60, check_health, ()).start()
else:
exit()
def exit():
print('exit: ' + SPAWN_ID)
logging.debug('exit: ' + SPAWN_ID)
data = {}
data['namespace'] = 'index'
data['id'] = SPAWN_ID
spawn = spawning_pool.SpawningPool()
spawn.setServerUrl(REDIS_SERVER)
spawn.delete(data)
def redis_pub(message):
rconn.publish('crop', message)
def take_object(image_info, image_np, boxes, scores, classes):
max_boxes_to_save = 10
min_score_thresh = .7
if not max_boxes_to_save:
max_boxes_to_save = boxes.shape[0]
for i in range(min(max_boxes_to_save, boxes.shape[0])):
if scores is None or scores[i] > min_score_thresh:
if classes[i] in category_index.keys():
class_name = category_index[classes[i]]['name']
# class_code = category_index[classes[i]]['code']
class_code = 'n0100000'
else:
class_name = 'na'
class_code = 'na'
ymin, xmin, ymax, xmax = tuple(boxes[i].tolist())
image_info.format = 'jpg'
image_info.class_code = class_code
id = crop_bounding_box(
image_info,
image_np,
ymin,
xmin,
ymax,
xmax,
use_normalized_coordinates=True)
image_info.name = id
# print(image_info)
save_to_storage(image_info)
save_to_redis(image_info)
def save_to_redis(image_info):
image = image_class_to_json(image_info)
rconn.lpush(REDIS_IMAGE_INDEX_QUEUE, image)
def image_class_to_json(image):
image_info = {}
image_info['name'] = image.name
image_info['host_url'] = image.host_url
image_info['host_code'] = image.host_code
image_info['tags'] = image.tags
image_info['format'] = image.format
image_info['product_name'] = image.product_name
image_info['parent_image_raw'] = image.parent_image_raw
image_info['parent_image_mobile'] = image.parent_image_mobile
image_info['parent_image_mobile_thumb'] = image.parent_image_mobile_thumb
image_info['image'] = image.image
image_info['class_code'] = image.class_code
image_info['bucket'] = image.bucket
image_info['storage'] = image.storage
image_info['product_price'] = image.product_price
image_info['currency_unit'] = image.currency_unit
image_info['product_url'] = image.product_url
image_info['product_no'] = image.product_no
image_info['main'] = image.main
image_info['nation'] = image.nation
s = json.dumps(image_info)
print(s)
return s
def save_to_db(image):
try:
api_response = api_instance.add_image(image)
pprint(api_response)
except ApiException as e:
print("Exception when calling ImageApi->add_image: %s\n" % e)
return api_response.data._id
def save_to_storage(image_info):
print('save_to_storage')
storage = s3.S3(AWS_ACCESS_KEY, AWS_SECRET_ACCESS_KEY)
key = os.path.join(image_info.class_code, image_info.name + '.' + image_info.format)
is_public = False
if image_info.main == 1:
is_public = True
storage.upload_file_to_bucket(AWS_BUCKET, TMP_CROP_IMG_FILE, key, is_public=is_public)
print('save_to_storage done')
def load_image_into_numpy_array(image):
(im_width, im_height) = image.size
return np.array(image.getdata()).reshape(
(im_height, im_width, 3)).astype(np.uint8)
def crop_bounding_box(image_info,
image,
ymin,
xmin,
ymax,
xmax,
use_normalized_coordinates=True):
"""Adds a bounding box to an image (numpy array).
Args:
image: a numpy array with shape [height, width, 3].
ymin: ymin of bounding box in normalized coordinates (same below).
xmin: xmin of bounding box.
ymax: ymax of bounding box.
xmax: xmax of bounding box.
name: classname
color: color to draw bounding box. Default is red.
thickness: line thickness. Default value is 4.
display_str_list: list of strings to display in box
each to be shown on its own line).
use_normalized_coordinates: If True (default), treat coordinates
ymin, xmin, ymax, xmax as relative to the image. Otherwise treat
coordinates as absolute.
"""
image_pil = Image.fromarray(np.uint8(image)).convert('RGB')
im_width, im_height = image_pil.size
if use_normalized_coordinates:
(left, right, top, bottom) = (xmin * im_width, xmax * im_width,
ymin * im_height, ymax * im_height)
else:
(left, right, top, bottom) = (xmin, xmax, ymin, ymax)
# print(image_pil)
area = (left, top, left + abs(left-right), top + abs(bottom-top))
cropped_img = image_pil.crop(area)
size = 300, 300
cropped_img.thumbnail(size, Image.ANTIALIAS)
cropped_img.save(TMP_CROP_IMG_FILE)
# cropped_img.show()
id = save_to_db(image_info)
# save_image_to_file(image_pil, ymin, xmin, ymax, xmax,
# use_normalized_coordinates)
# np.copyto(image, np.array(image_pil))
return id
def detect_objects(image_np, sess, detection_graph, show_box=True):
# Expand dimensions since the model expects images to have shape: [1, None, None, 3]
image_np_expanded = np.expand_dims(image_np, axis=0)
image_tensor = detection_graph.get_tensor_by_name('image_tensor:0')
# Each box represents a part of the image where a particular object was detected.
boxes = detection_graph.get_tensor_by_name('detection_boxes:0')
# Each score represent how level of confidence for each of the objects.
# Score is shown on the result image, together with the class label.
scores = detection_graph.get_tensor_by_name('detection_scores:0')
classes = detection_graph.get_tensor_by_name('detection_classes:0')
num_detections = detection_graph.get_tensor_by_name('num_detections:0')
# Actual detection.
(boxes, scores, classes, num_detections) = sess.run(
[boxes, scores, classes, num_detections],
feed_dict={image_tensor: image_np_expanded})
if show_box:
# Visualization of the results of a detection.
vis_util.visualize_boxes_and_labels_on_image_array(
image_np,
np.squeeze(boxes),
np.squeeze(classes).astype(np.int32),
np.squeeze(scores),
category_index,
use_normalized_coordinates=True,
line_thickness=8)
# print(image_np)
return image_np, boxes, scores, classes, num_detections
if __name__ == '__main__':
Timer(60, check_health, ()).start()
job()
|
Suppression of indirect exchange and symmetry breaking in antiferromagnetic metal with dynamic charge stripes Precise angle-resolved magnetoresistance (ARM) measurements are applied to reveal the origin for the lowering of symmetry in electron transport and the emergence of a huge number of magnetic phases in the ground state of antiferromagnetic metal HoB12 with fcc crystal structure. By analyzing of the polar H-theta-phi magnetic phase diagrams of this compound reconstructed from the experimental ARM data we argue that non-equilibrium electron density oscillations (dynamic charge stripes) are responsible for the suppression of the indirect RKKY exchange along<110>directions between the nearest neighboring magnetic moments of Ho3+ ions in this strongly correlated electron system. It was recently demonstrated that Ho x Lu 1-x B 12 dodecaborides with a face-centered cubic (fcc) crystal structure may be treated as model SCES, which show electronic phase separation (dynamic charge stripes along the <110> axis, Fig.1a) in combination with dynamic Jahn-Teller instability and a frustrated AF ground state with Nel temperature T N 7.4 K. In these compounds, the competition between Ruderman-Kittel-Kasuya-Yosida (RKKY) oscillations of the electron spin density (indirect exchange interaction) and quantum oscillations of the electron density (dynamic charge stripes) is shown to result in the extremely complicated and anisotropic magnetic phase diagram, which have a form of maltese cross with a huge number of various magnetic phases. Since the arrangement of magnetic phases depends dramatically both on the magnitude and direction of the external magnetic field the high precision studies of charge transport was performed here to reconstruct the three-dimensional (3D) H-- magnetic phase diagram of HoB 12. As a result, we argue that non-equilibrium electron density oscillations (stripes) seem to be responsible for the suppression of the indirect exchange interaction along <110> directions and lead to symmetry breaking in this strongly correlated electron system. The detailed study of heat capacity, magnetization and magnetoresistance was performed for high-quality single-domain and isotopically enriched ( 11 B) single crystals of Ho 11 B 12 (T N ≈ 7.4 K). The related experimental details are given in Supplementary materials. Besides, we show below that despite high symmetry of the crystal lattice the magnetic phases for the principal field directions are separated by the radial phase boundaries and, hence, these are completely different, and that only one AF phase (marked as I in Fig.1) exists for any magnetic field orientation. To clarify the location of phase boundaries in the AF state in the external magnetic field up to 80 kOe, the angle-resolved magnetoresistance (ARM) was measured at fixed temperature T = 2. ). Results of these experiments may be summarized as follows. Firstly, only slight cosine-like ()~cos(2) modulation is detected when the magnitude of H does not exceed ~20 kOe (the phase boundary position, which restricts the "I" phase, see Figs.1c-1e). Secondly, the increase the magnetic field above ~25 kOe leads two additional features (sharp peaks in the neighborhood of <110> directions and "horns" that are symmetrical to the <100> axis) appear and become broader with H increase. Thirdly, the cosine-like behavior is restored above the Neel field (H N ~ 76 kOe) with two additional features, different from the low-field data: (a) the phase is shifted by 45 degrees and (b) a narrow local minimum of tiny amplitude appears near the <001> direction. It is worth noting that abrupt anomalies in the AF phase observed in the wide neighborhood of <100> directions may be associated with magnetic phase transitions between states with different magnetic order. Besides, the unusual behavior of sharp peaks in the vicinity of <110> directions in HoB 12 is suggested to be induced by the dynamic charge stripes along <110> axis (see Fig.1a). The same features can be easily resolved on the magnetic field dependences of resistivity measured at the same temperature T = 2.1 K for the set of different H directions. For example, the data for I|| presented in supplementary materials unambiguously evidence that varying of the angle between the normal to the sample surface n|| and the applied magnetic field H allows detecting the set of anomalies on the (H, 0 ) curves, which may be attributed to orientation magnetic transitions. We showed that positive magnetoresistance dominates in the AF phase up to the sharp drop just before the Neel field. It is important that a wide hump appears in the range of H=22-35kOe (in the proximity (=2-3) of direction (when a magnetic field is applied along the dynamic charge stripes). Similar data sets have been collected in our experiments with sample rotation around current directions (ii) I||, (iii) I|| and (iv) I|| (see, Figs.. The total review of both the magnetic phases and phase transitions inside the AF state of Ho 11 B 12 on the basis of our experiments is provided below. The extracted ARM data for all (i)-(iv) sample rotation experiments can be easily overlooked in the polar presentation. Figure, see ). Since these four H- planes for various exciting current directions are obtained for the different samples cut from one single crystal (n|| plate) of Ho 11 B 12, we can compare the behavior of MR rather than the absolute values of the MR amplitude. However, it can be seen that the phase boundaries obtained from these experiments with different rotational axes coincide very well with each other (see also ). One more schematic view (the projection on the spherical surface) of three basic high-field phases (III, IV, and VIII) is shown in Fig.3b. It is worth noting that these three segments corresponding to three different types of magnetic phases (III, IV, and VIII, see and (iv) B-a-b-C corresponds to the rotation from H|| to H||. Thus, it is obvious that despite the partial similarity of the borders on the H-T phase diagrams of Ho 11 B 12 for various directions of the external magnetic field (Fig.1c-e), the set of phases in three principal directions is almost completely different. Such a pronounced anisotropy of charge carriers scattering and of the magnetic phase diagram should be associated, from one side, with the interaction of the external magnetic field with the dynamic charge stripe structure in the Ho 11 B 12 matrix. Besides, if consider the stripes as the main factor to be responsible for a strong renormalization of the indirect RKKY exchange interaction one needs to expect a huge suppression of the nearest neighbor exchange (J 1 ) in this model AF metal. Indeed, the long-range RKKY magnetic interaction between the localized magnetic moments of d-, or f-orbitals in metals is transmitted by the spin density oscillations of conduction electrons (see fig.1b), and these are suppressed dramatically in the presence of the dynamic charge stripes (fast quantum vibrations of the non-equilibrium charge density with a frequency ~200 GHz ) directed along <110> axes. Thus, the stripe direction just corresponds to the location of neighboring magnetic ions (figs.1a) and it destroys totally the nearest neighbor RKKY interaction ( fig.1). To support this ARM experimental finding an independent estimate of the nearest neighbor (J 1 ) and next-nearest neighbor (J 2 ) interactions is undertaken here. With this purpose, the magnon dispersion data in HoB 12 are compared with the classical Monte Carlo (MC) simulation. The dispersion is derived from the MC generated structure by numerical integration of the classical equation of motion for a moment in a field,, where is the gyromagnetic ratio and field is the local exchange field obtained from the MC simulation. This first gives the time dependence of the moments which then is converted to the dispersion by a Fourier transform (see for details). The dispersion has been calculated for a system of 4 *16 3 spins cooled down from the paramagnetic state to an MC temperature of T=0.025 in 5000 steps. At each temperature, the structure was annealed. The nearest neighbor interaction J 1 was varied between -5 and 5 in steps of 0.5 and J 2 = 3 was kept fixed. In Fig. 3 we show the measured dispersion along the (, k,k) direction together with the simulation for J 1 = 0. For this value, the flat mode found in experiments is reproduced very well and it is not the case for any finite J 1. Deviations between simulation and experiment at the commensurate positions, e.g. at (,, ), are due to domain walls in the MC generated structure, leading to the strong streaks there. Note also, that the simulation does not account in detail crystal field anisotropy, which causes the energy gap in HoB 12. Summarizing up, the model SCES Ho 11 B 12 with incommensurate AF structure, cooperative Jahn-Teller instability of boron network and dynamic charge stripes was studied in detail by ARM measurements at liquid helium temperature. In this non-equilibrium AF metal, a strongly anisotropic polar H-- magnetic phase diagrams were reconstructed for the first time. These are shown to consist of four basic sectors: spherical low-field region and three different complicated cone-shaped segments detected in the vicinity of the principal directions: (a) along (H||) and (b) transverse to (H||) the dynamic charge stripes, and (c) parallel to the axis of magnetic structure (H||) in the fcc lattice. We argue that the strong anisotropy both of the phase diagram and the charge transport is a fingerprint of the electron instability related to the formation of a filamentary structure (fluctuating charge carrier channels along direction) of non-equilibrium electrons. As a result, the indirect RKKY exchange interaction between the nearest neighbored magnetic ions located at the distance of ~5.3 in the <110> directions is dramatically destroyed providing magnetic symmetry lowering and leading to field-angular phase diagrams with a huge number of magnetic phases and phase transitions.
|
#include "io.inc"
// Target: use loops to calculate calculator of 6!
//@author yixi
int N;
int h = 99;
int i = 100;
int j = 101;
int k = 102;
int total = 0;
int main() {
int a;
int b;
int c;
int d;
int e;
int f;
N = 6;
for (a = 1; a <= N; a++)
for (b = 1; b <= N; b++)
for (c = 1; c <= N; c++)
for (d = 1; d <= N; d++)
for (e = 1; e <= N; e++)
for (f = 1; f <= N; f++)
if (a != b && a != c && a != d && a != e && a != f && a != h &&
a != i && a != j && a != k && b != c && b != d && b != e &&
b != f && b != h && b != i && b != j && b != k && c != d &&
c != e && c != f && c != h && c != i && c != j && c != k &&
d != e && d != f && d != h && d != i && d != j && d != k &&
e != f && e != h && e != i && e != j && e != k && f != h &&
f != i && f != j && f != k && i != j && h != k) {
total++;
}
printInt(total);
return judgeResult % Mod; // 134
}
|
Morpho-Histological Comparisons of Liver between the Broiler Chickens and Wild Boar in Algeria | Aim: The objective of this study is to compare the normal macro and microscopic appearance of the liver in two very different species, one is an omnivorous mammal; the wild boar and the other belongs to the family of poultry; broiler chicken from the region of Bouhmama (Khenchela). Materials and methods: Eight broilers (58 days of age) and eight wild boars were included in the experiment to obtain information about the morpho-histological appearances of liver in two species.results: There is a big difference in the liver appearance between the two species, in the wild boar it is of firm consistency with a tiger aspect and divided into four lobes, whereas in the broiler, the liver is brown and sometimes pale during the first 10-14 days, so it was divided into two lobes. Concerning the liver parenchyma, we used the Russian LOMBO MBS-10 stereo microscope, our results showed that the liver parenchyma was well developed in wild boar than in broiler chickens whereas, in broiler chickens; an excessive development of the sinus; the latter were less developed in the wild boar. conclusion: The macroscopic observation showed a marked difference in liver between the two species. The microscopic examination of liver showed that the parenchyma is less pronounced in broilers while the sinuses were highly developed in the wild boar. Advances in Animal and Veterinary Sciences January 2019 | Volume 7 | Issue 1 | Page 25 sure on the fresh liver, it immediately restores the shape. A lot of research shows that the caloric content of the chicken liver is 136 kcal per 100 g of product. The composition and useful properties of the chicken liver contains a highly digestible protein, many nutrients such as vitamins A and B12, the first of which is essential for the process of skin cell renewal useful for improving vision. The mineral substances needed to allocate copper which is an essential element for the construction of all of the body's cells and the iron participates in the formation of increased level of haemoglobin in the blood and prevents anemia. The chicken liver must be with an intact glossy film, a saturated burgundy colour, without bruising and signs of friability (). In recent years, there has been a confusion of consumption of porcine liver taken as broiler chickens by this population.thus, the objective of present study was to compare the normal macro and microscopic appearance of the liver in two very different species, one is an omnivorous mammal; the wild boar and the other belongs to the family of poultry; broiler chicken from the region of Bouhmama (Khenchela). eThical approval The ethical approval is not necessary for such type of study. We have used the liver of chickens and Wild boar which were presented for post-mortem examination. Sample collecTion 8 wild boars obtained by hunting in Khenchla area, Algeria and 8 broiler chickens (Hubbard F15) were used in this experiment. macroScopic STuDy The livers obtained, from the two species (chickens, wild boars) undergoing a morphometric study (weight gain using a "Tehniprot-WTW" scale with an error point of 0.002 mg) and the measurement of the length and width dimensions of the organs with a GOCT17435-72 ruler set to 1mm. hiSTological STuDy The study was performed in the histology laboratory at the agro-veterinary institute of Taoura (Souk Ahras University, Algeria). The collected livers were subjected to a macroscopic and histological study. The following technique was adopted to prepare histological slide; Tissues obtained from chickens were fixed in 10% formalin for 24 hours and then underwent successive passes through the various compartments; dehydrated in increasing concentration of ethanol, then cleared in xylene and finally soaked in paraffin (;. The residence time of the fragments in the automate is 24 hours. The blocks were then cut to a thickness of 2 m with a microtome. The sections were placed into a flotation bath at 37° C. Then, they were placed on the slides with adhesive (egg white) and dried on a hot plate. The sections were stained by hematoxylin and eosin method of staining as per method suggested by Khenenou (). Microscopic examination was performed with an ocular microscope, the morphometric measurement of the parenchyma and the sinus was performed on five ocular areas, using the Russian LOMBO MBS-10 stereo microscope. rESultS And dIScuSSIon Normal macroscopic and histological aspect of broiler liver: Broiler chicken liver is a large gland, covered by a mesothelium beneath which is a layer of connective tissue (Glisson's capsule). Lobes of the liver are subdivided into many lobules indistinctly separated from each other. The broiler liver is dark brown. It is closely associated with the pro-ventricle and the spleen. The right lobe is larger than the left lobe ( Figure 1). Normal macroscopic and microscopic aspect of wild boar liver: Wild boar liver is located behind the diaphragm in the abdominal cavity, connected to the digestive system through the bile ducts, gall bladder and duodenum. We observed that the liver has deep interlobular fissures and a large amount of interlobular connective tissue (Glisson capsule) and its appearance is mottled ( Figure 5) The deep inter-lobular fissure divides the liver into four lobes: left, right, medial and lateral; the parenchyma is divided into lobules, which are partially separated by Glisson's capsule. We have observed that the blood vessels supplying the liver (portal vein and hepatic artery) enter the hilum (Portahepatis), from which the common bile duct and the lymphatic vessels also flow. We noted under optical microscope x400 that the parenchymal tissue of the liver is composed of hepatocytes, which are grouped into lobules. These lobules are limited by thin interlobular septa of appropriate collagen-supporting tissue that are particularly easy to identify in wild boar liver. The lobules of liver are almost hexagonal, polyhedral ( Figure 6). Under the microscope, the hepatocytes have a roughly cubic form in situ, take a rounded shape. The dissociated cells have an average diameter on the scale of approximately thirty microns, but considerable variations in size are observed, with some cells reaching twenty microns while others measure more than fifty microns. The nuclei are rounded. Different granulations are present in the cytoplasm but their size is variable. It is also noted that the lobules of the liver are composed of hepatocytes, forming plaques of liver. In the center of the lobule is located the central vein and around the lobule are inter-lobular arteries and veins, from which the inter-lobular capillaries derive. We observed that the hepatic parenchyma overlaid all central zones which narrowed towards the peripheries; the sinusoidal capillaries of central venous origin plungedthroughout the periphery. The inter-lobular capillaries penetrate the lobule and pass through the sinusoidal vessels, which are located between the liver's plaques. Advances in Animal and Veterinary Sciences January 2019 | Volume 7 | Issue 1 | Page 27 The sinusoidal vessels flow into the central, the right, middle and left hepatic veins. Among the most developed functional areas are those near to the conjunctive tissue, bordering on the deep liver parenchyma, especially in the liver of chicken, wild boar liver contains small amount of sinus (Figure 7). the examination of the liver at low magnification (ocular x 10) shows that; the parenchymal cells are arranged in rows, which come from the periphery of the lobule and converge towards its central vein, between these irregular rows of hepatocytes, there are bright spaces, also the hepatic lobules are generally separated from each other by inter-layers of loose connective tissue (inter-lobular septa) their shape is polyhedric and appear hexagonal in the cut. The examination of the hepatic parenchyma of broiler chicken showed that the five parenchymal surfaces less pronounced than those of the liver parenchyma of the wild boar with a maximum area of 12.9 ± 0.87% and a minimum of 8.33 ± 0.37%.The number of hepatic chicken sinuses depends on the regional characteristics of the parenchyma with a gradual increase in their volume especially in zones 1, 4 and 5, it is intermediate in zones 2 and 3, we also note that the amount of sinuses are in reduction when approaching the deep peripheral zones. With regard to the sinus of the liver of the wild boar, are less developed than that of the chicken because of the excessive volume occupied by the parenchyma, it is of 4.2 ± 0.30% in zone 1 and maximum 8, 7 ± 0, 31 in zone 3 (Table 1 and Figure 8). Advances in Animal and Veterinary Sciences January 2019 | Volume 7 | Issue 1 | Page 28 In broilers the parenchyma is less pronounced, the sinuses are highly developed, whereas in the wild boar is the opposite, the surface of the sinuses is less developed the parenchyma is very pronounced (Figure 9). Sus scrofa is a wild and productive mammal living in the forests of the North Africa. Represents an exploration target for scientific, despite much research carried out on this species, these vital organs are still a new topic in the histo-morphological field, in order to better understand the anatomy and hepatic histology of the animal.. The liver of wild boar represented by its structure a metabolisms regulation plant, therefore in other researches, they mention that the liver is an organ promoting a high adaptation for the fight against metabolic attacks, also against bacterial and parasitic infections, at the same time research showed that the liver is considered as an immune defence organ for its synthesis of immunological elements (Van Soest, 2013). The nutritional study for chicken (Hubbard F15) at the industrialized breeding phase is an asset, because it is an important source of animal protein for the human population.. The progress made in the study of the digestive system of the chicken include the oral cavity, tongue, salivary glands, esophagus, stomach, intestines and auxiliary glands, which are the organs that grap food, transport it, digests and excreta.. Our results are confirmed with those of other authors (Whitlow, 2002;;Iqbal, 2013) who noted that the right lobe of the poultry liver is larger than the left lobe, which are composed of two lobes whose left lobes are small and subdivided into dorsal and ventral parts, there was no other lobular subdivision in the chicken liver., also they are declared that chicken liver is a large lobed gland surrounded by a serous coating composed of a thin capsule of continuous connective tissue, subdividing the liver into lobes, to a lesser extent into lobes that provide physical support; they also indicate that the chicken liver is covered by the Glisson capsule. Quentin, has proved that the fibers are reticular type, supporting the livre cords and elastic fibers in capsule and vessels. However, According to () the hepatic lobules are indistinct (except which are close to the hilum) because of a lack of periobular connective tissue. The bile of the gallbladder helps to emulsify fat through its plenty in amylase and lipase. () Mentioned that wild boars liver is located behind the diaphragm in the abdominal cavity, connected to the digestive system through the bile ducts, gallbladder and duodenum. According to Zhiru et al. the liver has deep inter-lobular fissures and a large amount of inter-lobular connective tissue (Glisson's capsule), they also noted that his appearance is mottled. Das et al. reported that deep interlobular fissure is divided in the liver into 4 lobes -left, right, medial and lateral; The liver parenchyma is divided into lobules, which are partially separated by the capsule of Glisson. According to () blood vessels that supply the liver (portal vein and hepatic artery) penetrated through the hilum (or porta hepatis), from which the common bile canal (the secretion of bile through the liver) from where the outflow of lymphatic vessels as well. (Eurell and Frappier, 2013;;Hanan, 2013) demonstrated that the parenchyma of chicken liver is composed of hepatocytes, overlaid in radial form limiting around the central vein, so they noted that hepatocytes are polyhedral and angular shape, larger than mammalian cells. The cells have a large spherical nucleus and the base of the cell formed the the sinusoidal wall. The top of the cells communicate with the bile ducts its cytoplasmis grainy. In wild boar, the length of the lobules slightly exceeds their width. They are located at any section of the liver; the lobes have a wide variety of planes. The first landmark is the central vein, which has a circular cross-section. concluSIon The comparative morpho-histological study of species is less carried out by previous research, especially between mammals and birds. This type of study provides a lot of data for researchers in the different fields, and calls for other studies of the same type. Comparison between histological structures between different species, genera and families can help researchers in the field of animal origin and evolution. The hepatic morpho-histological differential study in both species (broiler chickens and wild boar) shows that; the liver is located in the epigastrium of the abdominal cavity, filling the right hypochondrium. The left part of the liver in the broiler is composed of 2 lobes, whereas in the wild boar it has 4 lobes on which the gallbladder is well fixed for both animals. In the broiler, the weight arrives on average to 205, 88 g, while in the wild boar it is 750 g. The microscopic examination of liver showed that In broilers the parenchyma is less pronounced, the sinuses are highly developed, whereas in the wild boar is the opposite, the surface of the sinuses is less developed the parenchyma is very pronounced.
|
/**
* Creates API without or with webhook support depending on properties set.
* At least the internal URL needs to be set to have webhook support enabled.
* @return api
* @throws TelegramApiException when the API is misconfigured
*/
TelegramBotsApi create() throws TelegramApiException {
TelegramBotsApi result;
if (properties.hasInternalUrl()) {
log.info("Initializing API with webhook support");
result = new TelegramBotsApi(DefaultBotSession.class, createDefaultWebhook());
} else {
log.info("Initializing API without webhook support");
result = new TelegramBotsApi(DefaultBotSession.class);
}
return result;
}
|
package back_tracking;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.StringTokenizer;
/**
*
* @author exponential-e
* 백준 17136번: 색종이 붙이기
*
* @see https://www.acmicpc.net/problem/17136
*
*/
public class Boj17136 {
private static int result = 30;
public static void main(String[] args) throws Exception {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int[][] map = new int[10][10];
for(int i = 0; i < map.length; i++) {
StringTokenizer st = new StringTokenizer(br.readLine());
for(int j = 0; j < map.length; j++) {
map[i][j] = Integer.parseInt(st.nextToken());
}
}
recursion(map, 0, 0, 0, 0, 0, 0, 0);
System.out.println(result == 30 ? -1: result);
}
/**
*
* Cover method
*
* line 63 ~ 77: size 5
* line 79 ~ 93: size 4
* line 95 ~ 109: size 3
* line 111 ~ 125: size 2
* line 127 ~ 131: size 1
*
* @param state
* @param x
* @param y
* @param a
* @param b
* @param c
* @param d
* @param e
*/
private static void recursion(int[][] state, int x, int y, int a, int b, int c, int d, int e) {
if(a > 5 || b > 5 || c > 5 || d > 5 || e > 5) return;
if(isCovered(state)){
result = Math.min(a + b + c + d + e, result);
return;
}
for(int i = x; i < 10; i++) {
for(int j = y; j < 10; j++) {
if(state[i][j] == 0) continue;
if(covering(i, j, 5, state)) {
for (int row = i; row < i + 5; row++) {
for (int col = j; col < j + 5; col++) {
state[row][col] = 0;
}
}
recursion(state, i, 0, a, b, c, d, e + 1);
for (int row = i; row < i + 5; row++) {
for (int col = j; col < j + 5; col++) {
state[row][col] = 1;
}
}
}
if(covering(i, j, 4, state)) {
for (int row = i; row < i + 4; row++) {
for (int col = j; col < j + 4; col++) {
state[row][col] = 0;
}
}
recursion(state, i, 0, a, b, c, d + 1, e);
for (int row = i; row < i + 4; row++) {
for (int col = j; col < j + 4; col++) {
state[row][col] = 1;
}
}
}
if(covering(i, j, 3, state)) {
for (int row = i; row < i + 3; row++) {
for (int col = j; col < j + 3; col++) {
state[row][col] = 0;
}
}
recursion(state, i, 0, a, b, c + 1, d, e);
for (int row = i; row < i + 3; row++) {
for (int col = j; col < j + 3; col++) {
state[row][col] = 1;
}
}
}
if(covering(i, j, 2, state)) {
for (int row = i; row < i + 2; row++) {
for (int col = j; col < j + 2; col++) {
state[row][col] = 0;
}
}
recursion(state, i, 0, a, b + 1, c, d, e);
for (int row = i; row < i + 2; row++) {
for (int col = j; col < j + 2; col++) {
state[row][col] = 1;
}
}
}
if(covering(i, j, 1, state)) {
state[i][j] = 0;
recursion(state, i, 0, a + 1, b, c, d, e);
state[i][j] = 1;
}
return;
}
}
}
private static boolean outOfRange(int row, int col) {
return row >= 10 || col >= 10;
}
private static boolean isCovered(int[][] arr) {
for(int i = 0; i < arr.length; i++) {
for(int j = 0; j < arr.length; j++) {
if(arr[i][j] == 1) return false;
}
}
return true;
}
private static boolean covering(int i, int j, int size, int[][] state ) {
for(int row = i; row < size + i; row++) {
for(int col = j; col < size + j; col++) {
if(outOfRange(row, col) || state[row][col] == 0) return false;
}
}
return true;
}
}
|
import React from 'react';
import { MatchList } from './MatchList';
export default {
title: 'Components/matches',
};
const matchListEntries = [
{
awayTeam: 'team away',
homeTeam: 'team home',
betPredictions: [{ betName: 'over1.5', prediction: 40 }],
},
];
export const Primary = () => <MatchList entries={matchListEntries} />;
|
/*---------------------------------------------------------------------------------------------
* Copyright (c) <NAME>. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
#pragma once
#include <stdlib.h>
#include <vector>
#include <memory>
#include "Keycodes.h"
#include "Trace.h"
#include "Object.h"
#include "RenderQueue.h"
#include "Physics.h"
using namespace std;
class State : public Object
{
public:
shared_ptr<Physics> physics;
State() : physics(make_shared<Physics>()) {}
virtual ~State(){}
virtual void StateDraw()
{
RenderQueue::Clear();
SubmitDrawCalls_R(0xFFFFFFFF);
RenderQueue::Sort();
RenderQueue::Execute();
}
virtual void OnTouchDown(float x, float y, int id){}
virtual void OnTouchMove(float x, float y, int id){}
virtual void OnTouchUp(float x, float y, int id){}
virtual void OnKeyDown(KeyCode keyCode){}
virtual void OnKeyUp(KeyCode keyCode){}
virtual void OnBackPressed(){}
virtual shared_ptr<State> state() {
return static_pointer_cast<State>(shared_from_this());
}
};
|
For the first time in more than five years travelers are paying more on average for their hotel rooms – a possible sign that the economy is rebounding. NBC’s Michelle Franzen reports.
>>> now to a sign of the times and the change of advises from travel experts about booking this year's winter vacation compared with last year. act now or you could end up paying the price. we get more now from nbc's michelle franzen .
>> reporter: emily is already planning her get abouts aways this fall. the lifestyle blogger is used to searching for the best deals, but this year she has noticed a change when it comes to hotels.
>> what i'm finding universally is that they're just really expensive, and they're more expensive than i remember them being in the last few years.
>> reporter: she's right. for the first time in five years travellers are paying more on average for their hotel rooms . globally prices rose 4% the first half of this year. they were up 5% in north america . signs, experts say, the economy is rebounding from the recession and as with higher airfares, demand is driving up room rates.
>> it's the first time that meter has moved in years, and so what we can say is the economy is getting healthier. it's good news.
>> reporter: despite higher prices, travel from business to pleasure is up across the board. in new york city a record 50 million tourists made the big apple their destination last year. hotels are still competing for customers, and adding extra perks during the stay, but gone, say experts, are the days of bargain rates.
>> the deals are still out there, but travel experts say there's been a big shift on how to get them. the best advice now, don't wait until the last minute.
>> right now you want to book as far in advance as possible, so what we're seeing is people are booking two to four months in advance on average. holiday travel, for example, people are booking now.
>> reporter: new rules, emily is starting to realize, as they continues her search for the right hotel at the right price. michelle franzen , nbc news, morning.
|
<filename>src/se/var.rs
use crate::{
errors::{serialize::DeError, Error},
events::{BytesEnd, BytesStart, Event},
se::Serializer,
writer::Writer,
};
use de::{INNER_VALUE, UNFLATTEN_PREFIX};
use serde::ser::{self, Serialize, SerializeMap};
use serde::Serializer as _;
use std::io::Write;
/// An implementation of `SerializeMap` for serializing to XML.
pub struct Map<'r, 'w, W>
where
W: 'w + Write,
{
parent: &'w mut Serializer<'r, W>,
}
impl<'r, 'w, W> Map<'r, 'w, W>
where
W: 'w + Write,
{
/// Create a new Map
pub fn new(parent: &'w mut Serializer<'r, W>) -> Self {
Map { parent }
}
}
impl<'r, 'w, W> ser::SerializeMap for Map<'r, 'w, W>
where
W: 'w + Write,
{
type Ok = ();
type Error = DeError;
fn serialize_key<T: ?Sized + Serialize>(&mut self, _: &T) -> Result<(), DeError> {
Err(DeError::Unsupported(
"impossible to serialize the key on its own, please use serialize_entry()",
))
}
fn serialize_value<T: ?Sized + Serialize>(&mut self, value: &T) -> Result<(), DeError> {
value.serialize(&mut *self.parent)
}
fn end(self) -> Result<Self::Ok, DeError> {
if let Some(tag) = self.parent.root_tag {
self.parent
.writer
.write_event(Event::End(BytesEnd::borrowed(tag.as_bytes())))?;
}
Ok(())
}
fn serialize_entry<K: ?Sized + Serialize, V: ?Sized + Serialize>(
&mut self,
key: &K,
value: &V,
) -> Result<(), DeError> {
// TODO: Is it possible to ensure our key is never a composite type?
// Anything which isn't a "primitive" would lead to malformed XML here...
write!(self.parent.writer.inner(), "<").map_err(Error::Io)?;
key.serialize(&mut *self.parent)?;
write!(self.parent.writer.inner(), ">").map_err(Error::Io)?;
value.serialize(&mut *self.parent)?;
write!(self.parent.writer.inner(), "</").map_err(Error::Io)?;
key.serialize(&mut *self.parent)?;
write!(self.parent.writer.inner(), ">").map_err(Error::Io)?;
Ok(())
}
}
/// An implementation of `SerializeStruct` for serializing to XML.
pub struct Struct<'r, 'w, W>
where
W: 'w + Write,
{
parent: &'w mut Serializer<'r, W>,
/// Buffer for holding fields, serialized as attributes. Doesn't allocate
/// if there are no fields represented as attributes
attrs: BytesStart<'w>,
/// Buffer for holding fields, serialized as elements
children: Vec<u8>,
/// Buffer for serializing one field. Cleared after serialize each field
buffer: Vec<u8>,
}
impl<'r, 'w, W> Struct<'r, 'w, W>
where
W: 'w + Write,
{
/// Create a new `Struct`
pub fn new(parent: &'w mut Serializer<'r, W>, name: &'r str) -> Self {
let name = name.as_bytes();
Struct {
parent,
attrs: BytesStart::borrowed_name(name),
children: Vec::new(),
buffer: Vec::new(),
}
}
}
impl<'r, 'w, W> ser::SerializeStruct for Struct<'r, 'w, W>
where
W: 'w + Write,
{
type Ok = ();
type Error = DeError;
fn serialize_field<T: ?Sized + Serialize>(
&mut self,
key: &'static str,
value: &T,
) -> Result<(), DeError> {
// TODO: Inherit indentation state from self.parent.writer
let writer = Writer::new(&mut self.buffer);
if key.starts_with(UNFLATTEN_PREFIX) {
let key = key.split_at(UNFLATTEN_PREFIX.len()).1;
let mut serializer = Serializer::with_root(writer, Some(key));
serializer.serialize_newtype_struct(key, value);
self.children.append(&mut self.buffer);
} else {
let mut serializer = Serializer::with_root(writer, Some(key));
value.serialize(&mut serializer)?;
if !self.buffer.is_empty() {
if self.buffer[0] == b'<' || key == INNER_VALUE {
// Drains buffer, moves it to children
self.children.append(&mut self.buffer);
} else {
self.attrs
.push_attribute((key.as_bytes(), self.buffer.as_ref()));
self.buffer.clear();
}
}
}
Ok(())
}
fn end(self) -> Result<Self::Ok, DeError> {
if self.children.is_empty() {
self.parent.writer.write_event(Event::Empty(self.attrs))?;
} else {
self.parent
.writer
.write_event(Event::Start(self.attrs.to_borrowed()))?;
self.parent.writer.write(&self.children)?;
self.parent
.writer
.write_event(Event::End(self.attrs.to_end()))?;
}
Ok(())
}
}
impl<'r, 'w, W> ser::SerializeStructVariant for Struct<'r, 'w, W>
where
W: 'w + Write,
{
type Ok = ();
type Error = DeError;
#[inline]
fn serialize_field<T: ?Sized + Serialize>(
&mut self,
key: &'static str,
value: &T,
) -> Result<(), Self::Error> {
<Self as ser::SerializeStruct>::serialize_field(self, key, value)
}
#[inline]
fn end(self) -> Result<Self::Ok, Self::Error> {
<Self as ser::SerializeStruct>::end(self)
}
}
/// An implementation of `SerializeSeq' for serializing to XML.
pub struct Seq<'r, 'w, W>
where
W: 'w + Write,
{
parent: &'w mut Serializer<'r, W>,
}
impl<'r, 'w, W> Seq<'r, 'w, W>
where
W: 'w + Write,
{
/// Create a new `Seq`
pub fn new(parent: &'w mut Serializer<'r, W>) -> Self {
Seq { parent }
}
}
impl<'r, 'w, W> ser::SerializeSeq for Seq<'r, 'w, W>
where
W: 'w + Write,
{
type Ok = ();
type Error = DeError;
fn serialize_element<T: ?Sized>(&mut self, value: &T) -> Result<(), Self::Error>
where
T: Serialize,
{
value.serialize(&mut *self.parent)?;
Ok(())
}
fn end(self) -> Result<Self::Ok, Self::Error> {
Ok(())
}
}
/// An implementation of `SerializeTuple`, `SerializeTupleStruct` and
/// `SerializeTupleVariant` for serializing to XML.
pub struct Tuple<'r, 'w, W>
where
W: 'w + Write,
{
parent: &'w mut Serializer<'r, W>,
/// Possible qualified name of XML tag surrounding each element
name: &'r str,
}
impl<'r, 'w, W> Tuple<'r, 'w, W>
where
W: 'w + Write,
{
/// Create a new `Tuple`
pub fn new(parent: &'w mut Serializer<'r, W>, name: &'r str) -> Self {
Tuple { parent, name }
}
}
impl<'r, 'w, W> ser::SerializeTuple for Tuple<'r, 'w, W>
where
W: 'w + Write,
{
type Ok = ();
type Error = DeError;
fn serialize_element<T: ?Sized>(&mut self, value: &T) -> Result<(), Self::Error>
where
T: Serialize,
{
write!(self.parent.writer.inner(), "<{}>", self.name).map_err(Error::Io)?;
value.serialize(&mut *self.parent)?;
write!(self.parent.writer.inner(), "</{}>", self.name).map_err(Error::Io)?;
Ok(())
}
#[inline]
fn end(self) -> Result<Self::Ok, Self::Error> {
Ok(())
}
}
impl<'r, 'w, W> ser::SerializeTupleStruct for Tuple<'r, 'w, W>
where
W: 'w + Write,
{
type Ok = ();
type Error = DeError;
#[inline]
fn serialize_field<T: ?Sized>(&mut self, value: &T) -> Result<(), Self::Error>
where
T: Serialize,
{
<Self as ser::SerializeTuple>::serialize_element(self, value)
}
#[inline]
fn end(self) -> Result<Self::Ok, Self::Error> {
<Self as ser::SerializeTuple>::end(self)
}
}
impl<'r, 'w, W> ser::SerializeTupleVariant for Tuple<'r, 'w, W>
where
W: 'w + Write,
{
type Ok = ();
type Error = DeError;
#[inline]
fn serialize_field<T: ?Sized>(&mut self, value: &T) -> Result<(), Self::Error>
where
T: Serialize,
{
<Self as ser::SerializeTuple>::serialize_element(self, value)
}
#[inline]
fn end(self) -> Result<Self::Ok, Self::Error> {
<Self as ser::SerializeTuple>::end(self)
}
}
|
package org.zhadok.poe.controller.config.pojo;
import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonProperty;
import net.java.games.input.Event;
/**
* Used to identify the exact method of input being used on the controller, for example
* a button or a joystick
*/
public class MappingKey {
/**
* Example:
* Hat switch
* Axis X
* Button 1
*/
private final String componentName;
/**
* Example:
* 'pov' for hat switch
* 'x' for joysticks
* '1' for Button 1
*/
private final String id;
private final Float valueWhenPressed;
private final boolean analog;
/**
* Optional field, not used for mapping
*/
private String buttonDescription;
@JsonCreator
public MappingKey(
@JsonProperty("componentName") String componentName,
@JsonProperty("id") String id,
@JsonProperty("valueWhenPressed") Float valueWhenPressed,
@JsonProperty("analog") boolean analog,
@JsonProperty("buttonDescription") String buttonDescription) {
this.componentName = componentName;
this.id = id;
this.valueWhenPressed = valueWhenPressed;
this.analog = analog;
this.buttonDescription = buttonDescription;
}
public MappingKey(Event inputEvent) {
this(inputEvent.getComponent().getName(),
inputEvent.getComponent().getIdentifier().toString(),
// Value should only be recorded if digital button, not analog (e.g. joystick)
inputEvent.getComponent().isAnalog() ? null : inputEvent.getValue(),
inputEvent.getComponent().isAnalog(),
null);
}
public String getId() {
return id;
}
public String getComponentName() {
return componentName;
}
public boolean isAnalog() {
return analog;
}
public Float getValueWhenPressed() {
return valueWhenPressed;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((componentName == null) ? 0 : componentName.hashCode());
result = prime * result + ((id == null) ? 0 : id.hashCode());
result = prime * result + (analog ? 1231 : 1237);
result = prime * result + ((valueWhenPressed == null) ? 0 : valueWhenPressed.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
MappingKey other = (MappingKey) obj;
if (componentName == null) {
if (other.componentName != null)
return false;
} else if (!componentName.equals(other.componentName))
return false;
if (id == null) {
if (other.id != null)
return false;
} else if (!id.equals(other.id))
return false;
if (analog != other.analog)
return false;
if (valueWhenPressed == null) {
if (other.valueWhenPressed != null)
return false;
} else if (!valueWhenPressed.equals(other.valueWhenPressed))
return false;
return true;
}
public String getButtonDescription() {
return buttonDescription;
}
public void setButtonDescription(String buttonDescription) {
this.buttonDescription = buttonDescription;
}
@Override
public String toString() {
return "MappingKey [componentName='" + componentName + "', id='" + id + "', valueWhenPressed=" + valueWhenPressed
+ ", isAnalog=" + analog + "]";
}
@JsonIgnore
public String toStringUI() {
String result = this.getComponentName();
if (this.getValueWhenPressed() != null) {
result += " (value=" + this.getValueWhenPressed() + ")";
}
return result;
}
}
|
After last year's debt ceiling stand-off, Senate Minority Leader Mitch McConnell declared that the nation's borrowing limit is "a hostage that's worth ransoming." Future requests, he warned, "will not be clean anymore." True to their leader's word, Sens. Bob Corker (R-TN) and Graham proclaimed the debt ceiling is their "leverage" to extract draconian cuts to entitlement spending. As Graham told Fox News, President Obama better start "maning up" on Medicare cuts—or else:
"In February or March you have to raise the debt ceiling. And I can tell you this, there is a hardening on the Republican side. We're not going to raise the debt ceiling. We're not going to let Obama borrow any more money or any American Congress borrow any more money until we fix this country from becoming Greece. That requires significant entitlement reform to save Social Security from bankruptcy and Medicare from bankruptcy. Social Security is going bankrupt in about 20, 25 years. Medicare is going bankrupt in 15 or 20 years."
"Let me tell you what's involved if we don't lift the debt ceiling: financial collapse and calamity throughout the world. That's not lost upon me. But we've done this 93 times. And if we keep doing the same old thing, then that is insanity to the nth degree."
A new analysis by the Bipartisan Policy Center concluded that failure to boost the debt ceiling by the August drop-dead window would force the U.S. Treasury to immediately slash spending by 44%. As The Hill reported, "On an annualized basis, the cut in spending alone is a 10 percent cut in GDP, BPC scholar Jay Powell told reporters." While the IMF similarly cautioned that "the debt ceiling should be raised as soon as possible to avoid damage to the economy and world financial markets," former McCain economic adviser Mark Zandi this week painted a grim portrait of just what that damage would look like.
Their answers were across-the-board apocalyptic. If the U.S. government is so incapable of solving its political problems that it can't come to an agreement on the debt ceiling, they said, that's basically the end of the United States as the world's reserve currency. We won't be considered safe enough to serve as the investment of last resort. We would lose the most important advantage our economy has in the global financial system -- and we'd probably lose it forever. Skyrocketing interest rates would slow our economy and, in real terms, make it even harder to pay back our debt, which would in turn send interest rates going even higher. It's an economic death spiral we associate with third-world countries, not with the United States.
"The people who are threatening not to pass the debt ceiling are our version of al Qaeda terrorists. Really. They're really putting our whole society at risk by threatening to round up 50 percent of the members of the Congress, who are loony, who would put our credit at risk."
Standard & Poor's director said for the first time Thursday that one reason the United States lost its triple-A credit rating was that several lawmakers expressed skepticism about the serious consequences of a credit default -- a position put forth by some Republicans. Without specifically mentioning Republicans, S&P senior director Joydeep Mukherji said the stability and effectiveness of American political institutions were undermined by the fact that "people in the political arena were even talking about a potential default," Mukherji said. "That a country even has such voices, albeit a minority, is something notable," he added. "This kind of rhetoric is not common amongst AAA sovereigns."
And in January 2011, Sen. Graham explained to CNN's Wolf Blitzer what that "or else" was. If President Obama didn't agree to agree to cut discretionary spending to 2008 levels and slash Social Security, Graham announced his GOP would kill the economy Now, while Graham's bogus claims about the supposed bankruptcy of Medicare and Social Security earned him a "Three Pinocchio" rating. His Greece analogy , too, was debunked long ago. But his ominous prediction of "financial collapse and calamity throughout the world" is spot on. As I wrote back in June 2011 Zandi's disturbing picture ("we go into recession and my forecast would be blown out of the water") sounded idyllic in comparison to the dystopian hellscape economists, investors and economic policymakers described to Ezra Klein It's no wonder conservative columnist David Brooks worried that his Republican Party is no longer "a normal party." Former Bush Treasury Secretary Paul O'Neill had a different description of his GOP colleagues:Mercifully, the Republican kamikazes in Congress did not sink the American ship of state in 2011. But the damage to the U.S. economy was significant nonetheless , as consumer confidence plunged and job creation stalled throughout that uncertain summer. In August 2011, Standard & Poors explained its Tea Party downgrade of the U.S. credit rating:Yes, threatening to trigger "financial collapse and calamity throughout the world" certainly is "notable" and "not common amongst AAA sovereigns." But it's just another day at the office for Republicans like Lindsey Graham. After all, Graham like John Boehner, Mitch McConnell and other GOP leaders, has another word term for "collapse" and calamity."
Leverage.
|
Media playback is unsupported on your device Media caption The prime minister made her comments in Kyoto on the first day of a three-day visit to Japan
Some Conservative backbenchers have said they do not believe Theresa May will be able to fight the next general election as prime minister.
Their comments follow Mrs May's claim she was "here for the long term".
Labour said she was "deluding herself" - but Foreign Secretary Boris Johnson led her defence, insisting she could win an absolute majority.
However, ex-Conservative Party chairman Grant Shapps said it was "too early to be talking about going on and on".
Having had "conversations with 50 or so colleagues" in the run-up to the summer, Mr Shapps said: "The truth is we ran a very poor election and you can't just brush that under the table and pretend it didn't happen - not least because we went from having a workable majority to no majority at all, so that stands to reason."
He added that while there was no mood for a leadership election, Mrs May's remarks "will certainly raise some eyebrows".
Image copyright PA Image caption The prime minister says she has a lengthy agenda and is not just focused on Brexit
"Let's get some performance, let's get some delivery for the British people and then let's see where we are, rather than vice versa," Mr Shapps told BBC Radio 4's Today programme.
The former Tory Chancellor, George Osborne, who became a newspaper editor after being sacked by Mrs May, compared her premiership to the "Living Dead in a second-rate horror film".
The former education secretary Nicky Morgan told BBC's Hardtalk it would be "difficult" for Mrs May to lead the party into the next election, due in 2022.
'Don't want people distracted'
But former Conservative leader Lord Howard told BBC Radio 4's World at One that she "should stay on".
"I think she was quite right to say what she said today. She has quite rightly said there's a job to be done. I think the government is back on track."
And Graham Brady, the chairman of the 1922 Committee of backbench Tory MPs told Sky News that the parliamentary Conservative party was not concerned with "the leadership question".
"We certainly want the prime minister to get on serving the national interest doing that job for our country. We don't want people distracted," he said.
Analysis by BBC political correspondent Iain Watson
Theresa May didn't set off to the Far East to deliver a message that she would "go on and on".
But have her interviews changed the facts on the ground?
While some MPs were swiftly deployed to make clear she can indeed stay on, from my soundings the former party chairman Grant Shapps and former Number 10 communications chief Katie Perrior are nearer the mark.
The former told the BBC her performance would be assessed post-Brexit, while the latter - admitting that Theresa May could have said little else in response to questions about her future - believes she still won't lead the party into the next election.
Lack of appetite for a leadership contest, never mind a general election, among her MPs means it's quite safe for the prime minister to say what she said - but it doesn't mean it's any more accurate than her repeated assurances that she wouldn't call a snap election. Read more
Debate over Mrs May's long-term ambitions was sparked after she told the BBC's Ben Wright in Kyoto that it was her intention to lead her party into another general election, whenever that was.
"Yes, I'm here for the long term. What me and my government are about is not just delivering on Brexit but delivering a brighter future for the UK," she said.
Mrs May said she wanted to ensure "global Britain" could take its trading place in the world, as well as dealing with "those injustices domestically that we need to do to ensure that strong, more global, but also fairer Britain for the future".
Emphasising her stance on Thursday, she told reporters: "I said I wasn't a quitter. There's a long-term job to do, there's an important job to be done in the UK. Yes, that's partly about Brexit and getting Brexit right, but if you think back to what I said when I became prime minister, when I stood in Downing Street, there are many other issues that we need to address."
The prime minister has been under pressure after losing her Commons majority in a snap election called earlier this year.
'Undivided backing'
Some reports had suggested she could stand down in 2019 after EU withdrawal.
But speaking on a visit to Nigeria, Mr Johnson, who received public backing from Mrs May after recent criticism of his performance, said: "I've made it clear I'm giving my undivided backing to Theresa May.
"We need to get Brexit done.
"She's ideally placed to deliver a great outcome for our country and then deliver what we all want to see, which is this exciting agenda of global Britain.
"I think she gets it. She really wants to deliver it. I'm here to support her."
Image copyright Getty Images Image caption Theresa May launching her leadership bid in June 2016
The UK is due to leave the EU in March 2019 and supporters of Mrs May have said leadership speculation serves only to undermine attempts to secure the best possible terms of exit.
Shadow Cabinet Office minister Jon Trickett said the prime minister was "deluding herself" about her plan to stay in power until the next election.
"Neither the public nor Tory MPs believe her fantasy of staying on till 2022," he said.
"Theresa May leads a zombie government."
Katie Perrior, former director of communications at Downing Street, said while she also did not believe Mrs May would fight the next general election as Conservative leader, the PM could not have answered any differently in the "middle of Brexit negotiations".
The next general election is not scheduled to take place until May 2022, by which point Mrs May - if she stayed in Downing Street - would have been prime minister for nearly six years.
In the immediate aftermath of her party's failure to win June's general election outright, several MPs called on her to consider her position.
The prime minister has sought to consolidate her position by negotiating a governing agreement with the Democratic Unionists and overhauling the way Downing Street works, replacing key advisers.
On the second day of her trip to Japan, Mrs May will hold official talks with her counterpart Shinzo Abe and emphasise the growing security links between the two countries.
|
Warren County Prosecutor Dave Fornshell (Photo: Provided)
School threats in Warren County were a near-daily occurrence from the end of April until the second week of May.
On April 27, a bomb threat was written on a bathroom wall at Springobro High School. The school was evacuated and remained closed the next day.
Two school days later, a written bomb threat was found in a girl’s bathroom at Lebanon High School. It said, “a bomb (was going) to go off at” 1 p.m., according to police records obtained by The Enquirer.
The high school was evacuated that day, May 2, as well as the next two days because of a shooting threat and then another bomb threat. The shooting threat was written on a stall in a different girl’s bathroom, according to police records.
By May 11, there had been multiple threats involving four Warren County schools. At least nine students, ranging in age from 12 to 18, face criminal charges in the incidents. The 18-year-old, Andrew Stadler, accused of writing the threat in the Springboro case, has been charged as an adult in Warren County Common Pleas Court and faces a possible prison sentence.
Caught up in what appears to be a crackdown on threats was a 17-year-old Lebanon High School junior, whose ill-timed Twitter posts about Nerf toy gun battles and then a school shooting led to criminal charges.
The 17-year-old’s attorney, Charles M. Rittgers, said the case is different than the others.
“While (he) certainly regrets and profusely apologizes for his actions,” Rittgers said in court documents, “he clearly indicated in his tweet he was being sarcastic.”
The 17-year-old's Twitter posts, made April 14 and 15, didn’t lead to evacuations or school closures. He eventually was expelled from the school for the year. The Enquirer is not naming him because he is a juvenile.
In the first post, according to court documents, he wrote: “Great idea for next (year’s) Nerf war! Instead of arguing over rules, let’s just use real guns! Ha ha, just joking. I’ll have shot up the school by then.”
On April 15, he wrote, according to court documents: “Haven’t been called to the office yet lmao…really just need to make it to lunch to follow through with the plan.”
Rittgers noted that including the acronym “lmao” in the tweet, which refers to laughing, showed that his client was being sarcastic. Nerf wars involve teams of people who shoot foam missiles at each other. The 17-year-old and his friends would set up brackets, Rittgers said.
“Unlike most of the other cases,” Rittgers said in the documents, “there was not an evacuation, was no bomb sweep, no third-party companies needed for ventilation searches…and no disruption of academic or school activities.”
The 17-year-old was arraigned May 2 in juvenile court – the same day as the first evacuation of Lebanon High School. A few days later, he pleaded guilty to a misdemeanor charge, after prosecutors said they were considering upgrading the charge to a felony. He is scheduled to be sentenced Wednesday in Warren County juvenile court.
Warren County Prosecutor Dave Fornshell could not be reached for comment.
The 17-year-old, like the others charged in juvenile court, is still being held without bond at a Warren County juvenile facility. Court documents say he missed his sister’s graduation and will lose college credits he was working on because he has been incarcerated and couldn’t take his final exam. The 18-year-old facing adult charges, Stadler, has been released from custody while his case is pending, according to court records.
Rittgers has asked the judge to place his client on probation and order him to work with local schools “through speeches and appearances, discussing with students the implications and importance of words, even when (they are) mere jokes.”
Read or Share this story: http://cin.ci/1TmaVPR
|
<gh_stars>0
/*
Copyright (c) 2010-2014, <NAME> - IntRoLab - Universite de Sherbrooke
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 Universite de Sherbrooke 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 THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY
DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include "rtabmap/core/CameraStereo.h"
#include "rtabmap/core/util2d.h"
#include "rtabmap/core/CameraRGB.h"
#include "rtabmap/core/Version.h"
#include <rtabmap/utilite/UEventsManager.h>
#include <rtabmap/utilite/UConversion.h>
#include <rtabmap/utilite/UStl.h>
#include <rtabmap/utilite/UConversion.h>
#include <rtabmap/utilite/UFile.h>
#include <rtabmap/utilite/UDirectory.h>
#include <rtabmap/utilite/UTimer.h>
#include <rtabmap/utilite/UMath.h>
#ifdef RTABMAP_DC1394
#include <dc1394/dc1394.h>
#endif
#ifdef RTABMAP_FLYCAPTURE2
#include <triclops.h>
#include <fc2triclops.h>
#endif
namespace rtabmap
{
//
// CameraStereoDC1394
// Inspired from ROS camera1394stereo package
//
#ifdef RTABMAP_DC1394
class DC1394Device
{
public:
DC1394Device() :
camera_(0),
context_(0)
{
}
~DC1394Device()
{
if (camera_)
{
if (DC1394_SUCCESS != dc1394_video_set_transmission(camera_, DC1394_OFF) ||
DC1394_SUCCESS != dc1394_capture_stop(camera_))
{
UWARN("unable to stop camera");
}
// Free resources
dc1394_capture_stop(camera_);
dc1394_camera_free(camera_);
camera_ = NULL;
}
if(context_)
{
dc1394_free(context_);
context_ = NULL;
}
}
const std::string & guid() const {return guid_;}
bool init()
{
if(camera_)
{
// Free resources
dc1394_capture_stop(camera_);
dc1394_camera_free(camera_);
camera_ = NULL;
}
// look for a camera
int err;
if(context_ == NULL)
{
context_ = dc1394_new ();
if (context_ == NULL)
{
UERROR( "Could not initialize dc1394_context.\n"
"Make sure /dev/raw1394 exists, you have access permission,\n"
"and libraw1394 development package is installed.");
return false;
}
}
dc1394camera_list_t *list;
err = dc1394_camera_enumerate(context_, &list);
if (err != DC1394_SUCCESS)
{
UERROR("Could not get camera list");
return false;
}
if (list->num == 0)
{
UERROR("No cameras found");
dc1394_camera_free_list (list);
return false;
}
uint64_t guid = list->ids[0].guid;
dc1394_camera_free_list (list);
// Create a camera
camera_ = dc1394_camera_new (context_, guid);
if (!camera_)
{
UERROR("Failed to initialize camera with GUID [%016lx]", guid);
return false;
}
uint32_t value[3];
value[0]= camera_->guid & 0xffffffff;
value[1]= (camera_->guid >>32) & 0x000000ff;
value[2]= (camera_->guid >>40) & 0xfffff;
guid_ = uFormat("%06x%02x%08x", value[2], value[1], value[0]);
UINFO("camera model: %s %s", camera_->vendor, camera_->model);
// initialize camera
// Enable IEEE1394b mode if the camera and bus support it
bool bmode = camera_->bmode_capable;
if (bmode
&& (DC1394_SUCCESS !=
dc1394_video_set_operation_mode(camera_,
DC1394_OPERATION_MODE_1394B)))
{
bmode = false;
UWARN("failed to set IEEE1394b mode");
}
// start with highest speed supported
dc1394speed_t request = DC1394_ISO_SPEED_3200;
int rate = 3200;
if (!bmode)
{
// not IEEE1394b capable: so 400Mb/s is the limit
request = DC1394_ISO_SPEED_400;
rate = 400;
}
// round requested speed down to next-lower defined value
while (rate > 400)
{
if (request <= DC1394_ISO_SPEED_MIN)
{
// get current ISO speed of the device
dc1394speed_t curSpeed;
if (DC1394_SUCCESS == dc1394_video_get_iso_speed(camera_, &curSpeed) && curSpeed <= DC1394_ISO_SPEED_MAX)
{
// Translate curSpeed back to an int for the parameter
// update, works as long as any new higher speeds keep
// doubling.
request = curSpeed;
rate = 100 << (curSpeed - DC1394_ISO_SPEED_MIN);
}
else
{
UWARN("Unable to get ISO speed; assuming 400Mb/s");
rate = 400;
request = DC1394_ISO_SPEED_400;
}
break;
}
// continue with next-lower possible value
request = (dc1394speed_t) ((int) request - 1);
rate = rate / 2;
}
// set the requested speed
if (DC1394_SUCCESS != dc1394_video_set_iso_speed(camera_, request))
{
UERROR("Failed to set iso speed");
return false;
}
// set video mode
dc1394video_modes_t vmodes;
err = dc1394_video_get_supported_modes(camera_, &vmodes);
if (err != DC1394_SUCCESS)
{
UERROR("unable to get supported video modes");
return (dc1394video_mode_t) 0;
}
// see if requested mode is available
bool found = false;
dc1394video_mode_t videoMode = DC1394_VIDEO_MODE_FORMAT7_3; // bumblebee
for (uint32_t i = 0; i < vmodes.num; ++i)
{
if (vmodes.modes[i] == videoMode)
{
found = true;
}
}
if(!found)
{
UERROR("unable to get video mode %d", videoMode);
return false;
}
if (DC1394_SUCCESS != dc1394_video_set_mode(camera_, videoMode))
{
UERROR("Failed to set video mode %d", videoMode);
return false;
}
// special handling for Format7 modes
if (dc1394_is_video_mode_scalable(videoMode) == DC1394_TRUE)
{
if (DC1394_SUCCESS != dc1394_format7_set_color_coding(camera_, videoMode, DC1394_COLOR_CODING_RAW16))
{
UERROR("Could not set color coding");
return false;
}
uint32_t packetSize;
if (DC1394_SUCCESS != dc1394_format7_get_recommended_packet_size(camera_, videoMode, &packetSize))
{
UERROR("Could not get default packet size");
return false;
}
if (DC1394_SUCCESS != dc1394_format7_set_packet_size(camera_, videoMode, packetSize))
{
UERROR("Could not set packet size");
return false;
}
}
else
{
UERROR("Video is not in mode scalable");
}
// start the device streaming data
// Set camera to use DMA, improves performance.
if (DC1394_SUCCESS != dc1394_capture_setup(camera_, 4, DC1394_CAPTURE_FLAGS_DEFAULT))
{
UERROR("Failed to open device!");
return false;
}
// Start transmitting camera data
if (DC1394_SUCCESS != dc1394_video_set_transmission(camera_, DC1394_ON))
{
UERROR("Failed to start device!");
return false;
}
return true;
}
bool getImages(cv::Mat & left, cv::Mat & right)
{
if(camera_)
{
dc1394video_frame_t * frame = NULL;
UDEBUG("[%016lx] waiting camera", camera_->guid);
dc1394_capture_dequeue (camera_, DC1394_CAPTURE_POLICY_WAIT, &frame);
if (!frame)
{
UERROR("Unable to capture frame");
return false;
}
dc1394video_frame_t frame1 = *frame;
// deinterlace frame into two imagesCount one on top the other
size_t frame1_size = frame->total_bytes;
frame1.image = (unsigned char *) malloc(frame1_size);
frame1.allocated_image_bytes = frame1_size;
frame1.color_coding = DC1394_COLOR_CODING_RAW8;
int err = dc1394_deinterlace_stereo_frames(frame, &frame1, DC1394_STEREO_METHOD_INTERLACED);
if (err != DC1394_SUCCESS)
{
free(frame1.image);
dc1394_capture_enqueue(camera_, frame);
UERROR("Could not extract stereo frames");
return false;
}
uint8_t* capture_buffer = reinterpret_cast<uint8_t *>(frame1.image);
UASSERT(capture_buffer);
cv::Mat image(frame->size[1], frame->size[0], CV_8UC3);
cv::Mat image2 = image.clone();
//DC1394_COLOR_CODING_RAW16:
//DC1394_COLOR_FILTER_BGGR
cv::cvtColor(cv::Mat(frame->size[1], frame->size[0], CV_8UC1, capture_buffer), left, CV_BayerRG2BGR);
cv::cvtColor(cv::Mat(frame->size[1], frame->size[0], CV_8UC1, capture_buffer+image.total()), right, CV_BayerRG2GRAY);
dc1394_capture_enqueue(camera_, frame);
free(frame1.image);
return true;
}
return false;
}
private:
dc1394camera_t *camera_;
dc1394_t *context_;
std::string guid_;
};
#endif
bool CameraStereoDC1394::available()
{
#ifdef RTABMAP_DC1394
return true;
#else
return false;
#endif
}
CameraStereoDC1394::CameraStereoDC1394(float imageRate, const Transform & localTransform) :
Camera(imageRate, localTransform),
device_(0)
{
#ifdef RTABMAP_DC1394
device_ = new DC1394Device();
#endif
}
CameraStereoDC1394::~CameraStereoDC1394()
{
#ifdef RTABMAP_DC1394
if(device_)
{
delete device_;
}
#endif
}
bool CameraStereoDC1394::init(const std::string & calibrationFolder, const std::string & cameraName)
{
#ifdef RTABMAP_DC1394
if(device_)
{
bool ok = device_->init();
if(ok)
{
// look for calibration files
if(!calibrationFolder.empty())
{
if(!stereoModel_.load(calibrationFolder, cameraName.empty()?device_->guid():cameraName))
{
UWARN("Missing calibration files for camera \"%s\" in \"%s\" folder, you should calibrate the camera!",
cameraName.empty()?device_->guid().c_str():cameraName.c_str(), calibrationFolder.c_str());
}
else
{
UINFO("Stereo parameters: fx=%f cx=%f cy=%f baseline=%f",
stereoModel_.left().fx(),
stereoModel_.left().cx(),
stereoModel_.left().cy(),
stereoModel_.baseline());
}
}
}
return ok;
}
#else
UERROR("CameraDC1394: RTAB-Map is not built with dc1394 support!");
#endif
return false;
}
bool CameraStereoDC1394::isCalibrated() const
{
return stereoModel_.isValidForProjection();
}
std::string CameraStereoDC1394::getSerial() const
{
#ifdef RTABMAP_DC1394
if(device_)
{
return device_->guid();
}
#endif
return "";
}
SensorData CameraStereoDC1394::captureImage()
{
SensorData data;
#ifdef RTABMAP_DC1394
if(device_)
{
cv::Mat left, right;
device_->getImages(left, right);
if(!left.empty() && !right.empty())
{
// Rectification
if(stereoModel_.left().isValidForRectification())
{
left = stereoModel_.left().rectifyImage(left);
}
if(stereoModel_.right().isValidForRectification())
{
right = stereoModel_.right().rectifyImage(right);
}
StereoCameraModel model;
if(stereoModel_.isValidForProjection())
{
model = StereoCameraModel(
stereoModel_.left().fx(), //fx
stereoModel_.left().fy(), //fy
stereoModel_.left().cx(), //cx
stereoModel_.left().cy(), //cy
stereoModel_.baseline(),
this->getLocalTransform(),
left.size());
}
data = SensorData(left, right, model, this->getNextSeqID(), UTimer::now());
}
}
#else
UERROR("CameraDC1394: RTAB-Map is not built with dc1394 support!");
#endif
return data;
}
//
// CameraTriclops
//
CameraStereoFlyCapture2::CameraStereoFlyCapture2(float imageRate, const Transform & localTransform) :
Camera(imageRate, localTransform),
camera_(0),
triclopsCtx_(0)
{
#ifdef RTABMAP_FLYCAPTURE2
camera_ = new FlyCapture2::Camera();
#endif
}
CameraStereoFlyCapture2::~CameraStereoFlyCapture2()
{
#ifdef RTABMAP_FLYCAPTURE2
// Close the camera
camera_->StopCapture();
camera_->Disconnect();
// Destroy the Triclops context
triclopsDestroyContext( triclopsCtx_ ) ;
delete camera_;
#endif
}
bool CameraStereoFlyCapture2::available()
{
#ifdef RTABMAP_FLYCAPTURE2
return true;
#else
return false;
#endif
}
bool CameraStereoFlyCapture2::init(const std::string & calibrationFolder, const std::string & cameraName)
{
#ifdef RTABMAP_FLYCAPTURE2
if(camera_)
{
// Close the camera
camera_->StopCapture();
camera_->Disconnect();
}
if(triclopsCtx_)
{
triclopsDestroyContext(triclopsCtx_);
triclopsCtx_ = 0;
}
// connect camera
FlyCapture2::Error fc2Error = camera_->Connect();
if(fc2Error != FlyCapture2::PGRERROR_OK)
{
UERROR("Failed to connect the camera.");
return false;
}
// configure camera
Fc2Triclops::StereoCameraMode mode = Fc2Triclops::TWO_CAMERA_NARROW;
if(Fc2Triclops::setStereoMode(*camera_, mode ))
{
UERROR("Failed to set stereo mode.");
return false;
}
// generate the Triclops context
FlyCapture2::CameraInfo camInfo;
if(camera_->GetCameraInfo(&camInfo) != FlyCapture2::PGRERROR_OK)
{
UERROR("Failed to get camera info.");
return false;
}
float dummy;
unsigned packetSz;
FlyCapture2::Format7ImageSettings imageSettings;
int maxWidth = 640;
int maxHeight = 480;
if(camera_->GetFormat7Configuration(&imageSettings, &packetSz, &dummy) == FlyCapture2::PGRERROR_OK)
{
maxHeight = imageSettings.height;
maxWidth = imageSettings.width;
}
// Get calibration from th camera
if(Fc2Triclops::getContextFromCamera(camInfo.serialNumber, &triclopsCtx_))
{
UERROR("Failed to get calibration from the camera.");
return false;
}
float fx, cx, cy, baseline;
triclopsGetFocalLength(triclopsCtx_, &fx);
triclopsGetImageCenter(triclopsCtx_, &cy, &cx);
triclopsGetBaseline(triclopsCtx_, &baseline);
UINFO("Stereo parameters: fx=%f cx=%f cy=%f baseline=%f", fx, cx, cy, baseline);
triclopsSetCameraConfiguration(triclopsCtx_, TriCfg_2CAM_HORIZONTAL_NARROW );
UASSERT(triclopsSetResolutionAndPrepare(triclopsCtx_, maxHeight, maxWidth, maxHeight, maxWidth) == Fc2Triclops::ERRORTYPE_OK);
if(camera_->StartCapture() != FlyCapture2::PGRERROR_OK)
{
UERROR("Failed to start capture.");
return false;
}
return true;
#else
UERROR("CameraStereoFlyCapture2: RTAB-Map is not built with Triclops support!");
#endif
return false;
}
bool CameraStereoFlyCapture2::isCalibrated() const
{
#ifdef RTABMAP_FLYCAPTURE2
if(triclopsCtx_)
{
float fx, cx, cy, baseline;
triclopsGetFocalLength(triclopsCtx_, &fx);
triclopsGetImageCenter(triclopsCtx_, &cy, &cx);
triclopsGetBaseline(triclopsCtx_, &baseline);
return fx > 0.0f && cx > 0.0f && cy > 0.0f && baseline > 0.0f;
}
#endif
return false;
}
std::string CameraStereoFlyCapture2::getSerial() const
{
#ifdef RTABMAP_FLYCAPTURE2
if(camera_ && camera_->IsConnected())
{
FlyCapture2::CameraInfo camInfo;
if(camera_->GetCameraInfo(&camInfo) == FlyCapture2::PGRERROR_OK)
{
return uNumber2Str(camInfo.serialNumber);
}
}
#endif
return "";
}
// struct containing image needed for processing
#ifdef RTABMAP_FLYCAPTURE2
struct ImageContainer
{
FlyCapture2::Image tmp[2];
FlyCapture2::Image unprocessed[2];
} ;
#endif
SensorData CameraStereoFlyCapture2::captureImage()
{
SensorData data;
#ifdef RTABMAP_FLYCAPTURE2
if(camera_ && triclopsCtx_ && camera_->IsConnected())
{
// grab image from camera.
// this image contains both right and left imagesCount
FlyCapture2::Image grabbedImage;
if(camera_->RetrieveBuffer(&grabbedImage) == FlyCapture2::PGRERROR_OK)
{
// right and left image extracted from grabbed image
ImageContainer imageCont;
// generate triclops input from grabbed image
FlyCapture2::Image imageRawRight;
FlyCapture2::Image imageRawLeft;
FlyCapture2::Image * unprocessedImage = imageCont.unprocessed;
// Convert the pixel interleaved raw data to de-interleaved and color processed data
if(Fc2Triclops::unpackUnprocessedRawOrMono16Image(
grabbedImage,
true /*assume little endian*/,
imageRawLeft /* right */,
imageRawRight /* left */) == Fc2Triclops::ERRORTYPE_OK)
{
// convert to color
FlyCapture2::Image srcImgRightRef(imageRawRight);
FlyCapture2::Image srcImgLeftRef(imageRawLeft);
bool ok = true;;
if ( srcImgRightRef.SetColorProcessing(FlyCapture2::HQ_LINEAR) != FlyCapture2::PGRERROR_OK ||
srcImgLeftRef.SetColorProcessing(FlyCapture2::HQ_LINEAR) != FlyCapture2::PGRERROR_OK)
{
ok = false;
}
if(ok)
{
FlyCapture2::Image imageColorRight;
FlyCapture2::Image imageColorLeft;
if ( srcImgRightRef.Convert(FlyCapture2::PIXEL_FORMAT_MONO8, &imageColorRight) != FlyCapture2::PGRERROR_OK ||
srcImgLeftRef.Convert(FlyCapture2::PIXEL_FORMAT_BGRU, &imageColorLeft) != FlyCapture2::PGRERROR_OK)
{
ok = false;
}
if(ok)
{
//RECTIFY RIGHT
TriclopsInput triclopsColorInputs;
triclopsBuildRGBTriclopsInput(
grabbedImage.GetCols(),
grabbedImage.GetRows(),
imageColorRight.GetStride(),
(unsigned long)grabbedImage.GetTimeStamp().seconds,
(unsigned long)grabbedImage.GetTimeStamp().microSeconds,
imageColorRight.GetData(),
imageColorRight.GetData(),
imageColorRight.GetData(),
&triclopsColorInputs);
triclopsRectify(triclopsCtx_, const_cast<TriclopsInput *>(&triclopsColorInputs) );
// Retrieve the rectified image from the triclops context
TriclopsImage rectifiedImage;
triclopsGetImage( triclopsCtx_,
TriImg_RECTIFIED,
TriCam_REFERENCE,
&rectifiedImage );
cv::Mat left,right;
right = cv::Mat(rectifiedImage.nrows, rectifiedImage.ncols, CV_8UC1, rectifiedImage.data).clone();
//RECTIFY LEFT COLOR
triclopsBuildPackedTriclopsInput(
grabbedImage.GetCols(),
grabbedImage.GetRows(),
imageColorLeft.GetStride(),
(unsigned long)grabbedImage.GetTimeStamp().seconds,
(unsigned long)grabbedImage.GetTimeStamp().microSeconds,
imageColorLeft.GetData(),
&triclopsColorInputs );
cv::Mat pixelsLeftBuffer( grabbedImage.GetRows(), grabbedImage.GetCols(), CV_8UC4);
TriclopsPackedColorImage colorImage;
triclopsSetPackedColorImageBuffer(
triclopsCtx_,
TriCam_LEFT,
(TriclopsPackedColorPixel*)pixelsLeftBuffer.data );
triclopsRectifyPackedColorImage(
triclopsCtx_,
TriCam_LEFT,
&triclopsColorInputs,
&colorImage );
cv::cvtColor(pixelsLeftBuffer, left, CV_RGBA2RGB);
// Set calibration stuff
float fx, cy, cx, baseline;
triclopsGetFocalLength(triclopsCtx_, &fx);
triclopsGetImageCenter(triclopsCtx_, &cy, &cx);
triclopsGetBaseline(triclopsCtx_, &baseline);
StereoCameraModel model(
fx,
fx,
cx,
cy,
baseline,
this->getLocalTransform(),
left.size());
data = SensorData(left, right, model, this->getNextSeqID(), UTimer::now());
}
}
}
}
}
#else
UERROR("CameraStereoFlyCapture2: RTAB-Map is not built with Triclops support!");
#endif
return data;
}
//
// CameraStereoImages
//
bool CameraStereoImages::available()
{
return true;
}
CameraStereoImages::CameraStereoImages(
const std::string & pathLeftImages,
const std::string & pathRightImages,
bool rectifyImages,
float imageRate,
const Transform & localTransform) :
CameraImages(pathLeftImages, imageRate, localTransform),
camera2_(new CameraImages(pathRightImages))
{
this->setImagesRectified(rectifyImages);
}
CameraStereoImages::CameraStereoImages(
const std::string & pathLeftRightImages,
bool rectifyImages,
float imageRate,
const Transform & localTransform) :
CameraImages("", imageRate, localTransform),
camera2_(0)
{
std::vector<std::string> paths = uListToVector(uSplit(pathLeftRightImages, uStrContains(pathLeftRightImages, ":")?':':';'));
if(paths.size() >= 1)
{
this->setPath(paths[0]);
this->setImagesRectified(rectifyImages);
if(paths.size() >= 2)
{
camera2_ = new CameraImages(paths[1]);
}
}
else
{
UERROR("The path is empty!");
}
}
CameraStereoImages::~CameraStereoImages()
{
UDEBUG("");
if(camera2_)
{
delete camera2_;
}
UDEBUG("");
}
bool CameraStereoImages::init(const std::string & calibrationFolder, const std::string & cameraName)
{
// look for calibration files
if(!calibrationFolder.empty() && !cameraName.empty())
{
if(!stereoModel_.load(calibrationFolder, cameraName))
{
UWARN("Missing calibration files for camera \"%s\" in \"%s\" folder, you should calibrate the camera!",
cameraName.c_str(), calibrationFolder.c_str());
}
else
{
UINFO("Stereo parameters: fx=%f cx=%f cy=%f baseline=%f",
stereoModel_.left().fx(),
stereoModel_.left().cx(),
stereoModel_.left().cy(),
stereoModel_.baseline());
}
}
stereoModel_.setLocalTransform(this->getLocalTransform());
stereoModel_.setName(cameraName);
if(this->isImagesRectified() && !stereoModel_.isValidForRectification())
{
UERROR("Parameter \"rectifyImages\" is set, but no stereo model is loaded or valid.");
return false;
}
//desactivate before init as we will do it in this class instead for convenience
bool rectify = this->isImagesRectified();
this->setImagesRectified(false);
bool success = false;
if(CameraImages::init())
{
if(camera2_)
{
camera2_->setBayerMode(this->getBayerMode());
if(camera2_->init())
{
if(this->imagesCount() == camera2_->imagesCount())
{
success = true;
}
else
{
UERROR("Cameras don't have the same number of images (%d vs %d)",
this->imagesCount(), camera2_->imagesCount());
}
}
else
{
UERROR("Cannot initialize the second camera.");
}
}
else
{
success = true;
}
}
this->setImagesRectified(rectify); // reset the flag
return success;
}
bool CameraStereoImages::isCalibrated() const
{
return stereoModel_.isValidForProjection();
}
std::string CameraStereoImages::getSerial() const
{
return stereoModel_.name();
}
SensorData CameraStereoImages::captureImage()
{
SensorData data;
SensorData left, right;
left = CameraImages::captureImage();
if(!left.imageRaw().empty())
{
if(camera2_)
{
right = camera2_->takeImage();
}
else
{
right = this->takeImage();
}
if(!right.imageRaw().empty())
{
// Rectification
cv::Mat leftImage = left.imageRaw();
cv::Mat rightImage = right.imageRaw();
if(rightImage.type() != CV_8UC1)
{
cv::Mat tmp;
cv::cvtColor(rightImage, tmp, CV_BGR2GRAY);
rightImage = tmp;
}
if(this->isImagesRectified() && stereoModel_.isValidForRectification())
{
leftImage = stereoModel_.left().rectifyImage(leftImage);
rightImage = stereoModel_.right().rectifyImage(rightImage);
}
if(stereoModel_.left().imageHeight() == 0 || stereoModel_.left().imageWidth() == 0)
{
stereoModel_.setImageSize(leftImage.size());
}
data = SensorData(left.laserScanRaw(), left.laserScanMaxPts(), 0, leftImage, rightImage, stereoModel_, left.id()/(camera2_?1:2), left.stamp());
data.setGroundTruth(left.groundTruth());
}
}
return data;
}
//
// CameraStereoVideo
//
bool CameraStereoVideo::available()
{
return true;
}
CameraStereoVideo::CameraStereoVideo(
const std::string & path,
bool rectifyImages,
float imageRate,
const Transform & localTransform) :
Camera(imageRate, localTransform),
path_(path),
rectifyImages_(rectifyImages)
{
}
CameraStereoVideo::~CameraStereoVideo()
{
capture_.release();
}
bool CameraStereoVideo::init(const std::string & calibrationFolder, const std::string & cameraName)
{
if(capture_.isOpened())
{
capture_.release();
}
ULOGGER_DEBUG("Camera: filename=\"%s\"", path_.c_str());
capture_.open(path_.c_str());
if(!capture_.isOpened())
{
ULOGGER_ERROR("Camera: Failed to create a capture object!");
capture_.release();
return false;
}
else
{
// look for calibration files
cameraName_ = cameraName;
if(!calibrationFolder.empty() && !cameraName.empty())
{
if(!stereoModel_.load(calibrationFolder, cameraName))
{
UWARN("Missing calibration files for camera \"%s\" in \"%s\" folder, you should calibrate the camera!",
cameraName.c_str(), calibrationFolder.c_str());
}
else
{
UINFO("Stereo parameters: fx=%f cx=%f cy=%f baseline=%f",
stereoModel_.left().fx(),
stereoModel_.left().cx(),
stereoModel_.left().cy(),
stereoModel_.baseline());
}
}
stereoModel_.setLocalTransform(this->getLocalTransform());
if(rectifyImages_ && !stereoModel_.isValidForRectification())
{
UERROR("Parameter \"rectifyImages\" is set, but no stereo model is loaded or valid.");
return false;
}
}
return true;
}
bool CameraStereoVideo::isCalibrated() const
{
return stereoModel_.isValidForProjection();
}
std::string CameraStereoVideo::getSerial() const
{
return cameraName_;
}
SensorData CameraStereoVideo::captureImage()
{
SensorData data;
cv::Mat img;
if(capture_.isOpened())
{
if(capture_.read(img))
{
// Rectification
cv::Mat leftImage(img, cv::Rect( 0, 0, img.size().width/2, img.size().height ));
cv::Mat rightImage(img, cv::Rect( img.size().width/2, 0, img.size().width/2, img.size().height ));
bool rightCvt = false;
if(rightImage.type() != CV_8UC1)
{
cv::Mat tmp;
cv::cvtColor(rightImage, tmp, CV_BGR2GRAY);
rightImage = tmp;
rightCvt = true;
}
if(rectifyImages_ && stereoModel_.left().isValidForRectification() && stereoModel_.right().isValidForRectification())
{
leftImage = stereoModel_.left().rectifyImage(leftImage);
rightImage = stereoModel_.right().rectifyImage(rightImage);
}
else
{
leftImage = leftImage.clone();
if(!rightCvt)
{
rightImage = rightImage.clone();
}
}
if(stereoModel_.left().imageHeight() == 0 || stereoModel_.left().imageWidth() == 0)
{
stereoModel_.setImageSize(leftImage.size());
}
data = SensorData(leftImage, rightImage, stereoModel_, this->getNextSeqID(), UTimer::now());
}
}
else
{
ULOGGER_WARN("The camera must be initialized before requesting an image.");
}
return data;
}
} // namespace rtabmap
|
. In an investigation of correlation and factor analysis the relations between cell-mediated stromalreactions and immunological parameters are checked in 63 patients with malignant tumours. The stromalreaction is determined semi-quantitatively as a cell-mediated infiltration of the tumour by neutrophiles, lymphocytes, plasma cells and macrophages. In regard to immunological parameters circulating immuncomplexes, K-cell-activity, auto-antibodies, B- and T-cells and immunglobulins are determined among others. It is shown that the stromalreaction is to be regarded as a part of an immunological answer of the organism against the tumour.
|
<filename>src/types/capsules.ts
export interface ICapsule {
reuse_count: number
water_landings: number
land_landings: number
last_update: string
launches: string[]
serial: string
status: string
type: string
id: string
}
|
Influence of converting-enzyme inhibition on rat des-angiotensin I-angiotensinogen. The effects of high plasma renin levels on plasma levels of both total immunoreactive angiotensinogen (direct radioimmunoassay) and intact angiotensinogen measured by angiotensin I released by renin (indirect assay) were studied in sodium-depleted rats both with and without captopril treatment and in adrenalectomized rats. The direct assay measures both intact angiotensinogen and des-angiotensin I-angiotensinogen, its residue cleaved by renin. The indirect assay measures only intact angiotensinogen. Neither sodium depletion, captopril treatment, nor adrenalectomy modified the circulating levels of total angiotensinogen. However these treatments produced a decrease in intact angiotensinogen that was in proportion to the elevation of renin levels. The difference between the two assays for angiotensin represents the level of des-angiotensin I-angiotensinogen and correlated satisfactorily with the plasma levels of renin. Identical correlations were observed in adrenalectomized rats and captopril-treated rats. We conclude that des-angiotensin I-angiotensinogen levels are an index of activation of the renin-angiotensin system dependent on the circulating level of renin.
|
There’s just something wonderful about seeing these cars do what they were MEANT to do. A car is a tool, or at the very least, a toy. It’s not a decoration. We want to see them drive!
|
// Disable sets the disabled flag on the given replication controller, instructing
// any running farm instances to cease handling it.
func (s *ConsulStore) Disable(id fields.ID) error {
return s.retryMutate(id, func(rc fields.RC) (fields.RC, error) {
rc.Disabled = true
return rc, nil
})
}
|
// Checks if the lodestone is in the right dimension
private static boolean isSameDimension(ItemStack stack, PlayerEntity mob) {
@Nullable String lodeDim = getLodestoneDimension(stack);
String mobDim = mob.world.getRegistryKey().getValue().toString();
return lodeDim != null && lodeDim.equals(mobDim);
}
|
// New returns a new web driver REST Client instance.
func New(s *Session) (*Client, error) {
if s == nil {
return nil, errors.New("session is empty")
}
if s.URL == "" {
return nil, errors.New("URL is empty")
}
s.URL = strings.TrimSuffix(s.URL, "/") + "/"
httpc := http.DefaultClient
u, err := url.Parse(s.URL)
if err != nil {
return nil, err
}
c := &Client{
session: s,
client: httpc,
url: u,
}
return c, nil
}
|
District Practices Associated With Successful SWPBIS Implementation Schoolwide positive behavior interventions and supports (SWPBIS) is a widely implemented model for systematically supporting the social and behavioral development of students with and without disabilities, including those with and at risk for emotional and behavioral disorders. Identifying district factors associated with SWPBIS implementation fidelity and improved student outcomes can assist district personnel with appropriate allocation of resources, including professional development and school-based implementation support. Due to the limited empirical support for district-level factors that influence school practices and student outcomes, this exploratory study was conducted with the goal of identifying characteristics associated with school districts that have a high proportion of schools implementing SWPBIS with fidelity and sustained positive student discipline outcomes. Six high-implementing districts were identified, and semi-structured interviews with district staff were then conducted to identify common features staff attributed to their districts positive outcomes. Analysis of those interviews revealed eight themes including District Coordinator, Coaches, District Teaming, Internal Implementation Drivers, Leadership Buy-In and Support, District Data Infrastructure, Direct Support to Schools, and Communication. Limitations and implications are discussed.
|
Clarifying the Developmental Perspective in Response to Carta, Schwartz, Atwater, and McConnell A reaction to Carta, Schwartz, Atwater, and McConnell is given to shed light on the meaning of developmentally appropriate practice (DAP) for early childhood education (ECE) and for early childhood special education (ECSE). Evidence is offered that nondirective instructional models are indeed beneficial in early childhood and that, moreover, they are effective and workable with special needs children. DAP is viewed as a working hypothesis and as a continuous variable, not as a dichotomous variable. Areas of needed work are suggested to further identify and articulate the relationships between the two sister disciplines of ECE and ECSE.
|
<gh_stars>0
package ex01우선정리부터.ex0105조건문NPE회피;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.StandardOpenOption;
import java.time.LocalDate;
import java.util.Collections;
/**
* 1.5 조건문에서 NullPointerException 피하기
* @author jkoogi
* 1. null 우선체크, isEmpty 사용
* 2. 매개변수 검증 - 파라미터 순서에 따라 체크(체크누락 예방)
*
* * 매개변수 검사는 public, protected, default 접근자의 메서드를 대상으로 구현
* - private는 호출부에서 통제 가능
*/
public class Logbook {
// 1. null 체크순서 확인
// 2. 매개변수 검증 필요 - 파라미터 순서에 따라 체크(체크누락 예방)
void writeMessage(String message, Path location) throws IOException, IllegalAccessException{
/* 대상소스 */
// if(Files.isDirectory(location)) {
// throw new IllegalAccessException("The path is invalid!");
// }
// if(message.trim().equals("") || message == null) {
// throw new IllegalAccessException("The message is invalid!");
// }
/* 개선소스 */
// 1. null 체크 우선, isEmpty 사용
if(message == null || message.trim().isEmpty()) {
throw new IllegalAccessException("The message is invalid!");
}
// 2. 매개변수 순서에 맞게 파라미터 검증 - 체크누락 방지
if(location == null || Files.isDirectory(location)) {
throw new IllegalAccessException("The path is invalid!");
}
String entry = LocalDate.now() + ":" +message;
Files.write(location, Collections.singleton(entry),
StandardCharsets.UTF_8, StandardOpenOption.CREATE,
StandardOpenOption.APPEND);
}
}
|
Phosphoinositide phosphatases: emerging roles as voltage sensors? During a genomic survey of the transparent sea squirt (Ciona intestinalis), Murata et al. discovered a gene that encodes a protein containing homologous sequences to both a CXR phosphatase and an ion channel. The authors named the novel protein, C. intestinalis voltage-sensor-containing phosphatase, Ci-VSP. The N terminus of Ci-VSP appears to function as a voltage-gated sensor; the C terminus functions as a phosphoinositide phosphatase. The authors suggest that when the N-terminal voltage sensor is activated, this in turn activates the phosphatase, which converts PIP to PIP. Localized changes in membrane PIP levels could then serve to either positively or negatively regulate a variety of ion transporters and channels.
|
Source Term Derivation and Radioactive Release Evaluation for JRTR Research Reactor under Severe Accident )e source term for the JRTR research reactor is derived under an assumed hypothetical severe accident resulting in generation of the most severe consequences. )e reactor core is modeled based on the reactor technical design specifications, and the fission products inventory is calculated by using the SCALE/TRITON depletion sequence to perform burnup and decay analyses via coupling the NEWT 2-D transport lattice code to the ORIGEN-S fuel depletion code. Fifty radioisotopes contributed to the evaluation, resulting in a source term of 3.710 Bq. Atmospheric dispersion was evaluated using the Gaussian plume model via the HOTSPOT code. )e plume centerline total effective dose (TED) was found to exceed the IAEA limits for occupational exposure of 0.02 Sv; the results showed that the maximum dose is 200 Sv within 200m from the reactor, under all the weather stability classes, after which it starts to decrease with distance, reaching 0.1 Sv at 1 km from the reactor. )e radiation dose plume centerlines continue to the exceed international basic safety standards annual limit of 1mSv for public exposure, up to 80 km from the reactor. Introduction e utilization of research reactors in a variety of scientific, production, and training applications requires unique design characteristics and operational modes, consequently exerting additional burden on their safety systems and procedures. Although, in comparison to power reactors, research reactors are small and contain smaller inventory of fuel and radionuclides, they have a higher number of reported accidents. e lack of containment building, proximity to densely populated areas, and high burnup cores, coupled with life extension, have raised worldwide interest for indepth safety evaluation of these systems. In 2008, the international atomic energy agency (IAEA) published a research reactor safety report. It aims to provide safety analysts, regulators, and reactor operation staff and management, with the essential calculation methods and techniques for evaluating the source term and analyzing the radiological consequences of accidents in research reactor. e magnitude, composition, form, and mode of release of radioactive elements released during a reactor accident define the source term. e derivation of the source term is an essential step of the safety analysis. One approach commonly used in research reactors safety analyses is to assume a hypothetical accident that results in generating the most severe consequences ; this is the subject of this paper. Recently, several studies for the evaluation of research reactors source term have been conducted. Foudil et al. have estimated the source term and doses for the NUR research reactor under a hypothetical severe accident. Muswema et al. carried out a study to drive the source term and analyze the radiological safety for the TRICOII research reactor in Kinshasa. Charalampos et al. published a study about source term derivation and radiological consequences for the Greek Research Reactor. Birikorang et al. have estimated the source term and ground deposition of radionuclides following a hypothetical release from Ghana Research Reactor. Sadeghi. In this work, the JRTR research and training reactor core inventory is calculated using the SCALE/TRITON depletion sequence to perform burnup and decay analyses via coupling the NEWT 2-D transport lattice code to the ORIGEN-S fuel depletion code. e corresponding source term and the release of radionuclides during postulated severe accident are estimated in accordance with the IAEA recommendation and the US-NRC regulatory guide 1.183. e atmospheric dispersion of radionuclide concentrations are simulated based on the Gaussian Plume Model (GPM) using the HOTSPOT code. Reactor Description e JRTR is a multipurpose research reactor optimized for research, training, and isotope production. It is light water moderated and cooled open-tank-in-pool type reactor with nominal power of 5 MW upgradable to 10 MW. e reactor core (shown in Figure 1) consists of 18 MTR plate type fuel assemblies loaded in a 33 squares grid matrix, the remaining 15 grid positions are loaded with beryllium blocks serving as internal reflector, and the grid central position is designated as a flux trap experimental facility. Heavy water reflectors are placed at the four corners of the core. e fuel assemblies and beryllium blocks are interchangeable and can be shuffled to reconfigure the reactor core. e core is designed to produce the utmost thermal fluxes at the core's internal and external irradiation facilities. e maximum in-core thermal-flux-to-power ratio is 2.9 10 13 cm −2 s −1 per MW, producing a maximum thermal flux of 1.45 10 14 cm −2 s −1, at full power. e maximum external thermal flux to power ratio is 1.4 10 13 cm −2 s −1 per MW producing a maximum thermal flux of 6.78 10 13 cm −2 s −1 at full power. Forced convection cooling is used to cool the reactor under normal operating conditions. e coolant flows downward at a rate of 170 kg/s, with an inlet temperature of around 37°C and exits the core with an outlet temperature of 44.2°C. e average heat flux is 17.3 W/cm 2, with a maximum of 51.9 W/cm 2, and the power peaking factor is 2.54. e main design characteristics of the JRTR reactor are listed in Table 1. Fuel Assembly. e fuel is MTR plate type, uranium silicide (U 3 Si 2 ) enriched to 19.75% 235 U and in aluminum clad. e core loading is 18 standard fuel assemblies containing approximately 7.0 kg of 235 U, as shown in Figure 1. Each assembly has 21 plates with a thickness of 1.27 mm and are placed 2.35 mm a part, allowing cooling water to flow between them as shown in Figure 2. e fuel material is 19.75 wt% enriched uranium silicide (U 3 Si 2 ) in aluminum matrix sandwiched between two 0.38 mm thick aluminum plates, 680.0 mm long, and 70.7 mm wide. e fuel meat covers an area of 640 6.21 mm in each plate with a density of 6.543 g/cm 3. Fuel assembly contains 97.2939 g of uranium in each plate, with uranium density of 4.8 g/cm 3. e fuel technical specifications and material data are listed in Table 2. Operating Cycle. e life cycle length of the JRTR is 50 days of full power operation, with an average discharge burnup of 900 effective full power days (EFPD). Fuel reloading consists of adding one new assembly into the F17 position and discharging one assembly from position F09. All of the fuel assemblies are shuffled, such that each assembly is placed in one new position every cycle, covering all 18 positions in the core before being discharged. us, at the end of cycle, the core will have assemblies that are burned from one cycle to 18 cycles. Fuel reloading is assumed to take 5 days, during which the reactor is shutdown. Materials and Methods In this study, the core inventory is calculated using the SCALE/TRITON depletion sequence to perform burnup and decay analyses via coupling the NEWT 2-D transport lattice code to the ORIGEN-S fuel depletion code. e TRITON depletion sequences use the 2-D arbitrary polygonal mesh discrete ordinates transport code NEWT to calculate the flux distribution in the assembly. In the T-DEPL calculation sequence, the cross section processing and neutron transport solution of the NEWT sequence is used to create three-group weighted cross sections based on calculated volume averaged fluxes for each material. ese newly weighted cross sections are used to update the ORIGEN-S cross section library via the COUPLE code. e NEWT calculated three-group averaged fluxes for each material and they are used for depletion calculations in the ORIGEN-S code. e three-neutron energy groups are the thermal group below 0.625 eV, the resonance group 0.625 eV to 1 MeV, and the fast group above 1 MeV. T-DEPL uses a rigorous iterative procedure to update both fluxes and cross sections as a function of burnup. First, transport calculations are performed to estimate fluxes and prepare weighted cross-sections and other lattice physics parameters. Second, depletion calculations are performed using COUPLE and ORIGEN-S codes to update the nuclide concentrations. At each interval, ORIGEN-S updated nuclide concentrations are input into the assembly lattice transport analysis, and the neutron flux spectrum is recalculated. Cross sections are again updated and used by ORIGEN-S for the following computational step. Assembly Modeling. e TRITON 2-D model was developed for the fuel assembly based on its technical design data provided in Table 2. e geometrical dimensions and material compositions of the fuel, clad, and moderator were explicitly modeled, as illustrated in Figure 2. Reactor design operational and power data of 50 effective full power days, refueling cycle, and 5 days shutdown established the burnup step in the model. Burnup calculations were performed using burnup steps of 135.95 MW/ MTU, with one additional small step at the beginning of the cycle (BOC) to generate cross sections for effectively unirradiated fuel. e moderator/coolant temperature of 317 K was used as the average water temperature and 325 K as the fuel temperature. e moderator density of water from steam tables at 317 K and 1.4 bars is 0.990 g/cm 3. Core Modeling. Aimed at modeling a realistic worst case scenario, the core is modeled at the end of cycle (EOC) for a fully burned up core. As shown in Figure 3, each assembly has been burned for a different number of cycles, and thus it will have a different radionuclide inventory. In each cycle, it is assumed that all assemblies will contribute equally to the reactor power, which results in assembly F09 discharge burnup of 122.36 MWd/kg. e fuel burnup in MWd/kg for each assembly is shown in Figure 3. Selected Hypothetical Accident Scenario. e research reactor accident scenario, that is, the accident initiating event and its sequence determine both the magnitude and the nature of radioactive release, and thus the characteristic progressions of different scenarios generally lead to different radioactive release patterns. In this approach, a comprehensive assessment of accident progression for several accident scenarios is performed to calculate several different source terms. Another approach that is commonly used in performing the safety analyses of research reactors, and adopted in this paper, is to assume a hypothetical severe accident that results in a limiting source term. e accident scenario considered in this study assumes that one or more projectiles target the reactor, leading to the destruction the reactor building and pool, resulting in the uncovering of the core and damaging all of the fuel assemblies. Not all the fission products that are released from the damaged fuel assemblies transfer to the atmosphere of the reactor building. e atmospheric release fractions assumed in this study are 1.0 for noble gases, 0.4 for halogens, 0.3 for alkali metals, 0.02 for alkaline earths, 0.05 for tellurium, and 0.0025 for noble metals. Site-Specific Conditions. e JRTR is located in Jordan University of Science and Technology campus, home to more than 20,000 students. e city of Ramtha is approximately 7 km away, with a population of 170,000 people, and approximately two million people reside in Irbid metropolitan located about 15 km from the site. e site has a Mediterranean climate with four seasons. e summer average temperatures range from 27°C to 33°C and drops to an average of 10°C in the winter. e average annual rainfall is 300 mm, spreading over 77 rainy days. e prevailing average hourly wind direction in the JRTR site varies throughout the year. However, for about 11 months of the year, it is most often from the west and it switches to the eastern direction from November 12 to December 20. e average hourly wind speed experiences mild seasonal variation over the year, with a speed of more than 3.2 m/s from November 14 to May 2 and 2.8 m/s for the rest of the year. e frequency of wind speed and direction are shown in Figure 4. e wind rose diagram for Ramtha shows the annual number of hours the wind blows from the indicated direction. e atmospheric stability classes are estimated using a number of meteorological measurements such as weather condition, solar insulation, humidity, and wind speed and are classified from A (very unstable) to F (moderately stable). Core Inventory. e core fission product inventory calculations have been performed using the SCALE/TRI-TON depletion sequence, based on reactor maximum full power operation. e activity of 200 fission products has been tracked, consequently accounting for the maximum possible activity in the core. e reactor core radionuclide inventory available for release to the environment is classified into eight groups, based on the NRC regulatory guide 1.183 and is shown in Figure 5 e complete list of the fission products inventory and the their release fractions is included in Supplementary appendix 1. Source Term. Fifty radioisotopes are selected for the source term evaluation, based on their yield, half-life, and radiotoxicity due to both inhalation and ingestion. e activity released in the form of noble gases and other aerosols is presented in Table 3, assuming the core remains exposed and all fission products are released to the atmosphere. Noble gases which can be considered inert and have very low chemical reactivity are the major contributors to the source term, accounting for 62.7% of the released activity, as illustrated in Figure 6. e highest release of noble gases is 133 Xe with an activity of 9.91 10 15 Becquerel (Bq); this is followed closely by 138 Xe and 137 Xe with an activity of 9.61 10 15 and 9.53 10 15 Bq, followed by the rest of the xenon radioisotopes. Six krypton isotopes contribute 1.79 10 16 Bq to the noble gas release, with the largest contribution of 6.44 10 15 Bq from 89 Kr. e second major contributor to the source term is the halogen group consisting of six iodine isotopes in addition to 84 Br. e group contributes 22% of the source term released activity, mainly from iodine with 1.76 10 16 Bq. Indeed, the radioisotopes of krypton, xenon, and iodine contribute a total of 6.94 10 16 Bq accounting for 84% of the source term. Cesium and rubidium which comprise the alkali metal group are the next main contributors with a total activity of 9.80 10 15 Bq accounting for approximately 12% of the source term. e radioisotopes of the remaining four groups, alkaline earths, tellurium group, noble metals, and cerium group, account for approximately 4% of the released activity, as shown in Figure 6. Atmospheric Dispersion and Dose Calculation Atmospheric dispersion of 50 selected radionuclides has been evaluated using the Gaussian plume model (GPM) via the HOTSPOT 3.1.0 code. e radiation dose was calculated using FGR 13 library and the ICRP-recommended absorption types. Site-specific e results of the total effective dose (TED) as a function of distance from the reactor are illustrated in Figure 7, which shows that the radiation dose may reach people up to 80 km from the reactor, under neutrally stable (D) weather conditions. Under very unstable (A) weather conditions, the dose will be received by people within 10 km from the reactor. e maximum dose is about 200 Sv for most weather stability classes (A-D), and it extends from 15 m to 100 m from the reactor. For people within 300 m of the reactor, the TED dose is above 1 Sv, which is higher than the IAEA limits for occupational exposure of 0.02 Sv per year for radiation workers. Radiation doses exceeding international basic safety standards annual limit of 1 mSv for public exposure extend up to 80 km as shown in Figure 7, depending on the distance from the reactor and the weather stability class. e results of plume centerline ground deposition are depicted in Figure 8, which shows that the maximum ground deposition is between 9 and 10 8 kBq/m 2 and falls within 300 meters from the reactor depending on the weather stability class. Contaminant spreads to 100 km depositing more than 1000 kBq/m 2 for all stability classes. Science and Technology of Nuclear Installations 7 Conclusions In order to drive the source term, the JRTR reactor was modeled in the SCALE/TRITON code based on its design technical specifications. Burnup and decay analyses for a fully burned-up core using NEWT transport lattice and ORIGEN-S fuel depletion code were performed to calculate the core radionuclides inventory available for release to the environment. A hypothetical accident scenario assuming that all of the fuel assemblies are damaged and the reactor building is destroyed is selected. e fraction of fission products released to the atmosphere of the reactor building is calculated in accordance with the IAEA recommendation, resulting in the release 191 radioisotopes. Fifty radioisotopes are selected based on their yield, half-life, and radiotoxicity, to evaluate the source term, resulting in an activity of 3.7 10 14 Bq. Although the reactor core radionuclide inventory available for release to the environment comprises of 191 radioisotopes, it was found that krypton, xenon, and iodine account for 84% of the source term. Noble gases, halogens, and alkali metal groups consisting of 27 radioisotopes are the vast contributors to the source term, accounting for more than 96% of the released activity. e Gaussian Plume Model (GPM) via the HOTSPOT code is used to simulate the atmospheric dispersion of radionuclide concentrations. e results show the contaminants spread to 100 km depositing more than 1000 kBq/m 2. Communities as far as 80 km could be exposed to radiation doses higher than the international basic safety standard annual limit of 1 mSv for public exposure. Radiation workers in the vicinity of the reactor could be exposed to 50 times the recommended IAEA limits for occupational exposure of 0.02 Sv per year. Data Availability e data used to support the findings of this study are included within the article. e dataset for the reactor core inventory of 200 radionuclides and their release fraction (Appendix 1) has been deposited in the Mendeley repository (https://doi.org/10.17632/bcy9kg4g7h.1).
|
// +build integration
package importcmd_test
import (
"github.com/olli-ai/jx/v2/pkg/cmd/importcmd"
"github.com/olli-ai/jx/v2/pkg/cmd/testhelpers"
"github.com/olli-ai/jx/v2/pkg/kube/naming"
"io/ioutil"
"os"
"path"
"path/filepath"
"strings"
"testing"
"github.com/stretchr/testify/require"
"k8s.io/apimachinery/pkg/runtime"
v1 "github.com/jenkins-x/jx-api/pkg/apis/jenkins.io/v1"
"github.com/jenkins-x/jx-logging/pkg/log"
fake_clients "github.com/olli-ai/jx/v2/pkg/cmd/clients/fake"
"github.com/olli-ai/jx/v2/pkg/jenkinsfile"
resources_test "github.com/olli-ai/jx/v2/pkg/kube/resources/mocks"
"github.com/olli-ai/jx/v2/pkg/auth"
"github.com/olli-ai/jx/v2/pkg/cmd/opts"
"github.com/olli-ai/jx/v2/pkg/gits"
"github.com/olli-ai/jx/v2/pkg/helm"
"github.com/olli-ai/jx/v2/pkg/tests"
"github.com/olli-ai/jx/v2/pkg/util"
"github.com/stretchr/testify/assert"
)
const (
gitSuffix = "_with_git"
mavenKeepOldJenkinsfile = "maven_keep_old_jenkinsfile"
mavenOldJenkinsfile = "maven_old_jenkinsfile"
mavenCamel = "maven_camel"
mavenSpringBoot = "maven_springboot"
probePrefix = "probePath:"
)
func TestImportProjects(t *testing.T) {
originalJxHome, tempJxHome, err := testhelpers.CreateTestJxHomeDir()
assert.NoError(t, err)
defer func() {
err := testhelpers.CleanupTestJxHomeDir(originalJxHome, tempJxHome)
assert.NoError(t, err)
}()
originalKubeCfg, tempKubeCfg, err := testhelpers.CreateTestKubeConfigDir()
assert.NoError(t, err)
defer func() {
err := testhelpers.CleanupTestKubeConfigDir(originalKubeCfg, tempKubeCfg)
assert.NoError(t, err)
}()
tempDir, err := ioutil.TempDir("", "test-import-projects")
assert.NoError(t, err)
testData := path.Join("test_data", "import_projects")
_, err = os.Stat(testData)
assert.NoError(t, err)
files, err := ioutil.ReadDir(testData)
assert.NoError(t, err)
for _, f := range files {
if f.IsDir() {
name := f.Name()
srcDir := filepath.Join(testData, name)
testImportProject(t, tempDir, name, srcDir, false, false)
testImportProject(t, tempDir, name, srcDir, true, false)
}
}
}
func TestImportProjectNextGenPipeline(t *testing.T) {
originalJxHome, tempJxHome, err := testhelpers.CreateTestJxHomeDir()
assert.NoError(t, err)
defer func() {
err := testhelpers.CleanupTestJxHomeDir(originalJxHome, tempJxHome)
assert.NoError(t, err)
}()
originalKubeCfg, tempKubeCfg, err := testhelpers.CreateTestKubeConfigDir()
assert.NoError(t, err)
defer func() {
err := testhelpers.CleanupTestKubeConfigDir(originalKubeCfg, tempKubeCfg)
assert.NoError(t, err)
}()
tempDir, err := ioutil.TempDir("", "test-import-ng-projects")
assert.NoError(t, err)
testData := path.Join("test_data", "import_projects")
_, err = os.Stat(testData)
assert.NoError(t, err)
files, err := ioutil.ReadDir(testData)
assert.NoError(t, err)
for _, f := range files {
if f.IsDir() {
name := f.Name()
if strings.HasPrefix(name, "maven_keep_old_jenkinsfile") {
continue
}
srcDir := filepath.Join(testData, name)
testImportProject(t, tempDir, name, srcDir, false, true)
}
}
}
func testImportProject(t *testing.T, tempDir string, testcase string, srcDir string, withRename bool, nextGenPipeline bool) {
testDirSuffix := "DefaultJenkinsfile"
if withRename {
testDirSuffix = "RenamedJenkinsfile"
}
testDir := filepath.Join(tempDir+"-"+testDirSuffix, testcase)
util.CopyDir(srcDir, testDir, true)
if strings.HasSuffix(testcase, gitSuffix) {
gitDir := filepath.Join(testDir, ".gitdir")
dotGitExists, gitErr := util.FileExists(gitDir)
if gitErr != nil {
log.Logger().Warnf("Git source directory %s does not exist: %s", gitDir, gitErr)
} else if dotGitExists {
dotGitDir := filepath.Join(testDir, ".git")
util.RenameDir(gitDir, dotGitDir, true)
}
}
err := assertImport(t, testDir, testcase, withRename, nextGenPipeline)
assert.NoError(t, err, "Importing dir %s from source %s", testDir, srcDir)
}
func createFakeGitProvider() *gits.FakeProvider {
testOrgName := "jstrachan"
testRepoName := "myrepo"
stagingRepoName := "environment-staging"
prodRepoName := "environment-production"
fakeRepo, _ := gits.NewFakeRepository(testOrgName, testRepoName, nil, nil)
stagingRepo, _ := gits.NewFakeRepository(testOrgName, stagingRepoName, nil, nil)
prodRepo, _ := gits.NewFakeRepository(testOrgName, prodRepoName, nil, nil)
fakeGitProvider := gits.NewFakeProvider(fakeRepo, stagingRepo, prodRepo)
userAuth := auth.UserAuth{
Username: "jx-testing-user",
ApiToken: "<PASSWORD>apito<PASSWORD>",
BearerToken: "<PASSWORD>",
Password: "password",
}
authServer := auth.AuthServer{
Users: []*auth.UserAuth{&userAuth},
CurrentUser: userAuth.Username,
URL: "https://github.com",
Kind: gits.KindGitHub,
Name: "jx-testing-server",
}
fakeGitProvider.Server = authServer
return fakeGitProvider
}
func assertImport(t *testing.T, testDir string, testcase string, withRename bool, nextGenPipeline bool) error {
_, dirName := filepath.Split(testDir)
dirName = naming.ToValidName(dirName)
o := &importcmd.ImportOptions{
CommonOptions: &opts.CommonOptions{},
}
o.SetFactory(fake_clients.NewFakeFactory())
o.GitProvider = createFakeGitProvider()
k8sObjects := []runtime.Object{}
jxObjects := []runtime.Object{}
helmer := helm.NewHelmCLI("helm", helm.V2, dirName, true)
testhelpers.ConfigureTestOptionsWithResources(o.CommonOptions, k8sObjects, jxObjects, gits.NewGitCLI(), nil, helmer, resources_test.NewMockInstaller())
if o.Out == nil {
o.Out = tests.Output()
}
if o.Out == nil {
o.Out = os.Stdout
}
o.Dir = testDir
o.DryRun = true
o.DisableMaven = true
o.UseDefaultGit = true
if dirName == "maven-camel" {
o.DeployKind = opts.DeployKindKnative
}
if nextGenPipeline {
callback := func(env *v1.Environment) error {
env.Spec.TeamSettings.ImportMode = v1.ImportModeTypeYAML
return nil
}
err := o.ModifyDevEnvironment(callback)
require.NoError(t, err, "failed to modify Dev Environment")
}
if withRename {
o.Jenkinsfile = "Jenkinsfile-Renamed"
}
if strings.HasPrefix(testcase, mavenKeepOldJenkinsfile) {
o.DisableJenkinsfileCheck = true
}
if testcase == mavenCamel || dirName == mavenSpringBoot {
o.DisableMaven = tests.TestShouldDisableMaven()
}
err := o.Run()
require.NoError(t, err, "Failed %s with %s", dirName, err)
if err == nil {
defaultJenkinsfileName := jenkinsfile.Name
defaultJenkinsfileBackupSuffix := jenkinsfile.BackupSuffix
defaultJenkinsfile := filepath.Join(testDir, defaultJenkinsfileName)
jfname := defaultJenkinsfile
if o.Jenkinsfile != "" && o.Jenkinsfile != defaultJenkinsfileName {
jfname = filepath.Join(testDir, o.Jenkinsfile)
}
if dirName == "custom-jenkins" {
tests.AssertFileExists(t, filepath.Join(testDir, jenkinsfile.Name))
tests.AssertFileDoesNotExist(t, filepath.Join(testDir, jenkinsfile.Name+".backup"))
tests.AssertFileDoesNotExist(t, filepath.Join(testDir, jenkinsfile.Name+"-Renamed"))
} else if nextGenPipeline {
tests.AssertFileDoesNotExist(t, jfname)
} else {
tests.AssertFileExists(t, jfname)
}
if dirName == "docker" || dirName == "docker-helm" {
tests.AssertFileExists(t, filepath.Join(testDir, "skaffold.yaml"))
} else if dirName == "helm" || dirName == "custom-jenkins" {
tests.AssertFileDoesNotExist(t, filepath.Join(testDir, "skaffold.yaml"))
}
if dirName == "helm" || dirName == "custom-jenkins" {
tests.AssertFileDoesNotExist(t, filepath.Join(testDir, "Dockerfile"))
} else {
tests.AssertFileExists(t, filepath.Join(testDir, "Dockerfile"))
}
if dirName == "docker" || dirName == "custom-jenkins" {
tests.AssertFileDoesNotExist(t, filepath.Join(testDir, "charts", dirName, "Chart.yaml"))
tests.AssertFileDoesNotExist(t, filepath.Join(testDir, "charts"))
if !nextGenPipeline && dirName != "custom-jenkins" {
tests.AssertFileDoesNotContain(t, jfname, "helm")
}
} else {
tests.AssertFileExists(t, filepath.Join(testDir, "charts", dirName, "Chart.yaml"))
}
// lets test we modified the deployment kind
if dirName == "maven-camel" {
tests.AssertFileContains(t, filepath.Join(testDir, "charts", "maven-camel", "values.yaml"), "knativeDeploy: true")
}
if !nextGenPipeline {
if strings.HasPrefix(testcase, mavenKeepOldJenkinsfile) {
tests.AssertFileContains(t, jfname, "THIS IS OLD!")
tests.AssertFileDoesNotExist(t, jfname+defaultJenkinsfileBackupSuffix)
} else if strings.HasPrefix(testcase, mavenOldJenkinsfile) {
tests.AssertFileExists(t, jfname)
if withRename {
tests.AssertFileExists(t, defaultJenkinsfile)
tests.AssertFileContains(t, defaultJenkinsfile, "THIS IS OLD!")
} else {
tests.AssertFileExists(t, jfname+defaultJenkinsfileBackupSuffix)
tests.AssertFileContains(t, jfname+defaultJenkinsfileBackupSuffix, "THIS IS OLD!")
}
}
if strings.HasPrefix(dirName, "maven") && !strings.Contains(testcase, "keep_old") {
tests.AssertFileContains(t, jfname, "mvn")
}
if strings.HasPrefix(dirName, "gradle") {
tests.AssertFileContains(t, jfname, "gradle")
}
}
if !o.DisableMaven {
if testcase == mavenCamel {
// should have modified it
assertProbePathEquals(t, filepath.Join(testDir, "charts", dirName, "values.yaml"), "/health")
}
if testcase == mavenSpringBoot {
// should have left it
assertProbePathEquals(t, filepath.Join(testDir, "charts", dirName, "values.yaml"), "/actuator/health")
}
}
}
return err
}
func assertProbePathEquals(t *testing.T, fileName string, expectedProbe string) {
if tests.AssertFileExists(t, fileName) {
data, err := ioutil.ReadFile(fileName)
assert.NoError(t, err, "Failed to read file %s", fileName)
if err == nil {
text := string(data)
found := false
lines := strings.Split(text, "\n")
for _, line := range lines {
if strings.HasPrefix(line, probePrefix) {
found = true
value := strings.TrimSpace(strings.TrimPrefix(line, probePrefix))
assert.Equal(t, expectedProbe, value, "file %s probe with key: %s", fileName, probePrefix)
break
}
}
assert.True(t, found, "No probe found in file %s with key: %s", fileName, probePrefix)
}
}
}
|
/**
* Model for a Trello Board
*
* <code>
* {
* "id":"4d5ea62fd76aa1136000000c",
* "name":"Trello Development",
* "desc":"Trello board used by the Trello team to
* track work on Trello. How meta!\n\nThe
* development of the Trello API is being
* tracked at https://trello.com/api\n\n
* The development of Trello Mobile applications
* is being tracked at https://trello.com/mobile",
* "closed":false,
* "idOrganization":"4e1452614e4b8698470000e0",
* "url":"https://trello.com/board/trello-development/4d5ea62fd76aa1136000000c",
* "prefs":{
* "voting":"public",
* "permissionLevel":"public",
* "invitations":"members",
* "comments":"public"
* }
* }
* </code>
* @author joel
*
*/
public class Board extends TrelloObject {
// TODO: memberships
// TODO: invitations
/**
* The Enum PERMISSION_TYPE.
*/
public enum PERMISSION_TYPE { /** The PUBLIC. */
PUBLIC, /** The ORGANIZATION. */
ORGANIZATION, /** The MEMBERS. */
MEMBERS }
/** The name. */
private String name;
/** The desc. */
private String desc;
/** The closed. */
private boolean closed;
/** The invited. */
private boolean invited = false;
/** The id organization. */
private String idOrganization;
/** The url. */
private String url;
/** The prefs. */
private Prefs prefs;
/**
* Gets the name.
*
* @return the name
*/
public String getName() {
return name;
}
/**
* Sets the name.
*
* @param name the new name
*/
public void setName(String name) {
this.name = name;
}
/**
* Gets the desc.
*
* @return the desc
*/
public String getDesc() {
return desc;
}
/**
* Sets the desc.
*
* @param desc the new desc
*/
public void setDesc(String desc) {
this.desc = desc;
}
/**
* Gets the id organization.
*
* @return the id organization
*/
public String getIdOrganization() {
return idOrganization;
}
/**
* Sets the id organization.
*
* @param idOrganization the new id organization
*/
public void setIdOrganization(String idOrganization) {
this.idOrganization = idOrganization;
}
/**
* Checks if is closed.
*
* @return true, if is closed
*/
public boolean isClosed() {
return closed;
}
/**
* Sets the closed.
*
* @param closed the new closed
*/
public void setClosed(boolean closed) {
this.closed = closed;
}
/**
* Gets the url.
*
* @return the url
*/
public String getUrl() {
return url;
}
/**
* Sets the url.
*
* @param url the new url
*/
public void setUrl(String url) {
this.url = url;
}
/**
* Gets the prefs.
*
* @return the prefs
*/
public Prefs getPrefs() {
return prefs;
}
/**
* Sets the prefs.
*
* @param prefs the new prefs
*/
public void setPrefs(Prefs prefs) {
this.prefs = prefs;
}
/**
* Checks if is invited.
*
* @return true, if is invited
*/
public boolean isInvited() {
return invited;
}
/**
* Sets the invited.
*
* @param invited the new invited
*/
public void setInvited(boolean invited) {
this.invited = invited;
}
/**
* The Class Prefs.
*/
public class Prefs {
/** The voting. */
private PERMISSION_TYPE voting;
/** The permission level. */
private PERMISSION_TYPE permissionLevel;
/** The invitations. */
private PERMISSION_TYPE invitations;
/** The comments. */
private PERMISSION_TYPE comments;
/**
* Gets the voting.
*
* @return the voting
*/
public PERMISSION_TYPE getVoting() {
return voting;
}
/**
* Sets the voting.
*
* @param voting the new voting
*/
public void setVoting(PERMISSION_TYPE voting) {
this.voting = voting;
}
/**
* Gets the permission level.
*
* @return the permission level
*/
public PERMISSION_TYPE getPermissionLevel() {
return permissionLevel;
}
/**
* Sets the permission level.
*
* @param permissionLevel the new permission level
*/
public void setPermissionLevel(PERMISSION_TYPE permissionLevel) {
this.permissionLevel = permissionLevel;
}
/**
* Gets the invitations.
*
* @return the invitations
*/
public PERMISSION_TYPE getInvitations() {
return invitations;
}
/**
* Sets the invitations.
*
* @param invitations the new invitations
*/
public void setInvitations(PERMISSION_TYPE invitations) {
this.invitations = invitations;
}
/**
* Gets the comments.
*
* @return the comments
*/
public PERMISSION_TYPE getComments() {
return comments;
}
/**
* Sets the comments.
*
* @param comments the new comments
*/
public void setComments(PERMISSION_TYPE comments) {
this.comments = comments;
}
}
}
|
. UNLABELLED Cryptococcosis is a fungal infection caused by cryptococcus neoformans. Cryptococcal pneumonia occurs due to inhalation of the organism into the respiratory tract, sometimes accompanied by meningitis in immunocompromised patients, and can be life-threatening. We report a case of cryptococcal meningitis occurring during corticosteroid therapy for rheumatoid arthritis. CASE A 82-year-old woman with rheumatoid arthritis was given a diagnosis of cryptococcal meningitis, and improved after administeration of amphotericin B in combination with flucytosine. However 3 weeks later, side effects occurred, she was given fluconazole alone, but her condition worsened and she died. In severe cases of cryptococcal meningitis, we should take into account drug susceptibility tests and drug concentrations at the site of infection.
|
COST-EFFECTIVENESS OF RADIOFREQUENCY ABLATION VERSUS LASER FOR VARICOSE VEINS Objectives: Although the clinical benefits of endovenous thermal ablation are widely recognized, few studies have evaluated the health economic implications of different treatments. This study compares 6-month clinical outcomes and cost-effectiveness of endovenous laser ablation (EVLA) compared with radiofrequency ablation (RFA) in the setting of a randomized clinical trial. Methods: Patients with symptomatic primary varicose veins were randomized to EVLA or RFA and followed up for 6 months to evaluate clinical improvements, health related quality of life (HRQOL) and cost-effectiveness. Results: A total of 131 patients were randomized, of which 110 attended 6-month follow-up (EVLA n = 54; RFA n = 56). Improvements in quality of life (AVVQ and SF-12v2) and Venous Clinical Severity Scores (VCSS) achieved at 6 weeks were maintained at 6 months, with no significant difference detected between treatment groups. There were no differences in treatment failure rates. There were small differences in favor of EVLA in terms of costs and 6-month HRQOL but these were not statistically significant. However, RFA is associated with less pain at up to 10 days. Conclusions: EVLA and RFA result in comparable and significant gains in quality of life and clinical improvements at 6 months, compared with baseline values. EVLA is more likely to be cost-effective than RFA but absolute differences in costs and HRQOL are small.
|
<gh_stars>1-10
import { Transform } from 'stream';
export default class OggDemuxer extends Transform {}
|
The present invention relates to a circuit configuration for operating a household appliance, having a switching power supply, by means of which a control unit can be at least indirectly supplied with current for controlling processes of the household appliance, and having a pushbutton, by means of which the switching power supply can be coupled to a supply grid. The invention further relates to a corresponding method.
Such circuit arrangements are already known from the prior art. In order to generate required low voltages, for example 12, 9, 5, 3.3 volts, these circuit configurations normally include a switching power supply, by means of which a line voltage from a supply grid is converted into the aforementioned DC supply voltage. As a general rule, such circuit configurations furthermore have a control unit which is coupled indirectly or directly to the switching power supply and enables the control of processes of the household appliance and the operation of the circuit configurations.
A method and a device for reducing the energy consumption in the case of an electrical appliance fed by a voltage converter are known from the publication DE 195 30 594 C1. In this situation, during operation of the appliance the voltage converter is connected on the primary side for only short periods of time to the supply grid or to another electrical supply. During these periods of time, in addition to providing the supply for a possibly required appliance function the voltage converter also enables the charging of a suitable energy store, whereby in the periods of time during which the voltage converter is disconnected from the power supply the function of the appliance is assured by drawing energy from the energy store. The voltage converter is automatically connected to the supply grid as soon as the energy supply in the energy store runs short in order to charge said energy store or if the appliance function otherwise requires it.
To be regarded as a disadvantage associated with this known method, or this device, is the fact that during the periods of time in which the voltage converter is disconnected from the power supply a self-sustaining behavior of the device in the event of an extended power outage is no longer assured, as a result of which only an inadequate principle of operation is made possible.
|
package com.proyecto.AbeRol;
import java.util.List;
import com.proyecto.AbeRol.Model.Master;
import com.proyecto.AbeRol.Model.MasterDAO;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.scene.control.Alert;
import javafx.scene.control.Button;
import javafx.scene.control.ProgressBar;
import javafx.scene.control.TextField;
import javafx.stage.Stage;
public class SignUpController {
@FXML
private TextField txtName;
@FXML
private TextField txtPass;
@FXML
private TextField txtEmail;
@FXML
private Button buttCreate;
@FXML
private Button buttSave;
@FXML
private ProgressBar progress;
@FXML
public void initialize() {
}
@FXML
private void saveMaster(ActionEvent event) {
String name = this.txtName.getText();
String email = this.txtEmail.getText();
String password = this.txtPass.getText();
if (!this.txtName.getText().trim().isEmpty() && !this.txtPass.getText().trim().isEmpty()
&& !this.txtEmail.getText().trim().isEmpty()) {
List<String> dummyDao = MasterDAO.getMasters();
if (!dummyDao.contains(name)) {
Master dummy = new Master(name, email, password);
MasterDAO aux = new MasterDAO(dummy);
aux.SaveMaster();
Alert alert = new Alert(Alert.AlertType.INFORMATION);
alert.setHeaderText(null);
alert.setTitle("Informacion");
alert.setContentText("Se ha añadido correctamente");
alert.showAndWait();
} else {
Alert alert = new Alert(Alert.AlertType.ERROR);
alert.setHeaderText(null);
alert.setTitle("Error de creacion");
alert.setContentText("El usuario ya existe, recuerde que siempre puede recuperar su cuenta");
alert.showAndWait();
}
} else {
Alert alert = new Alert(Alert.AlertType.ERROR);
alert.setHeaderText(null);
alert.setTitle("Error de creacion");
alert.setContentText("Porfavor no deje ningun dato vacío");
alert.showAndWait();
}
}
@FXML
private void exit(ActionEvent event) {
Stage stage = (Stage) this.buttSave.getScene().getWindow();
stage.close();
}
}
|
<reponame>DomRe/galaxy
///
/// ALError.cpp
/// galaxy
///
/// Refer to LICENSE.txt for more details.
///
#include <format>
#include <AL/al.h>
#include <AL/alc.h>
#include "ALError.hpp"
namespace galaxy
{
namespace error
{
std::string al_parse_error(std::string_view message, const int error)
{
return std::format("OpenAL: {0} | {1}.", message, alGetString(error));
}
std::string al_errcode_as_string(const int err) noexcept
{
switch (err)
{
case AL_NO_ERROR:
return "AL_NO_ERROR";
break;
case AL_INVALID_NAME:
return "AL_INVALID_NAME";
break;
case AL_INVALID_ENUM:
return "AL_INVALID_ENUM";
break;
case AL_INVALID_VALUE:
return "AL_INVALID_VALUE";
break;
case AL_INVALID_OPERATION:
return "AL_INVALID_OPERATION";
break;
case AL_OUT_OF_MEMORY:
return "AL_OUT_OF_MEMORY";
break;
default:
return "AL_NO_ERROR";
break;
}
}
} // namespace error
} // namespace galaxy
|
The challenge of chronic mental illness: a retrospective and prospective view. The challenge of chronic mental illness lies in developing effective service delivery systems that will preserve patients' functioning and limit their disability. The author uses a review of changes and excesses of the past 30 years--including deinstitutionalization, relocation of patients to nursing homes, the domination of psychodynamic concepts, and the naivety and partial successes of the community mental health movement--as a basis for outlining manageable ways to meet this challenge. Care for the chronic patient must be developed within a long-term rehabilitative context and with wiser use of available benefits and funds, including consolidation of funding sources. Mental health advocates should coordinate activities rather than compete with one another, and case management should be based on more sophisticated concepts and training.
|
To remain competitive as technology advances, electronic designers must reduce required system physical space while increasing the system performance. This generally translates into increased power dissipation in a smaller space. However, as is well known, component reliability/life is related to operating temperature. Thus, the challenge is to pack the heat generating components closer together while maintaining acceptably cool temperatures. Traditionally, heat sinks are used to transfer heat from these components to the surrounding environment.
There are many prior art methods of attaching heat generating components, such as field effect transistors (FETs) and diodes, to heat dissipating devices. These include screws, straps, adhesives and spring clips of various types. Among the disadvantages of using screws is the time for attachment, along with the problem of electrical insulation of the component from the screw and heat sink. Straps often require some mode of securing them to the heat sink that causes an undesirable increase in space required for the combination of parts. Adhesives have disadvantages with storage and handling and some can fail with time. Further, a good adhesive may well prevent the reuse of the heat sink in the case where a failed component needs replacement. Known prior art spring clips interfere with air flow on the surface of the component(s) being cooled, some being of a design which increase the length of the path from the component to the fins of the heat sink and/or unduly increase the space required for the heat sink/component package relative nearby components.
As known among thermodynamic experts, having slots periodically situated in the fins of a heat sink disrupts air flow patterns and results in better heat dissipation than unslotted fins. While the slots are important to disrupt air flow patterns, the wider the slot, the less material is left to conduct and/or radiate heat to the environment. Thus most manufacturers of finned heat sinks have slots of a width just enough to provide adequate air flow disruption. For electronic circuits, these slots are typically about 1/10 inch or less in width. There are, however, many other types of finned and non-finned heat dissipating devices to which heat generating devices need to be attached.
It would be desirable if an attachment device could allow quick assembly of one or more components to a heat sink in a secure manner that did not substantially increase package profile dimensions, thereby allowing a higher density packaging, and still allowing replacement of components in a repair mode. It would further be desirable if such attachment device could, without major design modification, be adapted to be used on many different styles of heat dissipating devices.
|
Formal modeling and verification of distributed failure detectors Model checking is a systematic way of checking the absence of errors in a distributed system, i.e., assessing the functional requirements in a distributed system. However, there are certain challenges in this field, e.g., developing true abstract models and on their basis generalizing/guranteeing results, limited capacity of model checking tools and computational resources, identification of all requirements and their accurate specifications, etc. To understand and face such challenges, it is necessary to apply the prominent model checking techniques to different distributed systems designed for different communication models. In this thesis this challenge is accepted and resultantly encountered issues are discussed/addressed. The results reported are sufficient for advocating the need for applying model checking techniques as debugging. Therefore, we report bugs and the propose fixes but for ambiguous algorithms, we reconstruct them. We model check both fixed and reconstructed algorithms. We assess the following protocols: Accelerated heartbeat protocols, Consensus protocols in asynchronous distributed systems, Group membership protocols and Efficient algorithms to implement failure detectors in partially synchronous systems. We found that the accelerated heartbeat protocols proposed in , violated some natural and essential properties. We proved the results by giving counterexamples and developed the techniques to address the time-triggered events in mCRL2 and investigated the correct time bounds for all the protocols. Regarding consensus problem, we proved the correctness of the proposed algorithms where the failure detectors are unreliable (i.e., failure detectors may make mistakes). These algorithms are proposed in . For the group membership protocols proposed in , we found that the original specifications and the text explaining the protocols can be interpreted in different ways and even some natural interpretations contradict each other. Our formalization with respect to different interpretations showed the violation of claimed properties. So to resolve the ambiguities, we reconstructed the protocols and model-checked them. For analyzing the algorithms proposed in , we applied symmetry reduction techniques. We found that every algorithm encounters a deadlock if there is a bounded (yet arbitrarily large) buffer in the communication channel between a pair of nodes. We propose fixes for deadlock avoidance and model check the proposed algorithm in UPPAAL, FDR2 and MCRL2. We also present a comparison of these three tools for model checking one of the given four protocols.
|
Seeing Shania Twain in the Central Valley? Here's what you need to know.
The country star plays Save Mart Center as part of the "Now" tour.
Man! It feels like a Shania Twain summer in the Central Valley.
The award-winning country star returns Aug. 1 to the Save Mart Center for a one-night performance as part of the extensive “Now” tour.
Here’s a look at what you need to know before heading to Fresno State for a night with 1990s country royalty.
Twain plays the Central Valley in support of “Now,” her first full-length studio record in 15 years. The album features lead singles “Life’s About To Get Good” and “Swingin’ With My Eyes Closed” and it dropped in September, debuting at No. 1 on the Billboard 200 album sales chart.
She dabbles in some of the new material on this tour, but won’t keep fans from her biggest country-pop hits. A number of her 1990s arena rock-tinged staples, “That Don’t Impress Me Much,” “Man! I Feel Like A Woman!” and “You’re Still The One,” make the set.
Swiss songwriter Bastian Baker opens the show.
Twain’s 2018 Des Moines show comes a few months removed from a headline-grabbing comment that the Canadian singer, if eligible to cast a ballot, would’ve voted for President Trump in the 2016 election.
“... even though he was offensive, he seemed honest,” she said in an interview with the Guardian.
“Twain, who has been open about her struggle with regaining her vocal strength after a battle with Lyme disease resulting in dysphonia, sounded rested and clear,” the review reads. “Extensive therapy has obviously helped her get comfortable in her lower register, her richer tone bringing a smoky feel to newer songs 'More Fun' and 'Let’s Kiss and Make Up.' "
Praise continues to pile up for the “Now” tour, which comes following Twain temporarily retiring from the road in 2004. Shows kicked off in May and run through December.
All who plan to attend the show will pass through a full-body metal detector prior to entering the arena. Arena officials suggest show-goers plan for additional time to enter the building. Doors open at 7 p.m. and music kicks off at 8 p.m., the events center website says.
The Save Mart Center offers plentiful parking around the arena for $10 per vehicle. Limited free street parking is available, but plan to walk a good distance if you are too cheap to spring for facility parking.
Cost: $49.95 to $149.95 before fees.
|
<reponame>planaria/kumori
#pragma once
#include "exception.hpp"
namespace kumori
{
class duplicated_path_exception : public exception
{
public:
explicit duplicated_path_exception(std::string path)
: exception("duplicated_path(" + std::move(path) + ")")
{
}
};
class invalid_path_exception : public exception
{
public:
explicit invalid_path_exception(std::string path)
: exception("invalid_path(" + std::move(path) + ")")
{
}
};
}
|
<reponame>universekavish/Python-Training<filename>1Dec/serializationDemo.py<gh_stars>0
import pickle
#serialization process
L = [10, 20, 'Hello', [30, 40], {1:2, 3:4}, 50]
fout = open('mydata.serialized', 'wb')
pickle.dump(L, fout)
fout.close()
#Deserialization
fin = open('mydata.serialized', 'rb')
L1 = pickle.load(fin)
fin.close()
print(L1)
|
/*
* QEMU SPAPR PCI BUS definitions
*
* Copyright (c) 2011 Alexey Kardashevskiy <[email protected]>
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, see <http://www.gnu.org/licenses/>.
*/
#if !defined(__HW_SPAPR_H__)
#error Please include spapr.h before this file!
#endif
#if !defined(__HW_SPAPR_PCI_H__)
#define __HW_SPAPR_PCI_H__
#include "hw/pci/pci.h"
#include "hw/pci/pci_host.h"
#include "hw/ppc/xics.h"
#define TYPE_SPAPR_PCI_HOST_BRIDGE "spapr-pci-host-bridge"
#define TYPE_SPAPR_PCI_VFIO_HOST_BRIDGE "spapr-pci-vfio-host-bridge"
#define SPAPR_PCI_HOST_BRIDGE(obj) \
OBJECT_CHECK(sPAPRPHBState, (obj), TYPE_SPAPR_PCI_HOST_BRIDGE)
#define SPAPR_PCI_VFIO_HOST_BRIDGE(obj) \
OBJECT_CHECK(sPAPRPHBVFIOState, (obj), TYPE_SPAPR_PCI_VFIO_HOST_BRIDGE)
#define SPAPR_PCI_HOST_BRIDGE_CLASS(klass) \
OBJECT_CLASS_CHECK(sPAPRPHBClass, (klass), TYPE_SPAPR_PCI_HOST_BRIDGE)
#define SPAPR_PCI_HOST_BRIDGE_GET_CLASS(obj) \
OBJECT_GET_CLASS(sPAPRPHBClass, (obj), TYPE_SPAPR_PCI_HOST_BRIDGE)
typedef struct sPAPRPHBClass sPAPRPHBClass;
typedef struct sPAPRPHBState sPAPRPHBState;
typedef struct sPAPRPHBVFIOState sPAPRPHBVFIOState;
struct sPAPRPHBClass {
PCIHostBridgeClass parent_class;
void (*finish_realize)(sPAPRPHBState *sphb, Error **errp);
int (*eeh_set_option)(sPAPRPHBState *sphb, unsigned int addr, int option);
int (*eeh_get_state)(sPAPRPHBState *sphb, int *state);
int (*eeh_reset)(sPAPRPHBState *sphb, int option);
int (*eeh_configure)(sPAPRPHBState *sphb);
};
typedef struct spapr_pci_msi {
uint32_t first_irq;
uint32_t num;
} spapr_pci_msi;
typedef struct spapr_pci_msi_mig {
uint32_t key;
spapr_pci_msi value;
} spapr_pci_msi_mig;
struct sPAPRPHBState {
PCIHostState parent_obj;
uint32_t index;
uint64_t buid;
char *dtbusname;
MemoryRegion memspace, iospace;
hwaddr mem_win_addr, mem_win_size, io_win_addr, io_win_size;
MemoryRegion memwindow, iowindow, msiwindow;
uint32_t dma_liobn;
AddressSpace iommu_as;
MemoryRegion iommu_root;
struct spapr_pci_lsi {
uint32_t irq;
} lsi_table[PCI_NUM_PINS];
GHashTable *msi;
/* Temporary cache for migration purposes */
int32_t msi_devs_num;
spapr_pci_msi_mig *msi_devs;
QLIST_ENTRY(sPAPRPHBState) list;
};
struct sPAPRPHBVFIOState {
sPAPRPHBState phb;
int32_t iommugroupid;
};
#define SPAPR_PCI_MAX_INDEX 255
#define SPAPR_PCI_BASE_BUID 0x800000020000000ULL
#define SPAPR_PCI_MEM_WIN_BUS_OFFSET 0x80000000ULL
#define SPAPR_PCI_WINDOW_BASE 0x10000000000ULL
#define SPAPR_PCI_WINDOW_SPACING 0x1000000000ULL
#define SPAPR_PCI_MMIO_WIN_OFF 0xA0000000
#define SPAPR_PCI_MMIO_WIN_SIZE (SPAPR_PCI_WINDOW_SPACING - \
SPAPR_PCI_MEM_WIN_BUS_OFFSET)
#define SPAPR_PCI_IO_WIN_OFF 0x80000000
#define SPAPR_PCI_IO_WIN_SIZE 0x10000
#define SPAPR_PCI_MSI_WINDOW 0x40000000000ULL
static inline qemu_irq spapr_phb_lsi_qirq(struct sPAPRPHBState *phb, int pin)
{
return xics_get_qirq(spapr->icp, phb->lsi_table[pin].irq);
}
PCIHostState *spapr_create_phb(sPAPREnvironment *spapr, int index);
int spapr_populate_pci_dt(sPAPRPHBState *phb,
uint32_t xics_phandle,
void *fdt);
void spapr_pci_msi_init(sPAPREnvironment *spapr, hwaddr addr);
void spapr_pci_rtas_init(void);
#endif /* __HW_SPAPR_PCI_H__ */
|
The present invention relates to a fiber with permanent hydrophilic nature having anti-static properties and softness obtained by adhering a fiber treating agent of a specific composition onto the fiber comprising hydrophobic thermoplastic resin; and to fabrics using said fiber.
More particularly, the present invention relates to a fiber having durable hydrophilicity and relates to fabrics using said fiber which is mainly useful as a face of hygienic goods such as disposable diaper or sanitary napkin in contact with human skin; or as a wiping cloth for industrial and medical use.
The consumption of fabrics represented by nonwoven fabric is increasing worldwide; especially the ratio shared by nonwoven fabric made of polyolefin fiber and polyester fiber is increasing year by year due to the spreading of one way goods such as disposable diaper, sanitary napkin or a wiping cloth. In the market of one way goods, cost competitiveness and differentiation from the other products are especially demanded in view of the product""s nature of only one time use.
Among the requirements to fiber and nonwoven fabric used for such products, regarded as important are antistaticity to produce nonwoven fabric at high speed and durable hydrophilicity to differentiate from the other products.
Following methods are generally known to impart antistaticity and durable hydrophilicity to highly hydrophobic polyolefin or polyester fibers:
1) adhering a fiber treating agent onto fibers
2) fiber using resin comprising hydrophilic polymers
3) introduction of hydrophilic group to the surface of fiber through sulfonation, plasma treatment or corona discharge treatment.
Method 1) is most generally applied for hydrophilic fibers used in one way products. For example, in JP-A-49166/97, a fiber imparted to durable hydrophilicity through adhering small amount of fiber treating agent onto the surface of a fiber, is proposed. However, the fiber treating agent disclosed here, can impart durable hydrophilicity to some extent but insufficient to meet the current market demand.
By method 2), sufficient durable hydrophilicity has not yet been achieved. Moreover, problem is its high cost for disposable article.
As to method 3), though good hydrophilicity is obtained just after the treatment to fiber as mentioned above, hydrophilicity deteriorates due to change of the introduced hydrophilic group on the surface of fiber with time.
Inventors of the present invention have made enthusiastic effort to solve the above mentioned problems. As the result, we have found that a fiber or fabrics having durable hydrophilicity together with good antistaticity can be obtained by adhering a fiber treating agent containing specific amount of the mixture made by mixing specific compounds to the specific composition to the surface of thermoplastic resin fiber or fabrics, and have achieved the present invention based on the above finding.
As apparent from the foregoing, the object of the present invention is to provide a thermoplastic resin fiber having durable hydrophilicity which has been the problem of prior art as mentioned above together with good antistaticity and to provide fabrics using the fiber.
The present invention also consists in:
(1) A fiber having durable hydrophilicity obtained by adhering a fiber treating agent comprising at least 60% by weight of a mixture consisting of the following components (A), (B), (C), (D) and (E) each at the following composition to fiber of thermoplastic resin at the level of 0.1 to 1.0% by weight based on fiber weight.
(A) 20 to 40% by weight, based on the total of (A) to (E), of polyglycerin fatty acid ester expressed by the following Formula A,
xe2x80x83wherein R1 represents alkyl or alkenyl group having 7 to 21 carbon atoms; R2 and R3 each represent H, alkanoyl group having 8 to 22 carbon atoms or alkenoyl group; xe2x80x9caxe2x80x9d indicates an integer of 5 to 15.
(B) 5 to 20% by weight, based on the total of (A) to (E), of polyoxyalkylene modified silicone expressed by the following Formula B,
xe2x80x83wherein R4 represents H or alkyl group having 1 to 12 carbon atoms; R5 represents CH3 or C3H6O (C2H4O)d(C3H6O)eR4; xe2x80x9cbxe2x80x9d indicates an integer of 3 to 15; xe2x80x9ccxe2x80x9d indicates an integer of 10 to 120; xe2x80x9cdxe2x80x9d indicates an integer of 5 to 100; xe2x80x9cexe2x80x9d indicates an integer of 5 to 100; with the proviso that xe2x80x9cd+exe2x80x9d is an integer equal to or less than 105.
(C) 10 to 25% by weight, based on the total of (A) to (E), of alkyl imidazolium alkyl sulfate expressed by the following Formula C,
xe2x80x83wherein R6 represents alkyl group having 7 to 21 carbon atoms; R7 represents methyl or ethyl group.
(D) 5 to 20% by weight, based on the total of (A) to (E), of alkylene oxide adduct of alkanoylamide expressed by the following Formula D,
xe2x80x83wherein R8 represents alkyl group having 7 to 21 carbon atoms; R9 represents alkylene unit having 2 to 4 carbon atoms; xe2x80x9cfxe2x80x9d indicates an integer of 5 to 30.
(E) 25 to 40% by weight, based on the total of (A) to (E), of polyetherester expressed by the following Formula E, Formula E:
R10xe2x80x94R11xe2x80x94R12
xe2x80x83wherein R10 represents moiety of aliphatic hydroxy compound having hydroxy value of 1 to 6; R11 represents polyether-polyester block expressed by Formula F or Formula G; R12 represents H, alkanoyl group having 2 to 18 carbon atoms or alkenoyl group having 16 to 22 carbon atoms.)
xe2x80x83wherein Formula F and Formula G, R13 represents alkylene unit having 2 to 4 carbon atoms; R14 represents alkylene unit having 2 to 12 carbon atoms; xe2x80x9cmxe2x80x9d and xe2x80x9cnxe2x80x9d each indicates an integer equal to or larger than 1; xe2x80x9cg1xe2x80x9d to xe2x80x9cgmxe2x80x9d each indicates an integer provided that the sum g=g1+g2+ . . . +gm is 5 to 200; xe2x80x9ch1xe2x80x9d to xe2x80x9chnxe2x80x9d each indicates an integer provided that the sum, h=h1+h2++ . . . hn is 5 to 200 and gxe2x89xa7h.
(2) A fiber having durable hydrophilicity described in item (1) above which is a conjugate fiber made by combining at least two kind of thermoplastic resins.
(3) A fiber having durable hydrophilicity described in either item (1) or (2) above in which at least one component of thermoplastic resins composing the fiber is polyolefin resin.
(4) A fiber having durable hydrophilicity described in either items (1) or (2), above in which at least one component of thermoplastic resins composing the fiber is polyester resin.
(5) A fabric comprising a fiber having durable hydrophilicity described in any one from item (1) to (4) above.
The present invention will be described in detail as follows.
As for fibers comprising thermoplastic resin in the present invention, the fibers comprising thermoplastic resin such as polyolefins, polyesters or polyamides can be illustrated. However, in case of using for the face material and so on in the field of hygienic materials, fibers comprising hydrophobic thermoplastic resin such as polyolefin resins or polyester resins are preferable from the point of dry touch feeling.
Polyolefin resins mentioned here indicate ethylene homopolymer, propylene homopolymer, xcex1-olefin copolymers of ethylene or propylene with other xcex1-olefin etc., or mixture of more than one of these. As for xcex1-olefin copolymers, binary or ternary copolymers comprising propylene as main component, copolymerized with ethylene, butene-1, 4-methyl pentene-1 etc. or mixture of one or more of these can be illustrated.
As for polyesters, polyethylene terephthalate, polybutylene terephthalate, poly(ethylene terephthalate-co-ethylene isophthalate), copolyetherester etc. or mixture of these can be illustrated.
Further, by use, a mixture of polyolefins with polyesters or polyamides can be suitably adopted.
When the fiber having durable hydrophilicity of the present invention is a conjugate fiber comprising two or more of thermoplastic resins, combination of thermoplastic resins to be used can be illustrated as polyethylene/polypropylene, polyethylene/xcex1-olefin copolymer, xcex1-olefin copolymer/polypropylene or polyethylene/polyester and so on. Further, by use, co-polyester or polyamide can be suitably used for the raw material of a fiber having durable hydrophilicity of the present invention.
To the raw material resin used for a fiber having durable hydrophilicity of the present invention, various additives such as pigments, anti-static agents, flame retardants or antibiotics etc. can be added as far as the expected effects of the present invention are not impaired. These additives can also be used by mixing with the raw material resins at the spinning stage. The shape of cross section of the fiber having durable hydrophilicity of the present invention is not especially limited to and can be any arbitrary shape such as circular or profiled.
Also in case of conjugate fiber, the type of conjugation can be any arbitrary type. For example, when the fiber is a conjugate fiber with circular cross-section, conjugation type of fiber can be any arbitrary one such as side-by-side, sheath-core or eccentric sheath-core. Further the shape of cross-section, either in single component fiber or in conjugate fiber, can be any arbitrary one and can be illustrated as oval shape, polygonal such as triangle to octagonal, T-shape, hollowed section or polyfoliate.
Although the single fiber size of the fiber having durable hydrophilicity of the present invention is not especially limited to, when used for hygienic materials which require softness and touch feeling, fibers of 22 dtex or less, preferably 11 dtex or less, further preferably 9 dtex or less are used.
As for the form of fiber, any form such as short fiber or filament, presence or absence of crimp is available and can be suitably adopted.
Then the individual components constituting the fiber treating agent used in the present invention will be described hereinafter.
Component (A) constituting the fiber treating agent is Polyglycerin fatty acid ester expressed by Formula A mentioned before which is an effective component for improvement of durable hydrophilicity.
As polyglycerin fatty acid ester used in the present invention, hydroxy groups in polyglycerin block may be partially or totally esterified but the degree of esterification is preferably in the range of 10 to 60%, more preferably in the range of 15 to 50%. R1 in Formula A expressing polyglycerin fatty acid ester represents alkyl or alkenyl group having 7 to 21 of carbon atoms, preferably 12 to 19 carbon atoms. When carbon atoms in R1 is 6 or less, durable hydrophilicity is low while carbon atoms therein is 22 or more, initial hydrophilicity lowers. R2 and R3 represents H, alkanoyl group having 8 to 22 carbon atoms, preferably 13 to 20 carbon atoms or alkenoyl group. When carbon atoms in R2 or R3 is 7 or less, durable hydrophilicity is low while carbon therein is 23 or more, initial hydrophilicity lowers. And xe2x80x9caxe2x80x9d, the degree of condensation of glycerin constituting polyglycerin part is 5 to 15, preferably 6 to 10. When degree of condensation xe2x80x9caxe2x80x9d is 4 or less, reduction of initial hydrophilicity occurs while degree of condensation xe2x80x9caxe2x80x9d is 16 or more, durable hydrophilicity lowers.
Component (B) constituting the fiber treating agent of the present invention is polyoxyalkylene modified silicone expressed by Formula B which is effective for improvement of durable hydrophilicity together with for improvement of initial hydrophilicity in the present invention. To obtain good initial durable hydrophilicity while imparting minimum water solubility to the polyoxyalkylene modified silicone, xe2x80x9cbxe2x80x9d in Formula B is necessarily in the range of 3 to 15. When xe2x80x9cbxe2x80x9d is 2 or less, initial hydrophilicity lowers, while xe2x80x9cbxe2x80x9d is 16 or more, durable hydrophilicity becomes insufficient, because of too much water solubility of polyoxyalkylene modified silicone. As for xe2x80x9ccxe2x80x9d, xe2x80x9cdxe2x80x9d and xe2x80x9cexe2x80x9d in Formula B, their ranges are also restricted due to similar reason as above.
First, as for xe2x80x9ccxe2x80x9d, it is preferable to be in the range of 10 To 120. When xe2x80x9ccxe2x80x9d is 9 or less, durable hydrophilicity lowers, while xe2x80x9ccxe2x80x9d is 121 or more, initial hydrophilicity lowers. Also for xe2x80x9cdxe2x80x9d, initial hydrophilicity is low when xe2x80x9cdxe2x80x9d is 4 or less while durable hydrophilicity becomes insufficient when xe2x80x9cdxe2x80x9d is 101 or more thus preferable range of xe2x80x9cdxe2x80x9d is 5 to 100. As for xe2x80x9cexe2x80x9d, durable hydrophilicity is insufficient when xe2x80x9cexe2x80x9d is 4 or less while initial hydrophilicity lowers when xe2x80x9cexe2x80x9d is 101 or more thus preferable range of xe2x80x9cexe2x80x9d is 5 to 100. Further, to compatibilize initial and durable hydrophilicity, it is necessary for xe2x80x9cd +exe2x80x9d to be 105 or less. When carbon atoms in R4 is more than 12, initial hydrophilicity of the fiber having durable hydrophilicity lowers.
Component (C) in the fiber treating agent is alkylimidazolium alkyl sulfate expressed by Formula C mentioned before being a component with excellent anti-static effect. In Formula C, R6 represents alkyl group having 7 to 21, preferably 15 to 19 carbon atoms. When carbon atoms is 6 or less, durable hydrophilicity lowers, while 22 or more anti-staticity lowers. R7 represents methyl or ethyl group both of which can be preferably used in the present invention
Component (D) in the fiber treating agent is alkylene oxide adduct of alkanoylamide expressed by Formula D mentioned before having a role to improve durable hydrophilicity. In Formula D, R8 represents alkyl group having 7 to 21, preferably 15 to 19 carbon atoms. When carbon atoms in R8 is 6 or less, durable hydrophilicity lowers, while initial hydrophilicity becomes low when 22 or more. R9 represents alkylene unit having 2 to 4 carbon atoms. When xe2x80x9cfxe2x80x9d in the formula D is 4 or less, initial hydrophilicity lowers, while durable hydrophilicity lowers when 31 or more, thus xe2x80x9cfxe2x80x9d is necessarily in the range of 5 to 30. Further, from the viewpoint of initial hydrophilicity, it is preferable for polyether block enclosed by xe2x80x9cfxe2x80x9d in Formula D to include 50 mol % or more ethylene group.
Component (E) in the fiber treating agent is polyetherester expressed by Formula E mentioned before having an effect to improve durable hydrophilicity. R10 in Formula E is a residue of aliphatic hydroxy compound having a hydroxy value of 1 to 6. As for aliphatic hydroxy compound having a hydroxy value of 1 to 6, there can be illustrated as aliphatic alcohols having a hydroxy value of 1 to 6, partial ester of polyhydroxy alcohol obtained by aliphatic alcohol; having a hydroxy value of 2 to 6 with aliphatic monocarboxylic acid having 6 to 18 carbon atoms, hydroxycarboxylic acid having 1 to 5 hydroxy group in the molecule, alkanolamine having 1 to 3 hydroxy group in the molecule, alkyl dialkanolamine and dialkylalkanolamine both having alkyl group of 1 to 18 carbon atoms and alkoxylated polyamine having 1 to 5 hydroxy group in the molecule. R11 in the Formula E is polyether-polyester block containing polyether block and polyester block comprising, respectively, alkylene unit having 2 to 4 carbon atoms represented by R13 and alkylene unit having 2 to 12, preferably 2 to 8, carbon atoms represented by R14 in the Formula F and G. When carbon atom in R14 is one, durable hydrophilicity lowers, while initial hydrophilicity lowers when carbon atoms exceeds 12.
In the present invention, either polyether-polyester block copolymer from the following 1) to 4) can be used but copolymer 1) is most preferably used for the present invention:
1) A polyether-polyester block copolymer wherein polyether block and polyester block are bonded in this order, to aliphatic hydroxy compound having a hydroxy value of 1 to 6 (namely, corresponds to the case of m=1 and n=1 in Formula F)
2) A polyether-polyester block copolymer wherein polyester block and polyether block are bonded in this order, to aliphatic hydroxy compound having a hydroxy value of 1 to 6 (namely, corresponds to the case of m=1 and n=1 in Formula G)
3) A polyether-polyester block copolymer wherein polyether block and polyester block each containing more than one unit are alternatively bonded to aliphatic hydroxy compound having a hydroxy value of 1 to 6 (namely corresponds to the case of mxe2x89xa72 and m=n or m=n+1).
4) A polyether-polyester block copolymer wherein polyester block and polyether block each containing more than one unit are alternatively bonded to aliphatic hydroxy compound having a hydroxy value of 1 to 6 (namely corresponds to the case of nxe2x89xa72 and n=m or n=m+1).
Also in the present invention, it is preferable that the sum of R3 representing alkylene unit having 2 to 4 carbon atoms per one hydroxy group of the residue of aliphatic hydroxy compound in the polyether-polyester block copolymer, g=g1+g2+ . . . +gm, is 5 to 200 and, at the same time, 40% or more of alkylene unit corresponding to R13 being ethylene. Further, it is preferable that the sum of R14 contained in total polyester block, h=h1+h2+ . . . +hn, is 5 to 200 and gxe2x89xa7h. Also R12 is H, alkanoyl group having 2 to 18 carbon atoms or alkenoyl group having 16 to 22 carbon atoms. Alkanoyl group having 2 to 8 carbon atoms or alkenoyl group having 16 to 22 carbon atoms can be introduced by reacting acylating agent with hydroxy group existing in the end of polyester block in the case where polyetherester used in the present invention is the copolymer 1) mentioned before or in the case where polyester block is bonded to the end of molecule corresponding to R11 in 3) or 4) mentioned before. Such an acylated polyetherester block copolymer can also be used in the present invention.
The reason why the fiber treating agent used in the present invention brings about preferable effect, exists in the point that both alkyl imidazolium alkyl sulfate and alkylene oxide adduct of alanoyl amine are used simultaneously. Imidazolin type surface active agent, a cationic surface active agent, has excellent antistatic effect. Although some anionic surface active agents have excellent anti-static effect, durable hydrophilicity could be severely suffered when such anionic surface active agents blended with cationic surface active agents, but such phenomenon has never been observed for imidazolin type surface active agents used in the present invention. Further, durable hydrophilicity of fiber treating agent of the present invention has been greatly improved by using alkylene oxide adduct of alkanoyl amide together with imidazolin type surface active agents.
The fiber having durable hydrophilicity and the fabrics using the fiber of the present invention are those adhered by the fiber treating agent comprising the components described above at the amount of 0.1 to 1% by weight based on the weight of fiber or fabrics. When adhered amount is below 0.1% by weight, not only durable hydrophilicity targeted by the present invention is failed to be acquired, but also caused a troubles such as sticking to cylinder in the process of carding or occurrence of neps due to the lack of anti-staticity. When adhered amount exceeds 1% by weight, improvement in durability remains relatively small and card scum is apt to be taken place. Adhered amount of fiber treating agent is preferably in the range of 0.2 to 0.7% by weight.
The fiber treating agent used for the fiber having durable hydrophilicity of the present invention comprises at least 60% by weight of components (A) to (E) in total based on the weight of fiber treating agent as mentioned before. As to the ratio of each component within the total of (A) to (E), ranges are determined individually by the following reasons.
First, the content of component (A) of polyglycerin fatty acid ester in the total of (A) to (E) is 20 to 40% by weight,preferably 30 to 35% by weight. When content of the polyglycerin fatty acid ester is below 20% by weight, durable hydrophilicity is not obtained, while initial hydrophilicity lowers when exceeding 40% by weight.
The content of component (B) of polyoxyalkylene modified silicone is 5 to 20% by weight, preferably 10 to 15% by weight, based on the total of (A) to (E). When content of the polyoxyalkylene modified silicone is below 5% by weight, initial hydrophilicity can not be obtained while durable hydrophilicity lowers when exceeding 20% by weight.
The content of component (C) of alkyl imidazolium alkyl sulfate is 10 to 25% by weight, preferably 15 to 20% by weight, based on the total of (A) to (E) When content of the alkyl imidazolium alkyl sulfate is below 10% by weight, antistaticity lowers while durable hydrophilicity lowers when exceeding 25% by weight.
The content of component (D) of alkylene oxide adduct of alkanoylamide is 5 to 20% by weight, preferably 10 to 15% by weight, based on the total of (A) to (E). When content of the alkylene oxide adduct of alkanoylamide is below 5% by weight, durable hydrophilicity lowers while initial hydrophilicity lowers when exceeding 20% by weight.
The content of component (E) of polyetherester is 25 to 40% by weight, preferably 30 to 35% by weight, based on the total of (A) to (E). When content of the polyetherester is below 25% by weight, durable hydrophilicity lowers while initial hydrophilicity lowers when exceeding 40% by weight.
In the fiber treating agent used in the present invention, other component can be used by mixing with the fiber treating agent comprising (A) to (E) as far as the expected effects of the present invention are not impaired. In this case, it is necessary that the content of. total of components of (A) to (E) is 60% by weight or more based on the fiber treating agent. As for components which can be used together with fiber treating agent of the present invention, polyhydric alcohol ester such as sorbitan-ester mono-oleate or glycerinester mono-stearate, or polyether obtained by polymerizing alkyleneoxide such as ethylene oxide or propylene oxide can be illustrated; also they can be used in mixture of more than two of them. Also surface active agents acting as emulsifier or smoothing agent can be added.
Process of adhering the fiber treating agent onto thermoplastic fiber is not specifically limited but any known process can be utilized such as contacting with oiling roll in the spinning or stretching process (contact method), dipping in the dipping vat (dipping method), adhering by spraying (spray method), or adhering after fabrication into fiber layer such as web or fabric such as nonwoven fabric by contact, dipping or spray method mentioned above.
Then it will be described that the behavior of fiber treating agent on the surface of fiber in case of dividable conjugate fiber in comparison between fiber treating agent of the present invention and that used traditionally. In the case of radial dividable shape conjugate fiber, for example, usually composed of hydrophobic thermoplastic fibers, hydrophilic fiber treating agent adhered to the fiber surface as fiber finishing agent will be immediately rinsed off in the non-woven process- using high pressure water. As these fibers themselves are highly hydrophobic, the fibers cannot uniformly get striking energy of water, as fibers keep off from water stream at the initial stage of the nonwoven process by hydro-entanglement. Therefore, nonwoven fabric comprising sufficiently divided ultra fine fibers can not be obtained without increasing stages of hydro-entanglement. On the other hand, radial dividable shape conjugate fiber adhered fiber treating agent of the present invention on the surface of the fiber, can maintain sufficient hydrophilicity and can get striking energy of water uniformly without keeping off from water stream even on repeated nonwoven process by hydro-entanglement, because of very slow loss of the fiber treating agent adhered to the surface of fiber, though fiber itself has very high hydrophobicity, thus being characterized by obtaining nonwoven fabric comprising fully and uniformly divided ultra fine fibers at less stages of hydro-entanglement.
Similarly in case of wet process such as paper making, the fiber having durable hydrophilicity of the present invention can maintain hydrophilicity of fiber and hold good dispersion of fiber in water, because of very slow loss of fiber treating agent into water even in case of fiber using highly hydrophobic resin such as polyolefins.
The fiber having durable hydrophilicity of the present invention can be processed into fabrics using known process. Fabrics as mentioned in the present invention are illustrated for example as woven textile, knitted textile, nonwoven fabric or nonwoven fiber aggregate. Also various mixed fibers made by cotton mixing, mix spinning, mix weaving, doubling and twisting, mixed knitting or union cloth can be formed into fabrics through the above-mentioned processes. Further, fabrics made of fiber having durable hydrophilicity of the present invention, may be used alone or as laminated or integrated state with other nonwoven fabric, knitted or woven fabric, mesh fabric, film or molded article.
The fabrics can be made by any known process. For example, nonwoven fabrics are made using the following processes: short fibers are piled up through dry or wet process into web; then the web is fixed by pressure on heated roll or by super-sonic wave, by partial melting through hot air or by fiber intermingling through high pressure water or needling. Also knitted or woven fabrics are made by knitting or weaving process using spun or continuous fibers. Also the object of the present invention can be achieved by adhering the fiber treating agent mentioned before onto nonwoven fabrics once established by the above mentioned process or by spun bond process, melt blown process or flush spinning process.
Further, among the fiber having durable hydrophilicity of the present invention, conjugate fibers having a cross-section of side-by-side, sheath and core, radial dividable shape or sea and island can be chopped, mixed with water absorbing material such as pulp or water absorbing polymer and heat treated to give a definite shape to water absorbing material. While thermoplastic conjugate fiber in general tend to lower the water absorbability of absorber used such thermoplastic conjugate fiber, when the fiber blending ratio rises higher, it is not the case for the fiber having durable hydrophilicity of the present invention due to maintaining its hydrophilicity.
The fiber having durable hydrophilicity and the fabrics using the fiber of the present invention has excellent durable hydrophilicity while it does not give unpleasant feeling such as stickiness to users. Thus, for example, in case of using for face or second sheet of hygienic products such as disposable diaper or sanitary napkin, a product is obtained which has continuous absorbing ability of body fluid. after using for a long time and comfortable feeling to skin. Further, the fiber having durable hydrophilicity and the fabrics using the fiber of the present invention can be widely used, besides the above-mentioned face material of hygienic product or shaping material of absorber, wiping cloth for medical or industrial use, absorbing pad, reinforcing fiber for construction structure in civil engineering and construction industry, liquid transporting membrane, aqueduct or water permeable sheet.
|
Biomarkers of Smoking - Which Cut-Off Values Should be Used? Abstract. Verification of smoking status by means of biomarkers is important for treatment decisions of patients with smoking-related diseases. Cotinine is currently the best biomarker to document nicotine consumption. A low cost alternative method to determine smoking status is by measurement of carboxyhemoglobin (CO-Hb) in the exhaled breath. The main disadvantage of CO-Hb is the short half-life. The appropriate cut-off value for active nicotine consumption in Switzerland is 50 ng/ml or higher cotinine in the urine or 10 ng/ml and 12 ng/ml in serum and saliva, respectively. CO-Hb levels greater than 2 % indicate smoking with high probability, levels above 3 % with very high probability.
|
Effects of intraventricular growth hormone-releasing factor on growth hormone release: further evidence for ultrashort loop feedback. We examined the effects of cerebroventricular injection of synthetic human GH-releasing factor on regulation of GH release in conscious male rats. These results were compared with the direct effects of hGRF on hormone released from dispersed anterior pituitary cells. Administration of two higher doses of hGRF (200 and 2000 ng) into the third ventricle (3V) produced a dose-related increase in plasma GH levels (P less than 0.001). Injection of hGRF into the 3V at two lower doses actually reduced GH release. Infusion of 20 ng (5 pmol) hGRF reduced plasma GH from 5-60 min (P less than 0.005), with a maximum suppression of 66%. The 2-ng (0.5-pmol) dose decreased GH secretion by 45% (P less than 0.05). hGRF stimulated a significant and dose-dependent release of GH from dispersed pituitary cells at concentrations of 10(-10) and 10(-9) M (P less than 0.025). The specificity of GRF for GH control, whether stimulatory or inhibitory, was seen by the failure of GRF to modify PRL, TSH, or LH release. Our results indicate that injection of larger doses of GRF into the 3V produce GH release, but at lower doses, 3V GRF may exert an action centrally to inhibit GH release. We propose that hypothalamic GRF may decrease its own neurosecretion by negative ultrashort loop feedback.
|
<reponame>andreitoledo/AG-AcademiaGinastica
package com.andreitoledo.ac.controller.entidade;
import java.io.Serializable;
import javax.faces.view.ViewScoped;
import javax.inject.Inject;
import javax.inject.Named;
import com.andreitoledo.ac.model.TipoAtividade;
import com.andreitoledo.ac.service.CadastroTipoAtividadeService;
import com.andreitoledo.ac.service.NegocioException;
import com.andreitoledo.ac.util.jsf.FacesMessages;
@Named
@ViewScoped
public class CadastroTipoAtividadeBean implements Serializable {
private static final long serialVersionUID = 1L;
private TipoAtividade tipoAtividade;
@Inject
private CadastroTipoAtividadeService cadastroTipoAtividadeService;
@Inject
private FacesMessages facesMessages;
public void inicializar() {
if (tipoAtividade == null) {
limpar();
}
}
private void limpar() {
this.tipoAtividade = new TipoAtividade();
}
public void salvar() {
try {
this.cadastroTipoAtividadeService.salvar(tipoAtividade);
facesMessages.info("Tipo Atividade " + tipoAtividade.getDescricao() + " salvo com sucesso.");
limpar();
} catch (NegocioException e) {
facesMessages.error(e.getMessage());
}
}
public TipoAtividade getTipoAtividade() {
return tipoAtividade;
}
public void setTipoAtividade(TipoAtividade tipoAtividade) {
this.tipoAtividade = tipoAtividade;
}
public boolean isEditando() {
return this.tipoAtividade.getCodigo() != null;
}
}
|
. From March 1993 to October 1994, 12 patients operated for persistent hyperparathyroidism had preoperative catheterization of large cervical and mediastinal veins (CLCMV) with determination of serum concentration of intact parathyroid hormone. Other localization procedures included: ultrasonography (US, n = 9), computed tomography (CT, n = 8), magnetic resonance imaging (MRI, n = 5), and sestamibi radionuclide imaging (MIBI, n = 9). A (1-84 PTH) gradient of 1-84 PTH was demonstrated in all patients, localizing a lesion in the neck (n = 9) or in the mediastinum (n = 3). An adenoma was found in nine patients either in the neck (n = 6) or in the mediastinum (n = 3), and 2 patients had glandular hyperplasia. Two patients remained hypercalcemic despite the removal of parathyroid tissue during CLCMV-guided reexploration. An other patient underwent unsuccessful neck reexploration. The sensitivity of other procedures was lower: US: 22%, CT: 50%, MRI: 60%, and MIBI: 66.5%. After a median follow-up of 13 months, 9 patients were cured of their hyperparathyroidism (75%) and 3 had persistent hypercalcemia. Our results suggest that CLCMV with 1-84 PTH measurement is the most accurate localization procedure in persistent hyperparathyroidism.
|
Carro Armato P 40
History
The development work began in 1940, on Benito Mussolini's specific orders. Initial requirements were for a 20 tonne (the maximum load allowed by pontoon bridges) tank with a 47 mm gun, three machine-guns and a crew of five, but this was quickly superseded by another 25 tonne design, to be named P26. The development work proceeded quickly except for the engine; the Italian military staff, the Stato Maggiore, wanted a diesel power-plant, while the builders favoured a petrol engine.
However, in Italy at the time there were no engines (diesel or petrol) available capable of developing the 300 hp (220 kW) required, and the Italian tank industry (i.e. the duopoly Fiat-Ansaldo) did not turn to easily available aircraft engines for its tanks as contemporary U.S. and British tank manufacturers had done. The design of a new engine was very slow, and in the end a 420 hp (310 kW) petrol engine (Fiat 262) was eventually tested, even though in the end it was not adopted.
Provisionally called P75 (from the gun's calibre), the first design (whose prototype was ready on mid-1941) was similar to an enlarged Fiat M13/40, but with a 75/18 howitzer (the same fitted on the Semovente da 75/18) and more armour; the prototype was then modified by replacing the main gun with a 75/32 gun with a co-axial machine-gun. After learning about Soviet T-34s in 1941, thanks to a captured tank supplied by the Germans, the whole design was radically modified: the armour was quickly thickened (from 40 to 50 mm on the front and from 30 to 40 mm on the sides) and re-designed, adopting more markedly sloped plates, and the new 75/34 gun was adopted; meanwhile the dual barbette mount in the hull was deleted. The gun designation "75/34" referred to a 75 mm bore diameter gun with a length equal to 34 calibres. However, the weight increase (which now topped at 26 tonne) and the difficulties in finding a suitable engine further hampered the start of mass production; in the end, it was decided that the prototype and the early production samples were to be equipped with a 330 HP SPA 8V diesel engine, later to be replaced by a 420 HP petrol engine.
Only a few (between one and five depending on the source) pre-production models were completed before the Italian Armistice in September 1943, at which point they were taken over by the German Wehrmacht. A few were used in combat, under the German designation of Panzerkampfwagen P40 737(i), for example at Anzio; some, without engines, were used as static strongpoints.
Combat history
Only 21 P 40s were finished prior to the armistice and it did not serve in Italian colors. The Germans ordered production to continue after the armistice and appropriated completed tanks to the Southern Tank Training Battalion, 10th and 15th Police Panzer Companies, and the 24th Waffen Mountain Division of the SS Karstjäger. The Southern Tank Training Battalion trained units to use captured Italian tanks and had five P 40s in their inventory. The 10th Police Panzer Company served in Russia before redeployment to northern Italy in late 1944 for anti-partisan duties with the 15th Police Panzer Company. Formed in summer of 1944, the 24th Waffen Mountain Division was deployed to Trieste and Udine along the Adriatic coast. While retreating towards Austria in March 1945, they lost several P 40 tanks to Shermans of the British 6th Armoured Division. About a hundred P 40s were used by the German military, of which about 40 were without engines and used as static emplacements at defensive positions such as the Gustav and Gothic Lines.
Design
The turret was operated by two crew members and this was a significant drawback as it put excessive workload on the tank's commander. At that time, most new tanks were designed with three-man turrets. Moreover, it lacked a commander's cupola.
The main weapon was the 75/34 gun, a development of the Model 37 divisional gun (34 calibres long), retaining the same dimensions. This weapon had a muzzle velocity of around 700 m/s (2,300 ft/s); and was normally provided with around 75 rounds of ammunition. Its armour-piercing shells could penetrate roughly 70 mm of armour at 500 meters. For secondary armament, the P 40 had a co-axial machine-gun and another which could be used in the anti-aircraft role, eschewing the traditional dual mount in the hull; the standard ammunition load was also lower, only around 600 rounds, compared to 3,000 of the "M" series.
The mechanical systems were a development of the "M" series, in particular the leaf spring suspension which was reliable, but in rough terrain would not allow speeds similar to the more modern Christie suspension or torsion bar suspension. Nevertheless, the good power-to-weight ratio represented a significant improvement in mobility over its predecessors.
The armour, quite resistant by Italian standards, was sloped and 60 mm thick at the turret front and mantlet (by comparison the M13/40 had 42 mm), but it was still riveted at a time when most tanks were constructed by welding. Compared to welded armour, riveted armour is vulnerable to breaking apart at the joints meaning that even quite resistant plates can be defeated by rivet failures. The front armour had a compound slope with a best facing of 50 mm/45 degrees.
The armour was capable of protecting the tank against early anti-tank guns such as the British QF 2 pounder (40 mm, 1.6 in), but was vulnerable to subsequent anti-tank weapons such as the British QF 6 pounder (57 mm, 2.24 in) that entered service in 1942 and the QF 17 pounder (76 mm, 3 in) coming into use in 1943.
The P 40 design was reasonably up-to-date, but the tank was without some modern features such as welded armour, modern suspension, and a cupola for the commander. The P 40 was designated as a heavy tank in Italy, not because of its weight, but because of its intended role in support of the widely used medium ("M") tanks on the battlefields. In weight, armour and armament it was similar to the medium tanks of the Wehrmacht or other contemporary armies, its armament and protection being roughly the same as the early production American M4 Sherman tank. It was the final evolution of Italian tank designs, that began with the Vickers-based tankettes (such as the CV29 and L3/35) and developed into models such as the M11/39 medium tank, a much heavier construction whose internal design shared many characteristics of the earlier tankettes.
Production
Some 1,200 tanks were ordered (but the total was later reduced to 500 when development work on the heavier P 43 began), but the start of production was delayed by the engine problems and by other factors, such as the bombing of the SPA factory in Turin in September 1942; in the end, production began only in summer 1943. About a hundred P 40s were built by Ansaldo from then until the end of the war, although most were not entirely completed because of a lack of engines.
Variants
There were at least two planned variants of the P 40, developed from early 1943 when the Italian Army realized that the tank was inferior to other designs such as the German Panther. The first one was named P 43, a tank with a weight of some 30 tonnes, with armour plates some 50–80 mm thick and a main armament of either the 75/34 gun or a 105/23 gun. In September 1943 Fiat and Ansaldo began development of a new design which could be comparable to the Panther, and the result was the P 43 bis, with heavily sloped armour, a 450 HP engine and a 90/42 gun. These designs never passed the wooden mock-up stage.
The other project was the Semovente 149/40, based on the P 40 hull. Only one of these vehicles was ever built. It was intended to be a highly mobile self-propelled gun, and its armament was the most powerful gun of the Royal Italian Army: a 149 mm / 40 calibre artillery piece with a range of over 23 km (14 mi) (slightly more than that of the US 155 mm M1 Long Tom). This gun was produced in very few numbers, and the Italian artillery remained equipped mainly with obsolete weapons for the duration of the war. Due to its mass, it was quite bulky to move, and so it was decided to build a self-propelled version, utilizing the most powerful of all Italian military vehicles. All space of the P 40 hull was dedicated to supporting the gun, so the ammunition and crew would have required additional vehicles to be moved. The gun would have been ready to fire in three minutes from coming to a stop, compared to the 17 minutes required by towed artillery.
Work on the Semovente 149/40 started in 1942 and the prototype was tested in 1943, but the Italian Army was not very impressed. After the Armistice the vehicle was acquired by the Germans, and they were not impressed by it either. Finally American forces captured it during the invasion of Germany and sent it to the Aberdeen Proving Ground for testing.
Surviving vehicles
Two P26/40s still exist, one preserved at the Museo della Motorizzazione in Rome and another is currently on display near the army barracks near Lecce.
|
When Karen Kulp was a child, she believed that the United States of America as she knew it was going to end on June 6, 1966. Her parents were from the South, and they had migrated to Colorado, where Kulp’s father was involved in mining operations and various entrepreneurial activities. In terms of ideology, her parents had started with the John Birch Society, and then they became more radical, until they thought that an invasion was likely to take place on 6/6/66, because it resembled the number of the Beast. “We thought we were going to have a world war, there would be Communists coming, we’d have to kill somebody for a loaf of bread,” Kulp said recently. She was thirteen when doomsday came. The family was living in Del Norte, Colorado, and they had packed gas masks, ammunition, canned food, and other supplies. As the day went on, Kulp said, she began to think that the invasion wasn’t going to happen. “And then I thought, I’m going to have to go to school tomorrow.” In time, Kulp began to question her parents’ ideas. Her father became a pioneer in far-right radio, re-broadcasting the shows of Tom Valentine, who often promoted conspiracy theories and was accused of anti-Semitism. The family sometimes attended Aryan Nations training camps. “It was for whites only,” Kulp said. “It would teach you that whites were the supreme race, all of that shit.” She pointed to her heart: “It just didn’t fit in with this right here.” By the time Kulp was twenty, she had rejected her parents’ racism. She worked as a nurse, eventually specializing in geriatric care, and during the nineteen-eighties she participated in pro-choice demonstrations. Last autumn, she was energized by the Presidential election. In Grand Junction, the largest city in western Colorado, Kulp campaigned with a group of citizens who became active shortly after the release of the “Access Hollywood” recording, in which Trump was caught on tape bragging about assaulting women. One of the campaigners was a working mother named Lisa Gaizutis. Her eleven-year-old son had friends whose parents had declared that they would move to Canada if the election went the wrong way, so he did everything possible to free up his mother’s afternoons. “He said he’d take care of himself as long as I was campaigning,” Gaizutis remembered, after the election. “He’d text me and say, ‘You can stay late, I’m done with my homework.’ ” The majority of these activists were women, but their backgrounds were varied. Laureen Gutierrez’s ancestors had come from Spain via Mexico; Marjorie Haun was a special-education teacher who had left her job because of a vocal disability. Matt Patterson was a high-school dropout who, through a series of unlikely events, had acquired a classics degree from Columbia University. All of the activists had arrived in the same place, as fervent supporters of Donald Trump, and on the day of the Inauguration they met in Grand Junction to celebrate.
On January 20th, nearly two hundred people attended the Mesa County Republican Women’s DeploraBall. They watched a live feed of the Presidential Inaugural Ball, and they took photographs of one another next to cardboard cutouts of Donald Trump and Ronald Reagan, which had been arranged on the mezzanine of the Avalon Theatre. The theatre has an elegant Romanesque Revival façade, and it was built in the twenties, during one of the periodic resource-extraction booms that have shaped the city and its psyche. Grand Junction, with its surrounding area, has a population of some hundred and fifty thousand, and it sits in a wide, windswept valley. There are dry mountains and mesas on all sides, and the landscape gives the town a self-contained feel. Even its history revolves around events that were suffered alone. Residents often refer to their own “Black Sunday,” a date that’s meaningless anywhere else: May 2, 1982, when Exxon decided to abandon an enormous oil-shale project, with devastating effects on Grand Junction’s economy. The region is a Republican stronghold in a state that is starkly divided. Clinton won the Colorado popular vote by a modest margin, but Trump took nearly twice as many counties. The difference came from Denver and Boulder, two populous and liberal enclaves on the Front Range, the eastern side of the Rockies—the Colorado equivalents of New York and California. “Donald Trump lost those two counties by two hundred and seventy-three thousand votes, and he won the rest of the state by a hundred and forty thousand votes,” Steve House, the former chair of the state Republican Party, told me. “That means that most of Colorado, in my mind, is a conservative state.” It also means that Colorado’s economy and culture change dramatically from the Front Range to the Western Slope, on the other side of the Continental Divide. Between 2010 and 2015, the Front Range experienced ninety-six per cent of Colorado’s population growth, and the state’s unemployment rate is only 2.3 per cent. But Grand Junction lost eleven per cent of its workforce between 2009 and 2014, in part because the local energy industry collapsed in the wake of the worldwide drop in gas prices. Average annual family earnings are around ten thousand dollars less than the state figure. Most Grand Junction Republicans initially supported Ted Cruz, and, in August, 2016, after Trump won the nomination, a young first vice-chair of the county Party named Michael Lentz resigned. Lentz decided that advocating for Trump would contradict his Christian faith; he was particularly bothered by Trump’s attacks on immigrants and on the press. “I spent a month trying to come to grips with it, but I couldn’t,” Lentz told me. In October, Matt Patterson, who grew up in Grand Junction but now lives in Washington, D.C., returned to his home town to serve as the Party’s regional field director for the Presidential campaign. He lasted for four days. This was shortly after the “Access Hollywood” tape was leaked, and Patterson’s first act as field director was to propose that the Party hold a Women for Trump rally. But the county chairman refused. “His exact words were, ‘That’s picking a fight we can’t win,’ ” Patterson told me. He quit the campaign and organized the rally on his own. In his estimation, most Republicans would find Trump’s comments repugnant, but they would be even more resentful of the coastal media that was pushing the story. The Women for Trump rally was a local turning point. More than a hundred people showed up, and it galvanized a group of activists. Like other grassroots supporters across the country, they named themselves after Hillary Clinton’s comment that half of Trump’s adherents were racists, sexists, and others who belonged in a “basket of deplorables.” The Deplorables’ approach to the election was fiercely unapologetic. Karen Kulp told me that Trump wasn’t racist; he was simply calling for immigrants to be held accountable to the law. She said she would never support a hateful candidate, because her childhood contact with extremist groups had made her sensitive to such issues. For Kulp, who is in her mid-sixties and describes her income as limited, the campaign was empowering. Like many in Grand Junction, she believed that Trump would kick-start the local energy industry by reducing regulations. She told me that she had never shaken the sense that the country is under threat. “I think America is lost to us,” she said. “Because of the way I was raised, that is baggage that I will have for the rest of my life.” The Deplorables funded their own activities, and they pooled money in order to buy Trump shirts, hats, and buttons from Amazon, because the official campaign provided almost nothing. “I made about a dozen Amazon orders,” Kulp said, at the DeploraBall. “Every shirt you see here tonight, I bought.” At the Avalon, the crowd fell silent while a woman prayed: “Thank you for giving us a President who will, with your help, restore this nation to her former glory, the way you created her.” Less than two weeks later, the Deplorables effectively took over the county Republican leadership, with members winning three positions, including the chair. Others looked farther afield. “If Trump won Wisconsin, he could have won Colorado,” Patterson told me. “The issues were here—immigration and energy.” He believed that without the infighting of the last campaign they could do better. In 2018, there will be an election to replace John Hickenlooper, the Democratic Colorado governor, who will vacate his seat because of term limits. At the DeploraBall, Patterson told me that the Republicans can win the governorship and then, two years later, deliver Colorado to Trump. He said, “We’re going to start on the Western Slope and do a sweep east and color it red.”
Like many parts of America that strongly supported Trump, Grand Junction is a rural place with problems that have traditionally been associated with urban areas. In the past three years, felony filings have increased by nearly sixty-five per cent, and there are more than twice as many open homicide cases as there were a decade ago. There’s an epidemic of drug addiction and also of suicide: residents of Mesa County kill themselves at a rate that’s nearly two and a half times that of the nation. Some of this is tied to economic problems, but there’s also an issue of perception. The decrease in gas drilling weighs heavily on the minds of locals, although few people seem to realize that the energy industry now represents less than three per cent of local employment. They’ve been slow to embrace other sectors, such as health care and education, which seem to have more potential for future growth. During the campaign, Trump’s descriptions of inner-city crime and hopelessness often seemed cartoonish to urban residents, but not to rural voters—in Mesa County, Trump won nearly sixty-five per cent of the vote. Pueblo, another large rural Colorado county, has a steel industry that’s been on the wane since the nineteen-eighties. Its county seat now has the state’s highest homicide rate, and last election the county switched from blue to red. Far from Denver and Boulder, there are many places where an atmosphere of decline has lasted for two or more generations, leaving a profound impact on the outlook of young people. Matt Patterson told me that as a boy he had always hoped to escape his home town. In 1985, when he was twelve, almost fifteen per cent of the homes in Grand Junction were vacant, because of the effects of Black Sunday. Patterson’s dream was to become a magician. His parents were middle class—his father sold lumber; his mother worked in insurance—and they were upset when he dropped out of school at the beginning of tenth grade. He moved to South Florida, where he established himself as a specialist in closeup magic. He worked in restaurants, performing sleight-of-hand tricks for diners, and eventually he expanded into private parties, trade shows, and cruise ships. By his early twenties, he was earning more than forty thousand dollars a year. Years later, he described the experience as a “brutal education,” and he self-published a business manual for aspiring magicians. Some advice is technical: for magic, silver Liberty half-dollars are better than Kennedys; in low light, use cards that are red instead of blue. The manual was written long before Patterson entered politics, but any candidate would recognize the wisdom of sleight of hand. (“A good friend once told me that the only difference between a salesman and a con-man is that a salesman has confidence in his product.”) In 1997, Patterson was riding in a car that was hit by a drunk driver, and the bones of his left arm were shattered into several dozen pieces. After six surgeries, he suffered permanent nerve damage, decreased arm mobility, and no future as a closeup magician. Having acquired his G.E.D., he enrolled in classes at the University of Miami. The quality of Patterson’s writing impressed an instructor, who persuaded him to apply to Columbia. The year that Patterson turned thirty, he became an Ivy League freshman. He majored in classics. Every night, he translated four hundred lines of ancient Greek and Latin. In class, he often argued with professors and students. “The default view seemed to be that Western civilization is inherently bad,” he told me. In one history seminar, when students discussed the evils of the Western slave trade, Patterson pointed out that many cultures had practiced slavery, but that nobody decided to eradicate it until individuals in the West took up the cause. The class booed him. In Patterson’s opinion, most people at Columbia believed that only liberal views were legitimate, whereas his experiences in Grand Junction, and his textbook lessons from magic, indicated otherwise. (“States of mind are no different than feats of manual dexterity. Both can be learned through patience and diligence.”) “Look, I’m a high-school dropout who went to an Ivy League school,” Patterson said. “I’ve seen both sides. The people at Columbia are not smarter.” He continued, “I went to Columbia at the height of the Iraq War. There were really legitimate arguments against going into Iraq. But I found that the really good arguments against going were made by William F. Buckley, Bob Novak, and Pat Buchanan. What I saw on the left was all slogans and group thought and clichés.” Patterson graduated with honors and a reinvigorated sense of political conviction. For the past seven years, he’s worked for conservative nonprofit organizations, most recently in anti-union activism. In 2013, the United Auto Workers tried to unionize a Volkswagen plant in Chattanooga, where Patterson demonstrated a knack for billboards and catchphrases. On one sign, he paired a photograph of a hollowed-out Packard plant with the words “Detroit: Brought to You by the UAW.” Another billboard said “United Auto Workers,” with the word “Auto” crossed out and replaced by “Obama,” written in red. In Patterson’s opinion, such issues are cultural and emotional as much as economic. He believes that unions once served a critical function in American industry, but that the leadership, like that of the Democratic Party, has drifted too far from its base. Union heads back liberal candidates such as Obama and Clinton while dues-paying members tend to hold very different views. Patterson also thinks that free trade, which he once embraced as a conservative, has damaged American industries, and he now supports some more protectionist measures. His message resonated in Chattanooga, where, in 2014, workers delivered a stinging defeat to the U.A.W. Since then, Patterson has continued his advocacy in communities across the country, under the auspices of Americans for Tax Reform, which was founded by the conservative advocate Grover Norquist. “So now I bust unions for Grover Norquist with a classics degree and as a former magician,” he told me. As a magician, Patterson went by the name Magnus, taken from Albertus Magnus, the thirteenth-century saint and supposed alchemist. Patterson is of slightly less than average height, with features that are nondescript in a way that allows him to shift easily from one appearance to another. At the DeploraBall he wore a fedora, a pin-striped suit jacket, and eyeglasses with stylish John Varvatos frames. But at other times he dresses with the flair of a goth: black T-shirt, leather bracelet studded with skulls, silver ring decorated with a flying bat. Sometimes he paints his fingernails black. These accessories vanish when it’s time to interact with factory workers, voters, or Republicans in Middle America. In July, 2016, Patterson bet a friend two hundred dollars that Trump would win the Presidency. His conservative Washington friends didn’t take Trump seriously, but Patterson believed that the candidate’s ability to connect with voters was uncanny. (“Remember that you will be performing for people of varying degrees of education, in varying degrees of sobriety, and your routines must be easily understood by all of them.”)
Last October, three weeks before the election, Donald Trump visited Grand Junction for a rally in an airport hangar. Along with other members of the press, I was escorted into a pen near the back, where a metal fence separated us from the crowd. At that time, some prominent polls showed Clinton leading by more than ten percentage points, and Trump often claimed that the election might be rigged. During the rally he said, “There’s a voter fraud also with the media, because they so poison the minds of the people by writing false stories.” He pointed in our direction, describing us as “criminals,” among other things: “They’re lying, they’re cheating, they’re stealing! They’re doing everything, these people right back here!” The attacks came every few minutes, and they served as a kind of tether to the speech. The material could have drifted off into abstraction—e-mails, Benghazi, the Washington swamp. But every time Trump pointed at the media, the crowd turned, and by the end people were screaming and cursing at us. One man tried to climb over the barrier, and security guards had to drag him away. Such behavior is out of character for residents of rural Colorado, where politeness and public decency are highly valued. Erin McIntyre, a Grand Junction native who works for the Daily Sentinel, the local paper, stood in the crowd, where the people around her screamed at the journalists: “Lock them up!” “Hang them all!” “Electric chair!” Afterward, McIntyre posted a description of the event on Facebook. “I thought I knew Mesa County,” she wrote. “That’s not what I saw yesterday. And it scared me.” Before Trump took office, people I met in Grand Junction emphasized pragmatic reasons for supporting him. The economy was in trouble, and Trump was a businessman who knew how to make rational, profit-oriented decisions. Supporters almost always complained about some aspect of his character, but they also believed that these flaws were likely to help him succeed in Washington. “I’m not voting for him to be my pastor,” Kathy Rehberg, a local real-estate agent, said. “I’m voting for him to be President. If I have rats in my basement, I’m going to try to find the best rat killer out there. I don’t care if he’s ugly or if he’s sociable. All I care about is if he kills rats.” “Don’t worry, we only went out once. I never saw him naked—not until now, of course.” After the turbulent first two months of the Administration, I met again with Kathy Rehberg and her husband, Ron. They were satisfied with Trump’s performance, and their complaints about his behavior were mild. “I think some of it is funny, how he doesn’t let people push him around,” Ron Rehberg said. Over time, such remarks became more common. “I hate to say it, but I wake up in the morning looking forward to what else is coming,” Ray Scott, a Republican state senator who had campaigned for Trump, told me in June. One lawyer said bluntly, “I get a kick in the ass out of him.” The calculus seemed to have shifted: Trump’s negative qualities, which once had been described as a means to an end, now had value of their own. The point wasn’t necessarily to get things done; it was to retaliate against the media and other enemies. This had always seemed fundamental to Trump’s appeal, but people had been less likely to express it so starkly before he entered office. “For those of us who believe that the media has been corrupt for a lot of years, it’s a way of poking at the jellyfish,” Karen Kulp told me in late April. “Just to make them mad.”
In Grand Junction, people wanted Trump to accomplish certain things with the pragmatism of a businessman, but they also wanted him to make them feel a certain way. The assumption has always been that, while emotional appeal might have mattered during the campaign, the practical impact of a Trump Presidency would prove more important. Liberals claimed that Trump would fail because his policies would hurt the people who had voted for him. But the lack of legislative accomplishment seems only to make supporters take more satisfaction in Trump’s behavior. And thus far the President’s tone, rather than his policies, has had the greatest impact on Grand Junction. This was evident even before the election, with the behavior of supporters at the candidate’s rally, the conflicts within the local Republican Party, and an increased distrust of anything having to do with government. Sheila Reiner, a Republican who serves as the county clerk, said that during the campaign she had dealt with many allegations of fraud following Trump’s claims that the election could be rigged. “People came in and said, ‘I want to see where you’re tearing up the ballots!’ ” Reiner told me. Reiner and her staff gave at least twenty impromptu tours of their office, in an attempt to convince voters that the Republican county clerk wasn’t trying to throw the election to Clinton. The Daily Sentinel publishes editorials from both the right and the left, and it didn’t endorse a Presidential candidate. But supporters picked up on Trump’s obsession with crowd size, repeatedly accusing the Sentinel of underestimating attendance at rallies. The paper ran a story about vandalism of political signs, with examples given from both campaigns, but readers were outraged that the photograph featured only a torn Clinton banner. The Sentinel immediately ran a second article with a photograph of a vandalized Trump sign. When Erin McIntyre described the Grand Junction rally on Facebook, online attacks by Trump supporters were so vicious that she feared for her safety. After three days, she deleted the post. In February, a bill that was intended to give journalists better access to government records was introduced in a Colorado senate committee, which was chaired by Ray Scott, a Republican. The process was delayed for unknown reasons, and the Sentinel published an editorial with a mild prompt: “We call on our own Sen. Scott to announce a new committee hearing date and move this bill forward.” Scott responded with a series of Trump-style tweets. “We have our own fake news in Grand Junction,” he wrote. “The very liberal GJ Sentinel is attempting to apply pressure for me to move a bill.” Jay Seaton, the Sentinel’s publisher, threatened to sue Scott for defamation. In an editorial, he wrote, “When a state senator accused The Sentinel of being fake news, he was deliberately attempting to delegitimize a credible news source in order to avoid being held accountable by it.” The Huffington Post and other national outlets mentioned the spat. When I met with Scott, he seemed pleased by the attention. A burly, friendly man who works as a contractor, he told me, “I was kind of Trumpish before Trump was cool.” “We used to just take it on the chin if somebody said something about us,” he said. “The fake-news thing became the popular thing to say, because of Trump.” He believed that Trump has performed a service by popularizing the term. “I’ve seen journalists like yourself doing a better job,” Scott told me. He’s considering a run for governor, in part because of Trump’s example. “People are looking for something different,” he said. “They’re looking for somebody who means what they say.” In late February, shortly after the exchange between Scott and Seaton, an entrepreneur named Tyler Riehl started a campaign against the Sentinel. He wrote on Facebook, “If I’ve learned one thing from Donald Trump’s election it’s that we can ignore the political pundits telling us we must play nice with the press—even when they’re crooked and dishonest.” Riehl announced a five-hundred-dollar reward for anybody exposing “local media malfeasance,” and he fashioned a hundred newspaper delivery boxes decorated with a “Ghostbusters”-style icon that read, “FAKE NEWS.” Riehl distributed the boxes at a rally called Toast for Trump, which was dutifully covered by the Sentinel, along with a fact-checked head count (a hundred and twenty). In Grand Junction, I learned to suspend any customary assumptions regarding political identity. I encountered countless strong working women, some of whom believed in abortion rights, who had voted for Trump. Cultural cues could be misleading: I interviewed one gentle, hippieish Trump voter who wore his gray hair in a ponytail. An experience like leaving a small town for an Ivy League college, which might lead some people to embrace more liberal ideas, could inspire in others a deeper conservatism. And so I wasn’t entirely surprised to learn that Tyler Riehl, like me, was a former Peace Corps volunteer. He had served in Slovakia. “Every time you get to look at how somebody else lives, it gives you perspective that’s useful,” Riehl told me. In 2000, he was sent to a village in eastern Slovakia, where he advocated for bicyclists’ rights. Riehl told me that living in a post-Communist society strengthened his appreciation for freedom, truth, and the virtues of small government. Now he was applying that idealism to his current campaign. “I do unequivocally state that the Sentinel is full of fake news,” he said. Some residents found these attacks deeply misguided. “I think there’s a lot of emotion involved, and people are bringing opinions from the national debate into the local arena,” Bill Vrettos, a consultant with the Alternative Board, which advises businesses, told me. He described his politics as “radically middle-of-the-road,” and he didn’t believe that the Sentinel was slanted. In his opinion, a small-town newspaper plays a different role from that of a big publication, and he mentioned a recent incident in which two high-school students had killed themselves within a twenty-four-hour period. Before the Sentinel reported anything, Seaton, the publisher, had organized a meeting with school officials, mental-health experts, a suicide task force, and the father of a boy who had killed himself. The experts warned about copycat suicides, so the newspaper kept the deaths off the front page. I met with Seaton at the Sentinel’s downtown office, where a conference-room wall is decorated with two framed front pages that reported the news from historically tragic dates: September 11, 2001, and May 2, 1982. The building has a three-level Goss printing press that is capable of turning out a hundred and fifty thousand issues per hour, because it was purchased in the early eighties, when people once again thought the oil-shale industry was about to take off. The current circulation is around twenty-five thousand. Seaton is from a Kansas-based family that owns eight newspapers around the Midwest; in 2009, they acquired the Sentinel. “I come from a long line of Republicans,” he told me. “My great-uncle served in Eisenhower’s Cabinet as Interior Secretary.” But he admitted that he finds it increasingly difficult to reconcile himself to today’s conservative movement. “The Party is too accommodating of elements that I would consider fringe, bordering on hate groups,” he said. Seaton formerly worked as a corporate lawyer, and he believed that he had a valid case of defamation against Ray Scott. But he had decided not to proceed with a lawsuit. He worried that Trump uses the term “fake news” so often that its interpretation might change by the time a case reached judgment. “Maybe those words have lost their objective meaning,” Seaton said. During the election season, it’s common for some people to cancel their subscriptions, but last year the Sentinel lost more of them than usual. That’s one of the ironies of the age: the New York Times and the Washington Post, which Trump often attacks by name, have gained subscribers and public standing, while a small institution like the Sentinel has been damaged within its community. Seaton didn’t know how to handle the fake-news accusations, although he had considered inviting Tyler Riehl to shadow a reporter for a day. He had also thought about doubling the reward for local media malfeasance. That five hundred dollars still hasn’t been claimed.
In the past eight months, I have never heard anybody express regret for voting for Donald Trump. If anything, investigations into the Trump campaign’s connections with Russia have made supporters only more faithful. “I’m loving it—I hope they keep going down the Russia rabbit hole,” Matt Patterson told me, in June. He believes that Democrats are banking on an impeachment instead of doing the hard work of trying to connect with voters. “They didn’t even get rid of their leadership after the election,” he said. But Trump’s connection with supporters also involves a great risk. Many Presidential acts that feel satisfying—the unfiltered insults, the attacks on institutions—also make it difficult to achieve anything practical and positive. And the resulting legislative failures typically inspire more emotion. In late June, after the Senate delayed a vote on the health-care bill, Trump embarked on a Twitter spree, labelling various organizations fake news and claiming that Mika Brzezinski, the MSNBC host, had recently had a facelift that left her bleeding in public. Excuses are naturally built into this toxic cycle. Supporters can always say that Trump was never given a chance, and that the media, the Russia investigation, and other conspiracies have worked against him. In such a climate, it’s difficult to prove incompetence: true pragmatism would be quick and dirty, but emotional cycles can be sustained for much longer. I find it easy to imagine myself at a rally in 2020, standing in a pen while people scream at me. Smaller places may also be particularly vulnerable to the President’s negative tone, which makes it harder to find practical solutions to local problems. In Grand Junction, the average age of a school building is forty-four years, and the district is ranked a hundred and seventy-first out of a hundred and seventy-eight in the state, in terms of funding per student. Property taxes, which fund the schools, are among the lowest of Colorado cities. In November, two measures that would increase school funding will be on the ballot, but the last time such a proposal came to a vote, in 2011, it was rejected. Voters have also not approved an increase in the sales tax since 1989. The next ballot will propose a rise of about a third of one per cent, in order to fund local law enforcement and public-safety services. Even as crime has risen, resources have dropped; the county currently has 1.15 deputies per thousand residents, in comparison with a state average of 2.28. Police departments are so understaffed that many areas aren’t patrolled. “They just bounce from service call to service call,” Daniel Rubinstein, the Republican district attorney, told me. Approximately fourteen per cent of the population is Hispanic, although that figure would be higher if it included undocumented immigrants. When I asked Rubinstein about people who don’t have legal status, he said, “That’s never been a significant proportion of our crime problem.” Trump supporters also seemed to understand this. I never heard anybody blame Hispanics for local crime, or make racist remarks about them; it was much more common to encounter Islamophobia, although the nearest mosque is about four hours away. In a climate of intense distrust of government, it will be particularly difficult to persuade voters to approve new funding. Some residents told me that they want further cuts in education—even in the high desert they were determined to drain the swamp. But there are long-term costs to this mentality. One bright spot in the economy has been the growth of Colorado Mesa University, the largest institution of higher education on the Western Slope, but it’s hard to become a true college town when public schools are so badly underfunded. In June, at an economic conference at the university, I met Erik Valk, the founder of Principelle, a Dutch company that manufactures medical devices. Valk was thinking about opening a production center in Grand Junction, because he loved the natural setting, but he was concerned that the culture might be too inward-looking. “I’m trying to discover if there is a trend in this direction—whether they want to open to the world,” Valk said. “I spoke with the sheriff this morning and he has a funding problem, and he has a crime problem.” One person told me half in jest that the best way to get voters to approve new funding would be to blame everything on a lack of support by Denver élites: a tax increase in the guise of rugged self-reliance. “It’s about creating an us-versus-them victim narrative,” he said. He was being cynical, but he was also acknowledging the power of perspective and feeling. This seems to be the weakness of the Democratic Party, which often gives people the impression that they are being informed of their logical best interests. On the other side, people feel ignored or insulted—this was why they responded so strongly to Clinton’s use of the term “deplorables.” “What she said was, ‘If you don’t vote for me, you’re morally unworthy to talk to, to take seriously,’ ” Patterson told me. In Grand Junction, it was often dispiriting to see such enthusiasm for a figure who could become the ultimate political boom-and-bust. There was idealism, too, and so many pro-Trump opinions were the fruit of powerful and legitimate life experiences. “We just assume that if someone voted for Trump that they’re racist and uneducated,” Jeriel Brammeier, the twenty-six-year-old chair of the local Democratic Party, told me. “We can’t think about it like that.” People have reasons for the things that they believe, and the intensity of their experiences can’t be taken for granted; it’s not simply a matter of having Fox News on in the background. But perhaps this is a way to distinguish between the President and his supporters. Almost everybody I met in Grand Junction seemed more complex, more interesting, and more decent than the man who inspires them. During my conversation with Brammeier, I asked why she had entered politics. “I got pregnant when I was sixteen,” she said. Grand Junction has a high teen-pregnancy rate, and Brammeier had been one of eight girls, out of about two hundred in her twelfth-grade year, who had babies. The town has no Planned Parenthood clinic or designated abortion provider, and in 2015, for reasons both fiscal and ideological, the Republican-controlled state senate voted down a bill that would have provided funding for an effective state-wide contraception program. “Our state senator Ray Scott voted to defund it,” Brammeier said. Private funds filled the gap until last year, when it was included in the state budget. Brammeier told me that she wants to improve the community for her daughter: “She was on my back when she was three months old, and I was canvassing for Obama.” Who could stand before this woman and deny the power of her experience? But that was true on both sides; there were many hard-earned faiths in Grand Junction.
|
Q:
Discerning between in a way that, in such a way that, and in doing so?
Would any one possibly show me what is the exact difference between these, taking example?
As I am not a native speaker, and I am learning English, especially in such circumstance, I couldn't think of any situation or sentence to clarify the. They are too complex for me.
in doing so
in such a way that
in a way that
A:
It might help to realize that these are not merely stock phrases, but are productive forms.
The pattern "In [verb]ing, [result]" means that by taking a certain action, a person achieves a particular result. The construction defines the result or the meaning of the action. "In doing so" is a particularly generic example. But it applies to plenty of other verbs. For example, the rules of chess say that if you touch a piece, you have to move that piece. So a person describing these rules could say that "In touching a piece, you force yourself to move that piece next." Or another example from this article: "In making this statement, it is the mother's intent to not comment at this time". This is trying to control the meaning of her action: she states what she is doing, and then the result that she intends for it to have. (Or, in this case, not have.) "In writing a book which is so different from his previous successes, the author is taking a big risk." If it is already understood from context, I could replace "In writing a book which is so different from his previous successes" with "In doing so". (This is just an example of using "doing so" to replace a longer verb phrase; you can interpret this "so" as meaning "that thing I just said".)
The "In [verbing]" constructions frequently take the form of performatives: "In riding this roller coaster, you agree to accept all responsibility for any injuries which you receive." My making that statement affects the legal reality: by defining the meaning of your action, I've turned a basic action into acceptance of a contract.
"In such a way that" is similar to "In [verb]ing", in that it's trying to describe the result of the verb which comes before it. However, this one is more of a stock phrase. It doesn't involve a changing component the way "In [verb]ing" does (with the verb). Here the pattern is something like "[verb phrase] in such a way that [result]". Going back to chess again, an example could be "He moved his knight in such a way that I would lose either my bishop or my queen." Or "He wrote his name in such a way that no one could read it." Some people consider this a less favorable construction than the one above, because it uses more words to mean the same thing. Then again, sometimes people don't want to be concise!
"In a way that" is more general in application: it is not restricted to describing the result of an action, but merely the manner in which it was done. So you could say "He wrote his name in a way that no one could read" (this doesn't specifically indicate the result, it's purely descriptive) or "He whistled in a way that I'd never seen before" (which is absolutely not describing the result of his decision).
Hopefully these will seem more comfortable or more familiar with more practice.
|
<filename>src/test/java/com/google/security/zynamics/binnavi/disassembly/AddressSpaces/CAddressSpaceTest.java
/*
Copyright 2014 Google Inc. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package com.google.security.zynamics.binnavi.disassembly.AddressSpaces;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.fail;
import com.google.security.zynamics.binnavi.Database.Exceptions.CouldntLoadDataException;
import com.google.security.zynamics.binnavi.Database.Exceptions.CouldntSaveDataException;
import com.google.security.zynamics.binnavi.Database.Exceptions.LoadCancelledException;
import com.google.security.zynamics.binnavi.Database.MockClasses.MockSqlProvider;
import com.google.security.zynamics.binnavi.debug.debugger.DebuggerTemplate;
import com.google.security.zynamics.binnavi.disassembly.AddressSpaces.CAddressSpace;
import com.google.security.zynamics.binnavi.disassembly.INaviModule;
import com.google.security.zynamics.binnavi.disassembly.MockCreator;
import com.google.security.zynamics.binnavi.disassembly.MockProject;
import com.google.security.zynamics.zylib.disassembly.IAddress;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
import java.util.Date;
import java.util.HashMap;
@RunWith(JUnit4.class)
public final class CAddressSpaceTest {
private CAddressSpace m_addressSpace;
private final MockAddressSpaceConfigurationListener m_listener =
new MockAddressSpaceConfigurationListener();
private MockSqlProvider m_sql;
@Before
public void setUp() {
m_sql = new MockSqlProvider();
m_addressSpace = MockCreator.createAddressSpace(m_sql);
m_addressSpace.getConfiguration().addListener(m_listener);
}
@Test
public void test_C_Constructors() {
final MockSqlProvider sql = new MockSqlProvider();
try {
new CAddressSpace(0, "AS Name", "AS Description", new Date(), new Date(),
new HashMap<INaviModule, IAddress>(), null, sql, new MockProject());
fail();
} catch (final Exception exception) {
}
try {
new CAddressSpace(1, null, "AS Description", new Date(), new Date(),
new HashMap<INaviModule, IAddress>(), null, sql, new MockProject());
fail();
} catch (final Exception exception) {
}
try {
new CAddressSpace(1, "AS Name", null, new Date(), new Date(),
new HashMap<INaviModule, IAddress>(), null, sql, new MockProject());
fail();
} catch (final Exception exception) {
}
try {
new CAddressSpace(1, "AS Name", "AS Description", null, new Date(),
new HashMap<INaviModule, IAddress>(), null, sql, new MockProject());
fail();
} catch (final Exception exception) {
}
try {
new CAddressSpace(1, "AS Name", "AS Description", new Date(), null,
new HashMap<INaviModule, IAddress>(), null, sql, new MockProject());
fail();
} catch (final Exception exception) {
}
try {
new CAddressSpace(1, "AS Name", "AS Description", new Date(), new Date(), null, null, sql,
new MockProject());
fail();
} catch (final Exception exception) {
}
try {
new CAddressSpace(1, "AS Name", "AS Description", new Date(), new Date(),
new HashMap<INaviModule, IAddress>(), null, null, new MockProject());
fail();
} catch (final Exception exception) {
}
final CAddressSpace addressSpace =
new CAddressSpace(1, "AS Name", "AS Description", new Date(), new Date(),
new HashMap<INaviModule, IAddress>(), null, sql, new MockProject());
assertEquals(1, addressSpace.getConfiguration().getId());
assertEquals("AS Name", addressSpace.getConfiguration().getName());
assertEquals("AS Description", addressSpace.getConfiguration().getDescription());
}
@Test
public void testDebugger() throws CouldntSaveDataException, CouldntLoadDataException,
LoadCancelledException {
assertNull(m_addressSpace.getConfiguration().getDebugger());
assertNull(m_addressSpace.getConfiguration().getDebuggerTemplate());
final DebuggerTemplate template = MockCreator.createDebuggerTemplate(m_sql);
m_addressSpace.getConfiguration().setDebuggerTemplate(template);
assertNull(m_addressSpace.getConfiguration().getDebugger());
assertEquals(template, m_addressSpace.getConfiguration().getDebuggerTemplate());
m_addressSpace.load();
assertNotNull(m_addressSpace.getConfiguration().getDebugger());
assertEquals(template, m_addressSpace.getConfiguration().getDebuggerTemplate());
m_addressSpace.getConfiguration().setDebuggerTemplate(null);
assertNull(m_addressSpace.getConfiguration().getDebugger());
assertNull(m_addressSpace.getConfiguration().getDebuggerTemplate());
}
@Test
public void testSetDescription() throws CouldntSaveDataException {
try {
m_addressSpace.getConfiguration().setDescription(null);
fail();
} catch (final NullPointerException exception) {
}
m_addressSpace.getConfiguration().setDescription("New Description");
// Check listener events
assertEquals("changedDescription;changedModificationDate;", m_listener.events);
// Check address space
assertEquals("New Description", m_addressSpace.getConfiguration().getDescription());
m_addressSpace.getConfiguration().setDescription("New Description");
// Check listener events
assertEquals("changedDescription;changedModificationDate;", m_listener.events);
// Check address space
assertEquals("New Description", m_addressSpace.getConfiguration().getDescription());
}
@Test
public void testSetName() throws CouldntSaveDataException {
try {
m_addressSpace.getConfiguration().setName(null);
fail();
} catch (final NullPointerException exception) {
}
m_addressSpace.getConfiguration().setName("New Name");
// Check listener events
assertEquals("changedName;changedModificationDate;", m_listener.events);
// Check address space
assertEquals("New Name", m_addressSpace.getConfiguration().getName());
m_addressSpace.getConfiguration().setName("New Name");
// Check listener events
assertEquals("changedName;changedModificationDate;", m_listener.events);
// Check address space
assertEquals("New Name", m_addressSpace.getConfiguration().getName());
}
}
|
Q:
What's the canonical definition of end of the buddha sāsana?
I was under the impression that the end of buddha sāsana occurs when noble eight-fold path(and the dhamma practitioners) disappear form all the realms including Śuddhāvāsa where only anāgāmins live. This contradicts with Ghatikara sutta. It consists of a lord buddha's conversion with an anāgāmi brahma Ghatikara form Kashyapa buddha sāsana. That means at least anāgāmins and arahants from previous buddhas might still live in arupa brahma realms.
Did anyone come across a canonical reference for end of buddha sāsana?
A:
I was under the impression that the end of buddha sāsana occurs when noble eight-fold path(and the dhamma practitioners) disappear form all the realms including Śuddhāvāsa where only anāgāmins live.
Imagine a school where only music prodigies or math prodigies attend, one would never have to worry about the decay of the school's reputation. The Pure Abodes are also like that. Since it's a realm where Non-Returners reside, it'll never face the problem of Dhamma decline there. Earthlings on the other hands, are much more inclined towards sensual pleasures and many other unwholesome deeds. It's the Dhamma on earth that's facing a serious danger of going into decline.
In SN 20.7, although the Buddha didn't give an exact number on the life span of the Dhamma, He did give the clear sign and cause to its disappearance:
"...In the same way, in the course of the future there will be monks who won't listen when discourses that are words of the Tathagata — deep, deep in their meaning, transcendent, connected with emptiness — are being recited. They won't lend ear, won't set their hearts on knowing them, won't regard these teachings as worth grasping or mastering. But they will listen when discourses that are literary works — the works of poets, elegant in sound, elegant in rhetoric, the work of outsiders, words of disciples — are recited. They will lend ear and set their hearts on knowing them. They will regard these teachings as worth grasping & mastering.
"In this way the disappearance of the discourses that are words of the Tathagata — deep, deep in their meaning, transcendent, connected with emptiness — will come about.
|
<reponame>josehu07/SplitFS<gh_stars>10-100
// SPDX-License-Identifier: GPL-2.0-only
/*
* arch/sh/mm/kmap.c
*
* Copyright (C) 1999, 2000, 2002 <NAME>
* Copyright (C) 2002 - 2009 <NAME>
*/
#include <linux/mm.h>
#include <linux/init.h>
#include <linux/mutex.h>
#include <linux/fs.h>
#include <linux/highmem.h>
#include <linux/module.h>
#include <asm/mmu_context.h>
#include <asm/cacheflush.h>
#define kmap_get_fixmap_pte(vaddr) \
pte_offset_kernel(pmd_offset(pud_offset(pgd_offset_k(vaddr), (vaddr)), (vaddr)), (vaddr))
static pte_t *kmap_coherent_pte;
void __init kmap_coherent_init(void)
{
unsigned long vaddr;
/* cache the first coherent kmap pte */
vaddr = __fix_to_virt(FIX_CMAP_BEGIN);
kmap_coherent_pte = kmap_get_fixmap_pte(vaddr);
}
void *kmap_coherent(struct page *page, unsigned long addr)
{
enum fixed_addresses idx;
unsigned long vaddr;
BUG_ON(!test_bit(PG_dcache_clean, &page->flags));
preempt_disable();
pagefault_disable();
idx = FIX_CMAP_END -
(((addr >> PAGE_SHIFT) & (FIX_N_COLOURS - 1)) +
(FIX_N_COLOURS * smp_processor_id()));
vaddr = __fix_to_virt(idx);
BUG_ON(!pte_none(*(kmap_coherent_pte - idx)));
set_pte(kmap_coherent_pte - idx, mk_pte(page, PAGE_KERNEL));
return (void *)vaddr;
}
void kunmap_coherent(void *kvaddr)
{
if (kvaddr >= (void *)FIXADDR_START) {
unsigned long vaddr = (unsigned long)kvaddr & PAGE_MASK;
enum fixed_addresses idx = __virt_to_fix(vaddr);
/* XXX.. Kill this later, here for sanity at the moment.. */
__flush_purge_region((void *)vaddr, PAGE_SIZE);
pte_clear(&init_mm, vaddr, kmap_coherent_pte - idx);
local_flush_tlb_one(get_asid(), vaddr);
}
pagefault_enable();
preempt_enable();
}
|
Q:
Sony ICLA68 Preview Degrades in Quality after a second
I have had my Sony ICLA-68 for about a year now. I have always had problems with the images not coming out clear. I notice this when I am taking any kind of photo wither it be landscape, people, or light painting, the image I am seeing through the view finder or the LCD looks fine but after I take the photo the image becomes blurry and or soft. I notice it the most when I am taking macro shots. I use a tripod with a pluto trigger so I am not introducing any vibrations to the camera when the photo is being taken. Yet the images still come out bury.
For almost a year now I thought it was user error but recently I enabled the photo preview setting where it shows you the photo you took after you take it. I have noticed that the image I am seeing looks fantastic but then after about a second the image quality sharply degrades. As you can see in this video I took
I noticed that when the image degrades the SD card light turns off. At first I figured it was because I was saving to a standard quality jpeg so I switched over to using Raw images instead but I still have this problem where the quality is lacking compared to what I saw through the view finder.
I thought this might have something to do with me using a class 6 SD card so I tried using a better SD card thinking that it could be because I was not using a class 10 SD card. After I made the switch to a class 10 SD card I saw no difference.
I looked at this article and the accepted answer is because of vibrations being added to the photo when it has been taken which is not the case for me.
A:
As I think the linked answers aren't really duplicates, I want to give another answer here.
What you see before and after the exposure is taken directly from the sensor.
At this time the camera does not really know yet, how the image will look in the end.
The camera tries to apply all settings to the preview in EVF/LCD but this does not necessarily match the final result.
All effect on the image with respect to overall brightness, contrast, details, etc. are only an estimation done by the camera electronics.
After you took the image, the camera can read the real data from the sensor.
This time there is no need to estimate contrast etc. Now the values are fixed.
And now the created image can differ from the estimation you've seen before.
To improve speed the camera might prioritze writing into the file above showing the preview on the display. By doing this you are ready to fire again earlier.
On a side note: The same applies to lens correction if available.
Depending on your lens you can see the image be distorted after a while.
BTW: Did you enable or disable preview of "all effects" for the EVF? ;)
|
public class Test {
public static void main(String[] args) {
try {
Thread.sleep(5_000);
} catch (Exception e) {
e.printStackTrace();
}
int rc;
String exitCode = System.getenv("TEST_RC");
if (exitCode == null) {
rc = 10;
} else {
rc = Integer.parseInt(exitCode);
}
System.out.println("Exit with " + rc);
System.exit(rc);
}
}
|
from wip.naf_handler import inject_spacy, create_news_item_naf, write_naf, create_naf_from_item
import nl_core_news_sm
def test_load_naf_no_ext_refs():
"""reads a naf file and creates a news item"""
naf_file = 'tests/data/test_no_ext_refs.naf'
news_item = create_news_item_naf(naf_file)
assert news_item.identifier == 'example-news.html'
assert news_item.content == "onderkoopman <NAME> is in afwachting van werk naar Semarang gestuurd."
assert news_item.title is None
assert news_item.collection == 'newsreader-project'
assert news_item.dct == '2019-09-13T11:32:38+0200'
assert not news_item.gold_entity_mentions
assert len(news_item.sys_entity_mentions) == 2
entity = news_item.sys_entity_mentions[0]
assert entity.eid == 'e1'
assert entity.sentence == 1
assert entity.mention == "<NAME>"
assert entity.the_type == "PER"
assert entity.begin_index == 1
assert entity.end_index == 3
assert entity.begin_offset == 13
assert entity.end_offset == 32 # begin offset + length of last index (TODO check)
assert entity.identity is None
assert entity.tokens == ['t_1', 't_2', 't_3']
def test_load_naf_ext_refs():
"""reads a naf file and creates a news item"""
naf_file = 'tests/data/test_ext_refs.naf'
news_item = create_news_item_naf(naf_file)
assert news_item.identifier == 'wiki_1'
assert news_item.title == '"Crocodile Hunter" <NAME> omgekomen in Australië'
assert news_item.collection == 'wikinews2'
assert not news_item.gold_entity_mentions
assert len(news_item.sys_entity_mentions) == 25
entity = news_item.sys_entity_mentions[0]
assert entity.eid == 'e1'
assert entity.sentence == 1
assert entity.mention == '" Crocodile'
assert entity.the_type == "PER"
assert entity.begin_index == 1
assert entity.end_index == 2
assert entity.begin_offset == 0
assert entity.end_offset == 10
assert entity.identity == '0_3'
assert entity.tokens == ['t1', 't2']
def test_load_naf_empty_ext_refs():
naf_file = 'tests/data/test_empty_ext_ref.naf'
news_item = create_news_item_naf(naf_file)
entity = news_item.sys_entity_mentions[0]
assert entity.identity is None
def is_same_entity(e_spacy, e_mention):
return e_spacy.text == e_mention.mention \
and e_spacy.start_char == e_mention.begin_offset \
and e_spacy.end_char == e_mention.end_offset \
and e_spacy.label_ == e_mention.the_type
def test_spacy_entities():
naf_file = 'tests/data/test_ext_refs.naf'
news_item = create_news_item_naf(naf_file)
nl_nlp = nl_core_news_sm.load()
spacy_doc = nl_nlp(news_item.content)
assert len(spacy_doc.ents) == len(news_item.sys_entity_mentions)
assert spacy_doc.ents[0].text == "<NAME>"
naf = create_naf_from_item(news_item)
naf = inject_spacy(naf, spacy_doc)
naf_out = 'tests/data/test_ext_refs3.naf'
write_naf(naf, naf_out)
news_item2 = create_news_item_naf(naf_out)
assert news_item2.sys_entity_mentions[0].mention == "<NAME>"
assert is_same_entity(spacy_doc.ents[0], news_item2.sys_entity_mentions[0])
def test_naf2items2naf():
naf_file = 'tests/data/test_ext_refs.naf'
news_item = create_news_item_naf(naf_file)
out_naf = 'tests/data/test_ext_refs2.naf'
write_naf(create_naf_from_item(news_item), out_naf)
news_item2 = create_news_item_naf(out_naf)
assert news_item.has_same_header_and_content(news_item2)
|
Updating the Canadian obesity maps: an epidemic in progress. OBJECTIVES Obesity is a growing problem in Canada and worldwide. While obesity maps that convey changing rates over time and geography provide a useful way to convey such information, regional obesity surveillance maps for Canada have not been published since 1998. This research provides a summary of changing Canadian obesity rates since that time. METHODS We computed estimated obesity rates for provinces and territories across Canada from 2000 to 2011. Data were based on Canadian Community Health Survey and corrected for self-report bias. Data reporting the estimated percent of the adult population who are obese were mapped over time overall and by sex according to Canadian province and territory. RESULTS The data indicate that the estimated prevalence of obesity across Canada has continued to increase over the past 11 years. Current rates exceed 30% in the Maritime provinces (Newfoundland, New Brunswick, Nova Scotia, Prince Edward Island) and in two territories (Northwest Territory, Nunavut). Data for men and women are generally consistent. The major increase in obesity appears to have occurred in the first part of this period, with relatively stable rates found from 2008 to 2011. However, obesity rates are still climbing, warranting continued surveillance efforts. CONCLUSION Maps showing changing regional obesity rates provide a compelling pan-Canadian portrait that can lead to an impetus for action for the public, health care providers, and decision makers. Such colour-coded maps offer an efficient way to convey complex data that transcends language differences and personalizes the data for the viewer.
|
The NFL is partnering with Boston University brain researchers who have been critical of the league's stance on concussions, The Associated Press learned Sunday.
The league now plans to encourage current and former NFL players to agree to donate their brains to the Boston University Center for the Study of Traumatic Encephalopathy, which has said it found links between repeated head trauma and brain damage in boxers, football players and, most recently, a former NHL player.
"It's huge that the NFL actively gets behind this research," said Robert Cantu, a co-director of the BU center who has spoken negatively about the league in the past. "It forwards the research. It allows players to realize the NFL is concerned about the possibility that they could have this problem, and that the NFL is doing everything it can to find out about the risks and the preventive strategies that can be implemented."
NFL spokesman Greg Aiello told the AP on Sunday that the league also is committed to giving $1 million or more to the center.
"The precise amount hasn't been determined," Aiello said. "We will discuss it with them. It depends on their needs. We are committed to funding research" on brain injuries.
Robert Stern, an associate professor of neurology at the Boston University School of Medicine and one of Cantu's co-directors of the center, said the group is pleased that the NFL is playing a role.
"Although we discussed with the NFL how they might facilitate players' participation in our research into the long-term effects of repetitive head trauma in athletes, we did not request financial support to avoid any real or perceived conflict of interest," Stern said in a statement issued Sunday. "Any financial support from the NFL would need to be free of any real or perceived conflict of interest."
The BU group and the NFL Players Association jointly announced that the union also will work with the center and encourage players to participate in brain studies.
Stern noted that the league and union's support will allow research to "move at a much needed faster pace."
Aiello said the league already has held discussions with the NFL Alumni Association about suggesting that retired players look into participating in BU's work by offering their brains for study after they die.
The league also will contact the nearly 100 retired football players who have been diagnosed with Alzheimer's or dementia and are receiving benefits from the league to ask their families to consider donating those players' brains to the BU study.
Cantu noted that three current NFL players — Cardinals wide receiver Sean Morey, Ravens center Matt Birk, and Seahawks linebacker Lofa Tatupu — already agreed to donate their brains for research after death.
"The people affiliated with the center have identified the donation of brains, both from healthy people and those that have had multiple concussions, as their most critical need right now to further the research into this disease," Aiello said. "We ... will discuss with the center its research needs as we go forward in this partnership."
Cantu said he and NFL commissioner Roger Goodell met in October to discuss concussions and the BU project.
Sunday's news represents the latest in a series of moves the NFL has made in recent weeks to step up its attention to concussions in the aftermath of a congressional hearing on the topic and as high-profile players such as Ben Roethlisberger, Kurt Warner, Clinton Portis and Brian Westbrook have been sidelined by head injuries this season.
The league's steps included stricter return-to-play guidelines detailing what symptoms preclude someone from participating in games or practices; a mandate that each team select a league- and union-approved independent neurologist to be consulted when players get concussions; and the departure of the two co-chairmen of the NFL's committee on brain trauma.
"They have done a bit of an about-face. Pressure probably has played a role in that," Cantu said in a telephone interview. "But I honestly think that Goodell does believe in player safety and the product is just better with your best players on the field, not your best players injured."
Aiello said Sunday that a concussion study the league has been conducting since 2007 is on hold until the former committee co-chairmen — Ira Casson and David Viano — are replaced. They resigned last month. He said the league is interviewing candidates, none of whom is currently affiliated with the league or any team.
"Now that we're changing the committee, we want to make some revisions in how the study proceeds," Aiello said in a telephone interview.
The New York Times first reported that the study is on hold.
Casson is slated to testify at a House Judiciary Committee hearing Jan. 4 about football head injuries. He did not attend the panel's hearing Oct. 28, when BU's Cantu said there is "growing and convincing evidence" that repetitive concussive and subconcussive hits to the head in NFL players leads to a degenerative brain disease.
Another co-director of the BU center, Ann McKee, showed the committee images of brains of dead football players with the disease and told lawmakers, "We need to take radical steps" to change the way football is played.
|
<filename>pkg/controller/codebase/service/chain/put_jenkins_folder_cr_test.go<gh_stars>0
package chain
import (
"context"
"strings"
"testing"
"github.com/epam/edp-codebase-operator/v2/pkg/apis/edp/v1alpha1"
"github.com/epam/edp-codebase-operator/v2/pkg/util"
jenkinsv1alpha1 "github.com/epam/edp-jenkins-operator/v2/pkg/apis/v2/v1alpha1"
"github.com/epam/edp-jenkins-operator/v2/pkg/util/consts"
"github.com/stretchr/testify/assert"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/runtime"
"k8s.io/apimachinery/pkg/types"
"sigs.k8s.io/controller-runtime/pkg/client/fake"
)
func TestPutJenkinsFolder_ShouldCreateJenkinsfolder(t *testing.T) {
c := &v1alpha1.Codebase{
ObjectMeta: metav1.ObjectMeta{
Name: fakeName,
Namespace: fakeNamespace,
},
Spec: v1alpha1.CodebaseSpec{
BuildTool: "Maven",
GitServer: fakeName,
JobProvisioning: util.GetStringP("ci"),
Strategy: v1alpha1.Clone,
Repository: &v1alpha1.Repository{
Url: "https://example.com",
},
},
}
gs := &v1alpha1.GitServer{
ObjectMeta: metav1.ObjectMeta{
Name: fakeName,
Namespace: fakeNamespace,
},
Spec: v1alpha1.GitServerSpec{
NameSshKeySecret: fakeName,
GitHost: fakeName,
SshPort: 22,
GitUser: fakeName,
},
}
jf := &jenkinsv1alpha1.JenkinsFolder{}
scheme := runtime.NewScheme()
scheme.AddKnownTypes(v1alpha1.SchemeGroupVersion, c, gs, jf)
fakeCl := fake.NewClientBuilder().WithScheme(scheme).WithRuntimeObjects(c, gs, jf).Build()
pjf := PutJenkinsFolder{
client: fakeCl,
}
if err := pjf.ServeRequest(c); err != nil {
t.Error("ServeRequest failed for PutJenkinsFolder")
}
gjf := &jenkinsv1alpha1.JenkinsFolder{}
if err := fakeCl.Get(context.TODO(),
types.NamespacedName{
Name: "fake-name-codebase",
Namespace: fakeNamespace,
},
gjf); err != nil {
t.Error("Unable to get JenkinsFolder")
}
assert.Equal(t, gjf.Spec.Job.Name, "job-provisions/job/ci/job/ci")
}
func TestPutJenkinsFolder_ShouldSkipWhenJenkinsfolderExists(t *testing.T) {
c := &v1alpha1.Codebase{
ObjectMeta: metav1.ObjectMeta{
Name: fakeName,
Namespace: fakeNamespace,
},
}
jf := &jenkinsv1alpha1.JenkinsFolder{
ObjectMeta: metav1.ObjectMeta{
Name: "fake-name-codebase",
Namespace: fakeNamespace,
},
}
scheme := runtime.NewScheme()
scheme.AddKnownTypes(v1alpha1.SchemeGroupVersion, c, jf)
fakeCl := fake.NewClientBuilder().WithScheme(scheme).WithRuntimeObjects(c, jf).Build()
pjf := PutJenkinsFolder{
client: fakeCl,
}
if err := pjf.ServeRequest(c); err != nil {
t.Error("ServeRequest failed for PutJenkinsFolder")
}
}
func TestPutJenkinsFolder_ShouldFailWhenGetJenkinsfolder(t *testing.T) {
c := &v1alpha1.Codebase{
ObjectMeta: metav1.ObjectMeta{
Name: fakeName,
Namespace: fakeNamespace,
},
}
scheme := runtime.NewScheme()
scheme.AddKnownTypes(v1alpha1.SchemeGroupVersion, c)
fakeCl := fake.NewClientBuilder().WithScheme(scheme).WithRuntimeObjects(c).Build()
pjf := PutJenkinsFolder{
client: fakeCl,
}
if err := pjf.ServeRequest(c); err == nil {
t.Error("ServeRequest must fail because kind JenkinsFolder is not registered")
}
}
func TestPutJenkinsFolder_ShouldFailWhenGetGitServer(t *testing.T) {
c := &v1alpha1.Codebase{
ObjectMeta: metav1.ObjectMeta{
Name: fakeName,
Namespace: fakeNamespace,
},
Spec: v1alpha1.CodebaseSpec{
GitServer: fakeName,
},
}
jf := &jenkinsv1alpha1.JenkinsFolder{}
scheme := runtime.NewScheme()
scheme.AddKnownTypes(v1alpha1.SchemeGroupVersion, c, jf)
fakeCl := fake.NewClientBuilder().WithScheme(scheme).WithRuntimeObjects(c, jf).Build()
pjf := PutJenkinsFolder{
client: fakeCl,
}
err := pjf.ServeRequest(c)
assert.Error(t, err)
if !strings.Contains(err.Error(), "an error has occurred while getting fake-name Git Server CR") {
t.Fatalf("wrong error returned: %s", err.Error())
}
}
func Test_getRepositoryPath(t *testing.T) {
type args struct {
codebaseName string
strategy string
gitUrlPath *string
}
tests := []struct {
name string
args args
want string
}{
{"Import strategy", args{"codebase-name", consts.ImportStrategy, util.GetStringP("url")}, "url"},
{"Clone strategy", args{"codebase-name", string(v1alpha1.Clone), util.GetStringP("url")}, "/codebase-name"},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
if got := getRepositoryPath(tt.args.codebaseName, tt.args.strategy, tt.args.gitUrlPath); got != tt.want {
t.Errorf("getRepositoryPath() = %v, want %v", got, tt.want)
}
})
}
}
|
An osmium-free method of epon embedment that preserves both ultrastructure and antigenicity for post-embedding immunocytochemistry. Immunocytochemistry for amino acids with post-embedding gold is compatible with glutaraldehyde fixation, osmication, and embedding in epoxy-based plastics, but immunogold detection of larger molecules in the central nervous system commonly requires special procedures, e.g. minimizing exposure to glutaraldehyde, eliminating osmium, cryosectioning, and/or embedding in acrylic plastics. These make samples more difficult to prepare and view and may compromise structural preservation. We report a new technique, fixing with high levels of glutaraldehyde, replacing osmium with tannic acid followed by other heavy metals and p-phenylenediamine, and embedding in Epon. This method optimizes antigenicity while retaining the structural preservation and convenient handling of standard embedding techniques. Compared to standard Epon embedment, labeling for neuropeptides in brain and spinal cord is improved. Moreover, the present method yields excellent labeling of glutamate receptors (difficult to identify with traditional post-embedding techniques) and enables simultaneous visualization of associated neurotransmitters.
|
/*
* Copyright 2014, General Dynamics C4 Systems
*
* This software may be distributed and modified according to the terms of
* the GNU General Public License version 2. Note that NO WARRANTY is provided.
* See "LICENSE_GPLv2.txt" for details.
*
* @TAG(GD_GPL)
*/
#include <config.h>
#include <machine/io.h>
#include <arch/machine.h>
#include <arch/kernel/apic.h>
#include <linker.h>
#include <plat/machine/devices.h>
#include <plat/machine/pit.h>
static BOOT_CODE uint32_t
apic_measure_freq(void)
{
pit_init();
/* wait for 1st PIT wraparound */
pit_wait_wraparound();
/* start APIC timer countdown */
apic_write_reg(APIC_TIMER_DIVIDE, 0xb); /* divisor = 1 */
apic_write_reg(APIC_TIMER_COUNT, 0xffffffff);
/* wait for 2nd PIT wraparound */
pit_wait_wraparound();
/* calculate APIC/bus cycles per ms = frequency in kHz */
return (0xffffffff - apic_read_reg(APIC_TIMER_CURRENT)) / PIT_WRAPAROUND_MS;
}
BOOT_CODE paddr_t
apic_get_base_paddr(void)
{
apic_base_msr_t apic_base_msr;
apic_base_msr.words[0] = x86_rdmsr_low(IA32_APIC_BASE_MSR);
return apic_base_msr_get_base_addr(apic_base_msr);
}
BOOT_CODE bool_t
apic_init(bool_t mask_legacy_irqs)
{
apic_version_t apic_version;
uint32_t num_lvt_entries;
uint32_t apic_khz;
if (!apic_enable()) {
return false;
}
apic_khz = apic_measure_freq();
apic_version.words[0] = apic_read_reg(APIC_VERSION);
/* check for correct version (both APIC and x2APIC): 0x1X */
if (apic_version_get_version(apic_version) >> 4 != 1) {
printf("APIC: apic_version must be 0x1X\n");
return false;
}
/* check for correct number of LVT entries */
num_lvt_entries = apic_version_get_max_lvt_entry(apic_version) + 1;
if (num_lvt_entries < 3) {
printf("APIC: number of LVT entries: %d\n", num_lvt_entries);
printf("APIC: number of LVT entries must be >= 3\n");
return false;
}
/* initialise APIC timer */
apic_write_reg(APIC_TIMER_DIVIDE, 0xb); /* divisor = 1 */
apic_write_reg(APIC_TIMER_COUNT, apic_khz * CONFIG_TIMER_TICK_MS);
/* enable APIC using SVR register */
apic_write_reg(
APIC_SVR,
apic_svr_new(
0, /* focus_processor_chk */
1, /* enabled */
int_spurious /* spurious_vector */
).words[0]
);
/* mask/unmask LINT0 (used for legacy IRQ delivery) */
apic_write_reg(
APIC_LVT_LINT0,
apic_lvt_new(
0, /* timer_mode */
mask_legacy_irqs, /* masked */
0, /* trigger_mode */
0, /* remote_irr */
0, /* pin_polarity */
0, /* delivery_status */
7, /* delivery_mode */
0 /* vector */
).words[0]
);
/* mask LINT1 (used for NMI delivery) */
apic_write_reg(
APIC_LVT_LINT1,
apic_lvt_new(
0, /* timer_mode */
1, /* masked */
0, /* trigger_mode */
0, /* remote_irr */
0, /* pin_polarity */
0, /* delivery_status */
0, /* delivery_mode */
0 /* vector */
).words[0]
);
/* initialise timer */
apic_write_reg(
APIC_LVT_TIMER,
apic_lvt_new(
1, /* timer_mode */
0, /* masked */
0, /* trigger_mode */
0, /* remote_irr */
0, /* pin_polarity */
0, /* delivery_status */
0, /* delivery_mode */
int_timer /* vector */
).words[0]
);
/*
printf("APIC: ID=0x%x\n", apic_read_reg(APIC_ID) >> 24);
printf("APIC: SVR=0x%x\n", apic_read_reg(APIC_SVR));
printf("APIC: LVT_TIMER=0x%x\n", apic_read_reg(APIC_LVT_TIMER));
printf("APIC: LVT_LINT0=0x%x\n", apic_read_reg(APIC_LVT_LINT0));
printf("APIC: LVT_LINT1=0x%x\n", apic_read_reg(APIC_LVT_LINT1));
printf("APIC: LVT_ERROR=0x%x\n", apic_read_reg(APIC_LVT_ERROR));
printf("APIC: LVT_PERF_CNTR=0x%x\n", apic_read_reg(APIC_LVT_PERF_CNTR));
printf("APIC: LVT_THERMAL=0x%x\n", apic_read_reg(APIC_LVT_THERMAL));
*/
return true;
}
void apic_ack_active_interrupt(void)
{
apic_write_reg(APIC_EOI, 0);
}
|
import os
from django.core.urlresolvers import reverse
from estofadora.client.tests import create_client
from . import (
TestBase, ItemForm, create_item, Item, make_validated_item_form,
make_managementform_data, PATH_TO_IMAGE_TEST, Picture, create_picture,
ItemPictureForm, make_validated_item_picture_form,
PictureForm
)
class AddViewTest(TestBase):
def setUp(self):
self.login()
self.url = reverse('item:add')
self.response = self.client.get(self.url)
def test_get(self):
self.assertEqual(self.response.status_code, 200)
def test_get_logout(self):
self._test_get_logout(self.url)
def test_template(self):
self.assertTemplateUsed(self.response, 'item/add.html')
def test_if_has_forms(self):
item_picture_form = self.response.context['item_picture_form']
self.assertIsInstance(item_picture_form, ItemPictureForm)
def test_html(self):
self.assertContains(self.response, '<form')
self.assertContains(self.response, '<input', 7)
self.assertContains(self.response, 'type="submit"')
def test_csrf(self):
self.assertContains(self.response, 'csrfmiddlewaretoken')
class AddPostWithoutImageTest(TestBase):
"""
Test post without images.
"""
def setUp(self):
self.login()
data = make_validated_item_picture_form(commit=False)
self.response = self.client.post(reverse('item:add'), data)
def test_message(self):
self.assertContains(self.response, 'Item cadastrado com sucesso!')
def test_if_saved(self):
self.assertTrue(Item.objects.exists())
class AddPostWithImageTest(TestBase):
"""
Test post with image.
"""
def setUp(self):
self.login()
data = make_validated_item_picture_form(commit=False)
with open(PATH_TO_IMAGE_TEST, 'rb') as img:
data['files'] = img
self.response = self.client.post(reverse('item:add'), data)
def test_message(self):
self.assertContains(self.response, 'Item cadastrado com sucesso!')
def test_if_saved(self):
self.assertEqual(len(Item.objects.all()), 1)
self.assertEqual(len(Picture.objects.all()), 1)
class AddInvalidItemPostTest(TestBase):
def setUp(self):
self.login()
self.url = reverse('item:add')
def test_post_name_is_required(self):
data = make_validated_item_form(name='', commit=False)
self._test_if_got_errors(data)
def test_post_description_is_required(self):
data = make_validated_item_form(description='', commit=False)
self._test_if_got_errors(data)
def test_post_delivery_date_is_required(self):
data = make_validated_item_form(delivery_date='', commit=False)
self._test_if_got_errors(data)
def test_post_wrong_delivery_date(self):
data = make_validated_item_form(
delivery_date='2015/01/21 22:00:00', commit=False
)
self._test_if_got_errors(data)
def _test_if_got_errors(self, data):
data.update(make_managementform_data())
self.response = self.client.post(self.url, data)
self.assertTrue(self.response.context['item_picture_form'].errors)
class EditViewTest(AddViewTest):
def setUp(self):
self.login()
self.item = create_item()
self.url = reverse('item:edit', args=[self.item.pk])
self.response = self.client.get(self.url)
def test_template(self):
self.assertTemplateUsed(self.response, 'item/edit.html')
def test_if_has_forms(self):
form = self.response.context['form']
self.assertIsInstance(form, ItemForm)
def test_html(self):
self.assertContains(self.response, '<form')
self.assertContains(self.response, '<input', 6)
self.assertContains(self.response, 'type="submit"')
class EditPostTest(TestBase):
def setUp(self):
self.login()
self.item = create_item()
self.url = reverse('item:edit', args=[self.item.pk])
self.response = self.client.get(self.url)
self.form = self.response.context['form']
self.data = self.form.initial
def test_post_name(self):
self.data['name'] = 'Chair'
self._post_and_test_response()
self.assertEqual(Item.objects.first().name, 'Chair')
def test_post_description(self):
self.data['description'] = 'For sale!'
self._post_and_test_response()
self.assertEqual(Item.objects.first().description, 'For sale!')
def test_post_concluded(self):
self.data['concluded'] = True
self._post_and_test_response()
self.assertEqual(Item.objects.first().concluded, True)
def test_post_total_value(self):
self.data['total_value'] = 2000
self._post_and_test_response()
self.assertEqual(Item.objects.first().total_value, 2000)
def test_post_total_paid(self):
self.data['total_paid'] = 1000
self._post_and_test_response()
self.assertEqual(Item.objects.first().total_paid, 1000)
def test_post_delivery_date(self):
self.data['delivery_date'] = '19/01/2020 22:00:00'
self._post_and_test_response()
expected_date = '19/01/2020 22:00:00'
saved_date = Item.objects.first().delivery_date.strftime(
"%d/%m/%Y %H:%M:%S"
)
self.assertEqual(saved_date, expected_date)
def _post_and_test_response(self):
self.response = self.client.post(self.url, self.data, follow=True)
self.assertContains(self.response, 'Item alterado com sucesso!')
self.__test_redirect()
def __test_redirect(self):
expected_url = reverse('client:list_items', args=[self.item.client.pk])
self.assertRedirects(
self.response, expected_url,
status_code=302, target_status_code=200
)
class EditInvalidPostTest(TestBase):
def setUp(self):
self.login()
self.item = create_item()
self.url = reverse('item:edit', args=[self.item.pk])
self.response = self.client.get(self.url)
self.form = self.response.context['form']
self.data = self.form.initial
def test_post_name_required(self):
self.data['name'] = ''
self._test_if_got_errors()
def test_post_description_required(self):
self.data['description'] = ''
self._test_if_got_errors()
def test_post_delivery_date_required(self):
self.data['delivery_date'] = ''
self._test_if_got_errors()
def _test_if_got_errors(self):
self.response = self.client.post(self.url, self.data)
self.assertTrue(self.response.context['form'].errors)
class ListViewTest(TestBase):
def setUp(self):
self.login()
self.item1 = create_item()
self.client2 = create_client(name='Andre', email='<EMAIL>')
self.item2 = create_item(client=self.client2, name='Box')
self.item3 = create_item(
client=self.client2, name='Chair'
)
self.item4 = create_item(
client=self.client2, name='Table'
)
self.url = reverse('item:list')
self.response = self.client.get(self.url)
def test_get(self):
self.assertEqual(self.response.status_code, 200)
def test_template(self):
self.assertTemplateUsed(self.response, 'item/list.html')
def test_if_contains_items(self):
self.assertContains(self.response, self.item1.name)
self.assertContains(self.response, self.item1.client.name)
self.assertContains(self.response, self.item2.name)
self.assertContains(self.response, self.item2.client.name)
def test_if_contains_search_field(self):
self.assertContains(self.response, '<form')
self.assertContains(self.response, 'type="submit"')
def test_post(self):
data = {'name': 'Table'}
self.response = self.client.post(self.url, data)
self.assertContains(self.response, self.item4.name)
# client1 items should not appear
self.assertNotContains(self.response, self.item1.name)
self.assertNotContains(self.response, self.item2.name)
self.assertNotContains(self.response, self.item3.name)
def test_massage_when_view_is_empty(self):
Item.objects.all().delete()
self.response = self.client.get(self.url)
self.assertContains(self.response, 'Nenhum item encontrado.')
class DeleteViewTest(TestBase):
def setUp(self):
self.login()
self.item1 = create_item()
self.client2 = create_client(name='Andre', email='<EMAIL>')
self.item2 = create_item(client=self.client2)
self.picture1 = create_picture(self.item2)
self.picture2 = create_picture(self.item2)
# Must have 2 itens and 2 images before post.
self.assertEqual(len(Item.objects.all()), 2)
self.assertEqual(len(Picture.objects.all()), 2)
self.response = self.client.post(
reverse('item:delete', args=[self.item2.pk]), follow=True
)
def test_redirect(self):
expected_url = reverse('item:list')
self.assertRedirects(
self.response, expected_url,
status_code=302, target_status_code=200
)
def test_if_deleted(self):
self.assertEqual(len(Item.objects.all()), 1)
def test_if_images_was_deleted(self):
self.assertEqual(len(Picture.objects.all()), 0)
def test_message(self):
self.assertContains(self.response, 'Item removido com sucesso!')
class ImageListViewTest(TestBase):
def setUp(self):
self.login()
self.item1 = create_item()
self.picture1 = create_picture(self.item1, public=True)
self.picture2 = create_picture(self.item1)
self.url = reverse('item:image_list', args=[self.item1.pk])
self.response = self.client.get(self.url)
def test_get(self):
self.assertEqual(self.response.status_code, 200)
def test_get_logout(self):
self._test_get_logout(self.url)
def test_template(self):
self.assertTemplateUsed(self.response, 'item/list_images.html')
def test_if_contains_items(self):
self.assertContains(self.response, self.item1.name)
self.assertContains(self.response, self.item1.client.name)
self.assertContains(self.response, self.picture1.image.url)
self.assertContains(self.response, self.picture2.image.url)
def test_if_contain_checkbox_in_context(self):
# 2 from images(form list) and 1 from form to add a new image
self.assertContains(self.response, 'type="checkbox"', 2)
def test_if_contain_checked_checkbox_in_context(self):
self.assertContains(self.response, 'checked', 1)
def test_massage_when_view_is_empty(self):
Picture.objects.all().delete()
self.response = self.client.get(self.url)
self.assertContains(self.response, 'Nenhuma imagem adicionada!')
def test_if_has_forms(self):
picture_form = self.response.context['picture_form']
self.assertIsInstance(picture_form, PictureForm)
class ImageListViewPostWithImageTest(TestBase):
"""
Test post with image.
"""
def setUp(self):
self.login()
self.item1 = create_item()
self.url = reverse('item:image_list', args=[self.item1.pk])
with open(PATH_TO_IMAGE_TEST, 'rb') as img:
data = {
'add-form': '',
'files': img,
}
self.response = self.client.post(self.url, data, follow=True)
def test_message(self):
self.assertContains(self.response, 'Imagem enviada com sucesso!')
def test_redirect(self):
expected_url = reverse('item:image_list', args=[self.item1.pk])
self.assertRedirects(
self.response, expected_url,
status_code=302, target_status_code=200
)
def test_if_saved(self):
self.assertTrue(Picture.objects.exists())
class ImageListViewPostChangeStatesTest(TestBase):
"""
Test changing image' states(state and public).
"""
def setUp(self):
self.login()
self.item = create_item()
self.picture1 = create_picture(self.item, public=True)
self.picture2 = create_picture(self.item, state='after')
self.picture3 = create_picture(self.item)
self.picture4 = create_picture(self.item)
# State must be 'before' before post.
self.assertEqual(self.picture1.state, 'before')
# Public must be False before post.
self.assertFalse(self.picture2.public)
# State must be 'before' before post.
self.assertEqual(self.picture3.state, 'before')
# State must be 'before' before post.
self.assertEqual(self.picture4.state, 'before')
# Public must be False before post.
self.assertFalse(self.picture4.public)
# Change picture2.public from False to True
# and change picture1.state from 'before' to 'after'
# and change picture3.state from 'before' to 'after'
# and change picture4.state from 'before' to 'after'
# ang change picture4.public from False to True
data = {
'checks[]': ['2', '4'],
'selects[]': [
str(self.picture1.pk) + '_after',
str(self.picture3.pk) + '_after',
str(self.picture4.pk) + '_after',
]
}
self.url = reverse('item:image_list', args=[self.item.pk])
self.response = self.client.post(self.url, data, follow=True)
def test_message(self):
self.assertContains(self.response, 'Alterado com sucesso!')
def test_redirect(self):
expected_url = reverse('item:image_list', args=[self.item.pk])
self.assertRedirects(
self.response, expected_url,
status_code=302, target_status_code=200
)
def test_if_picture_1_state_has_changed(self):
picture = Picture.objects.get(id=self.picture1.pk)
self.assertEqual(picture.state, 'after')
def test_if_picture_2_public_has_changed(self):
picture = Picture.objects.get(id=self.picture2.pk)
self.assertTrue(picture.public)
def test_if_picture_3_state_has_changed(self):
picture = Picture.objects.get(id=self.picture3.pk)
self.assertEqual(picture.state, 'after')
class ImageDeleteViewTest(TestBase):
def setUp(self):
self.login()
self.item1 = create_item()
self.picture1 = create_picture(self.item1)
self.picture2 = create_picture(self.item1)
self.assertEqual(len(Picture.objects.all()), 2)
self.response = self.client.post(
reverse('item:image_delete', args=[self.picture1.pk]), follow=True
)
def test_redirect(self):
expected_url = reverse('item:image_list', args=[self.item1.pk])
self.assertRedirects(
self.response, expected_url,
status_code=302, target_status_code=200
)
def test_if_deleted(self):
self.assertEqual(len(Picture.objects.all()), 1)
def test_if_image_file_was_deleted(self):
path = self.picture1.image.path
self.assertFalse(os.path.exists(path))
def test_message(self):
self.assertContains(self.response, 'Imagem removida com sucesso!')
|
<reponame>TeamNotJava/networkx-related
def add_root_edge(network):
pass
def forget_direction_of_root_edge(structure):
pass
|
<gh_stars>1-10
from adapt.intent import IntentBuilder
from mycroft.skills.core import MycroftSkill, intent_handler
from mycroft.util.log import LOG
class uPortalDemoSkill(MycroftSkill):
def __init__(self):
super(uPortalDemoSkill, self).__init__(name="uPortalDemoSkill")
@intent_handler(IntentBuilder("").require("RequestMeal").require("Meals").optionally("TimeSpan"))
def request_menu_intent(self, message):
self.speak_dialog("todays.specials", data={"specials": "garden vegetable soup and grilled salmon salad"})
@intent_handler(IntentBuilder("").require("RequestAssignment").require("Assignments").optionally("TimeSpan"))
def request_assignment_intent(self, message):
self.speak_dialog("due.soon", data={
"timespan": "today",
"type": "assignments",
"assignments": "Literature review of Macbeth Act 1, Biology Lab 4, and Mathematics chapter 14 assessment"
})
@intent_handler(IntentBuilder("").require("RequestCourse").require("Course").optionally("TimeSpan"))
def request_course_schedule_intent(self, message):
self.speak_dialog("schedule", data={
"timespan": "today",
"courses": "Biology Lab at 11 in the morning, then in the afternoon Mathematics at 2 and Literature at 4"
})
@intent_handler(IntentBuilder("").require("RequestRegistration").require("Registration").optionally("RangeQualifier"))
def request_course_registration_intent(self, message):
self.speak_dialog("register", data={
"term": "Fall",
"startDate": "Friday, June one",
"endDate": "Wednesday, August one"
})
def create_skill():
return uPortalDemoSkill()
|
A low profile patch antenna for Ku-band applications ABSTRACT A low profile, small size and lightweight dual-band antenna prototype is presented for satellite application (Ku-band). The proposed design meets the spectrum necessity of region 3 specified by International Telecommunication Union (ITU). The proposed antenna achieves a frequency band of 11.6913.24 GHz and 13.7215.07 GHz for direct broadcast service (DBS) and fixed satellite service (FSS) in receive mode, and FSS in transmit mode, respectively. The antenna achieves the impedance bandwidth of 12.29%, and 9.37%, for first, and second band of frequency, respectively. In addition, the axial ratio of 160 MHz (12.3012.46 GHz) is achieved by the design. The proposed design is fabricated and measured for various parameters such as reflection coefficient, bandwidth, gain and radiation pattern. Moreover, the complexity in realising the design is less due to its single patch and a single layer.
|
Hormone-sensitive lipase is localized at synapses and is necessary for normal memory functioning in mice Hormone-sensitive lipase (HSL) is mainly present in adipose tissue where it hydrolyzes diacylglycerol. Although expression of HSL has also been reported in the brain, its presence in different cellular compartments is uncertain, and its role in regulating brain lipid metabolism remains hitherto unexplored. We hypothesized that HSL might play a role in regulating the availability of bioactive lipids necessary for neuronal function and therefore investigated whether dampening HSL activity could lead to brain dysfunction. In mice, we found HSL protein and enzymatic activity throughout the brain, localized within neurons and enriched in synapses. HSL-null mice were then analyzed using a battery of behavioral tests. Relative to wild-type littermates, HSL-null mice showed impaired short-term and long-term memory, yet preserved exploratory behaviors. Molecular analysis of the cortex and hippocampus showed increased expression of genes involved in glucose utilization in the hippocampus, but not cortex, of HSL-null mice compared with controls. Furthermore, lipidomics analyses indicated an impact of HSL deletion on the profile of bioactive lipids, including a decrease in endocannabinoids and eicosanoids that are known to modulate neuronal activity, cerebral blood flow, and inflammation processes. Accordingly, mild increases in the expression of proinflammatory cytokines in HSL mice compared with littermates were suggestive of low-grade inflammation. We conclude that HSL has a homeostatic role in maintaining pools of lipids required for normal brain function. It remains to be tested, however, whether the recruitment of HSL for the synthesis of these lipids occurs during increased neuronal activity or whether HSL participates in neuroinflammatory responses. Abstract Hormone-sensitive lipase (HSL) is mainly present in adipose tissue where it hydrolyzes diacylglycerol. Although expression of HSL has also been reported in the brain, its presence in different cellular compartments is uncertain, and its role in regulating brain lipid metabolism remains hitherto unexplored. We hypothesized that HSL might play a role in regulating the availability of bioactive lipids necessary for neuronal function and therefore investigated whether dampening HSL activity could lead to brain dysfunction. In mice, we found HSL protein and enzymatic activity throughout the brain, localized within neurons and enriched in synapses. HSL-null mice were then analyzed using a battery of behavioral tests. Relative to wild-type littermates, HSL-null mice showed impaired short-term and longterm memory, yet preserved exploratory behaviors. Molecular analysis of the cortex and hippocampus showed increased expression of genes involved in glucose utilization in the hippocampus, but not cortex, of HSL-null mice compared with controls. Furthermore, lipidomics analyses indicated an impact of HSL deletion on the profile of bioactive lipids, including a decrease in endocannabinoids and eicosanoids that are known to modulate neuronal activity, cerebral blood flow, and inflammation processes. Accordingly, mild increases in the expression of proinflammatory cytokines in HSL mice compared with littermates were suggestive of low-grade inflammation. We conclude that HSL has a homeostatic role in maintaining pools of lipids required for normal brain function. It remains to be tested, however, whether the recruitment of HSL for the synthesis of these lipids occurs during increased neuronal activity or whether HSL participates in neuroinflammatory responses. Supplementary key words endocannabinoids eicosanoids metabolism inflammation animal models hippocampus cortex lipidomics exploratory behavior cerebral blood flow Breakdown of triacylglycerols (TAGs) in adipose tissue is under hormonal regulation and is mediated by adipose triglyceride lipase that hydrolyzes a fatty acid from TAG-generating diacylglycerol (DAG), then the hormone-sensitive lipase (HSL) hydrolyzes DAGs, and finally monoacylglycerol lipase (MAGL) degrades monoacylglycerols into a fatty acid and glycerol. HSL is abundant in the adipose tissues, where it mainly hydrolyzes DAG and plays a key role in lipolysis regulation since it is stimulated by catecholamines and inhibited by insulin. The brain, like most organs, utilizes fatty acids as oxidative substrate. The brain expresses adipose triglyceride lipase and HSL, which have been suggested to control the release of free fatty acids to be used as energy substrate. Although brain cells can oxidize alternative substrates under a variety of physiological or pathological conditions, glucose is the obligatory fuel for adequate brain function. Therefore, HSL is unlikely to be necessary for regulating fatty acid availability from acylglycerols for local energy production. MAGL activity is ubiquitous in the brain and has a pivotal role in the endocannabinoid system: it terminates the action of the main endocannabinoid 2-arachidonoylglycerol (2-AG) through hydrolysis into glycerol and arachidonic acid. This is an example in which the lipase is not fulfilling energetic needs of brain cells but contributing to functional control of neuronal activity. Endocannabinoids control brain metabolism and synaptic function. The endocannabinoid 2-AG is synthetized by diacylglycerol lipase *For correspondence: Joo M. N. Duarte, [email protected]. (DAGL) and at postsynaptic terminals following stimulation by glutamate and is then released to presynaptic terminals, where it stimulates cannabinoid 1 receptors, thus dampening glutamatergic activity at synapses. Moreover, cannabinoid 1 receptors directly inhibit mitochondrial metabolism in neurons and astrocytes, which may contribute to 2-AG-dependent synaptic control. Interestingly, while having negligible 2-AG hydrolysis activity, HSL could rather fulfill a role in hormone-regulated 2-AG production, thus integrating signaling from catecholamines and cannabinoids at neuronal synapses. The main endocannabinoids 2-AG and N-arachidonoylethanolamine (or anandamide) are quickly hydrolyzed by MAGL and fatty acid amide hydrolase (FAAH), respectively. These reactions produce arachidonic acid that, in turn, is enzymatically oxidized to produce eicosanoids that are proinflammatory mediators and modulators of cerebral blood flow. Thus, DAG hydrolysis by HSL could also contribute to regulate metabolic and signaling pools of arachidonic acid and other bioactive lipids. Given the ability of HSL to be controlled by multiple cellular signals, we propose that its activity in the brain is poised to regulate lipid metabolism in cellular compartments where lipolysis is stimulated on demand for release of precursor fatty acids from esterified forms, which are then used for production of bioactive lipids. In this study, we aimed at mapping the relative distribution of HSL in the rodent brain and investigating the impact of HSL deletion on brain function, namely memory performance, and exploring underlying mechanisms. Animal models All procedures on animals were approved by the Malm-Lund Committee for Animal Experiment Ethics and conducted according to EU Directive 2010/63/EU and are reported following the ARRIVE guidelines (Animal Research: Reporting In Vivo Experiments, NC3Rs initiative, UK). Mice were housed on a 12-h light-dark cycle with lights on at 7:00, room temperature of 21-23 C and humidity at 55-60%, and had access to regular chow and water ad libitum. Male C57BL/6J mice were obtained from Taconic (Ry, Denmark) at 8 weeks of age and allowed to acclimatize to the animal facility for at least 2 weeks before experiments. HSL-null (HSL −/− ) mice were generated by targeted disruption of the HSL gene (Lipe) in 129SV-derived embryonic stem cells as described elsewhere and back-crossed to a C57BL/6J background for nine generations. HSL −/− mice and wild-type littermates (HSL +/+ ) of either gender were studied at 19-22 months of age. Behavior testing Mice were allowed to acclimatize to the testing room for 1 h before each experiment, and tests were performed from 9:00 to 18:00. Barnes maze tests were conducted under bright light over the platform. Otherwise, room light was adjusted to an illuminance of 15 lx in the test apparatus. Experiments were recorded by an infrared camera into the AnyMaze software (version 6.0.1; Stoelting). A circular Barnes maze with diameter of 92 cm and 20 holes placed at a height of 90 cm was used to test learning and memory. The target hole had a removable dark escape box under the maze, and four proximal visual cues were placed at 20 cm from the platform. Experiments consisted of habituation, 8-day acquisition (training), and memory retention trial. For the habituation, mice were placed in the escape box during 60 s and then released in the center of the apparatus and allowed it to explore until re-entering the escape box or until 5 min elapsed. The first acquisition trial was conducted 2 h after the habituation and was used to probe short-term memory. Acquisition trials took place in 8 consecutive days, at the same time of the day, in which mice were released in the center of the maze with head pointing in random direction, and allowed to explore the maze for 5 min. The test ended when mice escaped into the target-hole box. Whenever mice did not find the escape box within 5 min, they were gently guided into it. The memory retention trial took place 48 h after the last acquisition session, under identical conditions but in the absence of any escape box. To eliminate olfactory cues, the surface and the escape box were cleaned with 70% (v/v) ethanol in-between each trial. Measured parameters were path and latency to reach or enter the target hole and time spent in each quadrant of the maze during retention trial. Spontaneous alternations were observed in a Y-maze as surrogate of working memory performance. The Y-maze arms were 30 cm 15 cm 5 cm (length height wide) and converged to the center in 120 angles. Mice were placed an arm of the maze and allowed to freely explore for 5 min. A complete spontaneous alternation was defined as a successive entrance to each different arm and expressed relative to the total possible alternations in the respective test. The total number of entries was analyzed to access locomotor activity and exploratory behavior. Open-field exploration was recorded for 5 min in a cubic arena with length of 50 cm by an infrared camera. Arena exploration was analyzed for total walk distance, number of crossings between arena quadrants and number of rearing events, as well as exploration of the arena center at 6 cm from the walls. The elevated plus maze test was used to assess anxiety. Each maze arm was 35 cm 5 cm, and closed arms had 15 cm walls, at a 60 cm height from the floor. The mouse was placed in the maze center facing an open arm and was allowed to freely explore the maze for 5 min. Number of entries and time spent in each arm were analyzed. Tissue sampling Mice were anesthetized with isoflurane and quickly decapitated, and brains were dissected, frozen in nitrogen (l), and stored at −80 C until further experiments. For immunofluorescence experiments, mice under isoflurane anesthesia were sacrificed by cardiac perfusion with cold PBS and then cold phosphate-buffered formaldehyde (Histolab, Askim, Sweden), and brains were processed as detailed previously. HSL activity Tissues were mechanically homogenized in 0.25 mol/l sucrose, 1 mmol/l EDTA, 1 mmol/l dithiothreitol, and protease inhibitors (20 g/ml leupeptin, 2 g/ml antipain, and 1 g/ml pepstatin), pH 7.0, using a glass-glass homogenizer. To remove fat from the tissues, it was centrifuged at 110,000 g for 1 h at 4 C (Optima TLX Ultracentrifuge; Beckman), and the fat-free infranatant was used for HSL activity measurements. Measurement of HSL activity was performed using 1,3-oleoyl-2-0-oleylglycerol, a DAG analogue, as substrate, as previously detailed. It should be emphasized that the DAG analogue used as substrate does not generate substrate for MAGL because of the ether bond in position 2. To estimate the fraction of activity accounted for by HSL, samples were preincubated with either an activity-neutralizing hen antirat HSL serum (prepared in-house) or preimmune serum for 20 min at 37 C prior to the assay. Total protein content of the samples was measured with the bicinchoninic acid assay (kit from Pierce, Thermo Fisher Scientific; Gteborg, Sweden). Activity was expressed as mU/mg protein, where 1 U corresponds to the release of 1 mol of fatty acids per min at 37 C. Total protein extracts Tissue samples were homogenized with a sonicator probe in lysis buffer (in mmol/l: 150 NaCl, 1 EDTA, 50 Tris(hydroxymethyl)aminomethane -HCl, 1% SDS, and pH 8.0) containing protease inhibitors (catalog no.: 11697498001; Roche, Switzerland) and phosphatase inhibitors (catalog no.: 4906837001; Roche, Switzerland). The homogenate was maintained in constant agitation for 2 h at 4 C. After centrifugation at 3,000 g for 10 min at 4 C to remove major debris, the supernatant was saved. Protein concentration was determined as described previously. Preparation of synaptosomes and synaptic fractions Synaptosomal fractionation was modified from the study by Morat et al.. Briefly, mouse cortex was homogenized in 1 ml of isolation buffer (in mmol/l: 320 sucrose, 0.1 CaCl 2, 0.1 MgCl 2, and pH 7.4) at 4 C in a 5 ml Potter-Elvehjem glass/Teflon homogenizer (10 strokes at 700-900 rpm). The resulting homogenate was mixed with 6 ml sucrose (2 mol/l) and 2.5 ml CaCl 2 (0.1 mmol/l) in an ultraclear centrifuge tube (catalog no.: 344059; Beckman Coulter). Then, 2.5 ml of sucrose (1 mol/l) containing 0.1 mM CaCl 2 were carefully added on top to form a discontinuous sucrose gradient. All centrifugations were performed in an Optima XL-100K Ultracentrifuge (Beckman Coulter) with SW41Ti swinging bucket rotor (Beckman Coulter). After centrifugation for 3 h at 100,000 g, 4 C, the synaptosomes were collected from the interphase between 1.25 and 1 mol/l sucrose and diluted 10 times in isolation buffer, centrifuged for 30 min at 15,000 g, 4 C, and the resulting synaptosomal pellet was resuspended in 1 ml of isolation buffer. For fractioning synaptosomes, part of each sample was diluted 1:5 in 0.1 mmol/l CaCl 2, and an equal volume of solubilization buffer (2% Triton X-100, 40 mmol/l Tris, pH 6.0) was added to the suspension. The suspension was incubated for 30 min on ice with constant agitation, and the insoluble material (synaptic junctions) was pelleted by centrifugation for 30 min at 40,000 g, 4 C. The supernatant (extrasynaptic fraction) was concentrated using an Amicon Ultra 15 10K (catalog no.: UFC901008; Merck Millipore, Ireland), and protein was precipitated with six volumes of acetone at −20 C and recovered by centrifugation for 30 min at 18,000 g, at −15 C. The pellet containing synaptic junctions was washed in solubilization buffer at pH 6.0 and then resuspended in 10 volumes of a second solubilization buffer (1% Triton X-100 and 20 mmol/l Tris, pH 8.0). After incubation under agitation for 30 min on ice, the mixture was centrifuged and the supernatant (presynaptic fraction) was processed as described for the extrasynaptic fraction, whereas the insoluble pellet corresponds to the postsynaptic fraction All synaptic fractions were resuspended in 5% SDS with protease inhibitors. RT-PCR RNA was isolated from cortex and hippocampus from one hemisphere using Trizol (catalog no.: 15596026; Invitrogen) and then 1 g of total RNA was reverse transcribed with random hexamer primers using the qScript complementary DNA (cDNA) SuperMix (catalog no.: 95048; Quantabio, England), according to the manufacturers' instructions. The resulting cDNA was used as template for quantitative RT-PCR in triplicates using PerfeCTa SYBRgreen SuperMix (catalog no.: 95054; Quantabio, England) and the primers in supplemental Table S1. Cycling and detection were carried out using Quantstudio 5 Real-time PCR system (40 cycles of 5 s at 95 C and 30 s at 60 C). Primers were optimized prior usage by assessing the optimal annealing temperature. Specificity was monitored using melt-curve validation and confirmation of amplified product by agarose gel electrophoresis. The dynamic range of each PCR assay was determined by constructing a standard curve using serial dilution of cDNA representative of each sample. Samples and standards were run in triplicate. All data were normalized to the expression of 60S ribosomal protein L14 and analyzed with the comparative threshold cycle method (CT). Targeted lipidomics Analysis of oxylipins (supplemental Table S2) and endocannabinoids (supplemental Table S3) in tissue by UHPLC-QqQMSMS was carried out as detailed before. Briefly, 500 l methanol was added to ∼20 mg of sample material. The sample was shaken with two tungsten beads at 30 Hz for 3 min in a mixer mill (MM 400; Retsch) whereupon the beads were removed. Samples were centrifuged at 2,125 g for 10 min at 4 C, and 450 l of the supernatant was diluted in 8.5 ml of 0.1% acetic acid to reduce the methanol concentration to ≤5%. Blank samples, that is, samples without starting material, were prepared the same way as the tissue samples. Quantitative targeted liquid chromatography-mass spectrometry was conducted using an Agilent UHPLC system (Infinity 1290) coupled with an ESI to an Agilent 6490 triple quadrupole system equipped with iFunnel Technology (Agilent Technologies, Santa Clara, CA). Metabolite separation was performed using a Waters BEH C18 column (2.1 mm 150 mm, 130, particle size of 1.7 m). The mobile phase consisted of (A) 0.1% acetic acid in Milli-Q water and (B) acetonitrile:isopropanol (90:10). A flow rate of 300 l/min and injection volumes of 10 l were employed for each run. The endocannabinoids are easily degraded compared with the relatively stable oxylipins, wherefore all samples were first injected for ionization in positive mode (endocannabinoids) followed by all samples injected for negative (oxylipins) mode. Quantification of the compounds was performed with MassHunter Quantitative Analysis QQQ (Agilent). Analytes were quantified against native standards, with correction for recovery rates of deuterated internal standards, as detailed previously. Statistical analyses Results were analyzed with Prism 9.0.2 (GraphPad Software, Inc, San Diego, CA). The Kolmogorov-Smirnov test was used for normality testing. In the absence of normality deviations, results were analyzed using unpaired, 2-tailed Students t-test or ANOVA followed by independent comparisons with the Fisher's least significant difference test. Significance was accepted for P < 0.05. Partial least-squares discriminant analysis (PLS-DA) with two components was applied on z-scores of gene expression or lipidomics datasets using MATLAB 2019a (MathWorks, Natick, MA). For that, each sample was assigned a dummy variable as a reference value (0 = HSL −/− and 1 = HSL +/+ ). The variable importance in projection (VIP) was calculated for each gene or lipid in either brain area. Results are presented as mean ± SD unless otherwise stated. Statistical details of experiments can be found in the figure legends. RESULTS HSL is enriched in neuronal synapses and is widely distributed in the brain From the mouse cortex, we prepared synaptosomes, which are resealed nerve terminals after tissue homogenization. Synaptosomes were subsequently fractioned into synaptic preparations that are rich in postsynaptic density protein 95, synaptosomalassociated protein 25 (SNAP25), and synaptophysin, which correspond to the postsynaptic, presynaptic, and extrasynaptic zones, respectively (Fig. 1A). Upon immunoblotting, we observed two bands at the approximate molecular weight of previously described HSL isoforms, but only the band corresponding to the predominant isoform in adipose tissue (84 kDa) was absent from in protein extracts from HSL −/− mice (Fig. 1B). The synaptic fractions showed a more intense immunoreactivity against HSL than total protein extracts (Fig. 1B). Indeed, synaptosomes showed 8-fold more immunoreactivity than total extracts (P < 0.01) and, among the synaptic preparations, HSL immunoreactivity was observed in presynaptic and mostly postsynaptic fractions (Fig. 1C). We then set to investigate the cerebral distribution of HSL. First, we measured DAG lipase activity in the absence or the presence of an anti-HSL antibody that abrogates HSL activity. Although HSL-specific DAG lipase activity was 20-fold lower in brain than in adipose tissue, it was detected in all brain areas analyzed, and on average, it accounted for about two-thirds of total DAG lipase activity (Fig. 1D). Then, the presence of HSL in these mouse brain samples was confirmed by immunoblotting experiments (Fig. 1E). Different unspecific bands in blots of Fig. 1B and E are attributed to difference in sample preparation. Immunofluorescence microscopy in mouse brain slices showed that HSL immunoreactivity is observed within all cells that are positive for the widely used neuronal marker NeuN, as well as in NeuN-negative cells (Fig. 1F), suggesting that both neurons and glia express HSL. Notably, brain slices from HSL −/− mice showed no HSL immunoreactivity (Fig. 1G). In cultured cortical neurons, HSL immunoreactivity was observed in the cell soma and along dendritic processes ( Fig. 2A). In finer dendrites, HSL immunoreactivity was adjacent to that of postsynaptic density protein 95 (Fig. 2B), in line with its synaptic location. HSL ¡/¡ mice display short-term and long-term memory impairment To investigate whether HSL contributes to brain function, HSL −/− mice and wild-type littermates were analyzed using a battery of behavior tests that probe for memory, exploratory behavior and locomotor activity, and anxiety-like behavior. Spatial learning and memory was analyzed using the Barnes maze, in which mice were trained for 8 days to learn the escape box location, that is the target hole, and long-term memory was analyzed after 48 h (Fig. 3A). Learning during the 8 training days was indistinct between genotypes (Fig. 3B). In training day 1, the experiment was preceded by a habituation session in which mice were placed in the escape whole, that is, the target, and released in the center of the arena 2 h later. Thereafter, the first training session revealed short-term memory impairment in HSL −/− mice, as depicted by larger latency (P < 0.05) and number of errors until the target was reached (P < 0.05), when compared with wild-type mice (Fig. 3C). During a training period of 8 days, HSL −/− mice utilized more often a random than serial hole search to identify the target (Fig. 3D). Long-term memory was probed 48 h later, with mice being allowed to explore the maze without the escape box. HSL −/− mice searched less holes in the target quadrant (P < 0.05), took longer time to reach the target hole for the first time (P < 0.05), and spent overall less time in the target quadrant than controls (P < 0.01, Fig. 3E), suggesting impaired spatial memory performance. The reduced Y-maze spontaneous alternation in HSL −/− mice compared with controls (P < 0.05) further confirmed memory impairment caused by genetic HSL deletion (Fig. 3F). These memory assessments were not biased by alterations of exploratory behavior since the genotype had no effect on the number of entries in the Y-maze arms (Fig. 3F), or on any measure of the open-field exploration, such as quadrant crossings, rearing, and total walked distance in the arena (Fig. 3G). HSL deletion was also unrelated to development of anxietylike behaviors depicted by changes in the exploration of the unprotected open-field arena center (Fig. 1G) or of the open arms in the elevated plus maze test (Fig. 3H). HSL deletion impacts genes involved in glucose metabolism and inflammation As a first step to investigate the impact of HSL deletion on brain metabolism, we measured the expression of a panel of genes coding for proteins involved in glucose and lipid metabolism and genes encoding enzymes involved in the endocannabinoid system. Since neuroinflammation is known to be involved in a number of neurological and metabolic disorders, this gene panel also included the master regulator of inflammatory processes NF-B and Fig. 1. HSL is present in neurons and distributed throughout the mouse brain. A: Western blots of presynaptic (Pre), postsynaptic (Post), and extrasynaptic (Extra) fractions prepared from the mouse cortex show enrichment in SNAP25, PSD95, and synaptophysin, respectively. B: Relative to total protein extracts (TE), synaptosomes, presynaptic and postsynaptic fractions show immunoreactivity against HSL, a band of 84 kDa that is absent from protein extracts of the HSL −/− mouse cortex (picture on the right). Protein loaded in gels was 30 g for comparison of synaptic fractions and TE, and 40 g for comparing TE from HSL −/− and wild-type (WT) littermates. C: Quantitative analysis of Western blot immunoreactivity suggests presynaptic and mostly postsynaptic HSL enrichment. D and E: HSL-specific (blue circles) and nonspecific (orange crosses) DAG lipase activity in brain areas and adipose tissue (D) and respective immunoreactivity in Western blotting (E). Protein loaded for immunoblotting was 40 g for brain samples and 15 g for adipose tissue. F: Representative fluorescence micrographs of the mouse brain cortex immunolabeled for HSL (magenta), NeuN (green), and MAP2 (yellow). HSL immunoreactivity appears within NeuN-positive (filled arrowhead) and NeuN-negative (open arrowhead) cells. G: The absence of immunoreactivity in cortical slices from HSL −/− mice. The scale bars in micrographs are 20 m. Data in bar graphs are represented as individual data points and mean ± SD of n = 6 in C and n = 3 in D. Symbols over data points cytokines. Transcriptomics data from the hippocampus and cortex (supplemental Fig. S1) were analyzed with a two-component PLS-DA and allowed good separation of HSL −/− and wild-type mice (Fig. 4A), with principal component 1 and principal component 2 accounting for 72% and 16% of the variance in gene expression. The VIPs calculated from the PLS-DA model coefficients (Fig. 4B) indicate that, in the hippocampus, HSL deletion increases the expression of genes necessary for glucose metabolism, namely those coding for the glucose carriers glucose transporter (GLUT)1 and GLUT3, the glycogen phosphorylase muscle isoform, as well as PPAR and PPAR gamma coactivator 1- (PGC1) that are key in mitochondria physiology. The hippocampus of HSL −/− mice also showed reduced expression of hexokinase 1 and a number of genes coding for proteins involved in lipid metabolism (DAGL, alpha/beta-hydrolase domain containing 6 , and MAGL). Some of these observations were paralleled in the cortex (Fig. 4B). However, most strikingly, the cortex showed a prominent increase of the proinflammatory interleukins IL-6 and IL-1 (IL-1 was also increased in hippocampus), suggesting the occurrence of neuroinflammation. Relative to wild-type littermates, HSL −/− mice showed reduced expression of the gene coding for cyclooxygenase 1 (COX1) in the cortex, suggesting altered synthesis of eicosanoids that modulate inflammation. Given the association of HSL deletion to neuroinflammation, we then tested whether this process is accompanied by gliosis. Immunoblotting against the astrocytic marker glial fibrillary acidic protein (GFAP) or the microglial marker ionized indicate significant differences between control and HSL −/− mice (**P < 0.01 and ***P < 0.001) based on Fisher's least significant difference post hoc comparison after ANOVA. FC, frontal cortex; MAP2, microtubule-associated protein 2; OC, occipital cortex; PSD95, postsynaptic density protein 95; PTC, parietotemporal cortex. (Fig. 4C). Altogether, these results suggest that HSL deletion is associated with altered metabolism and low-grade neuroinflammation without the occurrence of important astrogliosis or microgliosis. HSL deletion does not impact typical markers of synaptic health Since HSL is located in synapses, we then tested whether memory impairment upon HSL deletion was caused by loss of synaptic proteins involved in neurotransmitter release, as observed in various models of metabolic disease. Protein extracts from the cortex showed reduced immunoreactivity against syntaxin-4 in HSL −/− mice compared with controls (P < 0.05), without substantial effects on syntaxin-1, SNAP25, or synaptophysin (Fig. 5A). In the hippocampus, the density of these four proteins was similar in the two genotypes (Fig. 5B). HSL deletion causes a shift in the profile of available bioactive lipids Given the particular synaptic enrichment of HSL in synapses, it is plausible that cellular signaling through HSL is involved in the control of lipid metabolites that modulate synaptic physiology. Thus, in a further set of experiments, we determined the concentration of endocannabinoids and oxylipins in the hippocampus Tables S2 and S3), and we then applied a twocomponent PLS-DA to determine the most important set of metabolites differentiating between HSL +/+ and HSL −/− mice. We were able to observe a reasonable separation of the two genotypes (Fig. 6A), with principal component 1 and principal component 2 accounting for 32% and 36% of the variance in lipids. VIPs from the PLS-DA model coefficients allowed us to identify a number of bioactive lipids of importance in the genotype discrimination ( Fig. 6B and C), including the endocannabinoids 2-linoleoylglycerol, N-arachidonoylglycine, palmitoleoylethanolamide (POEA), anandamide, and docosahexaenoylethanolamide, the prostaglandins D2 (PGD2) and F2 (PGF2), and other eicosanoids such as 20-hydroxyarachidonic acid, the epoxyeicosatrienoic acids 5,6-EpETrE, 8,9-EpETrE, 11,12-EpETrE, and 14,15-EpETrE, among others. When analyzing concentrations of the lipids individually (supplemental Tables S2 and S3), however, no significant differences were observed between HSL −/− mice and littermates. DISCUSSION Our results indicate that HSL is active throughout the brain and accounts for at least two-thirds of total DAG lipase activity throughout the assessed brain areas. Accordingly, HSL −/− mice were reported to have a substantial dampening of brain DAG lipase activity. It should be noted that our HSL activity assay is optimized for measuring HSL. It might be that the relative DAG lipase activity accounted from HSL is lower in the native tissue, which allows for further on-demand activation. Similarly, Blankman et al. have assayed lipase activity under conditions that are far from optimal for HSL, and concluded that HSL has negligible 2-AG hydrolysis activity. Therefore, further studies are necessary for the determination of the exact roles of brain HSL. Furthermore, the present study suggests that HSL is particularly located in synapses, where it might exert important regulatory mechanisms that are hitherto undescribed. For the first time, to our knowledge, we demonstrate here that HSL is necessary for memory performance, since the HSL −/− mouse exhibited impaired short-term and long-term memory in the Barnes maze as well as impaired spatial working memory in the Y-maze. This role of HSL in cognition adds up to previous suggestions of HSL-mediated lipolysis modulating hypothalamic function. Given the synaptic enrichment of HSL, we evaluated whether degeneration of cortical and hippocampal synapses was a possible cause for memory impairment, as in other models of metabolic and neurological disorders. Levels of synaptophysin, syntaxin-1, or SNAP25, which are enriched in nerve terminals, were not modified by HSL deletion. HSL deletion caused a reduction of syntaxin-4 levels in the cortex (but not hippocampus). Although this protein is part of the exocytosis machinery of nerve terminals, it is mainly present in processes of astrocytes. Therefore, it is possible that release of molecules from astrocytes acting on synapses is impaired. Nevertheless, we have not observed alterations in the levels of GFAP that is specific to astrocytes. Neuronal communication at synapses is crucial for cognition, and damage to synapses and impaired synaptic functions is associated to cognitive decline. Although HSL −/− mice do not show loss of synaptic markers that is typical of neurodegeneration, one cannot exclude impairment in the modulation of neurotransmitter release. Neuroinflammation is a key process by which lipid metabolism disorders and obesity impact brain function. HSL −/− mice show low-grade neuroinflammation characterized by higher expression of proinflammatory cytokines than wild-type littermates. This occurs mainly in the hippocampus and thus might contribute to the observed spatial memory impairment. Immunofluorescence experiments revealed HSL expression in NeuN-negative cells, which are likely astrocytes or microglia. Moreover, the concentration of oxylipins involved in inflammatory processes was modified upon genetic HSL deletion (see later). Lowgrade inflammation in adipose tissue of HSL −/− mice has been described. It has also been shown that HSL deficiency alters the expression of elongases and desaturases in liver and adipose tissue, which might impact lipogenesis and the profile of circulating long-chain polyunsaturated fatty acids from which inflammatory mediators are synthesized. Therefore, given the pivotal participation of lipid metabolism in microglia modulation, future studies should further address a putative role of HSL in controlling neuroinflammatory cues. The possibility of functional rather than structural derangement in synapses, as well as the low-grade inflammation, suggests that HSL is a key regulator of neuroactive lipid products. Indeed, we have identified overall basal changes in the concentration of eicosanoids and endocannabinoids induced by HSL deletion in the cortex and hippocampus. Most of these functional lipid products originate from arachidonic acid, which is a relatively abundant fatty acid in the brain produced from 2-AG and arachidonate-containing phospholipids. In addition to being the primary hydrolytic enzyme for 2-AG, the most abundant endocannabinoid in the brain, MAGL is considered to be the rate-limiting enzyme for release of arachidonic acid in the brain, to be used for the COX1/ 2-dependent synthesis of neuroinflammatory prostaglandins and other eicosanoids, namely prostaglandin E2, PGD2, PGF2, and thromboxane B2. Although HSL has no phospholipase activity, these metabolites contributed to the differences observed in the profile of bioactive lipids between HSL −/− and HSL +/+ mice (Fig. 6). Thus, HSL might also have a role in the production of such eicosanoids from arachidonate-containing TAGs that are stored in lipid droplets. Interestingly, we observed reduced expression of cortical Cox1 and hippocampal Magl and lower levels of PGD2 in both cortex and hippocampus of HSL −/− than HSL +/+ mice. PGD2 is a known driver of neuroinflammation and affords communication from activated microglia to astrocytes. The reduction of PGD2 in HSL −/− mice is thus in line with low-grade neuroinflammation in the absence of gliosis (we observed no increase in levels of ionized calcium binding adapter molecule 1 and GFAP). Eicosanoids also participate in the modulation of cerebral blood flow in response to neuronal demands by acting on the vascular bed. Namely, both hippocampus and cortex of HSL −/− mice showed reduced levels of 20-hydroxyarachidonic acid (or 20-Hydroxyeicosatetraenoic acid), which acts as vasoconstrictor and mediates autoregulation of cerebral blood flow. PGF2 also acts as cerebral vasoconstrictor and was found increased in both cortex and hippocampus of HSL −/− mice. In the brain, the epoxyeicosatrienoic acids 5,6-EpETrE, 8,9-EpETrE, 11,12-EpETrE, and 14,15-EpETrE are locally produced to induce vessel dilation. HSL −/− mice showed increased 5,6-EpETrE and 14,15-EpETrE in cortex and reduced 8,9-EpETrE and 11,12-EpETrE in the hippocampus. Altogether, these alterations could impact resting autoregulation as well as activity-induced neurovascular coupling. The lack of matching nutrient supply from the circulation to the demands of neuronal work is certainly critical for adequate functional performance. Cellular adaptations might be in place in HSL −/− mice to cope with the lack of vascular flexibility, and our analysis found for example the increase in expression of genes coding for PGC1 that regulates mitochondria physiology, the glucose carrier GLUT1 that is ubiquitous in blood vessels and brain cells, as well as the neuronal-specific GLUT3. In contrast, there were negligible changes in insulinsensitive GLUT4 that is strategically located near synapses for neurotransmission fueling, and there was a reduction in the expression of genes coding for hexokinase 1 and glycogen phosphorylase B (glycogen phosphorylase muscle isoform). These gene-expression alterations occurred in the hippocampus that controls spatial memory, and one might speculate that they could preclude that they limit glucose and glycogen metabolism during high energy demands of a memory task. Together, MAGL, ABHD12, and ABHD6 control about 99% of 2-AG signaling in the brain, and each enzyme exhibits a distinct subcellular distribution, suggesting that they regulate distinct pools of 2-AG in the nervous system. Expression of genes coding for ABHD12 and ABHD6 was modified in cortex and hippocampus, respectively. Furthermore, Magl expression tended to be increased in the cortex and reduced in the hippocampus to nearly half of that in wild-type mice. Despite small, Magl expression changes upon HSL deletion might still be critical in the dampening of endocannabinoid signaling in confined compartments such as the synapse, namely for removal of 2-AG produced following neurotransmitter release. Indeed, genetic deletion of MAGL results in the accumulation of 2-AG and other MAG species in the brain, without changes in expression of genes coding for HSL, ABHD6, and ABHD12. None of the most studied endocannabinoids-2-AG and anandamide-were modified in the hippocampus and cortex by HSL deletion. However, it should be noted that our lipid profile was measured in the resting brain, not in response to increased neuronal activity that is the trigger for endocannabinoid synthesis and release. Although no Faah expression changes were induced by HSL deletion, anandamide concentration was lower in the hippocampus of HSL −/− than HSL +/+ mice. While increase of brain anandamide by acute inhibition of FAAH is deleterious and causes memory impairment via CB1 receptor signaling in the hippocampus, it can also have anti-inflammatory actions on microglia, and consequently, a neuroprotective action. Thus, a chronic reduction of anandamide levels in the hippocampus of HSL −/− mice can dampen its role as a gatekeeper of microglia overactivation and contribute to low-grade neuroinflammation. Furthermore, anandamide can bind to PPAR and PPAR, through which affords neuroprotection, anti-inflammatory effects, or metabolic regulation. FAAH hydrolyzes other bioactive lipids, such as POEA that was increased by HSL deletion. POEA is believed to share physiological actions with oleoylethanolamide, to which is structurally similar. Oleoylethanolamide shows vasorelaxation properties that contribute to controlling brain perfusion and can function as endogenous ligand for cannabinoid receptors and PPAR. The alteration in the balance of anandamide and POEA is likely to impact hippocampal metabolism, including PPAR/ regulation of mitochondrial physiology, as suggested by the observed alterations in expression of Ppargc1a or its isoforms in HSL −/− mice. DAGL- deletion in mice was also proposed to disrupt learning and memory because of the depletion of 2-AG and arachidonic acid across the whole brain. Interestingly, Schurman et al. found effects of DAGL- deletion on brain anandamide levels that were not mimicked by pharmacological inhibition of the enzyme, indicating that enzyme activities producing and/or degrading anandamide are also impacted by deletion of DAGL-. In our study, we measured expression of such enzymes and found negligible effects triggered by HSL deletion. HSL shows broad substrate specificity. Despite highest lipase activity against DAG, HSL can hydrolyze any acylglycerol and also shows esterase activity toward cholesteryl esters, steroid fatty acid esters, or retinyl esters. Therefore, another possible role for HSL can be related to mobilization of cholesterol esters from lipid droplets in brain cells, which is necessary for the formation of myelin sheaths and synaptic contacts, as well as to synaptic strengthening during learning. Thus, we cannot exclude that the lack of a putative cholesterol esterase activity by HSL contributes to the observed memory impairment in HSL −/− mice. A limitation of our study is the employment of a mouse model with global deletion of HSL. The HSL −/− is leaner and shows increased circulating insulin but unaltered glycemia, suggesting insulin resistance. While reduced fat mass could be beneficial for brain function, severe insulin resistance can contribute for memory impairment. Brain insulin resistance in this model has hitherto not been explored. In sum, we found no signs of substantial synaptic degeneration, astrogliosis, or microgliosis, but there was a mild increase in levels of proinflammatory cytokines. The profile of endocannabinoids and eicosanoids was distinct in the hippocampus and cortex of HSL −/− and HSL +/+ mice, which might underlie the observed memory impairment. Therefore, we conclude that HSL is a key modulator of eicosanoids that are immunomodulators and further propose a role for HSL on the neuroactive and vasoactive lipid synthesis upon demand by increased neuronal activity. The later remains to be demonstrated. Data availability All data are contained within the article and can be shared upon request to J.M.N.D. (Lund University, joao. [email protected]). Supplemental data This article contains supplemental data.
|
#!/usr/bin/env python3
import rclpy
import time
from rclpy.executors import SingleThreadedExecutor
from rclpy.node import Node
import rmf_adapter as adpt
import rmf_adapter.vehicletraits as traits
import rmf_adapter.geometry as geometry
import rmf_adapter.graph as graph
import rmf_adapter.battery as battery
import rmf_adapter.plan as plan
from test_utils import MockRobotCommand
from functools import partial
test_task_id = 'patrol.direct_dispatch.001' # aka task_id
map_name = "test_map"
fleet_name = "test_fleet"
start_name = "start_wp" # 7
finish_name = "finish_wp" # 10
loop_count = 2
rmf_server_uri = "ws://localhost:7878" # random port
def main():
# INIT RCL ================================================================
rclpy.init()
try:
adpt.init_rclcpp()
except RuntimeError:
# Continue if it is already initialized
pass
# INIT GRAPH ==============================================================
test_graph = graph.Graph()
test_graph.add_waypoint(map_name, [0.0, -10.0]) # 0
test_graph.add_waypoint(map_name, [0.0, -5.0]) # 1
test_graph.add_waypoint(map_name, [5.0, -5.0]).set_holding_point(True) # 2
test_graph.add_waypoint(map_name, [-10.0, 0]) # 3
test_graph.add_waypoint(map_name, [-5.0, 0.0]) # 4
test_graph.add_waypoint(map_name, [0.0, 0.0]) # 5
test_graph.add_waypoint(map_name, [5.0, 0.0]) # 6
test_graph.add_waypoint(map_name, [10.0, 0.0]) # 7
test_graph.add_waypoint(map_name, [0.0, 5.0]) # 8
test_graph.add_waypoint(map_name, [5.0, 5.0]).set_holding_point(True) # 9
test_graph.add_waypoint(map_name, [0.0, 10.0]).set_holding_point(
True).set_charger(True) # 10
assert test_graph.get_waypoint(2).holding_point
assert test_graph.get_waypoint(9).holding_point
test_graph_legend = \
"""
D : Dispenser
I : Ingestor
H : Holding Point
K : Dock
Numerals : Waypoints
---- : Lanes
"""
test_graph_vis = \
test_graph_legend + \
"""
10(I,K)
|
|
8------9(H)
| |
| |
3------4------5------6------7(D,K)
| |
| |
1------2(H)
|
|
0
"""
test_graph.add_bidir_lane(0, 1) # 0 1
test_graph.add_bidir_lane(1, 2) # 2 3
test_graph.add_bidir_lane(1, 5) # 4 5
test_graph.add_bidir_lane(2, 6) # 6 7
test_graph.add_bidir_lane(3, 4) # 8 9
test_graph.add_bidir_lane(4, 5) # 10 11
test_graph.add_bidir_lane(5, 6) # 12 13
test_graph.add_dock_lane(6, 7, "A") # 14 15
test_graph.add_bidir_lane(5, 8) # 16 17
test_graph.add_bidir_lane(6, 9) # 18 19
test_graph.add_bidir_lane(8, 9) # 20 21
test_graph.add_dock_lane(8, 10, "B") # 22 23
assert test_graph.num_lanes == 24
test_graph.add_key(start_name, 7)
test_graph.add_key(finish_name, 10)
assert len(test_graph.keys) == 2 and start_name in test_graph.keys \
and finish_name in test_graph.keys
# INIT FLEET ==============================================================
profile = traits.Profile(geometry.make_final_convex_circle(1.0))
robot_traits = traits.VehicleTraits(linear=traits.Limits(0.7, 0.3),
angular=traits.Limits(1.0, 0.45),
profile=profile)
# Manages loop requests
adapter = adpt.MockAdapter("TestLoopAdapter")
fleet = adapter.add_fleet(
fleet_name, robot_traits, test_graph, rmf_server_uri)
def patrol_req_cb(json_desc):
confirmation = adpt.fleet_update_handle.Confirmation()
confirmation.accept()
print(f" accepted patrol req: {json_desc}")
return confirmation
# Callback when a patrol request is received
fleet.consider_patrol_requests(
patrol_req_cb)
# Set fleet battery profile
battery_sys = battery.BatterySystem.make(24.0, 40.0, 8.8)
mech_sys = battery.MechanicalSystem.make(70.0, 40.0, 0.22)
motion_sink = battery.SimpleMotionPowerSink(battery_sys, mech_sys)
ambient_power_sys = battery.PowerSystem.make(20.0)
ambient_sink = battery.SimpleDevicePowerSink(
battery_sys, ambient_power_sys)
tool_power_sys = battery.PowerSystem.make(10.0)
tool_sink = battery.SimpleDevicePowerSink(battery_sys, tool_power_sys)
b_success = fleet.set_task_planner_params(
battery_sys, motion_sink, ambient_sink, tool_sink, 0.2, 1.0, False)
assert b_success, "set task planner params failed"
cmd_node = Node("RobotCommandHandle")
# Test compute_plan_starts, which tries to place the robot on the navgraph
# Your robot MUST be near a waypoint or lane for this to work though!
starts = plan.compute_plan_starts(test_graph,
map_name,
[[-10.0], [0.0], [0.0]],
adapter.now())
assert [x.waypoint for x in starts] == [3], [x.waypoint for x in starts]
# Alternatively, if you DO know where your robot is, place it directly!
starts = [plan.Start(adapter.now(),
0,
0.0)]
# Lambda to insert an adapter
def updater_inserter(handle_obj, updater):
updater.update_battery_soc(1.0)
handle_obj.updater = updater
# Manages and executes robot commands
robot_cmd = MockRobotCommand(cmd_node, test_graph)
fleet.add_robot(robot_cmd,
"T0",
profile,
starts,
partial(updater_inserter, robot_cmd))
# FINAL PREP ==============================================================
rclpy_executor = SingleThreadedExecutor()
rclpy_executor.add_node(cmd_node)
# GO! =====================================================================
adapter.start()
# Wait a moment for the updater to be created
time.sleep(0.5)
robot_cmd.updater.unstable_declare_holding(
map_name,
[1.0, 2.0, 3.0],
4.0
)
# Wait a moment for the holding declaration to be processed
time.sleep(0.5)
participant = robot_cmd.updater.unstable_get_participant()
itinerary = participant.get_itinerary()
assert len(itinerary) > 0
for route in itinerary:
assert route.map == map_name
assert route.trajectory.size() == 2
for i in range(route.trajectory.size()):
assert route.trajectory.position(i)[0] == 1.0
assert route.trajectory.position(i)[1] == 2.0
assert route.trajectory.position(i)[2] == 3.0
# Note that this is not a very reliable test because the
# unstable_declare_holding will be competing with the responsive waiting
# behavior of the fleet adapter. Race conditions in that contention could
# cause this test to fail.
if __name__ == "__main__":
main()
|
// GetHierarchyCodelist obtains the codelist id for this hierarchy (also, check that it exists)
func (n *Neo4j) GetHierarchyCodelist(ctx context.Context, instanceID, dimension string) (string, error) {
neoStmt := fmt.Sprintf(query.HierarchyExists, instanceID, dimension)
logData := log.Data{"statement": neoStmt}
codelistID := new(string)
if err := n.Read(neoStmt, mapper.HierarchyCodelist(codelistID), false); err != nil {
log.ErrorC("getProps query", err, logData)
return "", err
}
return *codelistID, nil
}
|
<reponame>jo0natan/VSOLUTION-REST-API-SPRING-BOOT
package com.jonatan.springboot.rest.service;
import java.util.List;
import java.util.Optional;
import com.jonatan.springboot.rest.jonatan.JonatanRepository;
import com.jonatan.springboot.rest.model.Empresas;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
@Service
public class Myserviceimpl implements Myservice {
@Autowired
JonatanRepository rest;
@Override
public List<Empresas> getEmpresas() {
// TODO Auto-generated method stub
return rest.findAll();
}
@Override
public Optional<Empresas> getEmpresaId(int empid) {
return rest.findById(empid);
}
@Override
public Empresas addNewEmpresas(Empresas emp) {
return rest.save(emp);
}
@Override
public Empresas updateEmpresa(Empresas emp) {
return rest.save(emp);
}
@Override
public void deleteEmpresaById(int empid) {
rest.deleteById(empid);
}
@Override
public void deleteAllEmpresas() {
rest.deleteAll();
}
}
|
First Trimester Urinary Bisphenol and Phthalate Concentrations and Time to Pregnancy: A Population-Based Cohort Analysis Background Increasing evidence suggests that exposure to synthetic chemicals such as bisphenols and phthalates can influence fecundability. The current study describes associations of first trimester urinary concentrations of bisphenol A (BPA), BPA analogs, and phthalate metabolites with time to pregnancy (TTP). Methods Among 877 participants in the population-based Generation R pregnancy cohort, we measured first trimester urinary concentrations of bisphenols and phthalates . We used fitted covariate-adjusted Cox proportional hazard models to examine associations of bisphenol and phthalate concentrations with TTP. Participants who conceived using infertility treatment were censored at 12 months. Biologically plausible effect measure modification by folic acid supplement use was tested. Results In the main models, bisphenol and phthalate compounds were not associated with fecundability. In stratified models, total bisphenols and phthalic acid were associated with longer TTP among women who did not use folic acid supplements preconceptionally . Using an interaction term for the exposure and folic acid supplement use showed additional effect measure modification by folic acid supplement use for high-molecular-weight phthalate metabolites. Conclusions We found no associations of bisphenols and phthalates with fecundability. Preconception folic acid supplementation seems to modify effects of bisphenols and phthalates on fecundability. Folic acid supplements may protect against reduced fecundability among women exposed to these chemicals. Further studies are needed to replicate these findings and investigate potential mechanisms.
|
// cmd wrapper function for auth checks
func cmdWrapAuth(f CmdHandler) CmdHandler {
return func(c *Client, msg []byte) (resp string, err error) {
if c.state&scAuth == 0 {
return "", ErrUnauthUser
}
return f(c, msg)
}
}
|
Clinical DecisionMaking in Endocrine Physiology: Induced Hypoglycemia in Dogs Clinical endocrinology cases present unique challenges to veterinary students, as assessment and management encompasses various shades of grey. In order to process nuances and make clinical decisions, students must have a firm grasp of the basic tenets of endocrine physiology, such as the relationship between various hormones and negative feedback loops. We hypothesized that incorporating current diabetes monitoring technology into a handson firstyear veterinary physiology laboratory would improve their understanding of glucose homeostasis. Students receive didactic instruction in foundational endocrine physiology concepts during their physiology lecture class. The laboratory applies the concept of glucose homeostasis and the role of insulin and counterregulatory hormones, as well as the impetus for clinical decisionmaking in hypoglycemic patients. Before entering the laboratory, students complete a prelaboratory questionnaire assessing medical math, glucose homeostasis concepts, and overall predictions for decisionmaking as a team (approximately six students per laboratory group). Each group is assigned a dog from the Veterinary Physiology and Pharmacology (VTPP) teaching colony. The dogs are nondiabetic and fasted the night before the laboratory takes place. A flash glucose monitoring system (FGMS), which measures interstitial glucose concentration, is applied to each dog before the start of that days laboratory. The students must weigh their dog and calculate a dose of regular insulin at 0.3 U/kg; one of the abstracts authors double checks each dose for accuracy. Students administer regular insulin intravenously and use various methods to check the blood glucose with a portable blood glucose meter (PBGM) and the interstitial glucose concentration with the FGMS every 10 minutes. Based on the glucose concentration and the dogs clinical signs, students are empowered to make corrections using a single dose of dexamethasone, intravenous dextrose, and/or food. Once the dog is normoglycemic and they have completed at least 90 minutes worth of readings, the exercise is complete. Students complete a postlaboratory survey assessing the same concepts as the prelaboratory survey. In the prelaboratory survey, students frequently commented that they expected to gain a better understanding of glucose homeostasis and the effects of insulin on dogs. They discussed delegating work and the impact of various communication styles on the overall flow of the laboratory session. In the postlaboratory survey, students frequently commented on their newfound respect for how rapidly insulin acts within the body, as well as treating the clinical signs of hypoglycemia quickly. The students identified communication obstacles and various techniques and solutions developed in a short time period. Our endocrine physiology laboratory cements key concepts introduced in lecture, as 94% (164/174) of students reported that the laboratory improved their understanding of glucose homeostasis. When asked if their group communicated well, 97% (168/174) of students agreed. The laboratory is uniquely situated to blend conceptual physiology knowledge with critical thinking and clinical decisionmaking skills.
|
Apparent precoupling of kappa- but not mu-opioid receptors with a G protein in the absence of agonist. Rabbit and guinea-pig cerebellum membranes contain a very high (greater than 80%) proportion of mu- and kappa-opioid receptors, respectively. Rabbit (mu) and guinea-pig (kappa) cerebellum membranes were (i) labeled either with the opiate agonist, etorphine (Kd = 0.1-0.2 nM), or with the opiate antagonist, diprenorphine (Kd = 0.1 nM), in the absence or presence of Na+ and/or 5'-guanylylimidodiphosphate (GppNHp), (ii) solubilized with digitonin (1%, w:v) and (iii) the radioactivity in the soluble extracts analyzed by ultracentrifugation in sucrose gradients. In the soluble extracts from rabbit cerebellum (mu) membranes, bound etorphine sedimented faster (S20,w congruent to 12S) than bound diprenorphine (10S), while in those from guinea-pig cerebellum (kappa) membranes, bound etorphine and bound diprenorphine sedimented at the same position (12S). Na+ selectively decreased recovery of the bound tritiated agonist in the two soluble preparations. When they had been generated in the presence of GppNHp but in the absence of Na+, the etorphine complexes of the mu- and kappa-opioid receptors as well as the diprenorphine complex of the kappa-opioid receptor were all recovered at position 10S, indicating that GppNHp had induced a decrease of the apparent molecular size of the two types of opioid receptors. These data are interpreted in terms of mu- and kappa-opioid receptors being capable of physically interacting with a G protein (GTP binding regulatory protein) yet, unlike the mu-opioid receptor which does so only in the presence of an agonist, the kappa-opioid receptor appears to be precoupled with a G protein.
|
Financial Services Trade and Investment Board
The Financial Services Trade and Investment Board (FSTIB) is part of HM Treasury and is a partnership between the UK Government and industry. The Board meets on a quarterly basis to develop high-growth initiatives such as Renminbi internationalisation, green finance and financial technology. Its aim is to strengthen Britain's position as the centre of global finance and deliver jobs and growth across the country.
The FSTIB works closely with the Financial Services Organisation (FSO). The FSO is a key delivery partner for the FSTIB's initiatives.
History
The FSTIB was formed by Chancellor George Osborne in Budget 2013 to promote the UK's financial services industry. The Board first met on October 8, 2013, and was charged with leading the government's drive to promote external trade, attract inward investment and lift market access barriers for the UK's financial services sector.
In July 2015, the Chancellor re-launched the FSTIB with a new board composed of senior representatives from across government and industry.
|
/**
* Test of getCODIGO_EMPLEADO method, of class Empleado.
*/
@Test
public void testNuevoempleado() {
Calendar fc_nac = Calendar.getInstance();
fc_nac.set(1980, 1,20);
System.out.println("testNuevoempleado");
Empleado empleado = new Empleado();
empleado.setCODIGO_PAIS(1);
empleado.setCODIGO_TIPDOC(1);
empleado.setNRO_DOC("45818405");
empleado.setAPELLIDO_PATERNO("HUARCAYA");
empleado.setAPELLIDO_MATERNO("SALAS");
empleado.setNOMBRES("JONATHAN");
empleado.setFECHA_NACIMIENTO(fc_nac.getTime());
empleado.setDOMICILIO("Av. Paso de los Andes 1171");
empleado.setEMAIL("[email protected]");
int expResult = 0;
int result = empleado.getCODIGO_EMPLEADO();
assertEquals(expResult, result);
}
|
import base64
from utils import *
from ts.utils.util import map_class_to_label
from ts.torch_handler.vision_handler import VisionHandler
from ts.torch_handler.image_classifier import ImageClassifier
class MultiImageClassifier(ImageClassifier):
def lala(l): return l
# # def __init__(self, model):
# # super().__init__()
# """
# ImageClassifier handler class. This handler takes an image
# and returns the name of object in that image.
# """
# # topk = 5
# # These are the standard Imagenet dimensions
# # and statistics
# image_size = 512
# mean, std = tensor([0.4850, 0.4560, 0.4060]), tensor([0.2290, 0.2240, 0.2250])
# image_processing = instant_tfms(h=image_size, w=image_size, img_mean=mean, img_std=std, test_tfms=False)
# # image_processing = transforms.Compose([
# # transforms.Resize(600),
# # transforms.CenterCrop(image_size),
# # transforms.ToTensor(),
# # transforms.Normalize(mean=[0.485, 0.456, 0.406],
# # std=[0.229, 0.224, 0.225])
# # ])
# def preprocess(self, data):
# """The preprocess function of MNIST program converts the input data to a float tensor
# Args:
# data (List): Input data from the request is in the form of a Tensor
# Returns:
# list : The preprocess function returns the input image as a list of float tensors.
# """
# images = []
# for row in data:
# # Compat layer: normally the envelope should just return the data
# # directly, but older versions of Torchserve didn't have envelope.
# image = row.get("data") or row.get("body")
# if isinstance(image, str):
# # if the image is a string of bytesarray.
# image = base64.b64decode(image)
# # If the image is sent as bytesarray
# if isinstance(image, (bytearray, bytes)):
# image = Image.open(io.BytesIO(image))
# image = apply_tfms(image, self.image_processing)
# print(f'IMAAGGEEE SSSHHHAAAPPPEEEE: {image.shape}')
# else:
# # if the image is a list
# image = torch.FloatTensor(image)
# images.append(image)
# return torch.stack(images).to(self.device)
# def set_max_result_classes(self, topk):
# self.topk = topk
# def get_max_result_classes(self):
# return self.topk
# def postprocess(self, data):
# thresh = 0.65
# p_idx = []
# idx = F.sigmoid(data) > thresh
# idx = idx.tolist()
# classes = [[j for j,x in enumerate(id) if x] for id in idx]
# probs = [data[i][id].tolist() for i,id in enumerate(classes)]
# return map_class_to_label(probs, self.mapping, classes)
|
//
// BaseViewController.h
// WeChat
//
// Created by Siegrain on 16/3/28.
// Copyright © 2016年 siegrain. weChat. All rights reserved.
//
#import <UIKit/UIKit.h>
@interface BaseViewController : UIViewController
@end
|
That same facial-recognition software that simplifies the process of tagging Facebook photos will soon help make sure your photo isn’t being used as a stranger’s profile picture. On Tuesday, December 19, the company announced new (but optional) Facebook facial recognition tools, along with a handful of new options designed to help curb harassment.
The first tool uses the same software that automatically tags you in photos to look for you in someone else’s profile picture. The tool is designed to combat social media impersonation. If you have the facial-recognition tool turned on, you will get a notification if Facebook spots your face in someone else’s profile picture.
Facebook will also begin to send users notifications if they detect your mug in a photo that wasn’t tagged. The option, Facebook says, allows users to choose whether or not to tag themselves or to reach out to the posting user with concerns. The catch? You will only get a notification if the image was shared either publicly or in a group you are included in, so the privacy settings of the photo aren’t violated.
While users could turn facial recognition on and off before, Facebook is also simplifying the setting with a single control based on user feedback. Now, users can choose whether to use the facial recognition with one setting rather than setting all of the subcategories. The tools are also launching with expanded systems for visually impaired users that will now include names in the alt-text tool that describes what’s in a photo.
Facebook’s facial-recognition tools have been around since 2010. Earlier this year, Facebook launched other profile photo tools with a similar goal to protect users. The newest tools are rolling out soon, excluding Canada and the European Union, where facial recognition isn’t currently available.
Along with the facial-recognition tools, Facebook today also introduced new options designed for combatting harassment by preventing second accounts from a blocked user from contact and launching options for ignoring (but not blocking) messages.
For users that block a harasser, Facebook is working to help make sure the same person doesn’t create a second account to attempt to contact them after being blocked. The tool works by looking at different signals, such as the IP address, that suggests the new friend request or message is coming from someone the user has already blocked.
A new ignore feature for messages now allows users to stop receiving notifications for new messages without blocking the user entirely. Ignored messages also disable the tool that shows the sender when the messages have been read. The messages are moved to a filtered folder, where they can still be accessed.
The new tools for preventing harassment are a result of working with organizations and safety experts, including groups for domestic violence survivors, as well as discussing the tools with journalists, Facebook said.
|
When last Friday Russian Ministry of Defense announced that Syrian forces had broken through to the Iraqi border and enveloped the US forces in southern Syria this came as a shock to us here at RI.
Not because this was some move nobody could see coming. Anyone who can read a map could see that a Syrian advance to the east of US positions at al-Tanf base would effectively neutralize it. I spelled out as much a week before the Syrian offensive took place:
The obvious play for the Russian-backed Syrians is to neutralize Americans at al-Tanf by giving their base a 55 kilometer-wide berth and punch through to the Iraqi border further east. Such a maneuver would end US dreams of al-Tanf as a staging point for a push into the Euphrates valley and make it into an irrelevant, isolated outpost in the desert.
No, the shocking part was how quickly the Syrians advanced and with how little warning. Without any previous indication that they intend to do so, the Syrian forces covered 184 kilometers of barren desert in a single day.
It took place so unexpectedly and with such speed that the first we heard about it was when it was all already over — the Syrians were already shaking hands with Iraqis on their joint borders and the Americans had been cut off.
A 184 kilometer march executed in a single day would be a feather in the cap of any force, but is particularly impressive in the Syrian context where advances tend to be far, far slower.
Also, there were no prior announcements or social media rumors that such a move was being prepared — for once the Syrians kept their plans and preparations to themselves.
Additionally, it of was of great help that it took place while all eyes (and American bombs) were focused on much smaller forces testing the US-proclaimed 55 kilometer exclusion zone further east — and which may have been diversionary moves.
We have now learned that the US military was no less shocked by the advance than you and I. Testifying before Congress US Defense Secretary Mattis explained:
“As far as the Tanf situation, that was another operating area that we had. I did not anticipate that the Russians would move there. We knew it was a possibility. I did not anticipate it at that time but it was not a surprise to our intelligence people who saw the potential for them to move out in that direction.”
So then, exactly like RI, the Pentagon saw “the potential” for a Syrian move in that direction (everybody did), but was completely taken aback by how suddenly and quickly it developed.
In military parlance the Syrians did not achieve a “strategic surprise” but they did achieve an “operational surprise”.
In all likelihood US brass could only predict a typical haphazard Syrian advance that would give it plenty of time to react against. Instead it was presented with a fait accompli within a day.
Pentagon grossly underestimated the Syrian forces. Indeed, Mattis had by all appearances convinced himself that Russians were not interested in southern Syria, and that a push to the Iraqi border was a solely Iranian-backed operation with which the Russians disagreed.
In fact, that the Russian Ministry of Defence timed its press briefing for almost the very moment (figuratively speaking) when Syrian and allied forces had reached the border would imply just the opposite was the case.
It also likely means that the Russians contributed heavily to the planning for the operation and that this reflected in its swiftness and professionalism. Indeed, Mattis who speaks of “Russians moving there” now seems to believe so.
Actually he should have known better from the start. Here at RI we always wrote about al-Tanf as ultimately being between the Russians and the US. After all if the Syrians want to restore a land border with Iraq and profit from some of the latter’s manpower reserves that is also in the Russian interest in Syria.
All images in this article are from the author.
|
#-------------------------------------------------------------------------------
# General APP configuration
#-------------------------------------------------------------------------------
MS_APP_PORT="8089"
#-------------------------------------------------------------------------------
# MongoDB Connection Details
#-------------------------------------------------------------------------------
MONGO_HOST = 'den01ygd.us.oracle.com'
MONGO_PORT = 27017
MONGO_USER = ''
MONGO_PASSWORD = ''
MONGO_DB_NAME = 'liftserverdb'
|
SLS TECHNIQUE FOR FABRICATION OF CAST PARTIAL DENTURE One of the ancient and common method for rehabilitation of Bilateral end saddle cases is by Removable Partial Denture (RPD)-The framework of cast partial denture (CPD) made by lost wax technique can have many manual/lab errors. To minimize the errors and save time selective laser sintering (SLS) can be used as a method for framework fabrication and designing can be done by computer assisted designing (CAD) method. This a case report of 38 year old female with Kennedy's class 2 CPD was planned for the rehabilitation and framework was fabricated using SLS method. The framework fabricated had clinically better t.
|
The Effectiveness of Land Transportation Policy and the Dynamics of Travel Planned Behavior during the COVID-19 Pandemic in Indonesia Since 2020, Indonesia has become the country with the highest positive confirmed cases of COVID-19 in Southeast Asia. This situation has urged the Government to issue a series of policies in the transportation sector, namely the Large-Scale Social Restrictions and the new habitual adaptation period or the New Normal Period. This research aims to understand the effectiveness of both land transportation policy implementations during the COVID-19 pandemic and the dynamics of driving factors behind people's decision to travel during those periods. By taking a sample of 941 respondents in two phases of the survey, the data were processed by using Wilcoxon Signed Rank Test and Multiple Linear Regressions to be discussed in the Theory of Planned Behavior perspective. Serial data collection on two phases of travel restriction policies makes it possible to identify the dynamics of people's travel behavior. The results indicate that the policies were generally successful in reducing travel frequency. However, there were significant dynamics of intentional driving factors to travel. The upper-middle-income group has a more stable attitude between the two phases of the land transport restriction policy. On the contrary, the lower-middle-income group shows a more dynamic pattern of travel behavior with a higher intention to travel for work, particularly in the second phase. These results imply that the government's travel restriction policies during the pandemic should consider different strategies to cope with the different factors influencing the travel decision of each group. © 2021. All Rights Reserved.
|
Social and Ecological Impact of PES Program in Arid Region: The case from Zhang-ye in Northwest China This paper research provides applications of the integrated assessment approach, appraise effects of the payments for environmental services (PES) program in Zhang-ye from social and ecological impact. The results find that, from 2002 to 2004, the score of social impact (voluntary action and satisfaction) in all districts is more than 0.5, but ecological impact in almost countries is below 0.5. It indicates that we gain a better effect on social impact in the implementation of the PES program, but there is not better ecological impact in the implementation of the PES program.
|
from unittest import TestCase
from json import dumps
import requests
class ContextClass(object):
def __init__(self, request, endpoint_params, method_params, header_params, body_params):
self.endpoint = request[0]
self.method = request[1]
self.header = request[2]
self.body = request[3]
# parameters
self.endpoint_params = endpoint_params
self.method_params = method_params
self.header_params = header_params
self.body_params = body_params
def setup():
#####################################
# TODO: HERE IS YOUR CODE
# Insert your code to define prerequisities of SUT
None
def verify(test_case, request_id, response, context):
"""
Method to describe the expected values for all test cases
Take into account that these if-else statements will be duplicated for all test cases
You can also rewrite whole method from scretch and use [TODO:] argument while calling
suiter to avoid code duplicate
"""
# DO NOT TOUCH THIS <DUPLICATE>
<VERIFY>
# DO NOT TOUCH THIS </DUPLICATE>
def teardown():
#####################################
# TODO: HERE IS YOUR CODE
# Write a code to set the SUT to it's original state
# if it is dependend on given test_case, add a 'test_case' parameter to this function
# and write a code for all test_cases
## def teardown(test_case):
None
def all_test_cases(test_case, request_id):
"""
List of all test cases in this test suite
"""
# DO NOT TOUCH THIS <DUPLICATE>
<TEST_CASE_LIST>
# DO NOT TOUCH THIS </DUPLICATE>
return (url, method, header, body)
class TestClass(TestCase):
<TEST_SEQUENCE>
|
A grant program to help downtown businesses improve the look of their buildings has proved so popular that it ran out of funds before the budget year began.
As a result, the City Council's Downtown Committee is considering borrowing from the fiscal 1997 budget for facade improvement.
"It's gone beyond our wildest imagination," Ald. Sue Klinkhamer, former chairwoman of the committee, said of the merchants' response to the program.
The city began the program last year by pledging to spend $100,000 annually for five years in facade grants. Business owners are responsible for paying for the project; the city reimburses half the cost.
But the city dipped into the fiscal 1996 facade budget by $15,000 to pay for last year's projects.
Last week, five days before the new fiscal budget year was to begin, the Downtown Committee pledged the remaining $85,000 to six projects, including $30,000 to help renovate the Hotel Baker.
Klinkhamer said a way to come up with more funds is taking it out of the $100,000 the city planned to spend on the facade program in fiscal 1997, when the Illinois Department of Transportation plans to rebuild Illinois Highway 64 through downtown.
|
A bitcoin ATM was revealed at a London conference today, allowing users to convert bank notes into the digital currency.
The machine, from start-up Lamassu Bitcoin Ventures, lets users buy bitcoins, but doesn't allow the reverse transfer, from the digital currency to hard cash.
To use the ATM, you need to have an existing Bitcoin wallet number. First, it scans a QR code of your Bitcoin address. Then, the user has to feed bank notes into the machine, which are converted at the current exchange rate and deposited into their account. While the deposit takes moments, it can take several minutes for an account to be updated.
Find out more Bitcoin: the digital currency and how to buy it
Bitcoin can be purchased via online exchange sites, but the ATM means you don't need to use a credit or bank card, helping to keep the transactions anonymous, the company said.
"As banks in countries such as Canada and Israel make purchasing bitcoins from online exchanges more difficult, the Bitcoin Machine could serve as a worthy alternative," the company said. "Online exchanges are bound to the world's banking system as they require customers to hold bank accounts for buying and selling bitcoin. By accepting cash in all currencies, Lamassu's Bitcoin Machine is able to bypass any banking system."
The machine was first shown off in May in the US with American dollars, but has now been setup to be used in Europe. The company hopes to ship the devices globally in the autumn, and they will cost between $4,000 and $5,000.
Bitcoin is currently priced at about $90, after hitting highs above $260 earlier this year.
|
Though he ended his SportsLine radio show on WJEJ-AM in 2002, Russ Wiebel's reputation as a promoter of youth sports and young people in general never faded for his many friends and fans.
Wiebel died Thursday at the age of 79.
"Russ was one of the most beloved people in this area," said Lou Scally, who knew Wiebel through their years as fellow broadcasters.
Scally, who also is a weatherman at NBC25, pointed out that Wiebel also had the distinction of having his name on a bronze plaque at the new South Hagerstown High School press box.
Wiebel also is a member of the Washington County Sports Hall of Fame.
To many, Wiebel was the voice of high school and college sports, both on the radio and announcing games live.
"He officiated at ball games, and played sports for many years, too," Scally said.
Retired NBC25 sportscaster Glenn Presgraves first knew Wiebel when both men worked at the U.S. Post Office in the 1960s.
"I got into broadcasting auto racing because of Russ," Presgraves said. "We were always good friends through the years ... never competitors."
Carroll Reid, who retired in 1996 after 30 years coaching football at Smithsburg High School, said Wiebel meant a lot to him and many others to whom sports was a passion.
"Russ did it all and with endless energy," Reid said. "He was responsible for promoting sports in the area."
Dwight Scott, retired coach at Boonsboro High School, took that one step further and called Wiebel a pioneer in getting high school football broadcast on local radio.
"On his Monday night show, he had the local coaches on the air, and that was extremely beneficial for trying to get the message out about supporting youth," Scott said.
Jim Brown recalled his days at North Hagerstown High School when Wiebel was the voice of the Hubs.
"He broadcast our games at North and then at Hagerstown Community College," Brown said.
After leaving North as coach, Brown went to HCC, where he retired as athletic director and head basketball coach.
Brown said Wiebel and his wife, Helen, truly were a team, often sitting together while he broadcast games.
Brown also credited Wiebel and former Boston University coach Roy Sigler with initiating delayed broadcasts of games over Antietam Cable Television in the 1980s and 1990s, which was another big boost to local sports.
As president/general manager of WJEJ, John Staub said he has known Wiebel for most of his 34 years at the station.
"He was very sincere and very friendly, and it wasn't put on," Staub said. "Russ was a full-time supporter of any kind of youth sports."
|
. The results of 118 operations for club-foot are assessed, of these 57 were reoperations. It is stated that the relapse is most often the consequence of the insufficient primary operation and the relapse and the residual deformity are the more serious the more insufficient was the primary operation. The severity of the deformation is defined first of all by the position of the calcaneus. In milder cases the soft tissue operation only may be successful, in the more severe cases bony operation (Evans' operation in this series of the authors) has also to be performed. After their own primary operations reoperation was in 24 per cent necessary. The number of the bony operations was half of the soft tissue operations. The second and rarer case of the relapses was that the foot proved to be even originally rigid, not redressable, "rebel". First of all in these cases may multiple reoperations be necessary and the transposition of the anterior tibial muscle is also useful. The club-foot with a major dominant adduction deformity of the tarsometatarsal joint is thought to be a separate entity and it is corrected with tarsometatarsal capsulotomies or serial metatarsal osteotomies.
|
package basic
// DropWhilePtr returns a new list after dropping the given item
func DropWhilePtr() string {
return `
// DropWhile<FTYPE>Ptr drops the items from the list as long as condition satisfies.
//
// Takes two inputs
// 1. Function: takes one input and returns boolean
// 2. list
//
// Returns:
// New List.
// Empty list if either one of arguments or both of them are nil
func DropWhile<FTYPE>Ptr(f func(*<TYPE>) bool, list []*<TYPE>) []*<TYPE> {
if f == nil {
return []*<TYPE>{}
}
var newList []*<TYPE>
for i, v := range list {
if !f(v) {
listLen := len(list)
newList = make([]*<TYPE>, listLen-i)
j := 0
for i < listLen {
newList[j] = list[i]
i++
j++
}
return newList
}
}
return newList
}
`
}
// DropWhilePtrErr returns a new list after dropping the given item
func DropWhilePtrErr() string {
return `
// DropWhile<FTYPE>PtrErr drops the items from the list as long as condition satisfies.
//
// Takes two inputs
// 1. Function: takes one input and returns (boolean, error)
// 2. list
//
// Returns:
// New List, error
// Empty list if either one of arguments or both of them are nil
func DropWhile<FTYPE>PtrErr(f func(*<TYPE>) (bool, error), list []*<TYPE>) ([]*<TYPE>, error) {
if f == nil {
return []*<TYPE>{}, nil
}
var newList []*<TYPE>
for i, v := range list {
r, err := f(v)
if err != nil {
return nil, err
}
if !r {
listLen := len(list)
newList = make([]*<TYPE>, listLen-i)
j := 0
for i < listLen {
newList[j] = list[i]
i++
j++
}
return newList, nil
}
}
return newList, nil
}
`
}
// DropWhileErr returns a new list after dropping the given item
func DropWhileErr() string {
return `
// DropWhile<FTYPE>Err drops the items from the list as long as condition satisfies.
//
// Takes two inputs
// 1. Function: takes one input and returns (boolean, error)
// 2. list
//
// Returns:
// New List, error
// Empty list if either one of arguments or both of them are nil
func DropWhile<FTYPE>Err(f func(<TYPE>) (bool, error), list []<TYPE>) ([]<TYPE>, error) {
if f == nil {
return []<TYPE>{}, nil
}
var newList []<TYPE>
for i, v := range list {
r, err := f(v)
if err != nil {
return nil, err
}
if !r {
listLen := len(list)
newList = make([]<TYPE>, listLen-i)
j := 0
for i < listLen {
newList[j] = list[i]
i++
j++
}
return newList, nil
}
}
return newList, nil
}
`
}
|
Adaptation of the PERCEPT myeloma prehabilitation trial to virtual delivery: changes in response to the COVID-19 pandemic Introduction and objective Research activity was impacted by the novel COVID-19 pandemic, the PERCEPT myeloma trial was no exception. This pilot randomised trial delivered a face-to-face exercise intervention prior to and during autologous stem cell transplantation (ASCT) in myeloma patients, as a consequence of COVID-19 it required significant adaptions to continue. This brief communication describes how the previously published study protocol was adapted for virtual delivery. In addition, we highlight the challenge of continuing the study which was embedded within a clinical pathway also impacted by the pandemic. Summary The original trial protocol was amended and continued to recruit and deliver an exercise prehabilitation intervention virtually. Continued delivery of the intervention was deemed important to participants already enrolled within the trial and the adapted virtual version of the trial was acceptable to the research ethics committee as well as participants. Development of effective, remotely delivered rehabilitation and physical activity programmes are likely to benefit people living with myeloma. The COVID-19 pandemic provided an opportunity to explore the feasibility of a virtual programme for ASCT recipients, however, continued changes to the clinical pathway within which the study was embedded posed the greatest challenge and ultimately led to early termination of recruitment. Trial registration number ISRCTN15875290; pre-results INTRODUCTION The threat of the novel COVID-19 and declaration of a pandemic greatly impacted research activity around the world with many studies and trials paused and recruitment ceased unless COVID-19 related or providing potential life preserving interventions. 1 Pandemic responses led to changes in how clinical services were delivered across health systems, with many usual face to face outpatient activities changing quickly to be remotely delivered via telephone or video. 2 Reports have detailed how clinical services and clinical trials adapted in response to the need to lower the threat posed by COVID-19, 3 4 initially through reduced face-to-face attendance at healthcare institutions and protecting the most clinically vulnerable by promoting minimal activity outside of the home, practising social distancing and discouraging use of public transport. 5 In the UK, people considered to be clinically extremely vulnerable, such as those with haematological cancers, were advised to shield to protect themselves from exposure to infection. As a result, clinical pathways and research protocols required significant adaptations to continue. We report the challenges of continuing and adapting a prehabilitation and rehabilitation exercise intervention trial in response to the COVID-19 outbreak and subsequent changes to the clinical pathway into which the trial was integrated. This communication seeks to document changes to our previously published protocol, as well as facilitate study design in the immediate post pandemic era where future interventional trials need to be adaptable in case of unexpected future pandemics or other health emergencies. BACKGROUND TO TRIAL The PERCEPT myeloma prehabilitation study was a pilot, single-centre, randomised controlled trial (RCT) that aimed to investigate the feasibility of a physiotherapist-led exercise intervention, designed to be embedded as an integral part of an established clinical pathway for patients with multiple myeloma undergoing autologous stem cell transplantation (ASCT). Recruitment to the trial commenced at University College Hospital London (UCLH) in June 2019. In summary, all patients referred to the centre for consideration of ASCT for management Open access of myeloma, who were willing to and clinically able to undertake an exercise training programme and had good command of written and spoken English were eligible and approached. The trial assessments included a range of objective measures of functional capacity (6 min walk test, 30 s timed sit to stand test, hand grip strength test, levels of physical activity) as well as patient-reported outcome measures assessing quality of life (Functional Assessment of Cancer Therapy (FACT) bone marrow transplant and European Organisation for Research and Treatment of Cancer Quality of Life Questionnaire-C30), fatigue (FACT fatigue subscale) and physical activity behaviour (International Physical Activity Questionnaire and exercise self-efficacy scale). Assessments were initially designed to be conducted face to face at established touchpoints within the clinical pathway that usually coincided with patient attendance at transplant clinic appointments. The intervention involved an exercise intervention with incorporated behaviour change techniques, delivered in part through weekly face to face, group-based exercise sessions at a UCLH gym supervised by a physiotherapist and through unsupervised home exercise sessions with telephone support in the post-ASCT rehabilitation phase. Participants were asked to exercise three times per week, at moderate to high intensity, for 30 min of aerobic exercise and complete a programme of resistance exercises. Exercise was individually tailored and progressed by the study physiotherapist. In the prehabilitation phase before ASCT participants were expected to attend weekly supervised gym sessions and exercise independently twice per week. During hospital admission and following discharge from hospital participants were supported to continue three unsupervised exercise sessions per week with weekly telephone guidance from a physiotherapist. The original trial was registered (ISRCTN15875290) and the protocol is described in detail elsewhere. 9 TRIAL RECRUITMENT PRIOR TO THE PANDEMIC Trial recruitment was progressing as planned and between June 2019 and end of February 2020 90 potential participants had been identified and screened for eligibility. Of those, n=36 (40%) consented to take part and were randomised, n=8 (9%) were ineligible and n=46 (51%) declined. The main reasons for declining to take part were travel or distance to take part in the intervention, poor mobility/inability to use public transport and already having too many hospital appointments. Many of those who declined had a favourable opinion of the trial and would have taken part if it was closer to their home. It had been anticipated that target recruitment (n=60-75) would be reached by December 2020. Face-to-face recruitment was paused in March 2020, due to the COVID-19 pandemic, when all but essential NHS research activity was instructed to cease and research physiotherapists were redeployed to clinical services. In addition, the myeloma ASCT service was also paused due to resource limitations, lack of critical care provision and increased risk of COVID-19 infection in transplant recipients. RESUMING RECRUITMENT AND ADAPTATION TO VIRTUAL INTERVENTION DELIVERY Between March and June 2020, all participants already enrolled within the trial expressed their wish to continue in the trial while awaiting their delayed ASCT. All participants were placed on holding chemotherapy by their clinical teams. A minor ethics amendment was granted to allow participants to remain in the trial longer than in the original protocol, to continue delivery of the homebased component of the exercise intervention via telephone support and to collect follow-up assessment data via postal delivery of trial questionnaires. Following resumption of the myeloma ASCT clinical service in June 2020, elements of the clinical pathway on which the trial procedures were designed had changed significantly in response to the ongoing threat of the pandemic. Namely, patients were no longer attending UCLH clinics in person in the lead up to their ASCT and were instead receiving telephone contact for clinic appointments. It was therefore necessary to adapt the trial to accommodate these changes to the clinical pathway. Patient and public involvement Participants who had remained in the study during the first national lock down were consulted on how best to proceed with the trial. These participants were asked to consider their acceptability of receiving study assessments/questionnaires via post, and importantly, how they would feel about only having access to the physiotherapist and exercise intervention via video platform. Overwhelmingly, they supported adapting the trial to virtual delivery and reported that having regular contact with the study physiotherapist was supportive, especially as they were no longer attending their clinical services in person. Some reported that the exercise intervention was something positive to focus on while feeling apprehensive about having their ASCT delayed and remaining limited in their social activities due to shielding. These participants were consulted on the proposed substantial amendment and gave their approval to the changes described in this manuscript. Following review of emerging literature for adapting pulmonary rehabilitation services to virtual delivery and liaising with other cancer rehabilitation services delivering exercise virtually, the trial design was substantially amended. Virtual recruitment, consenting and baseline assessments ► Identifying potential participants from a list of patients awaiting consideration for ASCT, rather than from weekly clinic lists of expected clinic attendance. ► An additional inclusion criterion was added to require patients to have access to and the ability to Open access use internet-based videoconferencing platform, or a family member to facilitate access. ► Participants were sent trial consent forms, selfcomplete questionnaire measures and a preprogrammed ActivPAL accelerometer by post and a Zoom video call appointment was arranged for approximately 3 days later. Completion of consent forms, baseline questionnaires and fitting of accelerometer discussed and conducted virtually over Zoom appointment. ► Addition of the Activities-Specific Balance Confidence Scale 13 to assess risk of falling, used to screen those randomised to the intervention for any necessary actions required to reduce risk of exercising at home as no longer objectively assessed by the physiotherapist face to face. If any participant scored <65% on the scale they would be deemed high risk of falling 14 and their assessment and participation in the group sessions would be adapted to minimise risk. ► Objective measure of functional capacity changed to a remotely delivered 1 min timed sit to stand test, which has been demonstrated to induce comparable cardiovascular stress and lower limb muscle fatigue as the 6 min walk test. 15 Virtual delivery of the partly supervised exercise intervention ► The intervention delivery was changed to be completely online but following the principles of the original protocol in terms of frequency, intensity, time and type of exercise. Each new participant had an initial one to one session to introduce the programme and tailor to their individual abilities, including any symptoms of bone disease or balance deficits. Each participant was then asked to attend a weekly virtual group-based exercise class via Zoom until they were admitted for their ASCT. RECRUITMENT TO VIRTUAL TRIAL TO DATE Recruitment restarted after the first wave of the pandemic in August 2020. Up to October 2020 a further 33 potential participants were identified and screened for eligibility. Of those, 14 (43%) agreed and consented to take part, 6 (18%) were ineligible and 13 (39%) declined. This indicates that uptake to the virtual part of the trial was similar to the original face to face design. Despite fewer people declining the virtual trial, more people were ineligible. The main reason for increased proportion of ineligibility was related to some potential participants already having a date to be admitted for ASCT within the succeeding 2-4 weeks or not having access to the internet. With the resurgence of COVID-19 in the Autumn of 2020 and as clinical services for ASCT were disrupted again, it was decided to cease recruitment to the trial. The predominant challenge to the adapted trial was variable intervals between timepoints, which differed in length from those detailed in the original study schedule. Further, a small number of participants were withdrawn from the trial as their planned ASCT was deferred or delayed due to clinical risk of proceeding with the ongoing threat of the COVID-19 virus and prioritisation of ASCT admissions based on clinical need in this context. The main aim of the study was to investigate the feasibility of delivering an intervention embedded within an existing clinical pathway. As the pathway on which the trial was designed was significantly affected by the COVID-19 pandemic, which would likely continue to affect the pathway for some time, it was agreed by the study team that little more would be gained by recruiting further. The trial continued in follow-up until all those recruited either reached the final timepoint following ASCT or were withdrawn. The challenges to timely recruitment and delivery of the trial time points as based on the clinical ASCT pathway have implications on study design and will be addressed with the full reporting of the trial which is expected in 2022. CONCLUSION The emergence of the COVID-19 pandemic required significant adaptation for the continuation of this pilot RCT. Our sample population being clinically extremely vulnerable were advised to shield, as well as the requirement to reduce all but clinically necessary face to face contact altered how potential ASCT recipients accessed the clinical setting and consequently the planned trial delivery. We have briefly described how the trial protocol was amended and continued to recruit to and deliver a prehabilitation intervention virtually. Adaptation to virtual delivery was deemed important to participants already enrolled within the trial and appears to have been acceptable for the adapted virtual version of the trial while this was possible. The original trial design relied heavily on participant attendance at face-to-face clinical contacts as part of the routine ASCT pathway as it existed prepandemic. This was a strength in terms of increasing likely participation in follow-up study assessments and ensuring completeness of data capture as participants would be present in the centre at the planned follow-up time points. However, the assumption that all assessments would be conducted face to face resulted in a reliance on paper-based questionnaires and because study resources did not allow for transformation to electronic data capture, postal follow-up assessment was required. On reflection, the original study would have been somewhat future proofed had electronic questionnaires and intervention materials been incorporated at design and should certainly be a requirement of future work. As ASCT recipients with myeloma are generally older, with high incidence of disease-related bone disease, deconditioned by induction chemotherapy with possible impairments to mobility and function, adapting the trial to explore feasibility of a virtually delivered physiotherapy intervention was an important opportunity arising from the threat posed by the pandemic. Considering the possible increased risk from not assessing participants face to face, required implementation of a remotely delivered Open access balance assessment tool, an alternate objective measure of functional capacity suitable for remote assessment and on-line adaptation of intervention delivery to include a virtual group-based exercise class were all important steps. Development of effective, remotely delivered rehabilitation and physical activity programmes are likely to be increasingly valuable to people living with myeloma for whom shielding during clinically vulnerable periods of treatment and recovery, and travel to their specialist treatment centres will be continuing challenges in the post pandemic era.
|
package net.jackofalltrades.taterbot.service;
public class ChannelServiceStatusException extends RuntimeException {
public ChannelServiceStatusException(Service.Status actualStatus, Service.Status expectedStatus) {
super(String.format("Service is currently in '%s' status, but was supposed to be in '%s' status.",
actualStatus.name(), expectedStatus.name()));
}
}
|
/*
* CDDL HEADER START
*
* The contents of this file are subject to the terms of the
* Common Development and Distribution License, Version 1.0 only
* (the "License"). You may not use this file except in compliance
* with the License.
*
* You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE
* or http://www.opensolaris.org/os/licensing.
* See the License for the specific language governing permissions
* and limitations under the License.
*
* When distributing Covered Code, include this CDDL HEADER in each
* file and include the License file at usr/src/OPENSOLARIS.LICENSE.
* If applicable, add the following below this CDDL HEADER, with the
* fields enclosed by brackets "[]" replaced with your own identifying
* information: Portions Copyright [yyyy] [name of copyright owner]
*
* CDDL HEADER END
*/
/*
* Copyright (c) 1999 by Sun Microsystems, Inc.
* All rights reserved.
*/
#ifndef _ICONV_TM_H
#define _ICONV_TM_H
#pragma ident "%Z%%M% %I% %E% SMI"
#ifdef __cplusplus
extern "C" {
#endif
#include <inttypes.h>
#include <sys/isa_defs.h>
#include <sys/types.h>
#if !defined(DEBUG)
#define NDEBUG /* for assert() */
#endif /* DEBUG */
#if defined(DEBUG)
#define ENABLE_TRACE
#endif /* DEBUG */
#define MAXSEQUENCE (128)
#define MAXREGID (256)
#define MAXNAMELENGTH (255)
/*
* ITM Identifier
*/
#define ITM_IDENT_LEN (4)
#define ITM_IDENT_0 (0x49)
#define ITM_IDENT_1 (0x54)
#define ITM_IDENT_2 (0x4d)
#define ITM_IDENT_3 (0x00)
/*
* ITM Platform Specification
*/
#define ITM_SPEC_LEN (4)
#define ITM_SPEC_0 (0)
#define ITM_SPEC_1 (0)
#define ITM_SPEC_2 (0)
#define ITM_SPEC_3_UNSPECIFIED (0)
#define ITM_SPEC_3_32_BIG_ENDIAN (1)
#define ITM_SPEC_3_32_LITTLE_ENDIAN (2)
#define ITM_SPEC_3_64_BIG_ENDIAN (3)
#define ITM_SPEC_3_64_LITTLE_ENDIAN (4)
/*
* ITM Version
*/
#define ITM_VER_LEN (4)
#define ITM_VER_0 (0)
#define ITM_VER_1 (0)
#define ITM_VER_2 (0)
#define ITM_VER_3 (1)
/*
* PADDING
*/
#define ITM_PAD_LEN (4)
/*
* Generic offset&pointer/data/string
*/
typedef uint32_t pad_t;
typedef ulong_t itm_type_t;
typedef uintptr_t itm_place2_t; /* position of data */
typedef size_t itm_size_t;
typedef long itm_num_t;
typedef union itm_place_union {
int64_t itm_64d; /* positon of real data */
struct {
#if !defined(_LP64) && !defined(_LITTLE_ENDIAN)
pad_t pad;
#endif
itm_place2_t ptr;
#if !defined(_LP64) && defined(_LITTLE_ENDIAN)
pad_t pad;
#endif
}itm_place_union_struct;
char itm_c[8];
} itm_place_t;
#define itm_ptr itm_place_union_struct.ptr
#define itm_pad itm_place_union_struct.pad
typedef struct {
#if !defined(_LP64) && !defined(_LITTLE_ENDIAN)
pad_t pad;
#endif
itm_size_t size; /* size in bytes */
#if !defined(_LP64) && defined(_LITTLE_ENDIAN)
pad_t pad;
#endif
itm_place_t place; /* place of data */
} itm_data_t;
/*
* Generic place table information
*/
typedef struct {
#if !defined(_LP64) && !defined(_LITTLE_ENDIAN)
pad_t pad1;
#endif
itm_size_t size; /* size in bytes */
#if !defined(_LP64) && defined(_LITTLE_ENDIAN)
pad_t pad1;
#endif
itm_place_t place; /* place of place table */
#if !defined(_LP64) && !defined(_LITTLE_ENDIAN)
pad_t pad2;
#endif
itm_num_t number; /* number of entry */
#if !defined(_LP64) && defined(_LITTLE_ENDIAN)
pad_t pad2;
#endif
} itm_place_tbl_info_t;
/*
* Generic place table section
*/
typedef struct {
#if !defined(_LP64) && !defined(_LITTLE_ENDIAN)
pad_t pad1;
#endif
itm_size_t size; /* size in bytes */
#if !defined(_LP64) && defined(_LITTLE_ENDIAN)
pad_t pad1;
#endif
itm_place_t place; /* place of table section */
#if !defined(_LP64) && !defined(_LITTLE_ENDIAN)
pad_t pad2;
#endif
itm_num_t number; /* number of table */
#if !defined(_LP64) && defined(_LITTLE_ENDIAN)
pad_t pad2;
#endif
} itm_section_info_t;
/*
* Generic table header
*/
#define ITM_TBL_MASK (0x000000ffUL)
#define ITM_TBL_NONE (0x00000000UL)
#define ITM_TBL_ITM (0x00000001UL)
#define ITM_TBL_DIREC (0x00000002UL)
#define ITM_TBL_COND (0x00000003UL)
#define ITM_TBL_MAP (0x00000004UL)
#define ITM_TBL_OP (0x00000005UL)
#define ITM_TBL_RANGE (0x00000006UL)
#define ITM_TBL_ESCAPESEQ (0x00000007UL)
#define ITM_TBL_NONE_NONE (ITM_TBL_NONE | 0x00000000UL)
#define ITM_TBL_DIREC_NONE (ITM_TBL_DIREC | 0x00000000UL)
#define ITM_TBL_DIREC_RESET (ITM_TBL_DIREC | 0x00000100UL)
#define ITM_TBL_COND_NONE (ITM_TBL_COND | 0x00000000UL)
#define ITM_TBL_MAP_NONE (ITM_TBL_MAP | 0x00000000UL)
#define ITM_TBL_MAP_INDEX_FIXED_1_1 (ITM_TBL_MAP | 0x00000100UL)
#define ITM_TBL_MAP_INDEX_FIXED (ITM_TBL_MAP | 0x00000200UL)
#define ITM_TBL_MAP_LOOKUP (ITM_TBL_MAP | 0x00000300UL)
#define ITM_TBL_MAP_HASH (ITM_TBL_MAP | 0x00000400UL)
#define ITM_TBL_MAP_DENSE_ENC (ITM_TBL_MAP | 0x00000500UL)
#define ITM_TBL_MAP_VAR (ITM_TBL_MAP | 0x00000600UL)
#define ITM_TBL_OP_NONE (ITM_TBL_OP | 0x00000000UL)
#define ITM_TBL_OP_INIT (ITM_TBL_OP | 0x00000100UL)
#define ITM_TBL_OP_RESET (ITM_TBL_OP | 0x00000200UL)
#define ITM_TBL_RANGE_NONE (ITM_TBL_RANGE | 0x00000000UL)
#define ITM_TBL_ESCAPESEQ_NONE (ITM_TBL_ESCAPESEQ | 0x00000000UL)
typedef struct {
#if !defined(_LP64) && !defined(_LITTLE_ENDIAN)
pad_t pad1;
#endif
itm_type_t type; /* type of table */
#if !defined(_LP64) && defined(_LITTLE_ENDIAN)
pad_t pad1;
#endif
itm_place_t name; /* name of table */
#if !defined(_LP64) && !defined(_LITTLE_ENDIAN)
pad_t pad2;
#endif
itm_size_t size; /* size of table */
#if !defined(_LP64) && defined(_LITTLE_ENDIAN)
pad_t pad2;
#endif
#if !defined(_LP64) && !defined(_LITTLE_ENDIAN)
pad_t pad3;
#endif
itm_num_t number; /* number of entry */
#if !defined(_LP64) && defined(_LITTLE_ENDIAN)
pad_t pad3;
#endif
} itm_tbl_hdr_t;
/*
* Iconv Code Set Translation Module (ITM) header
*/
typedef struct {
unsigned char ident[ITM_IDENT_LEN]; /* identifier */
unsigned char spec[ITM_SPEC_LEN]; /* platform specification */
unsigned char version[ITM_VER_LEN]; /* version */
unsigned char padding[ITM_PAD_LEN]; /* padding */
#if !defined(_LP64) && !defined(_LITTLE_ENDIAN)
pad_t pad1;
#endif
itm_size_t itm_hdr_size; /* ITM header size */
#if !defined(_LP64) && defined(_LITTLE_ENDIAN)
pad_t pad1;
#endif
itm_place_t itm_size; /* size of ITM (file size) */
itm_data_t type_id; /* type identifier */
itm_data_t interpreter; /* interpreter */
itm_place_t op_init_tbl; /* init operation table */
itm_place_t op_reset_tbl; /* reset operation table */
itm_place_t direc_init_tbl; /* initial direction table */
#if !defined(_LP64) && !defined(_LITTLE_ENDIAN)
pad_t pad3;
#endif
itm_num_t reg_num; /* number of register */
#if !defined(_LP64) && defined(_LITTLE_ENDIAN)
pad_t pad3;
#endif
itm_place_t info_hdr; /* ITM Info header */
} itm_hdr_t;
/*
* ITM Info header
*/
typedef struct {
itm_section_info_t str_sec; /* string section */
itm_section_info_t direc_tbl_sec; /* direction table section */
itm_section_info_t cond_tbl_sec; /* condition table section */
itm_section_info_t map_tbl_sec; /* map table section */
itm_section_info_t op_tbl_sec; /* operation table section */
itm_section_info_t range_tbl_sec; /* range section */
itm_section_info_t escapeseq_tbl_sec; /* escapeseq section */
itm_section_info_t data_sec; /* data section */
itm_section_info_t name_sec; /* name section */
itm_place_tbl_info_t str_plc_tbl; /* string info */
itm_place_tbl_info_t direc_plc_tbl; /* direction table info */
itm_place_tbl_info_t cond_plc_tbl; /* condition table info */
itm_place_tbl_info_t map_plc_tbl; /* map table info */
itm_place_tbl_info_t op_plc_tbl; /* operation table info */
itm_place_tbl_info_t range_plc_tbl; /* range info */
itm_place_tbl_info_t escapeseq_plc_tbl; /* escape info */
itm_place_tbl_info_t data_plc_tbl; /* data info */
itm_place_tbl_info_t name_plc_tbl; /* name info */
itm_place_tbl_info_t reg_plc_tbl; /* register name info */
} itm_info_hdr_t;
/*
* Direction
*/
typedef enum {
ITM_ACTION_NONE, /* not used */
ITM_ACTION_DIRECTION, /* direction */
ITM_ACTION_MAP, /* map */
ITM_ACTION_OPERATION /* operation */
} itm_action_type_t;
typedef struct {
itm_place_t condition;
itm_place_t action;
} itm_direc_t;
/*
* Condition
*/
typedef enum {
ITM_COND_NONE = 0, /* not used */
ITM_COND_BETWEEN = 1, /* input data is inside of ranges */
ITM_COND_EXPR = 2, /* expression */
ITM_COND_ESCAPESEQ = 3 /* escape sequense */
} itm_cond_type_t;
typedef struct {
pad_t pad;
itm_cond_type_t type;
union {
itm_place_t place;
itm_data_t data;
} operand;
} itm_cond_t;
typedef struct {
#if !defined(_LP64) && !defined(_LITTLE_ENDIAN)
pad_t pad;
#endif
itm_size_t len;
#if !defined(_LP64) && defined(_LITTLE_ENDIAN)
pad_t pad;
#endif
} itm_range_hdr_t;
typedef struct {
#if !defined(_LP64) && !defined(_LITTLE_ENDIAN)
pad_t pad1;
#endif
itm_size_t len_min;
#if !defined(_LP64) && defined(_LITTLE_ENDIAN)
pad_t pad1;
#endif
#if !defined(_LP64) && !defined(_LITTLE_ENDIAN)
pad_t pad2;
#endif
itm_size_t len_max;
#if !defined(_LP64) && defined(_LITTLE_ENDIAN)
pad_t pad2;
#endif
} itm_escapeseq_hdr_t;
/*
* Map table: octet-sequence to octet-sequence: index
*/
typedef struct {
#if !defined(_LP64) && !defined(_LITTLE_ENDIAN)
pad_t pad1;
#endif
itm_size_t source_len; /* source length */
#if !defined(_LP64) && defined(_LITTLE_ENDIAN)
pad_t pad1;
#endif
#if !defined(_LP64) && !defined(_LITTLE_ENDIAN)
pad_t pad2;
#endif
itm_size_t result_len; /* result length */
#if !defined(_LP64) && defined(_LITTLE_ENDIAN)
pad_t pad2;
#endif
itm_place_t start; /* start offset */
itm_place_t end; /* end offset */
#if !defined(_LP64) && !defined(_LITTLE_ENDIAN)
pad_t pad3_num;
#endif
itm_num_t default_error;
/*
* -1:path through
* 0:with default value
* 1:with error table
* 2:without error table
*/
#if !defined(_LP64) && defined(_LITTLE_ENDIAN)
pad_t pad3_num;
#endif
#if !defined(_LP64) && !defined(_LITTLE_ENDIAN)
pad_t pad4_num;
#endif
itm_num_t error_num;
#if !defined(_LP64) && defined(_LITTLE_ENDIAN)
pad_t pad4_num;
#endif
} itm_map_idx_fix_hdr_t;
/*
* Map table: octet-sequence to octet-sequence: lookup
*/
typedef struct {
#if !defined(_LP64) && !defined(_LITTLE_ENDIAN)
pad_t pad1;
#endif
itm_size_t source_len; /* source length */
#if !defined(_LP64) && defined(_LITTLE_ENDIAN)
pad_t pad1;
#endif
#if !defined(_LP64) && !defined(_LITTLE_ENDIAN)
pad_t pad2;
#endif
itm_size_t result_len; /* result length */
#if !defined(_LP64) && defined(_LITTLE_ENDIAN)
pad_t pad2;
#endif
#if !defined(_LP64) && !defined(_LITTLE_ENDIAN)
pad_t pad3_num;
#endif
itm_num_t default_error;
/*
* -1:path through
* 0:with default value
* 1:with error table
* 2:without error table
*/
#if !defined(_LP64) && defined(_LITTLE_ENDIAN)
pad_t pad3_num;
#endif
#if !defined(_LP64) && !defined(_LITTLE_ENDIAN)
pad_t pad4_num;
#endif
itm_num_t error_num;
#if !defined(_LP64) && defined(_LITTLE_ENDIAN)
pad_t pad4_num;
#endif
} itm_map_lookup_hdr_t;
/*
* Map table: octet-sequence to octet-sequence: hash
*/
typedef struct {
#if !defined(_LP64) && !defined(_LITTLE_ENDIAN)
pad_t pad1;
#endif
itm_size_t source_len; /* source length */
#if !defined(_LP64) && defined(_LITTLE_ENDIAN)
pad_t pad1;
#endif
#if !defined(_LP64) && !defined(_LITTLE_ENDIAN)
pad_t pad2;
#endif
itm_size_t result_len; /* result length */
#if !defined(_LP64) && defined(_LITTLE_ENDIAN)
pad_t pad2;
#endif
#if !defined(_LP64) && !defined(_LITTLE_ENDIAN)
pad_t pad3;
#endif
itm_size_t hash_tbl_size; /* hash table size */
#if !defined(_LP64) && defined(_LITTLE_ENDIAN)
pad_t pad3;
#endif
#if !defined(_LP64) && !defined(_LITTLE_ENDIAN)
pad_t pad4;
#endif
itm_num_t hash_tbl_num; /* hash table entryies */
#if !defined(_LP64) && defined(_LITTLE_ENDIAN)
pad_t pad4;
#endif
#if !defined(_LP64) && !defined(_LITTLE_ENDIAN)
pad_t pad5;
#endif
itm_size_t hash_of_size; /* hash overflow table size */
#if !defined(_LP64) && defined(_LITTLE_ENDIAN)
pad_t pad5;
#endif
#if !defined(_LP64) && !defined(_LITTLE_ENDIAN)
pad_t pad6;
#endif
itm_num_t hash_of_num; /* hash overflow table entryies */
#if !defined(_LP64) && defined(_LITTLE_ENDIAN)
pad_t pad6;
#endif
#if !defined(_LP64) && !defined(_LITTLE_ENDIAN)
pad_t pad7_num;
#endif
itm_num_t default_error;
/*
* -1:path through
* 0:with default value
* 1:with error table
* 2:without error table
*/
#if !defined(_LP64) && defined(_LITTLE_ENDIAN)
pad_t pad7_num;
#endif
#if !defined(_LP64) && !defined(_LITTLE_ENDIAN)
pad_t pad8_num;
#endif
itm_num_t error_num;
#if !defined(_LP64) && defined(_LITTLE_ENDIAN)
pad_t pad8_num;
#endif
} itm_map_hash_hdr_t;
/*
* Map table: octet-sequence to octet-sequence: dense encoding
*/
typedef struct {
#if !defined(_LP64) && !defined(_LITTLE_ENDIAN)
pad_t pad1;
#endif
itm_size_t source_len; /* source length */
#if !defined(_LP64) && defined(_LITTLE_ENDIAN)
pad_t pad1;
#endif
#if !defined(_LP64) && !defined(_LITTLE_ENDIAN)
pad_t pad2;
#endif
itm_size_t result_len; /* result length */
#if !defined(_LP64) && defined(_LITTLE_ENDIAN)
pad_t pad2;
#endif
#if !defined(_LP64) && !defined(_LITTLE_ENDIAN)
pad_t pad3_num;
#endif
itm_num_t default_error;
/*
* -1:path through
* 0:with default value
* 1:with error table
* 2:without error table
*/
#if !defined(_LP64) && defined(_LITTLE_ENDIAN)
pad_t pad3_num;
#endif
#if !defined(_LP64) && !defined(_LITTLE_ENDIAN)
pad_t pad4_num;
#endif
itm_num_t error_num;
#if !defined(_LP64) && defined(_LITTLE_ENDIAN)
pad_t pad4_num;
#endif
} itm_map_dense_enc_hdr_t;
/*
* Operation
*/
typedef enum { /* Operation Type */
ITM_OP_NONE, /* not used */
ITM_OP_ERROR, /* error */
ITM_OP_ERROR_D, /* error */
ITM_OP_OUT, /* output */
ITM_OP_OUT_D, /* output */
ITM_OP_OUT_S, /* output */
ITM_OP_OUT_R, /* output */
ITM_OP_OUT_INVD, /* output */
ITM_OP_DISCARD, /* discard */
ITM_OP_DISCARD_D, /* discard */
ITM_OP_EXPR, /* expression */
ITM_OP_IF, /* if */
ITM_OP_IF_ELSE, /* if_else */
ITM_OP_DIRECTION, /* switch direction */
ITM_OP_MAP, /* use map */
ITM_OP_OPERATION, /* invoke operation */
ITM_OP_INIT, /* invoke init operation */
ITM_OP_RESET, /* invoke reset operation */
ITM_OP_BREAK, /* break */
ITM_OP_RETURN, /* return */
ITM_OP_PRINTCHR, /* print out argument as character */
ITM_OP_PRINTHD, /* print out argument as hexadecimal */
ITM_OP_PRINTINT /* print out argument as integer */
} itm_op_type_t;
typedef struct {
pad_t pad;
itm_op_type_t type;
itm_place_t name;
union {
itm_place_t operand[3];
itm_data_t value;
struct {
#if !defined(_LP64) && !defined(_LITTLE_ENDIAN)
pad_t pad_num;
#endif
itm_num_t num;
#if !defined(_LP64) && defined(_LITTLE_ENDIAN)
pad_t pad_num;
#endif
} itm_op_num;
} data;
} itm_op_t;
#define itm_opnum itm_op_num.num
#define itm_oppad itm_op_num.pad_num
/*
* Expression
*/
#define ITM_EXPR_PROTO(type, op0, op1) ITM_EXPR_##type##_##op0##_##op1
#define ITM_EXPR_BIN(type) \
ITM_EXPR_PROTO(type, E, E), \
ITM_EXPR_PROTO(type, E, D), \
ITM_EXPR_PROTO(type, E, R), \
ITM_EXPR_PROTO(type, E, INVD), \
ITM_EXPR_PROTO(type, D, E), \
ITM_EXPR_PROTO(type, D, D), \
ITM_EXPR_PROTO(type, D, R), \
ITM_EXPR_PROTO(type, D, INVD), \
ITM_EXPR_PROTO(type, R, E), \
ITM_EXPR_PROTO(type, R, D), \
ITM_EXPR_PROTO(type, R, R), \
ITM_EXPR_PROTO(type, R, INVD), \
ITM_EXPR_PROTO(type, INVD, E), \
ITM_EXPR_PROTO(type, INVD, D), \
ITM_EXPR_PROTO(type, INVD, R), \
ITM_EXPR_PROTO(type, INVD, INVD)
#define ITM_EXPR_PLUS ITM_EXPR_PLUS_E_E
#define ITM_EXPR_MINUS ITM_EXPR_MINUS_E_E
#define ITM_EXPR_MUL ITM_EXPR_MUL_E_E
#define ITM_EXPR_DIV ITM_EXPR_DIV_E_E
#define ITM_EXPR_MOD ITM_EXPR_MOD_E_E
#define ITM_EXPR_SHIFT_L ITM_EXPR_SHIFT_L_E_E
#define ITM_EXPR_SHIFT_R ITM_EXPR_SHIFT_R_E_E
#define ITM_EXPR_OR ITM_EXPR_OR_E_E
#define ITM_EXPR_XOR ITM_EXPR_XOR_E_E
#define ITM_EXPR_AND ITM_EXPR_AND_E_E
#define ITM_EXPR_EQ ITM_EXPR_EQ_E_E
#define ITM_EXPR_NE ITM_EXPR_NE_E_E
#define ITM_EXPR_GT ITM_EXPR_GT_E_E
#define ITM_EXPR_GE ITM_EXPR_GE_E_E
#define ITM_EXPR_LT ITM_EXPR_LT_E_E
#define ITM_EXPR_LE ITM_EXPR_LE_E_E
typedef enum { /* Expression Type */
ITM_EXPR_NONE, /* not used */
ITM_EXPR_NOP, /* not used */
ITM_EXPR_NAME, /* not used */
ITM_EXPR_INT, /* integer */
ITM_EXPR_SEQ, /* byte sequence */
ITM_EXPR_REG, /* register */
ITM_EXPR_IN_VECTOR, /* in[expr] */
ITM_EXPR_IN_VECTOR_D, /* in[DECIMAL] */
ITM_EXPR_OUT, /* out */
ITM_EXPR_TRUE, /* true */
ITM_EXPR_FALSE, /* false */
ITM_EXPR_IN, /* input data */
ITM_EXPR_UMINUS, /* unary minus */
ITM_EXPR_BIN(PLUS), /* A + B */
ITM_EXPR_BIN(MINUS), /* A - B */
ITM_EXPR_BIN(MUL), /* A * B */
ITM_EXPR_BIN(DIV), /* A / B */
ITM_EXPR_BIN(MOD), /* A % B */
ITM_EXPR_BIN(SHIFT_L), /* A << B */
ITM_EXPR_BIN(SHIFT_R), /* A >> B */
ITM_EXPR_BIN(OR), /* A | B */
ITM_EXPR_BIN(XOR), /* A ^ B */
ITM_EXPR_BIN(AND), /* A & B */
ITM_EXPR_BIN(EQ), /* A == B */
ITM_EXPR_BIN(NE), /* A != B */
ITM_EXPR_BIN(GT), /* A > B */
ITM_EXPR_BIN(GE), /* A >= B */
ITM_EXPR_BIN(LT), /* A < B */
ITM_EXPR_BIN(LE), /* A <= B */
ITM_EXPR_NOT, /* !A */
ITM_EXPR_NEG, /* ~A */
ITM_EXPR_LOR, /* A || B */
ITM_EXPR_LAND, /* A && B */
ITM_EXPR_ASSIGN, /* A = B */
ITM_EXPR_OUT_ASSIGN, /* out = A */
ITM_EXPR_IN_EQ, /* in == A */
ITM_EXPR_IF, /* if */
ITM_EXPR_ELSE /* else */
} itm_expr_type_t;
#define ITM_OPERAND_EXPR (0)
#define ITM_OPERAND_PLACE (1)
#define ITM_OPERAND_VALUE (2)
#define ITM_OPERAND_REGISTER (3)
typedef struct {
pad_t pad;
itm_expr_type_t type;
union {
itm_place_t operand[2];
itm_data_t value;
struct {
#if !defined(_LP64) && !defined(_LITTLE_ENDIAN)
pad_t pad_num;
#endif
itm_num_t num;
#if !defined(_LP64) && defined(_LITTLE_ENDIAN)
pad_t pad_num;
#endif
} itm_ex_num;
} data;
} itm_expr_t;
#define itm_exnum itm_ex_num.num
#define itm_expad itm_ex_num.pad_num
#ifdef __cplusplus
}
#endif
#endif /* !_ICONV_TM_H */
|
package com.tomnocon.keycloak.audit;
import lombok.Data;
@Data
public class AuthDescriptor {
private String realmId;
private String clientId;
private String userId;
private String username;
private String sessionId;
private String ipAddress;
}
|
Class Reproduction Among Men and Women in France: Reproduction Theory on Its Home Ground Through an analysis of a large survey of employment men and women in France, this article shows that French reproduction theory has overstated the role of education in reproducing class advantage from generation to generation. Among men, reproduction of control over labor power (i.e., managerial/supervisory positions) is primarily direct instead of indirect through education. At the same time, education plays no role in reproducing ownership of businesses (i.e., capitalist and petty bourgeois positions), and there is little tendency for capitalist or petty bourgeois fathers to convert their economic capital into the educational capital for their sons so that the sons can secure managerial positions. Education serves less as a reproducer of class advantage than as a vehicle of mobility into managerial positions. Although reproduction theory has tended to ignore gender differences in class reproduction, these are found to be substantial. In the reproduction of ownership, women are less likely than men to inherit a business from their father. In the reproduction of control over labor power, the considerations that are important to men's chances of acquiring managerial/supervisory positions are generally much less important to women's chances. Thus reproduction strategis that are succesful in perpetuating class privilege for men do not work as well for women.
|
Scotland faces multi-billion pound fiscal Brexit shocks, warns CIPFA
Don Peebles
The Chartered Institute of Public Finance and Accountancy (CIPFA) has warned the Scottish Government that it is facing a post-Brexit public spending black hole of as much as a £3.7 billion.
CIPFA Scotland has said it predicts that Brexit will likely have a negative impact on public spending power and therefore it is of “critical importance” that Holyrood leaders start preparing plans for public services post-Brexit.
In its submission, CIPFA Scotland cite research suggesting that Scottish GDP could be reduced by up to £11.2 billion by 2030, with a reduction in tax revenues of between £1.7 billion and £3.7 billion annually.
Summarising factors which will impact upon the Scottish budget, the Institute highlights that public services may experience volatility in tax revenue due to Brexit impacts on economic growth and potential constraints on immigration.
If combined with a share of the Brexit Bill and a loss in current EU funding levels, Scottish public spending power could reduce.
CIPFA Scotland argues that the Scottish Government should consider the impact during its budgeting process to ensure the financial resilience of public finances is not undermined during the Brexit negotiation process and once the UK has left the EU.
CIPFA Scotland also recommends that the Scottish Government should seek to understand how policy and tax measures could help services overcome any loss in income.
Head of CIPFA Scotland, Don Peebles said: “Scottish public spending power is significantly vulnerable to the impacts of Brexit. As it is likely that many of the fiscal risks predicted will be realised in future years, the Scottish Government must begin to budget for Brexit so that it will be in the best position to sustain any financial shocks.
“Considering the impact of Brexit may be keenly felt in Scotland, it is important that the Scottish Government has an influence on the negotiations to ensure any Brexit deal works for its public services.”
Scottish Finance Secretary Derek Mackay argued that the report highlighted the need for Scotland to have a seat at the Brexit negotiation table.
He added: “This report further highlights the danger posed by the UK Government’s extreme Brexit plans, which threaten jobs, investment and living standards. Leaving the European single market and customs union threatens 80,000 Scottish jobs over a decade and could cost our economy more than £11billion a year by 2030.”
However, MSP Alexander Burnett, who sits on Holyrood’s finance committee, responded that the report might be jumping the gun.
He said: “While the CIPFA report speculates there may be future fiscal shocks for Scotland, it comes with an important caveat that the process for withdrawal from the EU is still in its early stages.
“The key point is that what happens in terms of Scotland’s budget is very much dependent on the outcome of these negotiations and what the UK’s future relationship with the EU will be.”
To help guide the Scottish Government and negotiators, CIPFA’s Brexit Advisory Commission for Public Services, comprised of public service leaders, academics and economists, will be evaluating the finance and policy implications for public services in the UK.
The Commission will release analysis later this year which will include recommendations on how best EU funding could be replaced to bridge divides in regional inequalities between devolved nations.
|
//
// Copyright (c) Microsoft.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
//
import adalNode, { TokenResponse } from 'adal-node'; // NOTE: this is deprecated-ish
import { KeyVaultClient, KeyVaultCredentials } from 'azure-keyvault';
export default function createClient(kvConfig) {
if (!kvConfig.clientId) {
throw new Error('KeyVault client ID required at this time for the middleware to initialize.');
}
if (!kvConfig.clientSecret) {
throw new Error('KeyVault client credential/secret required at this time for the middleware to initialize.');
}
const authenticator = (challenge, authCallback) => {
const context = new adalNode.AuthenticationContext(challenge.authorization);
return context.acquireTokenWithClientCredentials(challenge.resource, kvConfig.clientId, kvConfig.clientSecret, (tokenAcquisitionError, tokenResponse) => {
if (tokenAcquisitionError) {
return authCallback(tokenAcquisitionError);
}
const tk = tokenResponse as TokenResponse;
const authorizationValue = `${tk.tokenType} ${tk.accessToken}`;
return authCallback(null, authorizationValue);
});
};
const credentials = new KeyVaultCredentials(authenticator, null);
const keyVaultClient = new KeyVaultClient(credentials);
return keyVaultClient;
};
|
<reponame>abayer/whirr-cm
/**
* Licensed to Cloudera, Inc. under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. Cloudera, Inc. 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 com.cloudera.whirr.cm.handler;
import static org.apache.whirr.RolePredicates.role;
import static org.jclouds.scriptbuilder.domain.Statements.call;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
import java.util.SortedSet;
import java.util.TreeSet;
import java.util.regex.Pattern;
import org.apache.commons.configuration.Configuration;
import org.apache.whirr.ClusterSpec;
import org.apache.whirr.service.ClusterActionEvent;
import org.apache.whirr.service.ClusterActionHandlerSupport;
import org.apache.whirr.service.FirewallManager.Rule;
import org.apache.whirr.service.hadoop.VolumeManager;
import org.jclouds.scriptbuilder.domain.Statement;
import com.cloudera.whirr.cm.CmConstants;
import com.cloudera.whirr.cm.CmServerClusterInstance;
import com.google.common.primitives.Ints;
public abstract class BaseHandler extends ClusterActionHandlerSupport implements CmConstants {
// jclouds allows '-', CM does not, CM allows '_', jclouds does not, so lets restrict to alphanumeric
private static final Pattern CM_CLUSTER_NAME_REGEX = Pattern.compile("[A-Za-z0-9]+");
public abstract Set<String> getPortsClient(ClusterActionEvent event) throws IOException;
@Override
protected void beforeBootstrap(ClusterActionEvent event) throws IOException, InterruptedException {
super.beforeBootstrap(event);
if (!CM_CLUSTER_NAME_REGEX.matcher(
CmServerClusterInstance.getConfiguration(event.getClusterSpec()).getString(
ClusterSpec.Property.CLUSTER_NAME.getConfigName(), CONFIG_WHIRR_NAME_DEFAULT)).matches()) {
throw new IOException("Illegal cluster name ["
+ CmServerClusterInstance.getConfiguration(event.getClusterSpec()).getString(
ClusterSpec.Property.CLUSTER_NAME.getConfigName(), CONFIG_WHIRR_NAME_DEFAULT) + "] passed in variable ["
+ ClusterSpec.Property.CLUSTER_NAME.getConfigName() + "] with default [" + CONFIG_WHIRR_NAME_DEFAULT
+ "]. Please use only alphanumeric characters.");
}
}
@Override
protected void beforeConfigure(ClusterActionEvent event) throws IOException, InterruptedException {
super.beforeConfigure(event);
addStatement(event, call("retry_helpers"));
if (CmServerClusterInstance.getConfiguration(event.getClusterSpec()).getList(CONFIG_WHIRR_DATA_DIRS_ROOT).isEmpty()) {
addStatement(event, call("prepare_all_disks", "'" + VolumeManager.asString(getDeviceMappings(event)) + "'"));
}
if (CmServerClusterInstance.getConfiguration(event.getClusterSpec()).getBoolean(CONFIG_WHIRR_FIREWALL_ENABLE)) {
Set<Integer> ports = CmServerClusterInstance.portsPush(event, getPortsClient(event));
if (!ports.isEmpty()) {
event.getFirewallManager().addRules(Rule.create().destination(role(getRole())).ports(Ints.toArray(ports)));
for (Statement portIngressStatement : event.getFirewallManager().getRulesAsStatements()) {
addStatement(event, portIngressStatement);
}
}
}
}
@Override
protected void afterConfigure(ClusterActionEvent event) throws IOException, InterruptedException {
super.afterConfigure(event);
if (CmServerClusterInstance.getConfiguration(event.getClusterSpec()).getBoolean(CONFIG_WHIRR_FIREWALL_ENABLE)) {
if (CmServerClusterInstance.portsPop(event) != null) {
event.getFirewallManager().authorizeAllRules();
}
}
}
@SuppressWarnings("unchecked")
protected SortedSet<String> getMounts(ClusterActionEvent event) throws IOException {
Configuration configuration = CmServerClusterInstance.getConfiguration(event.getClusterSpec());
SortedSet<String> mounts = new TreeSet<String>();
Set<String> deviceMappings = getDeviceMappings(event).keySet();
if (!configuration.getList(CONFIG_WHIRR_DATA_DIRS_ROOT).isEmpty()) {
mounts.addAll(configuration.getList(CONFIG_WHIRR_DATA_DIRS_ROOT));
} else if (!deviceMappings.isEmpty()) {
mounts.addAll(deviceMappings);
} else {
mounts.add(configuration.getString(CONFIG_WHIRR_INTERNAL_DATA_DIRS_DEFAULT));
}
return mounts;
}
protected Map<String, String> getDeviceMappings(ClusterActionEvent event) {
Map<String, String> deviceMappings = new HashMap<String, String>();
if (event.getCluster() != null && event.getCluster().getInstances() != null
&& !event.getCluster().getInstances().isEmpty()) {
deviceMappings.putAll(new VolumeManager().getDeviceMappings(event.getClusterSpec(), event.getCluster()
.getInstances().iterator().next()));
}
return deviceMappings;
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.