prompt
large_stringlengths 70
991k
| completion
large_stringlengths 0
1.02k
|
---|---|
<|file_name|>JavaObjectOutput.java<|end_file_name|><|fim▁begin|>/*
* Copyright 2014-2015 itas group
*
* 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.<|fim▁hole|> * limitations under the License.
*/
package org.itas.xcnet.common.serialize.support.java;
import java.io.IOException;
import java.io.ObjectOutputStream;
import java.io.OutputStream;
import org.itas.xcnet.common.serialize.ObjectOutput;
/**
* Java Object output.
*
* @author liuzhen<[email protected]>
* @createTime 2015年5月15日下午3:10:18
*/
public class JavaObjectOutput implements ObjectOutput {
private final ObjectOutputStream out;
public JavaObjectOutput(OutputStream os) throws IOException {
out = new ObjectOutputStream(os);
}
public JavaObjectOutput(OutputStream os, boolean compact) throws IOException {
out = compact ? new CompactedObjectOutputStream(os) : new ObjectOutputStream(os);
}
@Override
public void writeBool(boolean v) throws IOException {
out.writeBoolean(v);
}
@Override
public void writeByte(byte v) throws IOException {
out.writeByte(v);
}
@Override
public void writeShort(short v) throws IOException {
out.writeShort(v);
}
@Override
public void writeInt(int v) throws IOException {
out.writeInt(v);
}
@Override
public void writeLong(long v) throws IOException {
out.writeLong(v);
}
@Override
public void writeFloat(float v) throws IOException {
out.writeFloat(v);
}
@Override
public void writeDouble(double v) throws IOException {
out.writeDouble(v);
}
@Override
public void writeBytes(byte[] v) throws IOException {
if (v == null)
out.writeInt(-1);
else
out.write(v);
}
@Override
public void writeBytes(byte[] v, int off, int len) throws IOException {
out.writeInt(len);
out.write(v, off, len);
}
@Override
public void writeUTF8(String v) throws IOException {
if (v == null) {
out.writeInt(-1);
} else {
out.writeInt(v.length());
out.writeUTF(v);
}
}
@Override
public void writeObject(Object o) throws IOException {
if (o == null) {
out.writeInt(-1);
} else {
out.writeInt(1);
out.writeObject(o);
}
}
@Override
public void flushBuffer() throws IOException {
out.flush();
}
}<|fim▁end|> | * See the License for the specific language governing permissions and |
<|file_name|>type_.rs<|end_file_name|><|fim▁begin|>// Copyright 2013 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
#![allow(non_upper_case_globals)]
use llvm;
use llvm::{TypeRef, Bool, False, True, TypeKind, ValueRef};
use llvm::{Float, Double, X86_FP80, PPC_FP128, FP128};
use trans::context::CrateContext;
use util::nodemap::FnvHashMap;
use syntax::ast;
use std::ffi::CString;
use std::mem;
use std::ptr;
use std::cell::RefCell;
use libc::c_uint;
#[derive(Clone, Copy, PartialEq, Debug)]
#[repr(C)]
pub struct Type {
rf: TypeRef
}
macro_rules! ty {
($e:expr) => ( Type::from_ref(unsafe { $e }))
}
/// Wrapper for LLVM TypeRef
impl Type {
#[inline(always)]
pub fn from_ref(r: TypeRef) -> Type {
Type {
rf: r
}
}
#[inline(always)] // So it doesn't kill --opt-level=0 builds of the compiler
pub fn to_ref(&self) -> TypeRef {
self.rf
}
pub fn void(ccx: &CrateContext) -> Type {
ty!(llvm::LLVMVoidTypeInContext(ccx.llcx()))
}
pub fn nil(ccx: &CrateContext) -> Type {
Type::empty_struct(ccx)
}
pub fn metadata(ccx: &CrateContext) -> Type {
ty!(llvm::LLVMMetadataTypeInContext(ccx.llcx()))
}
pub fn i1(ccx: &CrateContext) -> Type {
ty!(llvm::LLVMInt1TypeInContext(ccx.llcx()))
}
pub fn i8(ccx: &CrateContext) -> Type {
ty!(llvm::LLVMInt8TypeInContext(ccx.llcx()))
}
pub fn i16(ccx: &CrateContext) -> Type {
ty!(llvm::LLVMInt16TypeInContext(ccx.llcx()))
}
pub fn i32(ccx: &CrateContext) -> Type {
ty!(llvm::LLVMInt32TypeInContext(ccx.llcx()))
}
pub fn i64(ccx: &CrateContext) -> Type {
ty!(llvm::LLVMInt64TypeInContext(ccx.llcx()))
}
// Creates an integer type with the given number of bits, e.g. i24
pub fn ix(ccx: &CrateContext, num_bits: u64) -> Type {
ty!(llvm::LLVMIntTypeInContext(ccx.llcx(), num_bits as c_uint))
}
pub fn f32(ccx: &CrateContext) -> Type {
ty!(llvm::LLVMFloatTypeInContext(ccx.llcx()))
}
pub fn f64(ccx: &CrateContext) -> Type {
ty!(llvm::LLVMDoubleTypeInContext(ccx.llcx()))
}
pub fn bool(ccx: &CrateContext) -> Type {
Type::i8(ccx)
}
pub fn char(ccx: &CrateContext) -> Type {
Type::i32(ccx)
}
pub fn i8p(ccx: &CrateContext) -> Type {
Type::i8(ccx).ptr_to()
}
pub fn int(ccx: &CrateContext) -> Type {
match &ccx.tcx().sess.target.target.target_pointer_width[..] {
"32" => Type::i32(ccx),
"64" => Type::i64(ccx),
tws => panic!("Unsupported target word size for int: {}", tws),
}
}
pub fn int_from_ty(ccx: &CrateContext, t: ast::IntTy) -> Type {
match t {
ast::TyIs => ccx.int_type(),
ast::TyI8 => Type::i8(ccx),
ast::TyI16 => Type::i16(ccx),
ast::TyI32 => Type::i32(ccx),
ast::TyI64 => Type::i64(ccx)
}
}
pub fn uint_from_ty(ccx: &CrateContext, t: ast::UintTy) -> Type {
match t {
ast::TyUs => ccx.int_type(),
ast::TyU8 => Type::i8(ccx),
ast::TyU16 => Type::i16(ccx),
ast::TyU32 => Type::i32(ccx),
ast::TyU64 => Type::i64(ccx)
}
}
pub fn float_from_ty(ccx: &CrateContext, t: ast::FloatTy) -> Type {
match t {
ast::TyF32 => Type::f32(ccx),
ast::TyF64 => Type::f64(ccx),
}
}
pub fn func(args: &[Type], ret: &Type) -> Type {
let vec : &[TypeRef] = unsafe { mem::transmute(args) };
ty!(llvm::LLVMFunctionType(ret.to_ref(), vec.as_ptr(),
args.len() as c_uint, False))
}
pub fn variadic_func(args: &[Type], ret: &Type) -> Type {
let vec : &[TypeRef] = unsafe { mem::transmute(args) };
ty!(llvm::LLVMFunctionType(ret.to_ref(), vec.as_ptr(),
args.len() as c_uint, True))
}
pub fn struct_(ccx: &CrateContext, els: &[Type], packed: bool) -> Type {
let els : &[TypeRef] = unsafe { mem::transmute(els) };
ty!(llvm::LLVMStructTypeInContext(ccx.llcx(), els.as_ptr(),
els.len() as c_uint,
packed as Bool))
}
pub fn named_struct(ccx: &CrateContext, name: &str) -> Type {
let name = CString::new(name).unwrap();
ty!(llvm::LLVMStructCreateNamed(ccx.llcx(), name.as_ptr()))
}
pub fn empty_struct(ccx: &CrateContext) -> Type {
Type::struct_(ccx, &[], false)
}
pub fn glue_fn(ccx: &CrateContext, t: Type) -> Type {
Type::func(&[t], &Type::void(ccx))
}
pub fn array(ty: &Type, len: u64) -> Type {
ty!(llvm::LLVMRustArrayType(ty.to_ref(), len))
}
pub fn vector(ty: &Type, len: u64) -> Type {
ty!(llvm::LLVMVectorType(ty.to_ref(), len as c_uint))
}
pub fn vec(ccx: &CrateContext, ty: &Type) -> Type {
Type::struct_(ccx,
&[Type::array(ty, 0), Type::int(ccx)],
false)
}
pub fn opaque_vec(ccx: &CrateContext) -> Type {
Type::vec(ccx, &Type::i8(ccx))
}
pub fn vtable_ptr(ccx: &CrateContext) -> Type {
Type::glue_fn(ccx, Type::i8p(ccx)).ptr_to().ptr_to()
}
pub fn kind(&self) -> TypeKind {
unsafe {
llvm::LLVMGetTypeKind(self.to_ref())
}
}
pub fn set_struct_body(&mut self, els: &[Type], packed: bool) {
unsafe {
let vec : &[TypeRef] = mem::transmute(els);
llvm::LLVMStructSetBody(self.to_ref(), vec.as_ptr(),
els.len() as c_uint, packed as Bool)
}
}
pub fn ptr_to(&self) -> Type {
ty!(llvm::LLVMPointerType(self.to_ref(), 0))
}
pub fn is_aggregate(&self) -> bool {
match self.kind() {
TypeKind::Struct | TypeKind::Array => true,
_ => false
}
}
pub fn is_packed(&self) -> bool {
unsafe {
llvm::LLVMIsPackedStruct(self.to_ref()) == True
}
}
pub fn element_type(&self) -> Type {
unsafe {
Type::from_ref(llvm::LLVMGetElementType(self.to_ref()))
}
}
/// Return the number of elements in `self` if it is a LLVM vector type.
pub fn vector_length(&self) -> usize {
unsafe {
llvm::LLVMGetVectorSize(self.to_ref()) as usize
}<|fim▁hole|> pub fn array_length(&self) -> usize {
unsafe {
llvm::LLVMGetArrayLength(self.to_ref()) as usize
}
}
pub fn field_types(&self) -> Vec<Type> {
unsafe {
let n_elts = llvm::LLVMCountStructElementTypes(self.to_ref()) as usize;
if n_elts == 0 {
return Vec::new();
}
let mut elts = vec![Type { rf: ptr::null_mut() }; n_elts];
llvm::LLVMGetStructElementTypes(self.to_ref(),
elts.as_mut_ptr() as *mut TypeRef);
elts
}
}
pub fn return_type(&self) -> Type {
ty!(llvm::LLVMGetReturnType(self.to_ref()))
}
pub fn func_params(&self) -> Vec<Type> {
unsafe {
let n_args = llvm::LLVMCountParamTypes(self.to_ref()) as usize;
let mut args = vec![Type { rf: ptr::null_mut() }; n_args];
llvm::LLVMGetParamTypes(self.to_ref(),
args.as_mut_ptr() as *mut TypeRef);
args
}
}
pub fn float_width(&self) -> usize {
match self.kind() {
Float => 32,
Double => 64,
X86_FP80 => 80,
FP128 | PPC_FP128 => 128,
_ => panic!("llvm_float_width called on a non-float type")
}
}
/// Retrieve the bit width of the integer type `self`.
pub fn int_width(&self) -> u64 {
unsafe {
llvm::LLVMGetIntTypeWidth(self.to_ref()) as u64
}
}
}
/* Memory-managed object interface to type handles. */
pub struct TypeNames {
named_types: RefCell<FnvHashMap<String, TypeRef>>,
}
impl TypeNames {
pub fn new() -> TypeNames {
TypeNames {
named_types: RefCell::new(FnvHashMap())
}
}
pub fn associate_type(&self, s: &str, t: &Type) {
assert!(self.named_types.borrow_mut().insert(s.to_string(),
t.to_ref()).is_none());
}
pub fn find_type(&self, s: &str) -> Option<Type> {
self.named_types.borrow().get(s).map(|x| Type::from_ref(*x))
}
pub fn type_to_string(&self, ty: Type) -> String {
llvm::build_string(|s| unsafe {
llvm::LLVMWriteTypeToString(ty.to_ref(), s);
}).expect("non-UTF8 type description from LLVM")
}
pub fn types_to_str(&self, tys: &[Type]) -> String {
let strs: Vec<String> = tys.iter().map(|t| self.type_to_string(*t)).collect();
format!("[{}]", strs.connect(","))
}
pub fn val_to_string(&self, val: ValueRef) -> String {
llvm::build_string(|s| unsafe {
llvm::LLVMWriteValueToString(val, s);
}).expect("nun-UTF8 value description from LLVM")
}
}<|fim▁end|> | }
|
<|file_name|>TomKitten48.xaml.cpp<|end_file_name|><|fim▁begin|>//
// TomKitten48.xaml.cpp
// Implementation of the TomKitten48 class
//
#include "pch.h"
#include "TomKitten48.xaml.h"
using namespace PrintableTomKitten;
using namespace Platform;
using namespace Windows::Foundation;
<|fim▁hole|>using namespace Windows::Foundation::Collections;
using namespace Windows::UI::Xaml;
using namespace Windows::UI::Xaml::Controls;
using namespace Windows::UI::Xaml::Controls::Primitives;
using namespace Windows::UI::Xaml::Data;
using namespace Windows::UI::Xaml::Input;
using namespace Windows::UI::Xaml::Media;
using namespace Windows::UI::Xaml::Navigation;
// The User Control item template is documented at http://go.microsoft.com/fwlink/?LinkId=234236
TomKitten48::TomKitten48()
{
InitializeComponent();
}<|fim▁end|> | |
<|file_name|>01-add-email-only-column-to-posts-meta-table.js<|end_file_name|><|fim▁begin|>const {createAddColumnMigration} = require('../../utils');<|fim▁hole|> defaultTo: false
});<|fim▁end|> |
module.exports = createAddColumnMigration('posts_meta', 'email_only', {
type: 'bool',
nullable: false, |
<|file_name|>project_setup.py<|end_file_name|><|fim▁begin|>"""
Load this into a Python Script widget (does not have
to be connected to any other widgets), and set the
project directory to the location of the git repo.
Hit execute and enjoy!
"""
PROJECT_DIR = '/home/mahmoud/work/qualityvis'
import sys
sys.path.append(PROJECT_DIR)<|fim▁hole|><|fim▁end|> | sys.path.append(PROJECT_DIR+'/orange_scripts') |
<|file_name|>test_init.py<|end_file_name|><|fim▁begin|>"""
Tests for waffle utils features.
"""
import crum
import ddt
from django.test import TestCase
from django.test.client import RequestFactory
from edx_django_utils.cache import RequestCache
from mock import patch
from opaque_keys.edx.keys import CourseKey
from waffle.testutils import override_flag
from .. import CourseWaffleFlag, WaffleFlagNamespace, WaffleSwitchNamespace, WaffleSwitch
from ..models import WaffleFlagCourseOverrideModel
@ddt.ddt
class TestCourseWaffleFlag(TestCase):
"""
Tests the CourseWaffleFlag.
"""
NAMESPACE_NAME = "test_namespace"
FLAG_NAME = "test_flag"
NAMESPACED_FLAG_NAME = NAMESPACE_NAME + "." + FLAG_NAME
TEST_COURSE_KEY = CourseKey.from_string("edX/DemoX/Demo_Course")
TEST_COURSE_2_KEY = CourseKey.from_string("edX/DemoX/Demo_Course_2")
TEST_NAMESPACE = WaffleFlagNamespace(NAMESPACE_NAME)
TEST_COURSE_FLAG = CourseWaffleFlag(TEST_NAMESPACE, FLAG_NAME)
def setUp(self):
super(TestCourseWaffleFlag, self).setUp()
request = RequestFactory().request()
self.addCleanup(crum.set_current_request, None)
crum.set_current_request(request)
RequestCache.clear_all_namespaces()
@ddt.data(
{'course_override': WaffleFlagCourseOverrideModel.ALL_CHOICES.on, 'waffle_enabled': False, 'result': True},
{'course_override': WaffleFlagCourseOverrideModel.ALL_CHOICES.off, 'waffle_enabled': True, 'result': False},
{'course_override': WaffleFlagCourseOverrideModel.ALL_CHOICES.unset, 'waffle_enabled': True, 'result': True},
{'course_override': WaffleFlagCourseOverrideModel.ALL_CHOICES.unset, 'waffle_enabled': False, 'result': False},
)
def test_course_waffle_flag(self, data):
"""
Tests various combinations of a flag being set in waffle and overridden
for a course.
"""
with patch.object(WaffleFlagCourseOverrideModel, 'override_value', return_value=data['course_override']):
with override_flag(self.NAMESPACED_FLAG_NAME, active=data['waffle_enabled']):
# check twice to test that the result is properly cached
self.assertEqual(self.TEST_COURSE_FLAG.is_enabled(self.TEST_COURSE_KEY), data['result'])
self.assertEqual(self.TEST_COURSE_FLAG.is_enabled(self.TEST_COURSE_KEY), data['result'])
# result is cached, so override check should happen once
WaffleFlagCourseOverrideModel.override_value.assert_called_once_with(
self.NAMESPACED_FLAG_NAME,
self.TEST_COURSE_KEY
)
# check flag for a second course
if data['course_override'] == WaffleFlagCourseOverrideModel.ALL_CHOICES.unset:
# When course override wasn't set for the first course, the second course will get the same
# cached value from waffle.
self.assertEqual(self.TEST_COURSE_FLAG.is_enabled(self.TEST_COURSE_2_KEY), data['waffle_enabled'])
else:
# When course override was set for the first course, it should not apply to the second
# course which should get the default value of False.
self.assertEqual(self.TEST_COURSE_FLAG.is_enabled(self.TEST_COURSE_2_KEY), False)
@ddt.data(
{'flag_undefined_default': None, 'result': False},
{'flag_undefined_default': False, 'result': False},
{'flag_undefined_default': True, 'result': True},
)
def test_undefined_waffle_flag(self, data):
"""
Test flag with various defaults provided for undefined waffle flags.
"""
test_course_flag = CourseWaffleFlag(
self.TEST_NAMESPACE,
self.FLAG_NAME,
flag_undefined_default=data['flag_undefined_default']
)<|fim▁hole|>
with patch.object(
WaffleFlagCourseOverrideModel,
'override_value',
return_value=WaffleFlagCourseOverrideModel.ALL_CHOICES.unset
):
# check twice to test that the result is properly cached
self.assertEqual(test_course_flag.is_enabled(self.TEST_COURSE_KEY), data['result'])
self.assertEqual(test_course_flag.is_enabled(self.TEST_COURSE_KEY), data['result'])
# result is cached, so override check should happen once
WaffleFlagCourseOverrideModel.override_value.assert_called_once_with(
self.NAMESPACED_FLAG_NAME,
self.TEST_COURSE_KEY
)
@ddt.data(
{'flag_undefined_default': None, 'result': False},
{'flag_undefined_default': False, 'result': False},
{'flag_undefined_default': True, 'result': True},
)
def test_without_request(self, data):
"""
Test the flag behavior when outside a request context.
"""
crum.set_current_request(None)
test_course_flag = CourseWaffleFlag(
self.TEST_NAMESPACE,
self.FLAG_NAME,
flag_undefined_default=data['flag_undefined_default']
)
self.assertEqual(test_course_flag.is_enabled(self.TEST_COURSE_KEY), data['result'])
class TestWaffleSwitch(TestCase):
"""
Tests the WaffleSwitch.
"""
NAMESPACE_NAME = "test_namespace"
WAFFLE_SWITCH_NAME = "test_switch_name"
TEST_NAMESPACE = WaffleSwitchNamespace(NAMESPACE_NAME)
WAFFLE_SWITCH = WaffleSwitch(TEST_NAMESPACE, WAFFLE_SWITCH_NAME)
def test_namespaced_switch_name(self):
"""
Verify namespaced_switch_name returns the correct namespace switch name
"""
expected = self.NAMESPACE_NAME + "." + self.WAFFLE_SWITCH_NAME
actual = self.WAFFLE_SWITCH.namespaced_switch_name
self.assertEqual(actual, expected)<|fim▁end|> | |
<|file_name|>input_examples.py<|end_file_name|><|fim▁begin|>"""Deals with input examples for deep learning.
One "input example" is one storm object.
--- NOTATION ---
The following letters will be used throughout this module.
E = number of examples (storm objects)
M = number of rows in each radar image
N = number of columns in each radar image
H_r = number of radar heights
F_r = number of radar fields (or "variables" or "channels")
H_s = number of sounding heights
F_s = number of sounding fields (or "variables" or "channels")
C = number of radar field/height pairs
"""
import copy
import glob
import os.path
import numpy
import netCDF4
from gewittergefahr.gg_utils import radar_utils
from gewittergefahr.gg_utils import soundings
from gewittergefahr.gg_utils import target_val_utils
from gewittergefahr.gg_utils import time_conversion
from gewittergefahr.gg_utils import number_rounding
from gewittergefahr.gg_utils import temperature_conversions as temp_conversion
from gewittergefahr.gg_utils import storm_tracking_utils as tracking_utils
from gewittergefahr.gg_utils import file_system_utils
from gewittergefahr.gg_utils import error_checking
from gewittergefahr.deep_learning import storm_images
from gewittergefahr.deep_learning import deep_learning_utils as dl_utils
SEPARATOR_STRING = '\n\n' + '*' * 50 + '\n\n'
BATCH_NUMBER_REGEX = '[0-9][0-9][0-9][0-9][0-9][0-9][0-9]'
TIME_FORMAT_IN_FILE_NAMES = '%Y-%m-%d-%H%M%S'
DEFAULT_NUM_EXAMPLES_PER_OUT_CHUNK = 8
DEFAULT_NUM_EXAMPLES_PER_OUT_FILE = 128
NUM_BATCHES_PER_DIRECTORY = 1000
AZIMUTHAL_SHEAR_FIELD_NAMES = [
radar_utils.LOW_LEVEL_SHEAR_NAME, radar_utils.MID_LEVEL_SHEAR_NAME
]
TARGET_NAMES_KEY = 'target_names'
ROTATED_GRIDS_KEY = 'rotated_grids'
ROTATED_GRID_SPACING_KEY = 'rotated_grid_spacing_metres'
FULL_IDS_KEY = 'full_storm_id_strings'
STORM_TIMES_KEY = 'storm_times_unix_sec'
TARGET_MATRIX_KEY = 'target_matrix'
RADAR_IMAGE_MATRIX_KEY = 'radar_image_matrix'
RADAR_FIELDS_KEY = 'radar_field_names'
RADAR_HEIGHTS_KEY = 'radar_heights_m_agl'
SOUNDING_FIELDS_KEY = 'sounding_field_names'
SOUNDING_MATRIX_KEY = 'sounding_matrix'
SOUNDING_HEIGHTS_KEY = 'sounding_heights_m_agl'
REFL_IMAGE_MATRIX_KEY = 'reflectivity_image_matrix_dbz'
AZ_SHEAR_IMAGE_MATRIX_KEY = 'az_shear_image_matrix_s01'
MAIN_KEYS = [
FULL_IDS_KEY, STORM_TIMES_KEY, RADAR_IMAGE_MATRIX_KEY,
REFL_IMAGE_MATRIX_KEY, AZ_SHEAR_IMAGE_MATRIX_KEY, TARGET_MATRIX_KEY,
SOUNDING_MATRIX_KEY
]
REQUIRED_MAIN_KEYS = [
FULL_IDS_KEY, STORM_TIMES_KEY, TARGET_MATRIX_KEY
]
METADATA_KEYS = [
TARGET_NAMES_KEY, ROTATED_GRIDS_KEY, ROTATED_GRID_SPACING_KEY,
RADAR_FIELDS_KEY, RADAR_HEIGHTS_KEY, SOUNDING_FIELDS_KEY,
SOUNDING_HEIGHTS_KEY
]
TARGET_NAME_KEY = 'target_name'
TARGET_VALUES_KEY = 'target_values'
EXAMPLE_DIMENSION_KEY = 'storm_object'
ROW_DIMENSION_KEY = 'grid_row'
COLUMN_DIMENSION_KEY = 'grid_column'
REFL_ROW_DIMENSION_KEY = 'reflectivity_grid_row'
REFL_COLUMN_DIMENSION_KEY = 'reflectivity_grid_column'
AZ_SHEAR_ROW_DIMENSION_KEY = 'az_shear_grid_row'
AZ_SHEAR_COLUMN_DIMENSION_KEY = 'az_shear_grid_column'
RADAR_FIELD_DIM_KEY = 'radar_field'
RADAR_HEIGHT_DIM_KEY = 'radar_height'
RADAR_CHANNEL_DIM_KEY = 'radar_channel'
SOUNDING_FIELD_DIM_KEY = 'sounding_field'
SOUNDING_HEIGHT_DIM_KEY = 'sounding_height'
TARGET_VARIABLE_DIM_KEY = 'target_variable'
STORM_ID_CHAR_DIM_KEY = 'storm_id_character'
RADAR_FIELD_CHAR_DIM_KEY = 'radar_field_name_character'
SOUNDING_FIELD_CHAR_DIM_KEY = 'sounding_field_name_character'
TARGET_NAME_CHAR_DIM_KEY = 'target_name_character'
RADAR_FIELD_KEY = 'radar_field_name'
OPERATION_NAME_KEY = 'operation_name'
MIN_HEIGHT_KEY = 'min_height_m_agl'
MAX_HEIGHT_KEY = 'max_height_m_agl'
MIN_OPERATION_NAME = 'min'
MAX_OPERATION_NAME = 'max'
MEAN_OPERATION_NAME = 'mean'
VALID_LAYER_OPERATION_NAMES = [
MIN_OPERATION_NAME, MAX_OPERATION_NAME, MEAN_OPERATION_NAME
]
OPERATION_NAME_TO_FUNCTION_DICT = {
MIN_OPERATION_NAME: numpy.min,
MAX_OPERATION_NAME: numpy.max,
MEAN_OPERATION_NAME: numpy.mean
}
MIN_RADAR_HEIGHTS_KEY = 'min_radar_heights_m_agl'
MAX_RADAR_HEIGHTS_KEY = 'max_radar_heights_m_agl'
RADAR_LAYER_OPERATION_NAMES_KEY = 'radar_layer_operation_names'
def _read_soundings(sounding_file_name, sounding_field_names, radar_image_dict):
"""Reads storm-centered soundings and matches w storm-centered radar imgs.
:param sounding_file_name: Path to input file (will be read by
`soundings.read_soundings`).
:param sounding_field_names: See doc for `soundings.read_soundings`.
:param radar_image_dict: Dictionary created by
`storm_images.read_storm_images`.
:return: sounding_dict: Dictionary created by `soundings.read_soundings`.
:return: radar_image_dict: Same as input, but excluding storm objects with
no sounding.
"""
print('Reading data from: "{0:s}"...'.format(sounding_file_name))
sounding_dict, _ = soundings.read_soundings(
netcdf_file_name=sounding_file_name,
field_names_to_keep=sounding_field_names,
full_id_strings_to_keep=radar_image_dict[storm_images.FULL_IDS_KEY],
init_times_to_keep_unix_sec=radar_image_dict[
storm_images.VALID_TIMES_KEY]
)
num_examples_with_soundings = len(sounding_dict[soundings.FULL_IDS_KEY])
if num_examples_with_soundings == 0:
return None, None
radar_full_id_strings = numpy.array(
radar_image_dict[storm_images.FULL_IDS_KEY]
)
orig_storm_times_unix_sec = (
radar_image_dict[storm_images.VALID_TIMES_KEY] + 0
)
indices_to_keep = []
for i in range(num_examples_with_soundings):
this_index = numpy.where(numpy.logical_and(
radar_full_id_strings == sounding_dict[soundings.FULL_IDS_KEY][i],
orig_storm_times_unix_sec ==
sounding_dict[soundings.INITIAL_TIMES_KEY][i]
))[0][0]
indices_to_keep.append(this_index)
indices_to_keep = numpy.array(indices_to_keep, dtype=int)
radar_image_dict[storm_images.STORM_IMAGE_MATRIX_KEY] = radar_image_dict[
storm_images.STORM_IMAGE_MATRIX_KEY
][indices_to_keep, ...]
radar_image_dict[storm_images.FULL_IDS_KEY] = sounding_dict[
soundings.FULL_IDS_KEY
]
radar_image_dict[storm_images.VALID_TIMES_KEY] = sounding_dict[
soundings.INITIAL_TIMES_KEY
]
return sounding_dict, radar_image_dict
def _create_2d_examples(
radar_file_names, full_id_strings, storm_times_unix_sec,
target_matrix, sounding_file_name=None, sounding_field_names=None):
"""Creates 2-D examples for one file time.
E = number of desired examples (storm objects)
e = number of examples returned
T = number of target variables
:param radar_file_names: length-C list of paths to storm-centered radar
images. Files will be read by `storm_images.read_storm_images`.
:param full_id_strings: length-E list with full IDs of storm objects to
return.
:param storm_times_unix_sec: length-E numpy array with valid times of storm
objects to return.
:param target_matrix: E-by-T numpy array of target values (integer class
labels).<|fim▁hole|> `soundings.read_soundings`). If `sounding_file_name is None`, examples
will not include soundings.
:param sounding_field_names: See doc for `soundings.read_soundings`.
:return: example_dict: Same as input for `write_example_file`, but without
key "target_names".
"""
orig_full_id_strings = copy.deepcopy(full_id_strings)
orig_storm_times_unix_sec = storm_times_unix_sec + 0
print('Reading data from: "{0:s}"...'.format(radar_file_names[0]))
this_radar_image_dict = storm_images.read_storm_images(
netcdf_file_name=radar_file_names[0],
full_id_strings_to_keep=full_id_strings,
valid_times_to_keep_unix_sec=storm_times_unix_sec)
if this_radar_image_dict is None:
return None
if sounding_file_name is None:
sounding_matrix = None
sounding_field_names = None
sounding_heights_m_agl = None
else:
sounding_dict, this_radar_image_dict = _read_soundings(
sounding_file_name=sounding_file_name,
sounding_field_names=sounding_field_names,
radar_image_dict=this_radar_image_dict)
if this_radar_image_dict is None:
return None
if len(this_radar_image_dict[storm_images.FULL_IDS_KEY]) == 0:
return None
sounding_matrix = sounding_dict[soundings.SOUNDING_MATRIX_KEY]
sounding_field_names = sounding_dict[soundings.FIELD_NAMES_KEY]
sounding_heights_m_agl = sounding_dict[soundings.HEIGHT_LEVELS_KEY]
full_id_strings = this_radar_image_dict[storm_images.FULL_IDS_KEY]
storm_times_unix_sec = this_radar_image_dict[storm_images.VALID_TIMES_KEY]
these_indices = tracking_utils.find_storm_objects(
all_id_strings=orig_full_id_strings,
all_times_unix_sec=orig_storm_times_unix_sec,
id_strings_to_keep=full_id_strings,
times_to_keep_unix_sec=storm_times_unix_sec, allow_missing=False)
target_matrix = target_matrix[these_indices, :]
num_channels = len(radar_file_names)
tuple_of_image_matrices = ()
for j in range(num_channels):
if j != 0:
print('Reading data from: "{0:s}"...'.format(radar_file_names[j]))
this_radar_image_dict = storm_images.read_storm_images(
netcdf_file_name=radar_file_names[j],
full_id_strings_to_keep=full_id_strings,
valid_times_to_keep_unix_sec=storm_times_unix_sec)
tuple_of_image_matrices += (
this_radar_image_dict[storm_images.STORM_IMAGE_MATRIX_KEY],
)
radar_field_names = [
storm_images.image_file_name_to_field(f) for f in radar_file_names
]
radar_heights_m_agl = numpy.array(
[storm_images.image_file_name_to_height(f) for f in radar_file_names],
dtype=int
)
example_dict = {
FULL_IDS_KEY: full_id_strings,
STORM_TIMES_KEY: storm_times_unix_sec,
RADAR_FIELDS_KEY: radar_field_names,
RADAR_HEIGHTS_KEY: radar_heights_m_agl,
ROTATED_GRIDS_KEY:
this_radar_image_dict[storm_images.ROTATED_GRIDS_KEY],
ROTATED_GRID_SPACING_KEY:
this_radar_image_dict[storm_images.ROTATED_GRID_SPACING_KEY],
RADAR_IMAGE_MATRIX_KEY: dl_utils.stack_radar_fields(
tuple_of_image_matrices),
TARGET_MATRIX_KEY: target_matrix
}
if sounding_file_name is not None:
example_dict.update({
SOUNDING_FIELDS_KEY: sounding_field_names,
SOUNDING_HEIGHTS_KEY: sounding_heights_m_agl,
SOUNDING_MATRIX_KEY: sounding_matrix
})
return example_dict
def _create_3d_examples(
radar_file_name_matrix, full_id_strings, storm_times_unix_sec,
target_matrix, sounding_file_name=None, sounding_field_names=None):
"""Creates 3-D examples for one file time.
:param radar_file_name_matrix: numpy array (F_r x H_r) of paths to storm-
centered radar images. Files will be read by
`storm_images.read_storm_images`.
:param full_id_strings: See doc for `_create_2d_examples`.
:param storm_times_unix_sec: Same.
:param target_matrix: Same.
:param sounding_file_name: Same.
:param sounding_field_names: Same.
:return: example_dict: Same.
"""
orig_full_id_strings = copy.deepcopy(full_id_strings)
orig_storm_times_unix_sec = storm_times_unix_sec + 0
print('Reading data from: "{0:s}"...'.format(radar_file_name_matrix[0, 0]))
this_radar_image_dict = storm_images.read_storm_images(
netcdf_file_name=radar_file_name_matrix[0, 0],
full_id_strings_to_keep=full_id_strings,
valid_times_to_keep_unix_sec=storm_times_unix_sec)
if this_radar_image_dict is None:
return None
if sounding_file_name is None:
sounding_matrix = None
sounding_field_names = None
sounding_heights_m_agl = None
else:
sounding_dict, this_radar_image_dict = _read_soundings(
sounding_file_name=sounding_file_name,
sounding_field_names=sounding_field_names,
radar_image_dict=this_radar_image_dict)
if this_radar_image_dict is None:
return None
if len(this_radar_image_dict[storm_images.FULL_IDS_KEY]) == 0:
return None
sounding_matrix = sounding_dict[soundings.SOUNDING_MATRIX_KEY]
sounding_field_names = sounding_dict[soundings.FIELD_NAMES_KEY]
sounding_heights_m_agl = sounding_dict[soundings.HEIGHT_LEVELS_KEY]
full_id_strings = this_radar_image_dict[storm_images.FULL_IDS_KEY]
storm_times_unix_sec = this_radar_image_dict[storm_images.VALID_TIMES_KEY]
these_indices = tracking_utils.find_storm_objects(
all_id_strings=orig_full_id_strings,
all_times_unix_sec=orig_storm_times_unix_sec,
id_strings_to_keep=full_id_strings,
times_to_keep_unix_sec=storm_times_unix_sec, allow_missing=False)
target_matrix = target_matrix[these_indices, :]
num_radar_fields = radar_file_name_matrix.shape[0]
num_radar_heights = radar_file_name_matrix.shape[1]
tuple_of_4d_image_matrices = ()
for k in range(num_radar_heights):
tuple_of_3d_image_matrices = ()
for j in range(num_radar_fields):
if not j == k == 0:
print('Reading data from: "{0:s}"...'.format(
radar_file_name_matrix[j, k]
))
this_radar_image_dict = storm_images.read_storm_images(
netcdf_file_name=radar_file_name_matrix[j, k],
full_id_strings_to_keep=full_id_strings,
valid_times_to_keep_unix_sec=storm_times_unix_sec)
tuple_of_3d_image_matrices += (
this_radar_image_dict[storm_images.STORM_IMAGE_MATRIX_KEY],
)
tuple_of_4d_image_matrices += (
dl_utils.stack_radar_fields(tuple_of_3d_image_matrices),
)
radar_field_names = [
storm_images.image_file_name_to_field(f)
for f in radar_file_name_matrix[:, 0]
]
radar_heights_m_agl = numpy.array([
storm_images.image_file_name_to_height(f)
for f in radar_file_name_matrix[0, :]
], dtype=int)
example_dict = {
FULL_IDS_KEY: full_id_strings,
STORM_TIMES_KEY: storm_times_unix_sec,
RADAR_FIELDS_KEY: radar_field_names,
RADAR_HEIGHTS_KEY: radar_heights_m_agl,
ROTATED_GRIDS_KEY:
this_radar_image_dict[storm_images.ROTATED_GRIDS_KEY],
ROTATED_GRID_SPACING_KEY:
this_radar_image_dict[storm_images.ROTATED_GRID_SPACING_KEY],
RADAR_IMAGE_MATRIX_KEY: dl_utils.stack_radar_heights(
tuple_of_4d_image_matrices),
TARGET_MATRIX_KEY: target_matrix
}
if sounding_file_name is not None:
example_dict.update({
SOUNDING_FIELDS_KEY: sounding_field_names,
SOUNDING_HEIGHTS_KEY: sounding_heights_m_agl,
SOUNDING_MATRIX_KEY: sounding_matrix
})
return example_dict
def _create_2d3d_examples_myrorss(
azimuthal_shear_file_names, reflectivity_file_names,
full_id_strings, storm_times_unix_sec, target_matrix,
sounding_file_name=None, sounding_field_names=None):
"""Creates hybrid 2D-3D examples for one file time.
Fields in 2-D images: low-level and mid-level azimuthal shear
Field in 3-D images: reflectivity
:param azimuthal_shear_file_names: length-2 list of paths to storm-centered
azimuthal-shear images. The first (second) file should be (low)
mid-level azimuthal shear. Files will be read by
`storm_images.read_storm_images`.
:param reflectivity_file_names: length-H list of paths to storm-centered
reflectivity images, where H = number of reflectivity heights. Files
will be read by `storm_images.read_storm_images`.
:param full_id_strings: See doc for `_create_2d_examples`.
:param storm_times_unix_sec: Same.
:param target_matrix: Same.
:param sounding_file_name: Same.
:param sounding_field_names: Same.
:return: example_dict: Same.
"""
orig_full_id_strings = copy.deepcopy(full_id_strings)
orig_storm_times_unix_sec = storm_times_unix_sec + 0
print('Reading data from: "{0:s}"...'.format(reflectivity_file_names[0]))
this_radar_image_dict = storm_images.read_storm_images(
netcdf_file_name=reflectivity_file_names[0],
full_id_strings_to_keep=full_id_strings,
valid_times_to_keep_unix_sec=storm_times_unix_sec)
if this_radar_image_dict is None:
return None
if sounding_file_name is None:
sounding_matrix = None
sounding_field_names = None
sounding_heights_m_agl = None
else:
sounding_dict, this_radar_image_dict = _read_soundings(
sounding_file_name=sounding_file_name,
sounding_field_names=sounding_field_names,
radar_image_dict=this_radar_image_dict)
if this_radar_image_dict is None:
return None
if len(this_radar_image_dict[storm_images.FULL_IDS_KEY]) == 0:
return None
sounding_matrix = sounding_dict[soundings.SOUNDING_MATRIX_KEY]
sounding_field_names = sounding_dict[soundings.FIELD_NAMES_KEY]
sounding_heights_m_agl = sounding_dict[soundings.HEIGHT_LEVELS_KEY]
full_id_strings = this_radar_image_dict[storm_images.FULL_IDS_KEY]
storm_times_unix_sec = this_radar_image_dict[storm_images.VALID_TIMES_KEY]
these_indices = tracking_utils.find_storm_objects(
all_id_strings=orig_full_id_strings,
all_times_unix_sec=orig_storm_times_unix_sec,
id_strings_to_keep=full_id_strings,
times_to_keep_unix_sec=storm_times_unix_sec, allow_missing=False)
target_matrix = target_matrix[these_indices, :]
azimuthal_shear_field_names = [
storm_images.image_file_name_to_field(f)
for f in azimuthal_shear_file_names
]
reflectivity_heights_m_agl = numpy.array([
storm_images.image_file_name_to_height(f)
for f in reflectivity_file_names
], dtype=int)
num_reflectivity_heights = len(reflectivity_file_names)
tuple_of_image_matrices = ()
for j in range(num_reflectivity_heights):
if j != 0:
print('Reading data from: "{0:s}"...'.format(
reflectivity_file_names[j]
))
this_radar_image_dict = storm_images.read_storm_images(
netcdf_file_name=reflectivity_file_names[j],
full_id_strings_to_keep=full_id_strings,
valid_times_to_keep_unix_sec=storm_times_unix_sec)
this_matrix = numpy.expand_dims(
this_radar_image_dict[storm_images.STORM_IMAGE_MATRIX_KEY], axis=-1
)
tuple_of_image_matrices += (this_matrix,)
example_dict = {
FULL_IDS_KEY: full_id_strings,
STORM_TIMES_KEY: storm_times_unix_sec,
RADAR_FIELDS_KEY: azimuthal_shear_field_names,
RADAR_HEIGHTS_KEY: reflectivity_heights_m_agl,
ROTATED_GRIDS_KEY:
this_radar_image_dict[storm_images.ROTATED_GRIDS_KEY],
ROTATED_GRID_SPACING_KEY:
this_radar_image_dict[storm_images.ROTATED_GRID_SPACING_KEY],
REFL_IMAGE_MATRIX_KEY: dl_utils.stack_radar_heights(
tuple_of_image_matrices),
TARGET_MATRIX_KEY: target_matrix
}
if sounding_file_name is not None:
example_dict.update({
SOUNDING_FIELDS_KEY: sounding_field_names,
SOUNDING_HEIGHTS_KEY: sounding_heights_m_agl,
SOUNDING_MATRIX_KEY: sounding_matrix
})
num_az_shear_fields = len(azimuthal_shear_file_names)
tuple_of_image_matrices = ()
for j in range(num_az_shear_fields):
print('Reading data from: "{0:s}"...'.format(
azimuthal_shear_file_names[j]
))
this_radar_image_dict = storm_images.read_storm_images(
netcdf_file_name=azimuthal_shear_file_names[j],
full_id_strings_to_keep=full_id_strings,
valid_times_to_keep_unix_sec=storm_times_unix_sec)
tuple_of_image_matrices += (
this_radar_image_dict[storm_images.STORM_IMAGE_MATRIX_KEY],
)
example_dict.update({
AZ_SHEAR_IMAGE_MATRIX_KEY: dl_utils.stack_radar_fields(
tuple_of_image_matrices)
})
return example_dict
def _read_metadata_from_example_file(netcdf_file_name, include_soundings):
"""Reads metadata from file with input examples.
:param netcdf_file_name: Path to input file.
:param include_soundings: Boolean flag. If True and file contains
soundings, this method will return keys "sounding_field_names" and
"sounding_heights_m_agl". Otherwise, will not return said keys.
:return: example_dict: Dictionary with the following keys (explained in doc
to `write_example_file`).
example_dict['full_id_strings']
example_dict['storm_times_unix_sec']
example_dict['radar_field_names']
example_dict['radar_heights_m_agl']
example_dict['rotated_grids']
example_dict['rotated_grid_spacing_metres']
example_dict['target_names']
example_dict['sounding_field_names']
example_dict['sounding_heights_m_agl']
:return: netcdf_dataset: Instance of `netCDF4.Dataset`, which can be used to
keep reading file.
"""
netcdf_dataset = netCDF4.Dataset(netcdf_file_name)
include_soundings = (
include_soundings and
SOUNDING_FIELDS_KEY in netcdf_dataset.variables
)
example_dict = {
ROTATED_GRIDS_KEY: bool(getattr(netcdf_dataset, ROTATED_GRIDS_KEY)),
TARGET_NAMES_KEY: [
str(s) for s in
netCDF4.chartostring(netcdf_dataset.variables[TARGET_NAMES_KEY][:])
],
FULL_IDS_KEY: [
str(s) for s in
netCDF4.chartostring(netcdf_dataset.variables[FULL_IDS_KEY][:])
],
STORM_TIMES_KEY: numpy.array(
netcdf_dataset.variables[STORM_TIMES_KEY][:], dtype=int
),
RADAR_FIELDS_KEY: [
str(s) for s in
netCDF4.chartostring(netcdf_dataset.variables[RADAR_FIELDS_KEY][:])
],
RADAR_HEIGHTS_KEY: numpy.array(
netcdf_dataset.variables[RADAR_HEIGHTS_KEY][:], dtype=int
)
}
# TODO(thunderhoser): This is a HACK to deal with bad files.
example_dict[TARGET_NAMES_KEY] = [
n for n in example_dict[TARGET_NAMES_KEY] if n != ''
]
if example_dict[ROTATED_GRIDS_KEY]:
example_dict[ROTATED_GRID_SPACING_KEY] = getattr(
netcdf_dataset, ROTATED_GRID_SPACING_KEY)
else:
example_dict[ROTATED_GRID_SPACING_KEY] = None
if not include_soundings:
return example_dict, netcdf_dataset
example_dict.update({
SOUNDING_FIELDS_KEY: [
str(s) for s in netCDF4.chartostring(
netcdf_dataset.variables[SOUNDING_FIELDS_KEY][:])
],
SOUNDING_HEIGHTS_KEY:
numpy.array(netcdf_dataset.variables[SOUNDING_HEIGHTS_KEY][:],
dtype=int)
})
return example_dict, netcdf_dataset
def _compare_metadata(netcdf_dataset, example_dict):
"""Compares metadata between existing NetCDF file and new batch of examples.
This method contains a large number of `assert` statements. If any of the
`assert` statements fails, this method will error out.
:param netcdf_dataset: Instance of `netCDF4.Dataset`.
:param example_dict: See doc for `write_examples_with_3d_radar`.
:raises: ValueError: if the two sets have different metadata.
"""
include_soundings = SOUNDING_MATRIX_KEY in example_dict
orig_example_dict = {
TARGET_NAMES_KEY: [
str(s) for s in
netCDF4.chartostring(netcdf_dataset.variables[TARGET_NAMES_KEY][:])
],
ROTATED_GRIDS_KEY: bool(getattr(netcdf_dataset, ROTATED_GRIDS_KEY)),
RADAR_FIELDS_KEY: [
str(s) for s in netCDF4.chartostring(
netcdf_dataset.variables[RADAR_FIELDS_KEY][:])
],
RADAR_HEIGHTS_KEY: numpy.array(
netcdf_dataset.variables[RADAR_HEIGHTS_KEY][:], dtype=int
)
}
if example_dict[ROTATED_GRIDS_KEY]:
orig_example_dict[ROTATED_GRID_SPACING_KEY] = int(
getattr(netcdf_dataset, ROTATED_GRID_SPACING_KEY)
)
if include_soundings:
orig_example_dict[SOUNDING_FIELDS_KEY] = [
str(s) for s in netCDF4.chartostring(
netcdf_dataset.variables[SOUNDING_FIELDS_KEY][:])
]
orig_example_dict[SOUNDING_HEIGHTS_KEY] = numpy.array(
netcdf_dataset.variables[SOUNDING_HEIGHTS_KEY][:], dtype=int
)
for this_key in orig_example_dict:
if isinstance(example_dict[this_key], numpy.ndarray):
if numpy.array_equal(example_dict[this_key],
orig_example_dict[this_key]):
continue
else:
if example_dict[this_key] == orig_example_dict[this_key]:
continue
error_string = (
'\n"{0:s}" in existing NetCDF file:\n{1:s}\n\n"{0:s}" in new batch '
'of examples:\n{2:s}\n\n'
).format(
this_key, str(orig_example_dict[this_key]),
str(example_dict[this_key])
)
raise ValueError(error_string)
def _filter_examples_by_class(target_values, downsampling_dict,
test_mode=False):
"""Filters examples by target value.
E = number of examples
:param target_values: length-E numpy array of target values (integer class
labels).
:param downsampling_dict: Dictionary, where each key is the integer
ID for a target class (-2 for "dead storm") and the corresponding value
is the number of examples desired from said class. If
`downsampling_dict is None`, `example_dict` will be returned
without modification.
:param test_mode: Never mind. Just leave this alone.
:return: indices_to_keep: 1-D numpy array with indices of examples to keep.
These are all integers in [0, E - 1].
"""
num_examples = len(target_values)
if downsampling_dict is None:
return numpy.linspace(0, num_examples - 1, num=num_examples, dtype=int)
indices_to_keep = numpy.array([], dtype=int)
class_keys = list(downsampling_dict.keys())
for this_class in class_keys:
this_num_storm_objects = downsampling_dict[this_class]
these_indices = numpy.where(target_values == this_class)[0]
this_num_storm_objects = min(
[this_num_storm_objects, len(these_indices)]
)
if this_num_storm_objects == 0:
continue
if test_mode:
these_indices = these_indices[:this_num_storm_objects]
else:
these_indices = numpy.random.choice(
these_indices, size=this_num_storm_objects, replace=False)
indices_to_keep = numpy.concatenate((indices_to_keep, these_indices))
return indices_to_keep
def _file_name_to_batch_number(example_file_name):
"""Parses batch number from file.
:param example_file_name: See doc for `find_example_file`.
:return: batch_number: Integer.
:raises: ValueError: if batch number cannot be parsed from file name.
"""
pathless_file_name = os.path.split(example_file_name)[-1]
extensionless_file_name = os.path.splitext(pathless_file_name)[0]
return int(extensionless_file_name.split('input_examples_batch')[-1])
def _check_target_vars(target_names):
"""Error-checks list of target variables.
Target variables must all have the same mean lead time (average of min and
max lead times) and event type (tornado or wind).
:param target_names: 1-D list with names of target variables. Each must be
accepted by `target_val_utils.target_name_to_params`.
:return: mean_lead_time_seconds: Mean lead time (shared by all target
variables).
:return: event_type_string: Event type.
:raises: ValueError: if target variables do not all have the same mean lead
time or event type.
"""
error_checking.assert_is_string_list(target_names)
error_checking.assert_is_numpy_array(
numpy.array(target_names), num_dimensions=1
)
num_target_vars = len(target_names)
mean_lead_times = numpy.full(num_target_vars, -1, dtype=int)
event_type_strings = numpy.full(num_target_vars, '', dtype=object)
for k in range(num_target_vars):
this_param_dict = target_val_utils.target_name_to_params(
target_names[k]
)
event_type_strings[k] = this_param_dict[target_val_utils.EVENT_TYPE_KEY]
mean_lead_times[k] = int(numpy.round(
(this_param_dict[target_val_utils.MAX_LEAD_TIME_KEY] +
this_param_dict[target_val_utils.MIN_LEAD_TIME_KEY])
/ 2
))
if len(numpy.unique(mean_lead_times)) != 1:
error_string = (
'Target variables (listed below) have different mean lead times.'
'\n{0:s}'
).format(str(target_names))
raise ValueError(error_string)
if len(numpy.unique(event_type_strings)) != 1:
error_string = (
'Target variables (listed below) have different event types.\n{0:s}'
).format(str(target_names))
raise ValueError(error_string)
return mean_lead_times[0], event_type_strings[0]
def _check_layer_operation(example_dict, operation_dict):
"""Error-checks layer operation.
Such operations are used for dimensionality reduction (to convert radar data
from 3-D to 2-D).
:param example_dict: See doc for `reduce_examples_3d_to_2d`.
:param operation_dict: Dictionary with the following keys.
operation_dict["radar_field_name"]: Field to which operation will be
applied.
operation_dict["operation_name"]: Name of operation (must be in list
`VALID_LAYER_OPERATION_NAMES`).
operation_dict["min_height_m_agl"]: Minimum height of layer over which
operation will be applied.
operation_dict["max_height_m_agl"]: Max height of layer over which operation
will be applied.
:raises: ValueError: if something is wrong with the operation params.
"""
if operation_dict[RADAR_FIELD_KEY] in AZIMUTHAL_SHEAR_FIELD_NAMES:
error_string = (
'Layer operations cannot be applied to azimuthal-shear fields '
'(such as "{0:s}").'
).format(operation_dict[RADAR_FIELD_KEY])
raise ValueError(error_string)
if (operation_dict[RADAR_FIELD_KEY] == radar_utils.REFL_NAME
and REFL_IMAGE_MATRIX_KEY in example_dict):
pass
else:
if (operation_dict[RADAR_FIELD_KEY]
not in example_dict[RADAR_FIELDS_KEY]):
error_string = (
'\n{0:s}\nExamples contain only radar fields listed above, '
'which do not include "{1:s}".'
).format(
str(example_dict[RADAR_FIELDS_KEY]),
operation_dict[RADAR_FIELD_KEY]
)
raise ValueError(error_string)
if operation_dict[OPERATION_NAME_KEY] not in VALID_LAYER_OPERATION_NAMES:
error_string = (
'\n{0:s}\nValid operations (listed above) do not include '
'"{1:s}".'
).format(
str(VALID_LAYER_OPERATION_NAMES), operation_dict[OPERATION_NAME_KEY]
)
raise ValueError(error_string)
min_height_m_agl = operation_dict[MIN_HEIGHT_KEY]
max_height_m_agl = operation_dict[MAX_HEIGHT_KEY]
error_checking.assert_is_geq(
min_height_m_agl, numpy.min(example_dict[RADAR_HEIGHTS_KEY])
)
error_checking.assert_is_leq(
max_height_m_agl, numpy.max(example_dict[RADAR_HEIGHTS_KEY])
)
error_checking.assert_is_greater(max_height_m_agl, min_height_m_agl)
def _apply_layer_operation(example_dict, operation_dict):
"""Applies layer operation to radar data.
:param example_dict: See doc for `reduce_examples_3d_to_2d`.
:param operation_dict: See doc for `_check_layer_operation`.
:return: new_radar_matrix: E-by-M-by-N numpy array resulting from layer
operation.
"""
_check_layer_operation(example_dict=example_dict,
operation_dict=operation_dict)
height_diffs_metres = (
example_dict[RADAR_HEIGHTS_KEY] - operation_dict[MIN_HEIGHT_KEY]
).astype(float)
height_diffs_metres[height_diffs_metres > 0] = -numpy.inf
min_height_index = numpy.argmax(height_diffs_metres)
height_diffs_metres = (
operation_dict[MAX_HEIGHT_KEY] - example_dict[RADAR_HEIGHTS_KEY]
).astype(float)
height_diffs_metres[height_diffs_metres > 0] = -numpy.inf
max_height_index = numpy.argmax(height_diffs_metres)
operation_dict[MIN_HEIGHT_KEY] = example_dict[
RADAR_HEIGHTS_KEY][min_height_index]
operation_dict[MAX_HEIGHT_KEY] = example_dict[
RADAR_HEIGHTS_KEY][max_height_index]
operation_name = operation_dict[OPERATION_NAME_KEY]
operation_function = OPERATION_NAME_TO_FUNCTION_DICT[operation_name]
if REFL_IMAGE_MATRIX_KEY in example_dict:
orig_matrix = example_dict[REFL_IMAGE_MATRIX_KEY][
..., min_height_index:(max_height_index + 1), 0]
else:
field_index = example_dict[RADAR_FIELDS_KEY].index(
operation_dict[RADAR_FIELD_KEY])
orig_matrix = example_dict[RADAR_IMAGE_MATRIX_KEY][
..., min_height_index:(max_height_index + 1), field_index]
return operation_function(orig_matrix, axis=-1), operation_dict
def _subset_radar_data(
example_dict, netcdf_dataset_object, example_indices_to_keep,
field_names_to_keep, heights_to_keep_m_agl, num_rows_to_keep,
num_columns_to_keep):
"""Subsets radar data by field, height, and horizontal extent.
If the file contains both 2-D shear images and 3-D reflectivity images (like
MYRORSS data):
- `field_names_to_keep` will be interpreted as a list of shear fields to
keep. If None, all shear fields will be kept.
- `heights_to_keep_m_agl` will be interpreted as a list of reflectivity
heights to keep. If None, all reflectivity heights will be kept.
If the file contains only 2-D images, `field_names_to_keep` and
`heights_to_keep_m_agl` will be considered together, as a list of
field/height pairs to keep. If either argument is None, then all
field-height pairs will be kept.
If the file contains only 3-D images, `field_names_to_keep` and
`heights_to_keep_m_agl` will be considered separately:
- `field_names_to_keep` will be interpreted as a list of fields to keep. If
None, all fields will be kept.
- `heights_to_keep_m_agl` will be interpreted as a list of heights to keep.
If None, all heights will be kept.
:param example_dict: See output doc for `_read_metadata_from_example_file`.
:param netcdf_dataset_object: Same.
:param example_indices_to_keep: 1-D numpy array with indices of examples
(storm objects) to keep. These are examples in `netcdf_dataset_object`
for which radar data will be added to `example_dict`.
:param field_names_to_keep: See discussion above.
:param heights_to_keep_m_agl: See discussion above.
:param num_rows_to_keep: Number of grid rows to keep. Images will be
center-cropped (i.e., rows will be removed from the edges) to meet the
desired number of rows. If None, all rows will be kept.
:param num_columns_to_keep: Same as above but for columns.
:return: example_dict: Same as input but with the following exceptions.
[1] Keys "radar_field_names" and "radar_heights_m_agl" may have different
values.
[2] If file contains both 2-D and 3-D images, dictionary now contains keys
"reflectivity_image_matrix_dbz" and "az_shear_image_matrix_s01".
[3] If file contains only 2-D or only 3-D images, dictionary now contains
key "radar_image_matrix".
"""
if field_names_to_keep is None:
field_names_to_keep = copy.deepcopy(example_dict[RADAR_FIELDS_KEY])
if heights_to_keep_m_agl is None:
heights_to_keep_m_agl = example_dict[RADAR_HEIGHTS_KEY] + 0
error_checking.assert_is_numpy_array(
numpy.array(field_names_to_keep), num_dimensions=1
)
heights_to_keep_m_agl = numpy.round(heights_to_keep_m_agl).astype(int)
error_checking.assert_is_numpy_array(
heights_to_keep_m_agl, num_dimensions=1)
if RADAR_IMAGE_MATRIX_KEY in netcdf_dataset_object.variables:
radar_matrix = numpy.array(
netcdf_dataset_object.variables[RADAR_IMAGE_MATRIX_KEY][
example_indices_to_keep, ...
],
dtype=float
)
num_radar_dimensions = len(radar_matrix.shape) - 2
if num_radar_dimensions == 2:
these_indices = [
numpy.where(numpy.logical_and(
example_dict[RADAR_FIELDS_KEY] == f,
example_dict[RADAR_HEIGHTS_KEY] == h
))[0][0]
for f, h in zip(field_names_to_keep, heights_to_keep_m_agl)
]
these_indices = numpy.array(these_indices, dtype=int)
radar_matrix = radar_matrix[..., these_indices]
else:
these_field_indices = numpy.array([
example_dict[RADAR_FIELDS_KEY].index(f)
for f in field_names_to_keep
], dtype=int)
radar_matrix = radar_matrix[..., these_field_indices]
these_height_indices = numpy.array([
numpy.where(example_dict[RADAR_HEIGHTS_KEY] == h)[0][0]
for h in heights_to_keep_m_agl
], dtype=int)
radar_matrix = radar_matrix[..., these_height_indices, :]
radar_matrix = storm_images.downsize_storm_images(
storm_image_matrix=radar_matrix,
radar_field_name=field_names_to_keep[0],
num_rows_to_keep=num_rows_to_keep,
num_columns_to_keep=num_columns_to_keep)
example_dict[RADAR_IMAGE_MATRIX_KEY] = radar_matrix
else:
reflectivity_matrix_dbz = numpy.array(
netcdf_dataset_object.variables[REFL_IMAGE_MATRIX_KEY][
example_indices_to_keep, ...
],
dtype=float
)
reflectivity_matrix_dbz = numpy.expand_dims(
reflectivity_matrix_dbz, axis=-1
)
azimuthal_shear_matrix_s01 = numpy.array(
netcdf_dataset_object.variables[AZ_SHEAR_IMAGE_MATRIX_KEY][
example_indices_to_keep, ...
],
dtype=float
)
these_height_indices = numpy.array([
numpy.where(example_dict[RADAR_HEIGHTS_KEY] == h)[0][0]
for h in heights_to_keep_m_agl
], dtype=int)
reflectivity_matrix_dbz = reflectivity_matrix_dbz[
..., these_height_indices, :]
these_field_indices = numpy.array([
example_dict[RADAR_FIELDS_KEY].index(f)
for f in field_names_to_keep
], dtype=int)
azimuthal_shear_matrix_s01 = azimuthal_shear_matrix_s01[
..., these_field_indices]
reflectivity_matrix_dbz = storm_images.downsize_storm_images(
storm_image_matrix=reflectivity_matrix_dbz,
radar_field_name=radar_utils.REFL_NAME,
num_rows_to_keep=num_rows_to_keep,
num_columns_to_keep=num_columns_to_keep)
azimuthal_shear_matrix_s01 = storm_images.downsize_storm_images(
storm_image_matrix=azimuthal_shear_matrix_s01,
radar_field_name=field_names_to_keep[0],
num_rows_to_keep=num_rows_to_keep,
num_columns_to_keep=num_columns_to_keep)
example_dict[REFL_IMAGE_MATRIX_KEY] = reflectivity_matrix_dbz
example_dict[AZ_SHEAR_IMAGE_MATRIX_KEY] = azimuthal_shear_matrix_s01
example_dict[RADAR_FIELDS_KEY] = field_names_to_keep
example_dict[RADAR_HEIGHTS_KEY] = heights_to_keep_m_agl
return example_dict
def _subset_sounding_data(
example_dict, netcdf_dataset_object, example_indices_to_keep,
field_names_to_keep, heights_to_keep_m_agl):
"""Subsets sounding data by field and height.
:param example_dict: See doc for `_subset_radar_data`.
:param netcdf_dataset_object: Same.
:param example_indices_to_keep: Same.
:param field_names_to_keep: 1-D list of field names to keep. If None, will
keep all fields.
:param heights_to_keep_m_agl: 1-D numpy array of heights to keep. If None,
will keep all heights.
:return: example_dict: Same as input but with the following exceptions.
[1] Keys "sounding_field_names" and "sounding_heights_m_agl" may have
different values.
[2] Key "sounding_matrix" has been added.
"""
if field_names_to_keep is None:
field_names_to_keep = copy.deepcopy(example_dict[SOUNDING_FIELDS_KEY])
if heights_to_keep_m_agl is None:
heights_to_keep_m_agl = example_dict[SOUNDING_HEIGHTS_KEY] + 0
error_checking.assert_is_numpy_array(
numpy.array(field_names_to_keep), num_dimensions=1
)
heights_to_keep_m_agl = numpy.round(heights_to_keep_m_agl).astype(int)
error_checking.assert_is_numpy_array(
heights_to_keep_m_agl, num_dimensions=1)
sounding_matrix = numpy.array(
netcdf_dataset_object.variables[SOUNDING_MATRIX_KEY][
example_indices_to_keep, ...
],
dtype=float
)
# TODO(thunderhoser): This is a HACK.
spfh_index = example_dict[SOUNDING_FIELDS_KEY].index(
soundings.SPECIFIC_HUMIDITY_NAME)
temp_index = example_dict[SOUNDING_FIELDS_KEY].index(
soundings.TEMPERATURE_NAME)
pressure_index = example_dict[SOUNDING_FIELDS_KEY].index(
soundings.PRESSURE_NAME)
theta_v_index = example_dict[SOUNDING_FIELDS_KEY].index(
soundings.VIRTUAL_POTENTIAL_TEMPERATURE_NAME)
sounding_matrix[..., spfh_index][
numpy.isnan(sounding_matrix[..., spfh_index])
] = 0.
nan_example_indices, nan_height_indices = numpy.where(numpy.isnan(
sounding_matrix[..., theta_v_index]
))
if len(nan_example_indices) > 0:
this_temp_matrix_kelvins = sounding_matrix[..., temp_index][
nan_example_indices, nan_height_indices]
this_pressure_matrix_pa = sounding_matrix[..., pressure_index][
nan_example_indices, nan_height_indices]
this_thetav_matrix_kelvins = (
temp_conversion.temperatures_to_potential_temperatures(
temperatures_kelvins=this_temp_matrix_kelvins,
total_pressures_pascals=this_pressure_matrix_pa)
)
sounding_matrix[..., theta_v_index][
nan_example_indices, nan_height_indices
] = this_thetav_matrix_kelvins
these_indices = numpy.array([
example_dict[SOUNDING_FIELDS_KEY].index(f)
for f in field_names_to_keep
], dtype=int)
sounding_matrix = sounding_matrix[..., these_indices]
these_indices = numpy.array([
numpy.where(example_dict[SOUNDING_HEIGHTS_KEY] == h)[0][0]
for h in heights_to_keep_m_agl
], dtype=int)
sounding_matrix = sounding_matrix[..., these_indices, :]
example_dict[SOUNDING_FIELDS_KEY] = field_names_to_keep
example_dict[SOUNDING_HEIGHTS_KEY] = heights_to_keep_m_agl
example_dict[SOUNDING_MATRIX_KEY] = sounding_matrix
return example_dict
def find_storm_images_2d(
top_directory_name, radar_source, radar_field_names,
first_spc_date_string, last_spc_date_string, radar_heights_m_agl=None,
reflectivity_heights_m_agl=None):
"""Locates files with 2-D storm-centered radar images.
D = number of SPC dates in time period (`first_spc_date_string`...
`last_spc_date_string`)
:param top_directory_name: Name of top-level directory. Files therein will
be found by `storm_images.find_storm_image_file`.
:param radar_source: Data source (must be accepted by
`radar_utils.check_data_source`).
:param radar_field_names: 1-D list of radar fields. Each item must be
accepted by `radar_utils.check_field_name`.
:param first_spc_date_string: First SPC date (format "yyyymmdd"). This
method will locate files from `first_spc_date_string`...
`last_spc_date_string`.
:param last_spc_date_string: Same.
:param radar_heights_m_agl: [used only if radar_source = "gridrad"]
1-D numpy array of radar heights (metres above ground level). These
heights apply to all radar fields.
:param reflectivity_heights_m_agl: [used only if radar_source != "gridrad"]
1-D numpy array of reflectivity heights (metres above ground level).
These heights do not apply to other radar fields.
:return: radar_file_name_matrix: D-by-C numpy array of file paths.
"""
radar_utils.check_data_source(radar_source)
first_spc_date_unix_sec = time_conversion.spc_date_string_to_unix_sec(
first_spc_date_string)
last_spc_date_unix_sec = time_conversion.spc_date_string_to_unix_sec(
last_spc_date_string)
if radar_source == radar_utils.GRIDRAD_SOURCE_ID:
storm_image_file_dict = storm_images.find_many_files_gridrad(
top_directory_name=top_directory_name,
radar_field_names=radar_field_names,
radar_heights_m_agl=radar_heights_m_agl,
start_time_unix_sec=first_spc_date_unix_sec,
end_time_unix_sec=last_spc_date_unix_sec,
one_file_per_time_step=False, raise_error_if_all_missing=True)
else:
storm_image_file_dict = storm_images.find_many_files_myrorss_or_mrms(
top_directory_name=top_directory_name, radar_source=radar_source,
radar_field_names=radar_field_names,
reflectivity_heights_m_agl=reflectivity_heights_m_agl,
start_time_unix_sec=first_spc_date_unix_sec,
end_time_unix_sec=last_spc_date_unix_sec,
one_file_per_time_step=False,
raise_error_if_all_missing=True, raise_error_if_any_missing=False)
radar_file_name_matrix = storm_image_file_dict[
storm_images.IMAGE_FILE_NAMES_KEY]
num_file_times = radar_file_name_matrix.shape[0]
if radar_source == radar_utils.GRIDRAD_SOURCE_ID:
num_field_height_pairs = (
radar_file_name_matrix.shape[1] * radar_file_name_matrix.shape[2]
)
radar_file_name_matrix = numpy.reshape(
radar_file_name_matrix, (num_file_times, num_field_height_pairs)
)
time_missing_indices = numpy.unique(
numpy.where(radar_file_name_matrix == '')[0]
)
return numpy.delete(
radar_file_name_matrix, time_missing_indices, axis=0)
def find_storm_images_3d(
top_directory_name, radar_source, radar_field_names,
radar_heights_m_agl, first_spc_date_string, last_spc_date_string):
"""Locates files with 3-D storm-centered radar images.
D = number of SPC dates in time period (`first_spc_date_string`...
`last_spc_date_string`)
:param top_directory_name: See doc for `find_storm_images_2d`.
:param radar_source: Same.
:param radar_field_names: List (length F_r) of radar fields. Each item must
be accepted by `radar_utils.check_field_name`.
:param radar_heights_m_agl: numpy array (length H_r) of radar heights
(metres above ground level).
:param first_spc_date_string: First SPC date (format "yyyymmdd"). This
method will locate files from `first_spc_date_string`...
`last_spc_date_string`.
:param last_spc_date_string: Same.
:return: radar_file_name_matrix: numpy array (D x F_r x H_r) of file paths.
"""
radar_utils.check_data_source(radar_source)
first_spc_date_unix_sec = time_conversion.spc_date_string_to_unix_sec(
first_spc_date_string)
last_spc_date_unix_sec = time_conversion.spc_date_string_to_unix_sec(
last_spc_date_string)
if radar_source == radar_utils.GRIDRAD_SOURCE_ID:
file_dict = storm_images.find_many_files_gridrad(
top_directory_name=top_directory_name,
radar_field_names=radar_field_names,
radar_heights_m_agl=radar_heights_m_agl,
start_time_unix_sec=first_spc_date_unix_sec,
end_time_unix_sec=last_spc_date_unix_sec,
one_file_per_time_step=False, raise_error_if_all_missing=True)
else:
file_dict = storm_images.find_many_files_myrorss_or_mrms(
top_directory_name=top_directory_name, radar_source=radar_source,
radar_field_names=[radar_utils.REFL_NAME],
reflectivity_heights_m_agl=radar_heights_m_agl,
start_time_unix_sec=first_spc_date_unix_sec,
end_time_unix_sec=last_spc_date_unix_sec,
one_file_per_time_step=False,
raise_error_if_all_missing=True, raise_error_if_any_missing=False)
radar_file_name_matrix = file_dict[storm_images.IMAGE_FILE_NAMES_KEY]
num_file_times = radar_file_name_matrix.shape[0]
if radar_source != radar_utils.GRIDRAD_SOURCE_ID:
radar_file_name_matrix = numpy.reshape(
radar_file_name_matrix,
(num_file_times, 1, len(radar_heights_m_agl))
)
time_missing_indices = numpy.unique(
numpy.where(radar_file_name_matrix == '')[0]
)
return numpy.delete(
radar_file_name_matrix, time_missing_indices, axis=0)
def find_storm_images_2d3d_myrorss(
top_directory_name, first_spc_date_string, last_spc_date_string,
reflectivity_heights_m_agl):
"""Locates files with 2-D and 3-D storm-centered radar images.
Fields in 2-D images: low-level and mid-level azimuthal shear
Field in 3-D images: reflectivity
D = number of SPC dates in time period (`first_spc_date_string`...
`last_spc_date_string`)
:param top_directory_name: See doc for `find_storm_images_2d`.
:param first_spc_date_string: Same.
:param last_spc_date_string: Same.
:param reflectivity_heights_m_agl: Same.
:return: az_shear_file_name_matrix: D-by-2 numpy array of file paths. Files
in column 0 are low-level az shear; files in column 1 are mid-level az
shear.
:return: reflectivity_file_name_matrix: D-by-H numpy array of file paths,
where H = number of reflectivity heights.
"""
first_spc_date_unix_sec = time_conversion.spc_date_string_to_unix_sec(
first_spc_date_string)
last_spc_date_unix_sec = time_conversion.spc_date_string_to_unix_sec(
last_spc_date_string)
field_names = AZIMUTHAL_SHEAR_FIELD_NAMES + [radar_utils.REFL_NAME]
storm_image_file_dict = storm_images.find_many_files_myrorss_or_mrms(
top_directory_name=top_directory_name,
radar_source=radar_utils.MYRORSS_SOURCE_ID,
radar_field_names=field_names,
reflectivity_heights_m_agl=reflectivity_heights_m_agl,
start_time_unix_sec=first_spc_date_unix_sec,
end_time_unix_sec=last_spc_date_unix_sec,
one_file_per_time_step=False,
raise_error_if_all_missing=True, raise_error_if_any_missing=False)
radar_file_name_matrix = storm_image_file_dict[
storm_images.IMAGE_FILE_NAMES_KEY]
time_missing_indices = numpy.unique(
numpy.where(radar_file_name_matrix == '')[0]
)
radar_file_name_matrix = numpy.delete(
radar_file_name_matrix, time_missing_indices, axis=0)
return radar_file_name_matrix[:, :2], radar_file_name_matrix[:, 2:]
def find_sounding_files(
top_sounding_dir_name, radar_file_name_matrix, target_names,
lag_time_for_convective_contamination_sec):
"""Locates files with storm-centered soundings.
D = number of SPC dates in time period
:param top_sounding_dir_name: Name of top-level directory. Files therein
will be found by `soundings.find_sounding_file`.
:param radar_file_name_matrix: numpy array created by either
`find_storm_images_2d` or `find_storm_images_3d`. Length of the first
axis is D.
:param target_names: See doc for `_check_target_vars`.
:param lag_time_for_convective_contamination_sec: See doc for
`soundings.read_soundings`.
:return: sounding_file_names: length-D list of file paths.
"""
error_checking.assert_is_numpy_array(radar_file_name_matrix)
num_file_dimensions = len(radar_file_name_matrix.shape)
error_checking.assert_is_geq(num_file_dimensions, 2)
error_checking.assert_is_leq(num_file_dimensions, 3)
mean_lead_time_seconds = _check_target_vars(target_names)[0]
num_file_times = radar_file_name_matrix.shape[0]
sounding_file_names = [''] * num_file_times
for i in range(num_file_times):
if num_file_dimensions == 2:
this_file_name = radar_file_name_matrix[i, 0]
else:
this_file_name = radar_file_name_matrix[i, 0, 0]
this_time_unix_sec, this_spc_date_string = (
storm_images.image_file_name_to_time(this_file_name)
)
sounding_file_names[i] = soundings.find_sounding_file(
top_directory_name=top_sounding_dir_name,
spc_date_string=this_spc_date_string,
lead_time_seconds=mean_lead_time_seconds,
lag_time_for_convective_contamination_sec=
lag_time_for_convective_contamination_sec,
init_time_unix_sec=this_time_unix_sec, raise_error_if_missing=True)
return sounding_file_names
def find_target_files(top_target_dir_name, radar_file_name_matrix,
target_names):
"""Locates files with target values (storm-hazard indicators).
D = number of SPC dates in time period
:param top_target_dir_name: Name of top-level directory. Files therein
will be found by `target_val_utils.find_target_file`.
:param radar_file_name_matrix: numpy array created by either
`find_storm_images_2d` or `find_storm_images_3d`. Length of the first
axis is D.
:param target_names: See doc for `_check_target_vars`.
:return: target_file_names: length-D list of file paths.
"""
error_checking.assert_is_numpy_array(radar_file_name_matrix)
num_file_dimensions = len(radar_file_name_matrix.shape)
error_checking.assert_is_geq(num_file_dimensions, 2)
error_checking.assert_is_leq(num_file_dimensions, 3)
event_type_string = _check_target_vars(target_names)[-1]
num_file_times = radar_file_name_matrix.shape[0]
target_file_names = [''] * num_file_times
for i in range(num_file_times):
if num_file_dimensions == 2:
this_file_name = radar_file_name_matrix[i, 0]
else:
this_file_name = radar_file_name_matrix[i, 0, 0]
_, this_spc_date_string = storm_images.image_file_name_to_time(
this_file_name)
target_file_names[i] = target_val_utils.find_target_file(
top_directory_name=top_target_dir_name,
event_type_string=event_type_string,
spc_date_string=this_spc_date_string, raise_error_if_missing=False)
if os.path.isfile(target_file_names[i]):
continue
target_file_names[i] = None
return target_file_names
def subset_examples(example_dict, indices_to_keep, create_new_dict=False):
"""Subsets examples in dictionary.
:param example_dict: See doc for `write_example_file`.
:param indices_to_keep: 1-D numpy array with indices of examples to keep.
:param create_new_dict: Boolean flag. If True, this method will create a
new dictionary, leaving the input dictionary untouched.
:return: example_dict: Same as input, but possibly with fewer examples.
"""
error_checking.assert_is_integer_numpy_array(indices_to_keep)
error_checking.assert_is_numpy_array(indices_to_keep, num_dimensions=1)
error_checking.assert_is_boolean(create_new_dict)
if not create_new_dict:
for this_key in MAIN_KEYS:
optional_key_missing = (
this_key not in REQUIRED_MAIN_KEYS
and this_key not in example_dict
)
if optional_key_missing:
continue
if this_key == TARGET_MATRIX_KEY:
if this_key in example_dict:
example_dict[this_key] = (
example_dict[this_key][indices_to_keep, ...]
)
else:
example_dict[TARGET_VALUES_KEY] = (
example_dict[TARGET_VALUES_KEY][indices_to_keep]
)
continue
if this_key == FULL_IDS_KEY:
example_dict[this_key] = [
example_dict[this_key][k] for k in indices_to_keep
]
else:
example_dict[this_key] = example_dict[this_key][
indices_to_keep, ...]
return example_dict
new_example_dict = {}
for this_key in METADATA_KEYS:
sounding_key_missing = (
this_key in [SOUNDING_FIELDS_KEY, SOUNDING_HEIGHTS_KEY]
and this_key not in example_dict
)
if sounding_key_missing:
continue
if this_key == TARGET_NAMES_KEY:
if this_key in example_dict:
new_example_dict[this_key] = example_dict[this_key]
else:
new_example_dict[TARGET_NAME_KEY] = example_dict[
TARGET_NAME_KEY]
continue
new_example_dict[this_key] = example_dict[this_key]
for this_key in MAIN_KEYS:
optional_key_missing = (
this_key not in REQUIRED_MAIN_KEYS
and this_key not in example_dict
)
if optional_key_missing:
continue
if this_key == TARGET_MATRIX_KEY:
if this_key in example_dict:
new_example_dict[this_key] = (
example_dict[this_key][indices_to_keep, ...]
)
else:
new_example_dict[TARGET_VALUES_KEY] = (
example_dict[TARGET_VALUES_KEY][indices_to_keep]
)
continue
if this_key == FULL_IDS_KEY:
new_example_dict[this_key] = [
example_dict[this_key][k] for k in indices_to_keep
]
else:
new_example_dict[this_key] = example_dict[this_key][
indices_to_keep, ...]
return new_example_dict
def find_example_file(
top_directory_name, shuffled=True, spc_date_string=None,
batch_number=None, raise_error_if_missing=True):
"""Looks for file with input examples.
If `shuffled = True`, this method looks for a file with shuffled examples
(from many different times). If `shuffled = False`, this method looks for a
file with examples from one SPC date.
:param top_directory_name: Name of top-level directory with input examples.
:param shuffled: Boolean flag. The role of this flag is explained in the
general discussion above.
:param spc_date_string: [used only if `shuffled = False`]
SPC date (format "yyyymmdd").
:param batch_number: [used only if `shuffled = True`]
Batch number (integer).
:param raise_error_if_missing: Boolean flag. If file is missing and
`raise_error_if_missing = True`, this method will error out.
:return: example_file_name: Path to file with input examples. If file is
missing and `raise_error_if_missing = False`, this is the *expected*
path.
:raises: ValueError: if file is missing and `raise_error_if_missing = True`.
"""
error_checking.assert_is_string(top_directory_name)
error_checking.assert_is_boolean(shuffled)
error_checking.assert_is_boolean(raise_error_if_missing)
if shuffled:
error_checking.assert_is_integer(batch_number)
error_checking.assert_is_geq(batch_number, 0)
first_batch_number = int(number_rounding.floor_to_nearest(
batch_number, NUM_BATCHES_PER_DIRECTORY))
last_batch_number = first_batch_number + NUM_BATCHES_PER_DIRECTORY - 1
example_file_name = (
'{0:s}/batches{1:07d}-{2:07d}/input_examples_batch{3:07d}.nc'
).format(top_directory_name, first_batch_number, last_batch_number,
batch_number)
else:
time_conversion.spc_date_string_to_unix_sec(spc_date_string)
example_file_name = (
'{0:s}/{1:s}/input_examples_{2:s}.nc'
).format(top_directory_name, spc_date_string[:4], spc_date_string)
if raise_error_if_missing and not os.path.isfile(example_file_name):
error_string = 'Cannot find file. Expected at: "{0:s}"'.format(
example_file_name)
raise ValueError(error_string)
return example_file_name
def find_many_example_files(
top_directory_name, shuffled=True, first_spc_date_string=None,
last_spc_date_string=None, first_batch_number=None,
last_batch_number=None, raise_error_if_any_missing=True):
"""Looks for many files with input examples.
:param top_directory_name: See doc for `find_example_file`.
:param shuffled: Same.
:param first_spc_date_string: [used only if `shuffled = False`]
First SPC date (format "yyyymmdd"). This method will look for all SPC
dates from `first_spc_date_string`...`last_spc_date_string`.
:param last_spc_date_string: See above.
:param first_batch_number: [used only if `shuffled = True`]
First batch number (integer). This method will look for all batches
from `first_batch_number`...`last_batch_number`.
:param last_batch_number: See above.
:param raise_error_if_any_missing: Boolean flag. If *any* desired file is
not found and `raise_error_if_any_missing = True`, this method will
error out.
:return: example_file_names: 1-D list of paths to example files.
:raises: ValueError: if no files are found.
"""
error_checking.assert_is_boolean(shuffled)
if shuffled:
error_checking.assert_is_integer(first_batch_number)
error_checking.assert_is_integer(last_batch_number)
error_checking.assert_is_geq(first_batch_number, 0)
error_checking.assert_is_geq(last_batch_number, first_batch_number)
example_file_pattern = (
'{0:s}/batches{1:s}-{1:s}/input_examples_batch{1:s}.nc'
).format(top_directory_name, BATCH_NUMBER_REGEX)
example_file_names = glob.glob(example_file_pattern)
if len(example_file_names) > 0:
batch_numbers = numpy.array(
[_file_name_to_batch_number(f) for f in example_file_names],
dtype=int)
good_indices = numpy.where(numpy.logical_and(
batch_numbers >= first_batch_number,
batch_numbers <= last_batch_number
))[0]
example_file_names = [example_file_names[k] for k in good_indices]
if len(example_file_names) == 0:
error_string = (
'Cannot find any files with batch number from {0:d}...{1:d}.'
).format(first_batch_number, last_batch_number)
raise ValueError(error_string)
return example_file_names
spc_date_strings = time_conversion.get_spc_dates_in_range(
first_spc_date_string=first_spc_date_string,
last_spc_date_string=last_spc_date_string)
example_file_names = []
for this_spc_date_string in spc_date_strings:
this_file_name = find_example_file(
top_directory_name=top_directory_name, shuffled=False,
spc_date_string=this_spc_date_string,
raise_error_if_missing=raise_error_if_any_missing)
if not os.path.isfile(this_file_name):
continue
example_file_names.append(this_file_name)
if len(example_file_names) == 0:
error_string = (
'Cannot find any file with SPC date from {0:s} to {1:s}.'
).format(first_spc_date_string, last_spc_date_string)
raise ValueError(error_string)
return example_file_names
def write_example_file(netcdf_file_name, example_dict, append_to_file=False):
"""Writes input examples to NetCDF file.
The following keys are required in `example_dict` only if the examples
include soundings:
- "sounding_field_names"
- "sounding_heights_m_agl"
- "sounding_matrix"
If the examples contain both 2-D azimuthal-shear images and 3-D
reflectivity images:
- Keys "reflectivity_image_matrix_dbz" and "az_shear_image_matrix_s01" are
required.
- "radar_heights_m_agl" should contain only reflectivity heights.
- "radar_field_names" should contain only the names of azimuthal-shear
fields.
If the examples contain 2-D radar images and no 3-D images:
- Key "radar_image_matrix" is required.
- The [j]th element of "radar_field_names" should be the name of the [j]th
radar field.
- The [j]th element of "radar_heights_m_agl" should be the corresponding
height.
- Thus, there are C elements in "radar_field_names", C elements in
"radar_heights_m_agl", and C field-height pairs.
If the examples contain 3-D radar images and no 2-D images:
- Key "radar_image_matrix" is required.
- Each field in "radar_field_names" appears at each height in
"radar_heights_m_agl".
- Thus, there are F_r elements in "radar_field_names", H_r elements in
"radar_heights_m_agl", and F_r * H_r field-height pairs.
:param netcdf_file_name: Path to output file.
:param example_dict: Dictionary with the following keys.
example_dict['full_id_strings']: length-E list of full storm IDs.
example_dict['storm_times_unix_sec']: length-E list of valid times.
example_dict['radar_field_names']: List of radar fields (see general
discussion above).
example_dict['radar_heights_m_agl']: numpy array of radar heights (see
general discussion above).
example_dict['rotated_grids']: Boolean flag. If True, storm-centered radar
grids are rotated so that storm motion is in the +x-direction.
example_dict['rotated_grid_spacing_metres']: Spacing of rotated grids. If
grids are not rotated, this should be None.
example_dict['radar_image_matrix']: See general discussion above. For 2-D
images, this should be a numpy array with dimensions E x M x N x C.
For 3-D images, this should be a numpy array with dimensions
E x M x N x H_r x F_r.
example_dict['reflectivity_image_matrix_dbz']: See general discussion above.
Dimensions should be E x M x N x H_refl x 1, where H_refl = number of
reflectivity heights.
example_dict['az_shear_image_matrix_s01']: See general discussion above.
Dimensions should be E x M x N x F_as, where F_as = number of
azimuthal-shear fields.
example_dict['target_names']: 1-D list with names of target variables. Each
must be accepted by `target_val_utils.target_name_to_params`.
example_dict['target_matrix']: E-by-T numpy array of target values (integer
class labels), where T = number of target variables.
example_dict['sounding_field_names']: list (length F_s) of sounding fields.
Each item must be accepted by `soundings.check_field_name`.
example_dict['sounding_heights_m_agl']: numpy array (length H_s) of sounding
heights (metres above ground level).
example_dict['sounding_matrix']: numpy array (E x H_s x F_s) of storm-
centered soundings.
:param append_to_file: Boolean flag. If True, this method will append to an
existing file. If False, will create a new file, overwriting the
existing file if necessary.
"""
error_checking.assert_is_boolean(append_to_file)
include_soundings = SOUNDING_MATRIX_KEY in example_dict
if append_to_file:
netcdf_dataset = netCDF4.Dataset(
netcdf_file_name, 'a', format='NETCDF3_64BIT_OFFSET'
)
_compare_metadata(
netcdf_dataset=netcdf_dataset, example_dict=example_dict
)
num_examples_orig = len(numpy.array(
netcdf_dataset.variables[STORM_TIMES_KEY][:]
))
num_examples_to_add = len(example_dict[STORM_TIMES_KEY])
this_string_type = 'S{0:d}'.format(
netcdf_dataset.dimensions[STORM_ID_CHAR_DIM_KEY].size
)
example_dict[FULL_IDS_KEY] = netCDF4.stringtochar(numpy.array(
example_dict[FULL_IDS_KEY], dtype=this_string_type
))
for this_key in MAIN_KEYS:
if (this_key not in REQUIRED_MAIN_KEYS and
this_key not in netcdf_dataset.variables):
continue
netcdf_dataset.variables[this_key][
num_examples_orig:(num_examples_orig + num_examples_to_add),
...
] = example_dict[this_key]
netcdf_dataset.close()
return
# Open file.
file_system_utils.mkdir_recursive_if_necessary(file_name=netcdf_file_name)
netcdf_dataset = netCDF4.Dataset(
netcdf_file_name, 'w', format='NETCDF3_64BIT_OFFSET')
# Set global attributes.
netcdf_dataset.setncattr(
ROTATED_GRIDS_KEY, int(example_dict[ROTATED_GRIDS_KEY])
)
if example_dict[ROTATED_GRIDS_KEY]:
netcdf_dataset.setncattr(
ROTATED_GRID_SPACING_KEY,
numpy.round(int(example_dict[ROTATED_GRID_SPACING_KEY]))
)
# Set dimensions.
num_storm_id_chars = 10 + numpy.max(
numpy.array([len(s) for s in example_dict[FULL_IDS_KEY]])
)
num_radar_field_chars = numpy.max(
numpy.array([len(f) for f in example_dict[RADAR_FIELDS_KEY]])
)
num_target_name_chars = numpy.max(
numpy.array([len(t) for t in example_dict[TARGET_NAMES_KEY]])
)
num_target_vars = len(example_dict[TARGET_NAMES_KEY])
netcdf_dataset.createDimension(EXAMPLE_DIMENSION_KEY, None)
netcdf_dataset.createDimension(TARGET_VARIABLE_DIM_KEY, num_target_vars)
netcdf_dataset.createDimension(STORM_ID_CHAR_DIM_KEY, num_storm_id_chars)
netcdf_dataset.createDimension(
RADAR_FIELD_CHAR_DIM_KEY, num_radar_field_chars
)
netcdf_dataset.createDimension(
TARGET_NAME_CHAR_DIM_KEY, num_target_name_chars
)
if RADAR_IMAGE_MATRIX_KEY in example_dict:
num_grid_rows = example_dict[RADAR_IMAGE_MATRIX_KEY].shape[1]
num_grid_columns = example_dict[RADAR_IMAGE_MATRIX_KEY].shape[2]
num_radar_dimensions = len(
example_dict[RADAR_IMAGE_MATRIX_KEY].shape) - 2
if num_radar_dimensions == 3:
num_radar_heights = example_dict[RADAR_IMAGE_MATRIX_KEY].shape[3]
num_radar_fields = example_dict[RADAR_IMAGE_MATRIX_KEY].shape[4]
netcdf_dataset.createDimension(
RADAR_FIELD_DIM_KEY, num_radar_fields)
netcdf_dataset.createDimension(
RADAR_HEIGHT_DIM_KEY, num_radar_heights)
else:
num_radar_channels = example_dict[RADAR_IMAGE_MATRIX_KEY].shape[3]
netcdf_dataset.createDimension(
RADAR_CHANNEL_DIM_KEY, num_radar_channels)
netcdf_dataset.createDimension(ROW_DIMENSION_KEY, num_grid_rows)
netcdf_dataset.createDimension(COLUMN_DIMENSION_KEY, num_grid_columns)
else:
num_reflectivity_rows = example_dict[REFL_IMAGE_MATRIX_KEY].shape[1]
num_reflectivity_columns = example_dict[REFL_IMAGE_MATRIX_KEY].shape[2]
num_reflectivity_heights = example_dict[REFL_IMAGE_MATRIX_KEY].shape[3]
num_az_shear_rows = example_dict[AZ_SHEAR_IMAGE_MATRIX_KEY].shape[1]
num_az_shear_columns = example_dict[AZ_SHEAR_IMAGE_MATRIX_KEY].shape[2]
num_az_shear_fields = example_dict[AZ_SHEAR_IMAGE_MATRIX_KEY].shape[3]
netcdf_dataset.createDimension(
REFL_ROW_DIMENSION_KEY, num_reflectivity_rows)
netcdf_dataset.createDimension(
REFL_COLUMN_DIMENSION_KEY, num_reflectivity_columns)
netcdf_dataset.createDimension(
RADAR_HEIGHT_DIM_KEY, num_reflectivity_heights)
netcdf_dataset.createDimension(
AZ_SHEAR_ROW_DIMENSION_KEY, num_az_shear_rows)
netcdf_dataset.createDimension(
AZ_SHEAR_COLUMN_DIMENSION_KEY, num_az_shear_columns)
netcdf_dataset.createDimension(RADAR_FIELD_DIM_KEY, num_az_shear_fields)
num_radar_dimensions = -1
# Add storm IDs.
this_string_type = 'S{0:d}'.format(num_storm_id_chars)
full_ids_char_array = netCDF4.stringtochar(numpy.array(
example_dict[FULL_IDS_KEY], dtype=this_string_type
))
netcdf_dataset.createVariable(
FULL_IDS_KEY, datatype='S1',
dimensions=(EXAMPLE_DIMENSION_KEY, STORM_ID_CHAR_DIM_KEY)
)
netcdf_dataset.variables[FULL_IDS_KEY][:] = numpy.array(full_ids_char_array)
# Add names of radar fields.
this_string_type = 'S{0:d}'.format(num_radar_field_chars)
radar_field_names_char_array = netCDF4.stringtochar(numpy.array(
example_dict[RADAR_FIELDS_KEY], dtype=this_string_type
))
if num_radar_dimensions == 2:
this_first_dim_key = RADAR_CHANNEL_DIM_KEY + ''
else:
this_first_dim_key = RADAR_FIELD_DIM_KEY + ''
netcdf_dataset.createVariable(
RADAR_FIELDS_KEY, datatype='S1',
dimensions=(this_first_dim_key, RADAR_FIELD_CHAR_DIM_KEY)
)
netcdf_dataset.variables[RADAR_FIELDS_KEY][:] = numpy.array(
radar_field_names_char_array)
# Add names of target variables.
this_string_type = 'S{0:d}'.format(num_target_name_chars)
target_names_char_array = netCDF4.stringtochar(numpy.array(
example_dict[TARGET_NAMES_KEY], dtype=this_string_type
))
netcdf_dataset.createVariable(
TARGET_NAMES_KEY, datatype='S1',
dimensions=(TARGET_VARIABLE_DIM_KEY, TARGET_NAME_CHAR_DIM_KEY)
)
netcdf_dataset.variables[TARGET_NAMES_KEY][:] = numpy.array(
target_names_char_array)
# Add storm times.
netcdf_dataset.createVariable(
STORM_TIMES_KEY, datatype=numpy.int32, dimensions=EXAMPLE_DIMENSION_KEY
)
netcdf_dataset.variables[STORM_TIMES_KEY][:] = example_dict[
STORM_TIMES_KEY]
# Add target values.
netcdf_dataset.createVariable(
TARGET_MATRIX_KEY, datatype=numpy.int32,
dimensions=(EXAMPLE_DIMENSION_KEY, TARGET_VARIABLE_DIM_KEY)
)
netcdf_dataset.variables[TARGET_MATRIX_KEY][:] = example_dict[
TARGET_MATRIX_KEY]
# Add radar heights.
if num_radar_dimensions == 2:
this_dimension_key = RADAR_CHANNEL_DIM_KEY + ''
else:
this_dimension_key = RADAR_HEIGHT_DIM_KEY + ''
netcdf_dataset.createVariable(
RADAR_HEIGHTS_KEY, datatype=numpy.int32, dimensions=this_dimension_key
)
netcdf_dataset.variables[RADAR_HEIGHTS_KEY][:] = example_dict[
RADAR_HEIGHTS_KEY]
# Add storm-centered radar images.
if RADAR_IMAGE_MATRIX_KEY in example_dict:
if num_radar_dimensions == 3:
these_dimensions = (
EXAMPLE_DIMENSION_KEY, ROW_DIMENSION_KEY, COLUMN_DIMENSION_KEY,
RADAR_HEIGHT_DIM_KEY, RADAR_FIELD_DIM_KEY
)
else:
these_dimensions = (
EXAMPLE_DIMENSION_KEY, ROW_DIMENSION_KEY, COLUMN_DIMENSION_KEY,
RADAR_CHANNEL_DIM_KEY
)
netcdf_dataset.createVariable(
RADAR_IMAGE_MATRIX_KEY, datatype=numpy.float32,
dimensions=these_dimensions
)
netcdf_dataset.variables[RADAR_IMAGE_MATRIX_KEY][:] = example_dict[
RADAR_IMAGE_MATRIX_KEY]
else:
netcdf_dataset.createVariable(
REFL_IMAGE_MATRIX_KEY, datatype=numpy.float32,
dimensions=(EXAMPLE_DIMENSION_KEY, REFL_ROW_DIMENSION_KEY,
REFL_COLUMN_DIMENSION_KEY, RADAR_HEIGHT_DIM_KEY)
)
netcdf_dataset.variables[REFL_IMAGE_MATRIX_KEY][:] = example_dict[
REFL_IMAGE_MATRIX_KEY][..., 0]
netcdf_dataset.createVariable(
AZ_SHEAR_IMAGE_MATRIX_KEY, datatype=numpy.float32,
dimensions=(EXAMPLE_DIMENSION_KEY, AZ_SHEAR_ROW_DIMENSION_KEY,
AZ_SHEAR_COLUMN_DIMENSION_KEY, RADAR_FIELD_DIM_KEY)
)
netcdf_dataset.variables[AZ_SHEAR_IMAGE_MATRIX_KEY][:] = example_dict[
AZ_SHEAR_IMAGE_MATRIX_KEY]
if not include_soundings:
netcdf_dataset.close()
return
num_sounding_heights = example_dict[SOUNDING_MATRIX_KEY].shape[1]
num_sounding_fields = example_dict[SOUNDING_MATRIX_KEY].shape[2]
num_sounding_field_chars = 1
for j in range(num_sounding_fields):
num_sounding_field_chars = max([
num_sounding_field_chars,
len(example_dict[SOUNDING_FIELDS_KEY][j])
])
netcdf_dataset.createDimension(
SOUNDING_FIELD_DIM_KEY, num_sounding_fields)
netcdf_dataset.createDimension(
SOUNDING_HEIGHT_DIM_KEY, num_sounding_heights)
netcdf_dataset.createDimension(
SOUNDING_FIELD_CHAR_DIM_KEY, num_sounding_field_chars)
this_string_type = 'S{0:d}'.format(num_sounding_field_chars)
sounding_field_names_char_array = netCDF4.stringtochar(numpy.array(
example_dict[SOUNDING_FIELDS_KEY], dtype=this_string_type
))
netcdf_dataset.createVariable(
SOUNDING_FIELDS_KEY, datatype='S1',
dimensions=(SOUNDING_FIELD_DIM_KEY, SOUNDING_FIELD_CHAR_DIM_KEY)
)
netcdf_dataset.variables[SOUNDING_FIELDS_KEY][:] = numpy.array(
sounding_field_names_char_array)
netcdf_dataset.createVariable(
SOUNDING_HEIGHTS_KEY, datatype=numpy.int32,
dimensions=SOUNDING_HEIGHT_DIM_KEY
)
netcdf_dataset.variables[SOUNDING_HEIGHTS_KEY][:] = example_dict[
SOUNDING_HEIGHTS_KEY]
netcdf_dataset.createVariable(
SOUNDING_MATRIX_KEY, datatype=numpy.float32,
dimensions=(EXAMPLE_DIMENSION_KEY, SOUNDING_HEIGHT_DIM_KEY,
SOUNDING_FIELD_DIM_KEY)
)
netcdf_dataset.variables[SOUNDING_MATRIX_KEY][:] = example_dict[
SOUNDING_MATRIX_KEY]
netcdf_dataset.close()
return
def read_example_file(
netcdf_file_name, read_all_target_vars, target_name=None,
metadata_only=False, targets_only=False, include_soundings=True,
radar_field_names_to_keep=None, radar_heights_to_keep_m_agl=None,
sounding_field_names_to_keep=None, sounding_heights_to_keep_m_agl=None,
first_time_to_keep_unix_sec=None, last_time_to_keep_unix_sec=None,
num_rows_to_keep=None, num_columns_to_keep=None,
downsampling_dict=None):
"""Reads examples from NetCDF file.
If `metadata_only == True`, later input args are ignored.
If `targets_only == True`, later input args are ignored.
:param netcdf_file_name: Path to input file.
:param read_all_target_vars: Boolean flag. If True, will read all target
variables. If False, will read only `target_name`. Either way, if
downsampling is done, it will be based only on `target_name`.
:param target_name: Will read this target variable. If
`read_all_target_vars == True` and `downsampling_dict is None`, you can
leave this alone.
:param metadata_only: Boolean flag. If False, this method will read
everything. If True, will read everything except predictor and target
variables.
:param targets_only: Boolean flag. If False, this method will read
everything. If True, will read everything except predictors.
:param include_soundings: Boolean flag. If True and the file contains
soundings, this method will return soundings. Otherwise, no soundings.
:param radar_field_names_to_keep: See doc for `_subset_radar_data`.
:param radar_heights_to_keep_m_agl: Same.
:param sounding_field_names_to_keep: See doc for `_subset_sounding_data`.
:param sounding_heights_to_keep_m_agl: Same.
:param first_time_to_keep_unix_sec: First time to keep. If
`first_time_to_keep_unix_sec is None`, all storm objects will be kept.
:param last_time_to_keep_unix_sec: Last time to keep. If
`last_time_to_keep_unix_sec is None`, all storm objects will be kept.
:param num_rows_to_keep: See doc for `_subset_radar_data`.
:param num_columns_to_keep: Same.
:param downsampling_dict: See doc for `_filter_examples_by_class`.
:return: example_dict: If `read_all_target_vars == True`, dictionary will
have all keys listed in doc for `write_example_file`. If
`read_all_target_vars == False`, key "target_names" will be replaced by
"target_name" and "target_matrix" will be replaced by "target_values".
example_dict['target_name']: Name of target variable.
example_dict['target_values']: length-E list of target values (integer
class labels), where E = number of examples.
"""
# TODO(thunderhoser): Allow this method to read only soundings without radar
# data.
if (
target_name ==
'tornado_lead-time=0000-3600sec_distance=00000-10000m'
):
target_name = (
'tornado_lead-time=0000-3600sec_distance=00000-30000m_min-fujita=0'
)
error_checking.assert_is_boolean(read_all_target_vars)
error_checking.assert_is_boolean(include_soundings)
error_checking.assert_is_boolean(metadata_only)
error_checking.assert_is_boolean(targets_only)
example_dict, netcdf_dataset = _read_metadata_from_example_file(
netcdf_file_name=netcdf_file_name, include_soundings=include_soundings)
need_main_target_values = (
not read_all_target_vars
or downsampling_dict is not None
)
if need_main_target_values:
target_index = example_dict[TARGET_NAMES_KEY].index(target_name)
else:
target_index = -1
if not read_all_target_vars:
example_dict[TARGET_NAME_KEY] = target_name
example_dict.pop(TARGET_NAMES_KEY)
if metadata_only:
netcdf_dataset.close()
return example_dict
if need_main_target_values:
main_target_values = numpy.array(
netcdf_dataset.variables[TARGET_MATRIX_KEY][:, target_index],
dtype=int
)
else:
main_target_values = None
if read_all_target_vars:
example_dict[TARGET_MATRIX_KEY] = numpy.array(
netcdf_dataset.variables[TARGET_MATRIX_KEY][:], dtype=int
)
else:
example_dict[TARGET_VALUES_KEY] = main_target_values
# Subset by time.
if first_time_to_keep_unix_sec is None:
first_time_to_keep_unix_sec = 0
if last_time_to_keep_unix_sec is None:
last_time_to_keep_unix_sec = int(1e12)
error_checking.assert_is_integer(first_time_to_keep_unix_sec)
error_checking.assert_is_integer(last_time_to_keep_unix_sec)
error_checking.assert_is_geq(
last_time_to_keep_unix_sec, first_time_to_keep_unix_sec)
example_indices_to_keep = numpy.where(numpy.logical_and(
example_dict[STORM_TIMES_KEY] >= first_time_to_keep_unix_sec,
example_dict[STORM_TIMES_KEY] <= last_time_to_keep_unix_sec
))[0]
if downsampling_dict is not None:
subindices_to_keep = _filter_examples_by_class(
target_values=main_target_values[example_indices_to_keep],
downsampling_dict=downsampling_dict
)
elif not read_all_target_vars:
subindices_to_keep = numpy.where(
main_target_values[example_indices_to_keep] !=
target_val_utils.INVALID_STORM_INTEGER
)[0]
else:
subindices_to_keep = numpy.linspace(
0, len(example_indices_to_keep) - 1,
num=len(example_indices_to_keep), dtype=int
)
example_indices_to_keep = example_indices_to_keep[subindices_to_keep]
if len(example_indices_to_keep) == 0:
return None
example_dict[FULL_IDS_KEY] = [
example_dict[FULL_IDS_KEY][k] for k in example_indices_to_keep
]
example_dict[STORM_TIMES_KEY] = (
example_dict[STORM_TIMES_KEY][example_indices_to_keep]
)
if read_all_target_vars:
example_dict[TARGET_MATRIX_KEY] = (
example_dict[TARGET_MATRIX_KEY][example_indices_to_keep, :]
)
else:
example_dict[TARGET_VALUES_KEY] = (
example_dict[TARGET_VALUES_KEY][example_indices_to_keep]
)
if targets_only:
netcdf_dataset.close()
return example_dict
example_dict = _subset_radar_data(
example_dict=example_dict, netcdf_dataset_object=netcdf_dataset,
example_indices_to_keep=example_indices_to_keep,
field_names_to_keep=radar_field_names_to_keep,
heights_to_keep_m_agl=radar_heights_to_keep_m_agl,
num_rows_to_keep=num_rows_to_keep,
num_columns_to_keep=num_columns_to_keep)
if not include_soundings:
netcdf_dataset.close()
return example_dict
example_dict = _subset_sounding_data(
example_dict=example_dict, netcdf_dataset_object=netcdf_dataset,
example_indices_to_keep=example_indices_to_keep,
field_names_to_keep=sounding_field_names_to_keep,
heights_to_keep_m_agl=sounding_heights_to_keep_m_agl)
netcdf_dataset.close()
return example_dict
def read_specific_examples(
netcdf_file_name, read_all_target_vars, full_storm_id_strings,
storm_times_unix_sec, target_name=None, include_soundings=True,
radar_field_names_to_keep=None, radar_heights_to_keep_m_agl=None,
sounding_field_names_to_keep=None, sounding_heights_to_keep_m_agl=None,
num_rows_to_keep=None, num_columns_to_keep=None):
"""Reads specific examples (with specific ID-time pairs) from NetCDF file.
:param netcdf_file_name: Path to input file.
:param read_all_target_vars: See doc for `read_example_file`.
:param full_storm_id_strings: length-E list of storm IDs.
:param storm_times_unix_sec: length-E numpy array of valid times.
:param target_name: See doc for `read_example_file`.
:param metadata_only: Same.
:param include_soundings: Same.
:param radar_field_names_to_keep: Same.
:param radar_heights_to_keep_m_agl: Same.
:param sounding_field_names_to_keep: Same.
:param sounding_heights_to_keep_m_agl: Same.
:param num_rows_to_keep: Same.
:param num_columns_to_keep: Same.
:return: example_dict: See doc for `write_example_file`.
"""
if (
target_name ==
'tornado_lead-time=0000-3600sec_distance=00000-10000m'
):
target_name = (
'tornado_lead-time=0000-3600sec_distance=00000-30000m_min-fujita=0'
)
error_checking.assert_is_boolean(read_all_target_vars)
error_checking.assert_is_boolean(include_soundings)
example_dict, dataset_object = _read_metadata_from_example_file(
netcdf_file_name=netcdf_file_name, include_soundings=include_soundings)
example_indices_to_keep = tracking_utils.find_storm_objects(
all_id_strings=example_dict[FULL_IDS_KEY],
all_times_unix_sec=example_dict[STORM_TIMES_KEY],
id_strings_to_keep=full_storm_id_strings,
times_to_keep_unix_sec=storm_times_unix_sec, allow_missing=False
)
example_dict[FULL_IDS_KEY] = [
example_dict[FULL_IDS_KEY][k] for k in example_indices_to_keep
]
example_dict[STORM_TIMES_KEY] = example_dict[STORM_TIMES_KEY][
example_indices_to_keep]
if read_all_target_vars:
example_dict[TARGET_MATRIX_KEY] = numpy.array(
dataset_object.variables[TARGET_MATRIX_KEY][
example_indices_to_keep, :],
dtype=int
)
else:
target_index = example_dict[TARGET_NAMES_KEY].index(target_name)
example_dict[TARGET_NAME_KEY] = target_name
example_dict.pop(TARGET_NAMES_KEY)
example_dict[TARGET_VALUES_KEY] = numpy.array(
dataset_object.variables[TARGET_MATRIX_KEY][
example_indices_to_keep, target_index],
dtype=int
)
example_dict = _subset_radar_data(
example_dict=example_dict, netcdf_dataset_object=dataset_object,
example_indices_to_keep=example_indices_to_keep,
field_names_to_keep=radar_field_names_to_keep,
heights_to_keep_m_agl=radar_heights_to_keep_m_agl,
num_rows_to_keep=num_rows_to_keep,
num_columns_to_keep=num_columns_to_keep)
if not include_soundings:
dataset_object.close()
return example_dict
example_dict = _subset_sounding_data(
example_dict=example_dict, netcdf_dataset_object=dataset_object,
example_indices_to_keep=example_indices_to_keep,
field_names_to_keep=sounding_field_names_to_keep,
heights_to_keep_m_agl=sounding_heights_to_keep_m_agl)
dataset_object.close()
return example_dict
def reduce_examples_3d_to_2d(example_dict, list_of_operation_dicts):
"""Reduces examples from 3-D to 2-D.
If the examples contain both 2-D azimuthal-shear images and 3-D
reflectivity images:
- Keys "reflectivity_image_matrix_dbz" and "az_shear_image_matrix_s01" are
required.
- "radar_heights_m_agl" should contain only reflectivity heights.
- "radar_field_names" should contain only the names of azimuthal-shear
fields.
If the examples contain 3-D radar images and no 2-D images:
- Key "radar_image_matrix" is required.
- Each field in "radar_field_names" appears at each height in
"radar_heights_m_agl".
- Thus, there are F_r elements in "radar_field_names", H_r elements in
"radar_heights_m_agl", and F_r * H_r field-height pairs.
After dimensionality reduction (from 3-D to 2-D):
- Keys "reflectivity_image_matrix_dbz", "az_shear_image_matrix_s01", and
"radar_heights_m_agl" will be absent.
- Key "radar_image_matrix" will be present. The dimensions will be
E x M x N x C.
- Key "radar_field_names" will be a length-C list, where the [j]th item is
the field name for the [j]th channel of radar_image_matrix
(radar_image_matrix[..., j]).
- Key "min_radar_heights_m_agl" will be a length-C numpy array, where the
[j]th item is the MINIMUM height for the [j]th channel of
radar_image_matrix.
- Key "max_radar_heights_m_agl" will be a length-C numpy array, where the
[j]th item is the MAX height for the [j]th channel of radar_image_matrix.
- Key "radar_layer_operation_names" will be a length-C list, where the [j]th
item is the name of the operation used to create the [j]th channel of
radar_image_matrix.
:param example_dict: See doc for `write_example_file`.
:param list_of_operation_dicts: See doc for `_check_layer_operation`.
:return: example_dict: See general discussion above, for how the input
`example_dict` is changed to the output `example_dict`.
"""
if RADAR_IMAGE_MATRIX_KEY in example_dict:
num_radar_dimensions = len(
example_dict[RADAR_IMAGE_MATRIX_KEY].shape
) - 2
assert num_radar_dimensions == 3
new_radar_image_matrix = None
new_field_names = []
new_min_heights_m_agl = []
new_max_heights_m_agl = []
new_operation_names = []
if AZ_SHEAR_IMAGE_MATRIX_KEY in example_dict:
new_radar_image_matrix = example_dict[AZ_SHEAR_IMAGE_MATRIX_KEY] + 0.
for this_field_name in example_dict[RADAR_FIELDS_KEY]:
new_field_names.append(this_field_name)
new_operation_names.append(MAX_OPERATION_NAME)
if this_field_name == radar_utils.LOW_LEVEL_SHEAR_NAME:
new_min_heights_m_agl.append(0)
new_max_heights_m_agl.append(2000)
else:
new_min_heights_m_agl.append(3000)
new_max_heights_m_agl.append(6000)
for this_operation_dict in list_of_operation_dicts:
this_new_matrix, this_operation_dict = _apply_layer_operation(
example_dict=example_dict, operation_dict=this_operation_dict)
this_new_matrix = numpy.expand_dims(this_new_matrix, axis=-1)
if new_radar_image_matrix is None:
new_radar_image_matrix = this_new_matrix + 0.
else:
new_radar_image_matrix = numpy.concatenate(
(new_radar_image_matrix, this_new_matrix), axis=-1
)
new_field_names.append(this_operation_dict[RADAR_FIELD_KEY])
new_min_heights_m_agl.append(this_operation_dict[MIN_HEIGHT_KEY])
new_max_heights_m_agl.append(this_operation_dict[MAX_HEIGHT_KEY])
new_operation_names.append(this_operation_dict[OPERATION_NAME_KEY])
example_dict.pop(REFL_IMAGE_MATRIX_KEY, None)
example_dict.pop(AZ_SHEAR_IMAGE_MATRIX_KEY, None)
example_dict.pop(RADAR_HEIGHTS_KEY, None)
example_dict[RADAR_IMAGE_MATRIX_KEY] = new_radar_image_matrix
example_dict[RADAR_FIELDS_KEY] = new_field_names
example_dict[MIN_RADAR_HEIGHTS_KEY] = numpy.array(
new_min_heights_m_agl, dtype=int)
example_dict[MAX_RADAR_HEIGHTS_KEY] = numpy.array(
new_max_heights_m_agl, dtype=int)
example_dict[RADAR_LAYER_OPERATION_NAMES_KEY] = new_operation_names
return example_dict
def create_examples(
target_file_names, target_names, num_examples_per_in_file,
top_output_dir_name, radar_file_name_matrix=None,
reflectivity_file_name_matrix=None, az_shear_file_name_matrix=None,
downsampling_dict=None, target_name_for_downsampling=None,
sounding_file_names=None):
"""Creates many input examples.
If `radar_file_name_matrix is None`, both `reflectivity_file_name_matrix`
and `az_shear_file_name_matrix` must be specified.
D = number of SPC dates in time period
:param target_file_names: length-D list of paths to target files (will be
read by `read_labels_from_netcdf`).
:param target_names: See doc for `_check_target_vars`.
:param num_examples_per_in_file: Number of examples to read from each input
file.
:param top_output_dir_name: Name of top-level directory. Files will be
written here by `write_example_file`, to locations determined by
`find_example_file`.
:param radar_file_name_matrix: numpy array created by either
`find_storm_images_2d` or `find_storm_images_3d`. Length of the first
axis is D.
:param reflectivity_file_name_matrix: numpy array created by
`find_storm_images_2d3d_myrorss`. Length of the first axis is D.
:param az_shear_file_name_matrix: Same.
:param downsampling_dict: See doc for `deep_learning_utils.sample_by_class`.
If None, there will be no downsampling.
:param target_name_for_downsampling:
[used only if `downsampling_dict is not None`]
Name of target variable to use for downsampling.
:param sounding_file_names: length-D list of paths to sounding files (will
be read by `soundings.read_soundings`). If None, will not include
soundings.
"""
_check_target_vars(target_names)
num_target_vars = len(target_names)
if radar_file_name_matrix is None:
error_checking.assert_is_numpy_array(
reflectivity_file_name_matrix, num_dimensions=2)
num_file_times = reflectivity_file_name_matrix.shape[0]
these_expected_dim = numpy.array([num_file_times, 2], dtype=int)
error_checking.assert_is_numpy_array(
az_shear_file_name_matrix, exact_dimensions=these_expected_dim)
else:
error_checking.assert_is_numpy_array(radar_file_name_matrix)
num_file_dimensions = len(radar_file_name_matrix.shape)
num_file_times = radar_file_name_matrix.shape[0]
error_checking.assert_is_geq(num_file_dimensions, 2)
error_checking.assert_is_leq(num_file_dimensions, 3)
these_expected_dim = numpy.array([num_file_times], dtype=int)
error_checking.assert_is_numpy_array(
numpy.array(target_file_names), exact_dimensions=these_expected_dim
)
if sounding_file_names is not None:
error_checking.assert_is_numpy_array(
numpy.array(sounding_file_names),
exact_dimensions=these_expected_dim
)
error_checking.assert_is_integer(num_examples_per_in_file)
error_checking.assert_is_geq(num_examples_per_in_file, 1)
full_id_strings = []
storm_times_unix_sec = numpy.array([], dtype=int)
target_matrix = None
for i in range(num_file_times):
print('Reading data from: "{0:s}"...'.format(target_file_names[i]))
this_target_dict = target_val_utils.read_target_values(
netcdf_file_name=target_file_names[i], target_names=target_names)
full_id_strings += this_target_dict[target_val_utils.FULL_IDS_KEY]
storm_times_unix_sec = numpy.concatenate((
storm_times_unix_sec,
this_target_dict[target_val_utils.VALID_TIMES_KEY]
))
if target_matrix is None:
target_matrix = (
this_target_dict[target_val_utils.TARGET_MATRIX_KEY] + 0
)
else:
target_matrix = numpy.concatenate(
(target_matrix,
this_target_dict[target_val_utils.TARGET_MATRIX_KEY]),
axis=0
)
print('\n')
num_examples_found = len(full_id_strings)
num_examples_to_use = num_examples_per_in_file * num_file_times
if downsampling_dict is None:
indices_to_keep = numpy.linspace(
0, num_examples_found - 1, num=num_examples_found, dtype=int)
if num_examples_found > num_examples_to_use:
indices_to_keep = numpy.random.choice(
indices_to_keep, size=num_examples_to_use, replace=False)
else:
downsampling_index = target_names.index(target_name_for_downsampling)
indices_to_keep = dl_utils.sample_by_class(
sampling_fraction_by_class_dict=downsampling_dict,
target_name=target_name_for_downsampling,
target_values=target_matrix[:, downsampling_index],
num_examples_total=num_examples_to_use)
full_id_strings = [full_id_strings[k] for k in indices_to_keep]
storm_times_unix_sec = storm_times_unix_sec[indices_to_keep]
target_matrix = target_matrix[indices_to_keep, :]
for j in range(num_target_vars):
these_unique_classes, these_unique_counts = numpy.unique(
target_matrix[:, j], return_counts=True
)
for k in range(len(these_unique_classes)):
print((
'Number of examples with "{0:s}" in class {1:d} = {2:d}'
).format(
target_names[j], these_unique_classes[k], these_unique_counts[k]
))
print('\n')
first_spc_date_string = time_conversion.time_to_spc_date_string(
numpy.min(storm_times_unix_sec)
)
last_spc_date_string = time_conversion.time_to_spc_date_string(
numpy.max(storm_times_unix_sec)
)
spc_date_strings = time_conversion.get_spc_dates_in_range(
first_spc_date_string=first_spc_date_string,
last_spc_date_string=last_spc_date_string)
spc_date_to_out_file_dict = {}
for this_spc_date_string in spc_date_strings:
this_file_name = find_example_file(
top_directory_name=top_output_dir_name, shuffled=False,
spc_date_string=this_spc_date_string,
raise_error_if_missing=False)
if os.path.isfile(this_file_name):
os.remove(this_file_name)
spc_date_to_out_file_dict[this_spc_date_string] = this_file_name
for i in range(num_file_times):
if radar_file_name_matrix is None:
this_file_name = reflectivity_file_name_matrix[i, 0]
else:
this_file_name = numpy.ravel(radar_file_name_matrix[i, ...])[0]
this_time_unix_sec, this_spc_date_string = (
storm_images.image_file_name_to_time(this_file_name)
)
if this_time_unix_sec is None:
this_first_time_unix_sec = (
time_conversion.get_start_of_spc_date(this_spc_date_string)
)
this_last_time_unix_sec = (
time_conversion.get_end_of_spc_date(this_spc_date_string)
)
else:
this_first_time_unix_sec = this_time_unix_sec + 0
this_last_time_unix_sec = this_time_unix_sec + 0
these_indices = numpy.where(
numpy.logical_and(
storm_times_unix_sec >= this_first_time_unix_sec,
storm_times_unix_sec <= this_last_time_unix_sec)
)[0]
if len(these_indices) == 0:
continue
these_full_id_strings = [full_id_strings[m] for m in these_indices]
these_storm_times_unix_sec = storm_times_unix_sec[these_indices]
this_target_matrix = target_matrix[these_indices, :]
if sounding_file_names is None:
this_sounding_file_name = None
else:
this_sounding_file_name = sounding_file_names[i]
if radar_file_name_matrix is None:
this_example_dict = _create_2d3d_examples_myrorss(
azimuthal_shear_file_names=az_shear_file_name_matrix[
i, ...].tolist(),
reflectivity_file_names=reflectivity_file_name_matrix[
i, ...].tolist(),
full_id_strings=these_full_id_strings,
storm_times_unix_sec=these_storm_times_unix_sec,
target_matrix=this_target_matrix,
sounding_file_name=this_sounding_file_name,
sounding_field_names=None)
elif num_file_dimensions == 3:
this_example_dict = _create_3d_examples(
radar_file_name_matrix=radar_file_name_matrix[i, ...],
full_id_strings=these_full_id_strings,
storm_times_unix_sec=these_storm_times_unix_sec,
target_matrix=this_target_matrix,
sounding_file_name=this_sounding_file_name,
sounding_field_names=None)
else:
this_example_dict = _create_2d_examples(
radar_file_names=radar_file_name_matrix[i, ...].tolist(),
full_id_strings=these_full_id_strings,
storm_times_unix_sec=these_storm_times_unix_sec,
target_matrix=this_target_matrix,
sounding_file_name=this_sounding_file_name,
sounding_field_names=None)
print('\n')
if this_example_dict is None:
continue
this_example_dict.update({TARGET_NAMES_KEY: target_names})
this_output_file_name = spc_date_to_out_file_dict[this_spc_date_string]
print('Writing examples to: "{0:s}"...'.format(this_output_file_name))
write_example_file(
netcdf_file_name=this_output_file_name,
example_dict=this_example_dict,
append_to_file=os.path.isfile(this_output_file_name)
)<|fim▁end|> | :param sounding_file_name: Path to sounding file (will be read by |
<|file_name|>debug_node.ts<|end_file_name|><|fim▁begin|>/**
* @license
* Copyright Google Inc. All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
import {Injector} from '../di';
import {DebugContext} from '../view/index';
export class EventListener {
constructor(public name: string, public callback: Function) {}
}
/**
* @experimental All debugging apis are currently experimental.
*/
export class DebugNode {
listeners: EventListener[] = [];
parent: DebugElement|null = null;
constructor(public nativeNode: any, parent: DebugNode|null, private _debugContext: DebugContext) {
if (parent && parent instanceof DebugElement) {
parent.addChild(this);
}
}
get injector(): Injector { return this._debugContext.injector; }
get componentInstance(): any { return this._debugContext.component; }
get context(): any { return this._debugContext.context; }
get references(): {[key: string]: any} { return this._debugContext.references; }
get providerTokens(): any[] { return this._debugContext.providerTokens; }
}
/**
* @experimental All debugging apis are currently experimental.
*/<|fim▁hole|> classes: {[key: string]: boolean} = {};
styles: {[key: string]: string | null} = {};
childNodes: DebugNode[] = [];
nativeElement: any;
constructor(nativeNode: any, parent: any, _debugContext: DebugContext) {
super(nativeNode, parent, _debugContext);
this.nativeElement = nativeNode;
}
addChild(child: DebugNode) {
if (child) {
this.childNodes.push(child);
child.parent = this;
}
}
removeChild(child: DebugNode) {
const childIndex = this.childNodes.indexOf(child);
if (childIndex !== -1) {
child.parent = null;
this.childNodes.splice(childIndex, 1);
}
}
insertChildrenAfter(child: DebugNode, newChildren: DebugNode[]) {
const siblingIndex = this.childNodes.indexOf(child);
if (siblingIndex !== -1) {
this.childNodes.splice(siblingIndex + 1, 0, ...newChildren);
newChildren.forEach(c => {
if (c.parent) {
c.parent.removeChild(c);
}
c.parent = this;
});
}
}
insertBefore(refChild: DebugNode, newChild: DebugNode): void {
const refIndex = this.childNodes.indexOf(refChild);
if (refIndex === -1) {
this.addChild(newChild);
} else {
if (newChild.parent) {
newChild.parent.removeChild(newChild);
}
newChild.parent = this;
this.childNodes.splice(refIndex, 0, newChild);
}
}
query(predicate: Predicate<DebugElement>): DebugElement {
const results = this.queryAll(predicate);
return results[0] || null;
}
queryAll(predicate: Predicate<DebugElement>): DebugElement[] {
const matches: DebugElement[] = [];
_queryElementChildren(this, predicate, matches);
return matches;
}
queryAllNodes(predicate: Predicate<DebugNode>): DebugNode[] {
const matches: DebugNode[] = [];
_queryNodeChildren(this, predicate, matches);
return matches;
}
get children(): DebugElement[] {
return this.childNodes.filter((node) => node instanceof DebugElement) as DebugElement[];
}
triggerEventHandler(eventName: string, eventObj: any) {
this.listeners.forEach((listener) => {
if (listener.name == eventName) {
listener.callback(eventObj);
}
});
}
}
/**
* @experimental
*/
export function asNativeElements(debugEls: DebugElement[]): any {
return debugEls.map((el) => el.nativeElement);
}
function _queryElementChildren(
element: DebugElement, predicate: Predicate<DebugElement>, matches: DebugElement[]) {
element.childNodes.forEach(node => {
if (node instanceof DebugElement) {
if (predicate(node)) {
matches.push(node);
}
_queryElementChildren(node, predicate, matches);
}
});
}
function _queryNodeChildren(
parentNode: DebugNode, predicate: Predicate<DebugNode>, matches: DebugNode[]) {
if (parentNode instanceof DebugElement) {
parentNode.childNodes.forEach(node => {
if (predicate(node)) {
matches.push(node);
}
if (node instanceof DebugElement) {
_queryNodeChildren(node, predicate, matches);
}
});
}
}
// Need to keep the nodes in a global Map so that multiple angular apps are supported.
const _nativeNodeToDebugNode = new Map<any, DebugNode>();
/**
* @experimental
*/
export function getDebugNode(nativeNode: any): DebugNode|null {
return _nativeNodeToDebugNode.get(nativeNode) || null;
}
export function getAllDebugNodes(): DebugNode[] {
return Array.from(_nativeNodeToDebugNode.values());
}
export function indexDebugNode(node: DebugNode) {
_nativeNodeToDebugNode.set(node.nativeNode, node);
}
export function removeDebugNodeFromIndex(node: DebugNode) {
_nativeNodeToDebugNode.delete(node.nativeNode);
}
/**
* A boolean-valued function over a value, possibly including context information
* regarding that value's position in an array.
*
* @experimental All debugging apis are currently experimental.
*/
export interface Predicate<T> { (value: T): boolean; }<|fim▁end|> | export class DebugElement extends DebugNode {
name !: string;
properties: {[key: string]: any} = {};
attributes: {[key: string]: string | null} = {}; |
<|file_name|>base.py<|end_file_name|><|fim▁begin|>from requests import request, ConnectionError
from social.utils import module_member, parse_qs
from social.exceptions import AuthFailed
class BaseAuth(object):
"""A django.contrib.auth backend that authenticates the user based on
a authentication provider response"""
name = '' # provider name, it's stored in database
supports_inactive_user = False # Django auth
ID_KEY = None
EXTRA_DATA = None
REQUIRES_EMAIL_VALIDATION = False
def __init__(self, strategy=None, redirect_uri=None, *args, **kwargs):
self.strategy = strategy
self.redirect_uri = redirect_uri
self.data = {}
if strategy:
self.data = self.strategy.request_data()
self.redirect_uri = self.strategy.absolute_uri(
self.redirect_uri
)
def setting(self, name, default=None):
"""Return setting value from strategy"""
return self.strategy.setting(name, default=default, backend=self)
def auth_url(self):
"""Must return redirect URL to auth provider"""
raise NotImplementedError('Implement in subclass')
def auth_html(self):
"""Must return login HTML content returned by provider"""
raise NotImplementedError('Implement in subclass')
def auth_complete(self, *args, **kwargs):
"""Completes loging process, must return user instance"""
raise NotImplementedError('Implement in subclass')
def process_error(self, data):
"""Process data for errors, raise exception if needed.
Call this method on any override of auth_complete."""
pass
def authenticate(self, *args, **kwargs):
"""Authenticate user using social credentials
Authentication is made if this is the correct backend, backend
verification is made by kwargs inspection for current backend
name presence.
"""
# Validate backend and arguments. Require that the Social Auth
# response be passed in as a keyword argument, to make sure we
# don't match the username/password calling conventions of
# authenticate.
if 'backend' not in kwargs or kwargs['backend'].name != self.name or \
'strategy' not in kwargs or 'response' not in kwargs:
return None
self.strategy = self.strategy or kwargs.get('strategy')
self.redirect_uri = self.redirect_uri or kwargs.get('redirect_uri')
self.data = self.strategy.request_data()
pipeline = self.strategy.get_pipeline()
kwargs.setdefault('is_new', False)
if 'pipeline_index' in kwargs:
pipeline = pipeline[kwargs['pipeline_index']:]
return self.pipeline(pipeline, *args, **kwargs)
def pipeline(self, pipeline, pipeline_index=0, *args, **kwargs):
out = self.run_pipeline(pipeline, pipeline_index, *args, **kwargs)
if not isinstance(out, dict):
return out
user = out.get('user')
if user:
user.social_user = out.get('social')
user.is_new = out.get('is_new')
return user
def disconnect(self, *args, **kwargs):
pipeline = self.strategy.get_disconnect_pipeline()
if 'pipeline_index' in kwargs:
pipeline = pipeline[kwargs['pipeline_index']:]
kwargs['name'] = self.strategy.backend.name
kwargs['user_storage'] = self.strategy.storage.user
return self.run_pipeline(pipeline, *args, **kwargs)
def run_pipeline(self, pipeline, pipeline_index=0, *args, **kwargs):
out = kwargs.copy()
out.setdefault('strategy', self.strategy)
out.setdefault('backend', out.pop(self.name, None) or self)
out.setdefault('request', self.strategy.request)
for idx, name in enumerate(pipeline):
out['pipeline_index'] = pipeline_index + idx
func = module_member(name)
result = func(*args, **out) or {}
if not isinstance(result, dict):
return result
out.update(result)
self.strategy.clean_partial_pipeline()
return out
def extra_data(self, user, uid, response, details):
"""Return deafault extra data to store in extra_data field"""
data = {}
for entry in (self.EXTRA_DATA or []) + self.setting('EXTRA_DATA', []):
if not isinstance(entry, (list, tuple)):
entry = (entry,)
size = len(entry)
if size >= 1 and size <= 3:
if size == 3:
name, alias, discard = entry
elif size == 2:
(name, alias), discard = entry, False
elif size == 1:
name = alias = entry[0]
discard = False
value = response.get(name) or details.get(name)
if discard and not value:
continue
data[alias] = value
return data
def auth_allowed(self, response, details):
"""Return True if the user should be allowed to authenticate, by
default check if email is whitelisted (if there's a whitelist)"""
emails = self.setting('WHITELISTED_EMAILS', [])
domains = self.setting('WHITELISTED_DOMAINS', [])
email = details.get('email')
allowed = True
if email and (emails or domains):
domain = email.split('@', 1)[1]
allowed = email in emails or domain in domains
return allowed
def get_user_id(self, details, response):
"""Return a unique ID for the current user, by default from server
response."""
return response.get(self.ID_KEY)
def get_user_details(self, response):
"""Must return user details in a know internal struct:
{'username': <username if any>,
'email': <user email if any>,
'fullname': <user full name if any>,
'first_name': <user first name if any>,
'last_name': <user last name if any>}
"""
raise NotImplementedError('Implement in subclass')
def get_user(self, user_id):
"""
Return user with given ID from the User model used by this backend.
This is called by django.contrib.auth.middleware.
"""
from social.strategies.utils import get_current_strategy
strategy = self.strategy or get_current_strategy()
return strategy.get_user(user_id)
def continue_pipeline(self, *args, **kwargs):
"""Continue previous halted pipeline"""
kwargs.update({'backend': self})
return self.strategy.authenticate(*args, **kwargs)
def request_token_extra_arguments(self):
"""Return extra arguments needed on request-token process"""
return self.setting('REQUEST_TOKEN_EXTRA_ARGUMENTS', {})
def auth_extra_arguments(self):
"""Return extra arguments needed on auth process. The defaults can be
overriden by GET parameters."""
extra_arguments = self.setting('AUTH_EXTRA_ARGUMENTS', {})
extra_arguments.update((key, self.data[key]) for key in extra_arguments<|fim▁hole|> def uses_redirect(self):
"""Return True if this provider uses redirect url method,
otherwise return false."""
return True
def request(self, url, method='GET', *args, **kwargs):
kwargs.setdefault('timeout', self.setting('REQUESTS_TIMEOUT') or
self.setting('URLOPEN_TIMEOUT'))
try:
response = request(method, url, *args, **kwargs)
except ConnectionError as err:
raise AuthFailed(self, str(err))
response.raise_for_status()
return response
def get_json(self, url, *args, **kwargs):
return self.request(url, *args, **kwargs).json()
def get_querystring(self, url, *args, **kwargs):
return parse_qs(self.request(url, *args, **kwargs).text)
def get_key_and_secret(self):
"""Return tuple with Consumer Key and Consumer Secret for current
service provider. Must return (key, secret), order *must* be respected.
"""
return self.setting('KEY'), self.setting('SECRET')<|fim▁end|> | if key in self.data)
return extra_arguments
|
<|file_name|>max-test.js<|end_file_name|><|fim▁begin|>var vows = require("vows"),
_ = require("../../"),
load = require("../load"),
assert = require("../assert");
var suite = vows.describe("d3.max");
suite.addBatch({
"max": {
topic: load("arrays/max").expression("d3.max"),
"returns the greatest numeric value for numbers": function(max) {
assert.equal(max([1]), 1);
assert.equal(max([5, 1, 2, 3, 4]), 5);
assert.equal(max([20, 3]), 20);
assert.equal(max([3, 20]), 20);
},
"returns the greatest lexicographic value for strings": function(max) {
assert.equal(max(["c", "a", "b"]), "c");
assert.equal(max(["20", "3"]), "3");
assert.equal(max(["3", "20"]), "3");
},
"ignores null, undefined and NaN": function(max) {
var o = {valueOf: function() { return NaN; }};
assert.equal(max([NaN, 1, 2, 3, 4, 5]), 5);
assert.equal(max([o, 1, 2, 3, 4, 5]), 5);
assert.equal(max([1, 2, 3, 4, 5, NaN]), 5);
assert.equal(max([1, 2, 3, 4, 5, o]), 5);
assert.equal(max([10, null, 3, undefined, 5, NaN]), 10);
assert.equal(max([-1, null, -3, undefined, -5, NaN]), -1);
},
"compares heterogenous types as numbers": function(max) {
assert.strictEqual(max([20, "3"]), 20);
assert.strictEqual(max(["20", 3]), "20");
assert.strictEqual(max([3, "20"]), "20");
assert.strictEqual(max(["3", 20]), 20);
},
"returns undefined for empty array": function(max) {
assert.isUndefined(max([]));
assert.isUndefined(max([null]));
assert.isUndefined(max([undefined]));
assert.isUndefined(max([NaN]));
assert.isUndefined(max([NaN, NaN]));
},
"applies the optional accessor function": function(max) {
assert.equal(max([[1, 2, 3, 4, 5], [2, 4, 6, 8, 10]], function(d) { return _.min(d); }), 2);
assert.equal(max([1, 2, 3, 4, 5], function(d, i) { return i; }), 4);
}
}
});<|fim▁hole|>
suite.export(module);<|fim▁end|> | |
<|file_name|>queue.ts<|end_file_name|><|fim▁begin|>import { createPool } from '../index';
const pool = createPool(
{
create: function () {
return Promise.resolve('test');
},
destroy: function (resource) {
}
},
{
max: 10,
idleTimeoutMillis: 30000,
priorityRange: 3
}
);
pool.acquire().then(function (client) {
pool.release(client);
});<|fim▁hole|>});
pool.acquire(1).then(function (client) {
pool.release(client);
});<|fim▁end|> |
pool.acquire(0).then(function (client) {
pool.release(client); |
<|file_name|>token.py<|end_file_name|><|fim▁begin|>#!/usr/bin/python
# -*- coding: utf-8 -*-
import mysql.connector
#from token find userId
#return 0 for error
def findUser(userToken, cnx):
userQuery = 'SELECT user_id FROM user_token WHERE user_token = %s'
try:
userCursor = cnx.cursor()
userCursor.execute(userQuery, (userToken, ))
return userCursor.fetchone()
#return 0 for db error
except mysql.connector.Error as err:
print('Something went wrong: {}'.format(err))
return '0'
finally:
userCursor.close()
#create new token
#return 1 for success
#return 0 for error
def addToken(userId, userToken, cnx):
addQuery = 'INSERT INTO user_token (user_id, user_token) VALUES (%s, %s) ON DUPLICATE KEY UPDATE user_token = %s'
try:
addCursor = cnx.cursor()
addCursor.execute(addQuery, (userId, userToken, userToken))<|fim▁hole|> cnx.rollback()
return '0'
finally:
addCursor.close()
#delete token
#return 1 for success
#return 0 for fail
def deleteToken(userId, cnx):
cleanQuery = 'DELETE FROM user_token WHERE user_id = %s'
try:
cleanCursor = cnx.cursor()
cleanCursor.execute(cleanQuery, (userId, ))
cnx.commit()
return '1'
except mysql.connector.Error as err:
cnx.rollback()
print('Something went wrong: {}'.format(err))
return '0'
finally:
cleanCursor.close()<|fim▁end|> | cnx.commit()
return '1'
except mysql.connector.Error as err:
print('Something went wrong: {}'.format(err)) |
<|file_name|>GetInvoiceInfoFromUploadedFile.py<|end_file_name|><|fim▁begin|>import os
import requests # pip install requests
# The authentication key (API Key).
# Get your own by registering at https://app.pdf.co
API_KEY = "******************************************"
# Base URL for PDF.co Web API requests
BASE_URL = "https://api.pdf.co/v1"
# Source PDF file
SourceFile = ".\\sample.pdf"
def main(args = None):
uploadedFileUrl = uploadFile(SourceFile)
if (uploadedFileUrl != None):
getInfoFromPDF(uploadedFileUrl)
def getInfoFromPDF(uploadedFileUrl):
"""Get Information using PDF.co Web API"""
# Prepare requests params as JSON
# See documentation: https://apidocs.pdf.co
parameters = {}
parameters["url"] = uploadedFileUrl
parameters["inline"] = True
<|fim▁hole|>
# Execute request and get response as JSON
response = requests.post(url, data=parameters, headers={ "x-api-key": API_KEY })
if (response.status_code == 200):
json = response.json()
if json["error"] == False:
# Display information
print(json["body"])
else:
# Show service reported error
print(json["message"])
else:
print(f"Request error: {response.status_code} {response.reason}")
def uploadFile(fileName):
"""Uploads file to the cloud"""
# 1. RETRIEVE PRESIGNED URL TO UPLOAD FILE.
# Prepare URL for 'Get Presigned URL' API request
url = "{}/file/upload/get-presigned-url?contenttype=application/octet-stream&name={}".format(
BASE_URL, os.path.basename(fileName))
# Execute request and get response as JSON
response = requests.get(url, headers={ "x-api-key": API_KEY })
if (response.status_code == 200):
json = response.json()
if json["error"] == False:
# URL to use for file upload
uploadUrl = json["presignedUrl"]
# URL for future reference
uploadedFileUrl = json["url"]
# 2. UPLOAD FILE TO CLOUD.
with open(fileName, 'rb') as file:
requests.put(uploadUrl, data=file, headers={ "x-api-key": API_KEY, "content-type": "application/octet-stream" })
return uploadedFileUrl
else:
# Show service reported error
print(json["message"])
else:
print(f"Request error: {response.status_code} {response.reason}")
return None
if __name__ == '__main__':
main()<|fim▁end|> | # Prepare URL for 'invoice info' API request
url = "{}/pdf/invoiceparser".format(BASE_URL) |
<|file_name|>index.js<|end_file_name|><|fim▁begin|>import Botkit from 'botkit';
import os from 'os';
import Wit from 'botkit-middleware-witai';<|fim▁hole|>
import storageCreator from '../lib/storage';
import setupReceiveMiddleware from '../middleware/receiveMiddleware';
import notWitController from './notWit';
import miscController from './misc';
import sessionsController from './sessions';
import pingsController from './pings';
import slashController from './slash';
import dashboardController from './dashboard';
import { seedAndUpdateUsers } from '../../app/scripts';
require('dotenv').config();
var env = process.env.NODE_ENV || 'development';
if (env == 'development') {
process.env.SLACK_ID = process.env.DEV_SLACK_ID;
process.env.SLACK_SECRET = process.env.DEV_SLACK_SECRET;
}
// actions
import { firstInstallInitiateConversation, loginInitiateConversation } from '../actions';
// Wit Brain
if (process.env.WIT_TOKEN) {
var wit = Wit({
token: process.env.WIT_TOKEN,
minimum_confidence: 0.55
});
} else {
console.log('Error: Specify WIT_TOKEN in environment');
process.exit(1);
}
export { wit };
/**
* *** CONFIG ****
*/
var config = {};
const storage = storageCreator(config);
var controller = Botkit.slackbot({
interactive_replies: true,
storage
});
export { controller };
/**
* User has joined slack channel ==> make connection
* then onboard!
*/
controller.on('team_join', function (bot, message) {
console.log("\n\n\n ~~ joined the team ~~ \n\n\n");
const SlackUserId = message.user.id;
console.log(message.user.id);
bot.api.users.info({ user: SlackUserId }, (err, response) => {
if (!err) {
const { user, user: { id, team_id, name, tz } } = response;
const email = user.profile && user.profile.email ? user.profile.email : '';
models.User.find({
where: { SlackUserId },
})
.then((user) => {
if (!user) {
models.User.create({
TeamId: team_id,
email,
tz,
SlackUserId,
SlackName: name
});
} else {
user.update({
TeamId: team_id,
SlackName: name
})
}
});
}
});
});
/**
* User has updated data ==> update our DB!
*/
controller.on('user_change', function (bot, message) {
console.log("\n\n\n ~~ user updated profile ~~ \n\n\n");
if (message && message.user) {
const { user, user: { name, id, team_id, tz } } = message;
const SlackUserId = id;
const email = user.profile && user.profile.email ? user.profile.email : '';
models.User.find({
where: { SlackUserId },
})
.then((user) => {
if (!user) {
models.User.create({
TeamId: team_id,
email,
tz,
SlackUserId,
SlackName: name
});
} else {
user.update({
TeamId: team_id,
SlackName: name
})
}
});
}
});
// simple way to keep track of bots
export var bots = {};
if (!process.env.SLACK_ID || !process.env.SLACK_SECRET || !process.env.HTTP_PORT) {
console.log('Error: Specify SLACK_ID SLACK_SECRET and HTTP_PORT in environment');
process.exit(1);
}
// Custom Toki Config
export function customConfigBot(controller) {
// beef up the bot
setupReceiveMiddleware(controller);
notWitController(controller);
dashboardController(controller);
pingsController(controller);
sessionsController(controller);
slashController(controller);
miscController(controller);
}
// try to avoid repeat RTM's
export function trackBot(bot) {
bots[bot.config.token] = bot;
}
/**
* *** TURN ON THE BOT ****
* VIA SIGNUP OR LOGIN
*/
export function connectOnInstall(team_config) {
console.log(`\n\n\n\n CONNECTING ON INSTALL \n\n\n\n`);
let bot = controller.spawn(team_config);
controller.trigger('create_bot', [bot, team_config]);
}
export function connectOnLogin(identity) {
// bot already exists, get bot token for this users team
var SlackUserId = identity.user_id;
var TeamId = identity.team_id;
models.Team.find({
where: { TeamId }
})
.then((team) => {
const { token } = team;
if (token) {
var bot = controller.spawn({ token });
controller.trigger('login_bot', [bot, identity]);
}
})
}
controller.on('rtm_open',function(bot) {
console.log(`\n\n\n\n** The RTM api just connected! for bot token: ${bot.config.token}\n\n\n`);
});
// upon install
controller.on('create_bot', (bot,team) => {
const { id, url, name, bot: { token, user_id, createdBy, accessToken, scopes } } = team;
// this is what is used to save team data
const teamConfig = {
TeamId: id,
createdBy,
url,
name,
token,
scopes,
accessToken
}
if (bots[bot.config.token]) {
// already online! do nothing.
console.log("already online! restarting bot due to re-install");
// restart the bot
bots[bot.config.token].closeRTM();
}
bot.startRTM((err) => {
if (!err) {
console.log("\n\n RTM on with team install and listening \n\n");
trackBot(bot);
controller.saveTeam(teamConfig, (err, id) => {
if (err) {
console.log("Error saving team")
}
else {
console.log("Team " + team.name + " saved");
console.log(`\n\n installing users... \n\n`);
bot.api.users.list({}, (err, response) => {
if (!err) {
const { members } = response;
seedAndUpdateUsers(members);
}
firstInstallInitiateConversation(bot, team);
});
}
});
} else {
console.log("RTM failed")
}
});
});
// subsequent logins
controller.on('login_bot', (bot,identity) => {
if (bots[bot.config.token]) {
// already online! do nothing.
console.log("already online! do nothing.");
loginInitiateConversation(bot, identity);
} else {
bot.startRTM((err) => {
if (!err) {
console.log("RTM on and listening");
trackBot(bot);
loginInitiateConversation(bot, identity);
} else {
console.log("RTM failed")
console.log(err);
}
});
}
});<|fim▁end|> | import moment from 'moment-timezone';
import models from '../../app/models'; |
<|file_name|>__init__.py<|end_file_name|><|fim▁begin|>from decimal import Decimal
import random
import hashlib
from django.conf import settings
from django.core.cache import cache
from django.db.models.signals import post_save, post_delete, m2m_changed
from waffle.models import Flag, Sample, Switch
VERSION = (0, 9, 2)
__version__ = '.'.join(map(str, VERSION))
CACHE_PREFIX = getattr(settings, 'WAFFLE_CACHE_PREFIX', u'waffle:')
FLAG_CACHE_KEY = u'flag:%s'
FLAGS_ALL_CACHE_KEY = u'flags:all'
FLAG_USERS_CACHE_KEY = u'flag:%s:users'
FLAG_GROUPS_CACHE_KEY = u'flag:%s:groups'
SAMPLE_CACHE_KEY = u'sample:%s'
SAMPLES_ALL_CACHE_KEY = u'samples:all'
SWITCH_CACHE_KEY = u'switch:%s'
SWITCHES_ALL_CACHE_KEY = u'switches:all'
COOKIE_NAME = getattr(settings, 'WAFFLE_COOKIE', 'dwf_%s')
TEST_COOKIE_NAME = getattr(settings, 'WAFFLE_TESTING_COOKIE', 'dwft_%s')
def keyfmt(k, v=None):
if v is None:
return CACHE_PREFIX + k
return CACHE_PREFIX + hashlib.md5(k % v).hexdigest()
class DoesNotExist(object):
"""The record does not exist."""
@property
def active(self):
return getattr(settings, 'WAFFLE_SWITCH_DEFAULT', False)
def set_flag(request, flag_name, active=True, session_only=False):
"""Set a flag value on a request object."""
if not hasattr(request, 'waffles'):
request.waffles = {}
request.waffles[flag_name] = [active, session_only]
def flag_is_active(request, flag_name):
flag = cache.get(keyfmt(FLAG_CACHE_KEY, flag_name))
if flag is None:
try:
flag = Flag.objects.get(name=flag_name)
cache_flag(instance=flag)
except Flag.DoesNotExist:
return getattr(settings, 'WAFFLE_FLAG_DEFAULT', False)
if getattr(settings, 'WAFFLE_OVERRIDE', False):
if flag_name in request.GET:
return request.GET[flag_name] == '1'
if flag.everyone:
return True
elif flag.everyone is False:
return False
if flag.testing: # Testing mode is on.
tc = TEST_COOKIE_NAME % flag_name
if tc in request.GET:
on = request.GET[tc] == '1'
if not hasattr(request, 'waffle_tests'):
request.waffle_tests = {}
request.waffle_tests[flag_name] = on
return on
if tc in request.COOKIES:
return request.COOKIES[tc] == 'True'
user = request.user
if flag.authenticated and user.is_authenticated():
return True
if flag.staff and user.is_staff:
return True
if flag.superusers and user.is_superuser:
return True
if flag.languages:
languages = flag.languages.split(',')
if (hasattr(request, 'LANGUAGE_CODE') and
request.LANGUAGE_CODE in languages):
return True
flag_users = cache.get(keyfmt(FLAG_USERS_CACHE_KEY, flag.name))
if flag_users is None:
flag_users = flag.users.all()
cache_flag(instance=flag)
if user in flag_users:
return True
flag_groups = cache.get(keyfmt(FLAG_GROUPS_CACHE_KEY, flag.name))
if flag_groups is None:
flag_groups = flag.groups.all()
cache_flag(instance=flag)
user_groups = user.groups.all()
for group in flag_groups:
if group in user_groups:
return True
if flag.percent > 0:<|fim▁hole|> return request.waffles[flag_name][0]
cookie = COOKIE_NAME % flag_name
if cookie in request.COOKIES:
flag_active = (request.COOKIES[cookie] == 'True')
set_flag(request, flag_name, flag_active, flag.rollout)
return flag_active
if Decimal(str(random.uniform(0, 100))) <= flag.percent:
set_flag(request, flag_name, True, flag.rollout)
return True
set_flag(request, flag_name, False, flag.rollout)
return False
def switch_is_active(switch_name):
switch = cache.get(keyfmt(SWITCH_CACHE_KEY, switch_name))
if switch is None:
try:
switch = Switch.objects.get(name=switch_name)
cache_switch(instance=switch)
except Switch.DoesNotExist:
switch = DoesNotExist()
switch.name = switch_name
cache_switch(instance=switch)
return switch.active
def sample_is_active(sample_name):
sample = cache.get(keyfmt(SAMPLE_CACHE_KEY, sample_name))
if sample is None:
try:
sample = Sample.objects.get(name=sample_name)
cache_sample(instance=sample)
except Sample.DoesNotExist:
return getattr(settings, 'WAFFLE_SAMPLE_DEFAULT', False)
return Decimal(str(random.uniform(0, 100))) <= sample.percent
def cache_flag(**kwargs):
action = kwargs.get('action', None)
# action is included for m2m_changed signal. Only cache on the post_*.
if not action or action in ['post_add', 'post_remove', 'post_clear']:
f = kwargs.get('instance')
cache.add(keyfmt(FLAG_CACHE_KEY, f.name), f)
cache.add(keyfmt(FLAG_USERS_CACHE_KEY, f.name), f.users.all())
cache.add(keyfmt(FLAG_GROUPS_CACHE_KEY, f.name), f.groups.all())
def uncache_flag(**kwargs):
flag = kwargs.get('instance')
data = {
keyfmt(FLAG_CACHE_KEY, flag.name): None,
keyfmt(FLAG_USERS_CACHE_KEY, flag.name): None,
keyfmt(FLAG_GROUPS_CACHE_KEY, flag.name): None,
keyfmt(FLAGS_ALL_CACHE_KEY): None
}
cache.set_many(data, 5)
post_save.connect(uncache_flag, sender=Flag, dispatch_uid='save_flag')
post_delete.connect(uncache_flag, sender=Flag, dispatch_uid='delete_flag')
m2m_changed.connect(uncache_flag, sender=Flag.users.through,
dispatch_uid='m2m_flag_users')
m2m_changed.connect(uncache_flag, sender=Flag.groups.through,
dispatch_uid='m2m_flag_groups')
def cache_sample(**kwargs):
sample = kwargs.get('instance')
cache.add(keyfmt(SAMPLE_CACHE_KEY, sample.name), sample)
def uncache_sample(**kwargs):
sample = kwargs.get('instance')
cache.set(keyfmt(SAMPLE_CACHE_KEY, sample.name), None, 5)
cache.set(keyfmt(SAMPLES_ALL_CACHE_KEY), None, 5)
post_save.connect(uncache_sample, sender=Sample, dispatch_uid='save_sample')
post_delete.connect(uncache_sample, sender=Sample,
dispatch_uid='delete_sample')
def cache_switch(**kwargs):
switch = kwargs.get('instance')
cache.add(keyfmt(SWITCH_CACHE_KEY, switch.name), switch)
def uncache_switch(**kwargs):
switch = kwargs.get('instance')
cache.set(keyfmt(SWITCH_CACHE_KEY, switch.name), None, 5)
cache.set(keyfmt(SWITCHES_ALL_CACHE_KEY), None, 5)
post_delete.connect(uncache_switch, sender=Switch,
dispatch_uid='delete_switch')
post_save.connect(uncache_switch, sender=Switch, dispatch_uid='save_switch')<|fim▁end|> | if not hasattr(request, 'waffles'):
request.waffles = {}
elif flag_name in request.waffles: |
<|file_name|>production.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*-
"""
Production Configurations
- Use djangosecure
- Use Amazon's S3 for storing static files and uploaded media
- Use mailgun to send emails
- Use Redis on Heroku
"""
from __future__ import absolute_import, unicode_literals
from boto.s3.connection import OrdinaryCallingFormat
from django.utils import six
from .common import * # noqa
# SECRET CONFIGURATION
# ------------------------------------------------------------------------------
# See: https://docs.djangoproject.com/en/dev/ref/settings/#secret-key
# Raises ImproperlyConfigured exception if DJANGO_SECRET_KEY not in os.environ
SECRET_KEY = env('DJANGO_SECRET_KEY')
# This ensures that Django will be able to detect a secure connection
# properly on Heroku.
SECURE_PROXY_SSL_HEADER = ('HTTP_X_FORWARDED_PROTO', 'https')
# SECURITY CONFIGURATION
# ------------------------------------------------------------------------------
# See https://docs.djangoproject.com/en/1.9/ref/middleware/#module-django.middleware.security
# and https://docs.djangoproject.com/ja/1.9/howto/deployment/checklist/#run-manage-py-check-deploy
# set this to 60 seconds and then to 518400 when you can prove it works
SECURE_HSTS_SECONDS = 60
SECURE_HSTS_INCLUDE_SUBDOMAINS = env.bool(
'DJANGO_SECURE_HSTS_INCLUDE_SUBDOMAINS', default=True)
SECURE_CONTENT_TYPE_NOSNIFF = env.bool(
'DJANGO_SECURE_CONTENT_TYPE_NOSNIFF', default=True)
SECURE_BROWSER_XSS_FILTER = True
SESSION_COOKIE_SECURE = True
SESSION_COOKIE_HTTPONLY = True
SECURE_SSL_REDIRECT = env.bool('DJANGO_SECURE_SSL_REDIRECT', default=True)
CSRF_COOKIE_SECURE = True
CSRF_COOKIE_HTTPONLY = True
X_FRAME_OPTIONS = 'DENY'
# SITE CONFIGURATION
# ------------------------------------------------------------------------------
# Hosts/domain names that are valid for this site
# See https://docs.djangoproject.com/en/1.6/ref/settings/#allowed-hosts
ALLOWED_HOSTS = env.list('DJANGO_ALLOWED_HOSTS', default=['mertisconsulting.com'])
# END SITE CONFIGURATION
INSTALLED_APPS += ('gunicorn', )
# STORAGE CONFIGURATION
# ------------------------------------------------------------------------------
# Uploaded Media Files
# ------------------------
# See: http://django-storages.readthedocs.io/en/latest/index.html
INSTALLED_APPS += (
'storages',
)
AWS_ACCESS_KEY_ID = env('DJANGO_AWS_ACCESS_KEY_ID')
AWS_SECRET_ACCESS_KEY = env('DJANGO_AWS_SECRET_ACCESS_KEY')
AWS_STORAGE_BUCKET_NAME = env('DJANGO_AWS_STORAGE_BUCKET_NAME')
AWS_AUTO_CREATE_BUCKET = True
AWS_QUERYSTRING_AUTH = False
AWS_S3_CALLING_FORMAT = OrdinaryCallingFormat()
# AWS cache settings, don't change unless you know what you're doing:
AWS_EXPIRY = 60 * 60 * 24 * 7
# TODO See: https://github.com/jschneier/django-storages/issues/47
# Revert the following and use str after the above-mentioned bug is fixed in
# either django-storage-redux or boto
AWS_HEADERS = {
'Cache-Control': six.b('max-age=%d, s-maxage=%d, must-revalidate' % (
AWS_EXPIRY, AWS_EXPIRY))
}
# URL that handles the media served from MEDIA_ROOT, used for managing
# stored files.
# See:http://stackoverflow.com/questions/10390244/
from storages.backends.s3boto import S3BotoStorage
StaticRootS3BotoStorage = lambda: S3BotoStorage(location='static')
MediaRootS3BotoStorage = lambda: S3BotoStorage(location='media')
DEFAULT_FILE_STORAGE = 'config.settings.production.MediaRootS3BotoStorage'
MEDIA_URL = 'https://s3.amazonaws.com/%s/media/' % AWS_STORAGE_BUCKET_NAME
# Static Assets
# ------------------------
STATIC_URL = 'https://s3.amazonaws.com/%s/static/' % AWS_STORAGE_BUCKET_NAME
STATICFILES_STORAGE = 'config.settings.production.StaticRootS3BotoStorage'
# See: https://github.com/antonagestam/collectfast
# For Django 1.7+, 'collectfast' should come before
# 'django.contrib.staticfiles'
AWS_PRELOAD_METADATA = True
INSTALLED_APPS = ('collectfast', ) + INSTALLED_APPS
# EMAIL
# ------------------------------------------------------------------------------
DEFAULT_FROM_EMAIL = env('DJANGO_DEFAULT_FROM_EMAIL',
default='cpq-exporter <[email protected]>')
EMAIL_SUBJECT_PREFIX = env('DJANGO_EMAIL_SUBJECT_PREFIX', default='[cpq-exporter] ')
SERVER_EMAIL = env('DJANGO_SERVER_EMAIL', default=DEFAULT_FROM_EMAIL)
# Anymail with Mailgun
INSTALLED_APPS += ("anymail", )
ANYMAIL = {
"MAILGUN_API_KEY": env('DJANGO_MAILGUN_API_KEY'),
}
EMAIL_BACKEND = "anymail.backends.mailgun.MailgunBackend"
# TEMPLATE CONFIGURATION
# ------------------------------------------------------------------------------
# See:
# https://docs.djangoproject.com/en/dev/ref/templates/api/#django.template.loaders.cached.Loader
TEMPLATES[0]['OPTIONS']['loaders'] = [
('django.template.loaders.cached.Loader', [
'django.template.loaders.filesystem.Loader', 'django.template.loaders.app_directories.Loader', ]),
]
# DATABASE CONFIGURATION
# ------------------------------------------------------------------------------
# Raises ImproperlyConfigured exception if DATABASE_URL not in os.environ
DATABASES['default'] = env.db('DATABASE_URL')<|fim▁hole|>CACHES = {
'default': {
'BACKEND': 'django_redis.cache.RedisCache',
'LOCATION': '{0}/{1}'.format(env('REDIS_URL', default='redis://127.0.0.1:6379'), 0),
'OPTIONS': {
'CLIENT_CLASS': 'django_redis.client.DefaultClient',
'IGNORE_EXCEPTIONS': True, # mimics memcache behavior.
# http://niwinz.github.io/django-redis/latest/#_memcached_exceptions_behavior
}
}
}
# LOGGING CONFIGURATION
# ------------------------------------------------------------------------------
# See: https://docs.djangoproject.com/en/dev/ref/settings/#logging
# A sample logging configuration. The only tangible logging
# performed by this configuration is to send an email to
# the site admins on every HTTP 500 error when DEBUG=False.
# See http://docs.djangoproject.com/en/dev/topics/logging for
# more details on how to customize your logging configuration.
LOGGING = {
'version': 1,
'disable_existing_loggers': False,
'filters': {
'require_debug_false': {
'()': 'django.utils.log.RequireDebugFalse'
}
},
'formatters': {
'verbose': {
'format': '%(levelname)s %(asctime)s %(module)s '
'%(process)d %(thread)d %(message)s'
},
},
'handlers': {
'mail_admins': {
'level': 'ERROR',
'filters': ['require_debug_false'],
'class': 'django.utils.log.AdminEmailHandler'
},
'console': {
'level': 'DEBUG',
'class': 'logging.StreamHandler',
'formatter': 'verbose',
},
},
'loggers': {
'django.request': {
'handlers': ['mail_admins'],
'level': 'ERROR',
'propagate': True
},
'django.security.DisallowedHost': {
'level': 'ERROR',
'handlers': ['console', 'mail_admins'],
'propagate': True
}
}
}
# Custom Admin URL, use {% url 'admin:index' %}
ADMIN_URL = env('DJANGO_ADMIN_URL')
# Your production stuff: Below this line define 3rd party library settings<|fim▁end|> |
# CACHING
# ------------------------------------------------------------------------------
# Heroku URL does not pass the DB number, so we parse it in |
<|file_name|>muldiv.rs<|end_file_name|><|fim▁begin|>use {Style, Sign, Float, add_overflow, sub_overflow};
use std::i64;
use std::ops::{Mul, MulAssign, Div, DivAssign};
use ramp::ll::limb::Limb;
impl<'a> MulAssign<&'a Float> for Float {
fn mul_assign(&mut self, other: &'a Float) {
self.debug_assert_valid();
other.debug_assert_valid();
assert_eq!(self.prec, other.prec);
let prec = self.prec;
match (self.style, other.style) {
(Style::NaN, _) | (_, Style::NaN) => *self = Float::nan(prec),
// 0.0 * inf, inf * 0.0 are NaN
(Style::Infinity, Style::Zero) | (Style::Zero, Style::Infinity) => {
*self = Float::nan(prec)
}
(Style::Infinity, _) | (_, Style::Infinity) => {
*self = Float::inf(prec, self.sign ^ other.sign)
}
(Style::Zero, _) | (_, Style::Zero) => {
// FIXME (#3): need to get the right sign
*self = Float::zero_(prec, Sign::Pos)
}
(Style::Normal, Style::Normal) => {
self.signif *= &other.signif;
self.sign = self.sign ^ other.sign;
let bits = self.signif.bit_length();<|fim▁hole|> let (adjusted_exp, o2) = add_overflow(raw_mult_exp,
shift as i64 - (prec - 1) as i64);
self.exp = adjusted_exp;
if o1 ^ o2 {
// if we only overflowed once, then there's a
// problem. A double overflow means we went over
// the limit and then back, but a single means we
// never returned.
let overflowed = if o1 { raw_mult_exp } else { adjusted_exp };
self.exp = if overflowed < 0 { i64::MAX } else { i64::MIN };
self.normalise(false);
} else {
let ulp_bit = self.signif.bit(shift);
let half_ulp_bit = self.signif.bit(shift - 1);
let has_trailing_ones = self.signif.trailing_zeros() < shift - 1;
self.signif >>= shift as usize;
let round = half_ulp_bit && (ulp_bit || has_trailing_ones);
if round {
self.signif += 1;
}
self.normalise(true);
}
}
}
}
}
impl MulAssign<Float> for Float {
fn mul_assign(&mut self, other: Float) {
*self *= &other
}
}
impl Mul<Float> for Float {
type Output = Float;
fn mul(mut self, other: Float) -> Float {
// FIXME (#6): this could/should decide to use the Normal one
// with the largest backing storage as the by-value arg
// (i.e. reuse the biggest allocation)
self *= other;
self
}
}
impl<'a> Mul<&'a Float> for Float {
type Output = Float;
fn mul(mut self, other: &'a Float) -> Float {
self *= other;
self
}
}
impl<'a> Mul<Float> for &'a Float {
type Output = Float;
fn mul(self, mut other: Float) -> Float {
other *= self;
other
}
}
impl<'a> Mul<&'a Float> for &'a Float {
type Output = Float;
fn mul(self, other: &'a Float) -> Float {
// FIXME: this could clone and reserve enough space for the
// intermediate multiplication, to avoid needing to realloc
self.clone() * other
}
}
impl<'a> DivAssign<&'a Float> for Float {
fn div_assign(&mut self, other: &'a Float) {
self.debug_assert_valid();
other.debug_assert_valid();
assert_eq!(self.prec, other.prec);
let prec = self.prec;
match (self.style, other.style) {
(Style::NaN, _) | (_, Style::NaN) => *self = Float::nan(prec),
// 0.0 / 0.0 is NaN
(Style::Zero, Style::Zero) => *self = Float::nan(prec),
// 0.0 / x == 0.0
(Style::Zero, _) => *self = Float::zero_(prec, self.sign),
// x / 0.0 == inf
(_, Style::Zero) => *self = Float::inf(prec, other.sign),
(Style::Infinity, Style::Infinity) => {
*self = Float::nan(prec)
}
// x / inf == 0.0
(_, Style::Infinity) => *self = Float::zero_(prec, other.sign),
// inf / x == inf (x != 0)
(Style::Infinity, _) => {
self.sign = self.sign ^ other.sign;
}
(Style::Normal, Style::Normal) => {
let (raw_mult_exp, o1) = sub_overflow(self.exp, other.exp);
let (adjusted_exp, o2) = sub_overflow(raw_mult_exp,
(self.signif < other.signif) as i64);
self.sign = self.sign ^ other.sign;
self.exp = adjusted_exp;
if o1 ^ o2 {
// if we only overflowed once, then there's a
// problem. A double overflow means we went over
// the limit and then back, but a single means we
// never returned.
let overflowed = if o1 { raw_mult_exp } else { adjusted_exp };
self.exp = if overflowed < 0 { i64::MAX } else { i64::MIN };
self.normalise(false);
} else {
// we compute (m1 * 2**x) / m2 for some x >= p + 1, to
// ensure we get the full significand, and the
// rounding bit, and can use the remainder to check
// for sticky bits.
// round-up so that we're shifting by whole limbs,
// ensuring there's no need for sub-limb shifts.
let shift = (prec as usize + 1 + Limb::BITS - 1) / Limb::BITS * Limb::BITS;
self.signif <<= shift;
let (q, r) = self.signif.divmod(&other.signif);
self.signif.clone_from(&q);
let bits = self.signif.bit_length();
assert!(bits >= prec + 1);
let unshift = bits - prec;
let ulp_bit = self.signif.bit(unshift);
let half_ulp_bit = self.signif.bit(unshift - 1);
let has_trailing_ones = r != 0 || self.signif.trailing_zeros() < unshift - 1;
self.signif >>= unshift as usize;
if half_ulp_bit && (ulp_bit || has_trailing_ones) {
self.signif += 1;
}
self.normalise(true);
}
}
}
}
}
impl DivAssign<Float> for Float {
fn div_assign(&mut self, other: Float) {
*self /= &other;
}
}
impl Div<Float> for Float {
type Output = Float;
fn div(mut self, other: Float) -> Float {
self /= &other;
self
}
}
impl<'a> Div<&'a Float> for Float {
type Output = Float;
fn div(mut self, other: &'a Float) -> Float {
self /= other;
self
}
}
impl<'a> Div<Float> for &'a Float {
type Output = Float;
fn div(self, other: Float) -> Float {
self.clone() / &other
}
}
impl<'a> Div<&'a Float> for &'a Float {
type Output = Float;
fn div(self, other: &'a Float) -> Float {
self.clone() / other
}
}<|fim▁end|> | let shift = bits - prec;
let (raw_mult_exp, o1) = add_overflow(self.exp, other.exp); |
<|file_name|>MaybeIgnoreElement.java<|end_file_name|><|fim▁begin|>/**
* Copyright 2016 Netflix, Inc.
*
* 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 io.reactivex.internal.operators.maybe;
import io.reactivex.*;
import io.reactivex.disposables.Disposable;
import io.reactivex.internal.disposables.DisposableHelper;
/**
* Turns an onSuccess into an onComplete, onError and onComplete is relayed as is.
*
* @param <T> the value type
*/
public final class MaybeIgnoreElement<T> extends AbstractMaybeWithUpstream<T, T> {
public MaybeIgnoreElement(MaybeSource<T> source) {
super(source);
}
@Override
protected void subscribeActual(MaybeObserver<? super T> observer) {
source.subscribe(new IgnoreMaybeObserver<T>(observer));
}
static final class IgnoreMaybeObserver<T> implements MaybeObserver<T>, Disposable {
final MaybeObserver<? super T> actual;
Disposable d;
IgnoreMaybeObserver(MaybeObserver<? super T> actual) {
this.actual = actual;
}
@Override
public void onSubscribe(Disposable d) {
if (DisposableHelper.validate(this.d, d)) {
this.d = d;
actual.onSubscribe(this);
}
}
@Override
public void onSuccess(T value) {
d = DisposableHelper.DISPOSED;
actual.onComplete();
}
@Override
public void onError(Throwable e) {
d = DisposableHelper.DISPOSED;
actual.onError(e);
}
@Override
public void onComplete() {
d = DisposableHelper.DISPOSED;
actual.onComplete();
}
@Override
public boolean isDisposed() {
return d.isDisposed();
}
@Override
public void dispose() {<|fim▁hole|> }
}
}<|fim▁end|> | d.dispose();
d = DisposableHelper.DISPOSED; |
<|file_name|>criteo.js<|end_file_name|><|fim▁begin|>/**
* @overview If this code is included on a page with wbads it will add the criteo data as global
* targeting params to all ad slots rendered on the page.
*
* Set the globals window.CRTG_* prior to including this script
* so the criteo tags are properly added.
*
* This script must be included AFTER wbads is included.
*
* @todo: consider rewriting all wbads and plugins as amd modules or at least with umd
*
* @requires window.CRTG_NID
* @requires window.CRTG_COOKIE_NAME
* @optional window.CRTG_VAR_NAME - defaults to 'crtg_content'
* @requires window.wbads
*/
/*jslint browser: true, devel: true, todo: true, regexp: true */
/*global wbads: true */
window.CRTG_NID = window.CRTG_NID || false;
window.CRTG_COOKIE_NAME = window.CRTG_COOKIE_NAME || false;
window.CRTG_VAR_NAME = window.CRTG_VAR_NAME || 'crtg_content';
(function(w, d, wbads) {
'use strict';
var ctagId = 'criteo-js',
ctag = d.getElementById(ctagId);
if (ctag) {
if (!w.CRTG_NID) {
w.CRTG_NID = ctag.getAttribute('data-nid') || false;
}
if (!w.CRTG_COOKIE_NAME) {
w.CRTG_COOKIE_NAME = ctag.getAttribute('data-cookie-name') || false;
}
}
if (!w.CRTG_NID || !w.CRTG_COOKIE_NAME || !w.CRTG_VAR_NAME) {
return;
}
if (!ctag) {
ctag = d.createElement('script');
ctag.type = 'text/javascript';
ctag.id = ctagId;
ctag.async = true;
ctag.setAttribute('class', ctagId);
ctag.setAttribute('data-nid', w.CRTG_NID);
ctag.setAttribute('data-cookie-name', w.CRTG_COOKIE_NAME);
ctag.setAttribute('data-var-name', w.CRTG_VAR_NAME);
var rnd = Math.floor(Math.random() * 99999999999);
var url = location.protocol + '//rtax.criteo.com/delivery/rta/rta.js?netId=' + encodeURIComponent(w.CRTG_NID);<|fim▁hole|> url += '&varName=' + encodeURIComponent(w.CRTG_VAR_NAME);
ctag.src = url;
d.getElementsByTagName('head')[0].appendChild(ctag);
}
/**
* Get the criteo cookie value.
*
* @param {string} cookieName
* @returns {string}
*/
function getCookie(cookieName) {
var i, x, y, cookies = document.cookie.split(';');
for (i = 0; i < cookies.length; i++) {
x = cookies[i].substr(0, cookies[i].indexOf('='));
y = cookies[i].substr(cookies[i].indexOf('=') + 1);
x = x.replace(/^\s+|\s+$/g, '');
if (x == cookieName) {
return decodeURIComponent(y);
}
}
return'';
}
wbads.defineCallback('pre.enable.services', function() {
var parts, params = getCookie(w.CRTG_COOKIE_NAME).split(';');
for (var i = 0; i < params.length; i++) {
parts = params[i].split('=');
wbads.setGlobalTargetingParam('' + parts[0], '' + parts[1]);
}
});
}(window, document, window.wbads));<|fim▁end|> | url += '&cookieName=' + encodeURIComponent(w.CRTG_COOKIE_NAME);
url += '&rnd=' + rnd; |
<|file_name|>parameters.spec.ts<|end_file_name|><|fim▁begin|>import 'reflect-metadata';
import { SchemaObject, XParameterObject } from '@ts-stack/openapi-spec';
import { Parameters } from './parameters';
import { Column } from '../decorators/column';
describe('Parameters', () => {
describe('without data model', () => {
it('required path with someName', () => {
const params = new Parameters().required('path', 'someName').getParams();
const expectParams: XParameterObject[] = [{ in: 'path', name: 'someName', required: true }];
expect(params).toEqual(expectParams);
});
it('optional cookie with otherName', () => {
const params = new Parameters().optional('cookie', 'otherName').getParams();
const expectParams: XParameterObject[] = [{ in: 'cookie', name: 'otherName', required: false }];
expect(params).toEqual(expectParams);
});
it('required and optional params', () => {
const params = new Parameters().required('path', 'postId').optional('cookie', 'someName').getParams();
const expectParams: XParameterObject[] = [
{ in: 'path', name: 'postId', required: true },
{ in: 'cookie', name: 'someName', required: false },
];
expect(params).toEqual(expectParams);
});
});<|fim▁hole|> describe('with data model', () => {
class Model1 {
prop1: number;
prop2?: string;
}
it('required path with prop1', () => {
const params = new Parameters().required('path', Model1, 'prop1').getParams();
const expectParams: XParameterObject[] = [{ in: 'path', name: 'prop1', required: true }];
expect(params).toEqual(expectParams);
});
it('optional cookie with prop2', () => {
const params = new Parameters().optional('cookie', Model1, 'prop2').getParams();
const expectParams: XParameterObject[] = [{ in: 'cookie', name: 'prop2', required: false }];
expect(params).toEqual(expectParams);
});
it('required and optional params', () => {
const params = new Parameters().required('path', Model1, 'prop1').optional('cookie', Model1, 'prop2').getParams();
const expectParams: XParameterObject[] = [
{ in: 'path', name: 'prop1', required: true },
{ in: 'cookie', name: 'prop2', required: false },
];
expect(params).toEqual(expectParams);
});
});
describe('with data model and metadata of the model', () => {
const column1: SchemaObject = { type: 'number', minimum: 0, maximum: 100 };
const column2: SchemaObject = { type: 'string', minLength: 1, maxLength: 5 };
class Model1 {
@Column(column1)
prop1: number;
@Column(column2)
prop2?: string;
}
it('required path with prop1', () => {
const params = new Parameters().required('path', Model1, 'prop1').getParams();
const expectParams: XParameterObject[] = [{ in: 'path', name: 'prop1', required: true, schema: column1 }];
expect(params).toEqual(expectParams);
});
it('optional cookie with prop2', () => {
const params = new Parameters().optional('cookie', Model1, 'prop2').getParams();
const expectParams: XParameterObject[] = [{ in: 'cookie', name: 'prop2', required: false, schema: column2 }];
expect(params).toEqual(expectParams);
});
it('required and optional params', () => {
const params = new Parameters().required('path', Model1, 'prop1').optional('cookie', Model1, 'prop2').getParams();
const expectParams: XParameterObject[] = [
{ in: 'path', name: 'prop1', required: true, schema: column1 },
{ in: 'cookie', name: 'prop2', required: false, schema: column2 },
];
expect(params).toEqual(expectParams);
});
});
describe('bindTo() and recursive()', () => {
it('case 1', () => {
const params = new Parameters()
.required('path', 'postId')
.optional('query', 'page')
.bindTo('lastParamInPath')
.bindTo('httpMethod', 'GET')
.getParams();
expect(params).toEqual([
{ in: 'path', name: 'postId', required: true },
{
in: 'query',
name: 'page',
required: false,
'x-bound-to-path-param': false,
'x-bound-to-http-method': 'GET',
},
]);
});
});
});<|fim▁end|> | |
<|file_name|>util.ts<|end_file_name|><|fim▁begin|>import * as Long from "long";
import * as loader from "../lib/loader/src";<|fim▁hole|>export const arrayHeaderSize = 12; // capacity:i32 + length:i32 + base:i32
export function hexdump(memory: WebAssembly.Memory, offset: number, length: number): string {
var buffer = new Uint8Array(memory.buffer);
var out: string[] = [];
for (let i = 0; i < length; ++i) {
let b = buffer[offset + i].toString(16);
if (b.length < 2) b = "0" + b;
if ((i % 16) === 0) {
let l = (offset + i).toString(16);
while (l.length < 6) l = "0" + l;
if (i > 0)
out.push("\n");
out.push("> " + l + ":");
}
out.push(" " + b);
}
return out.join("");
}<|fim▁end|> | export { Long, loader };
|
<|file_name|>test_customer.py<|end_file_name|><|fim▁begin|>from unittest import mock
import pytest
import stripe
from model_mommy import mommy
from rest_framework.reverse import reverse
from restframework_stripe import models
from restframework_stripe.test import get_mock_resource
@mock.patch("stripe.Customer.save")
@mock.patch("stripe.Customer.retrieve")
@pytest.mark.django_db
def test_customer_update_bank_acct(customer_retrieve, customer_update, customer,
bank_account, api_client):
bank_account.owner = customer.owner
bank_account.save()
api_client.force_authenticate(customer.owner)
data = {
"default_source": bank_account.id,
"default_source_type": "bank_account"
}
customer_retrieve.return_value = get_mock_resource("Customer")
customer_update.return_value = get_mock_resource("Customer", default_source=bank_account.source)
uri = reverse("rf_stripe:customer-detail", kwargs={"pk": customer.pk})
response = api_client.patch(uri, data=data, format="json")
customer.refresh_from_db()
assert response.status_code == 200, response.data
assert customer.default_source.id == bank_account.id
@mock.patch("stripe.Customer.save")
@mock.patch("stripe.Customer.retrieve")
@pytest.mark.django_db
def test_customer_update_card(customer_retrieve, customer_update, customer, card, api_client):
card.owner = customer.owner
card.save()
api_client.force_authenticate(customer.owner)
data = {
"default_source": card.id,
"default_source_type": "card"
}<|fim▁hole|> customer_update.return_value = get_mock_resource("Customer", default_source=card.source)
uri = reverse("rf_stripe:customer-detail", kwargs={"pk": customer.pk})
response = api_client.patch(uri, data=data, format="json")
customer.refresh_from_db()
assert response.status_code == 200, response.data
assert customer.default_source.id == card.id
@pytest.mark.django_db
def test_customer_to_record_with_card_as_source(card):
stripe_object = get_mock_resource("Customer", default_source=card.source)
record = models.Customer.stripe_object_to_record(stripe_object)
assert record["default_source"].id == card.id
@pytest.mark.django_db
def test_customer_to_record_with_bank_account_as_source(bank_account):
stripe_object = get_mock_resource("Customer", default_source=bank_account.source)
record = models.Customer.stripe_object_to_record(stripe_object)
assert record["default_source"].id == bank_account.id
@pytest.mark.django_db
def test_customer_to_record_with_string_as_source():
stripe_object = get_mock_resource("Customer", default_source="bjkldjkfd532")
record = models.Customer.stripe_object_to_record(stripe_object)
assert record.get("default_source", None) is None
@mock.patch("stripe.ListObject.create")
@mock.patch("stripe.Customer.save")
@mock.patch("stripe.Customer.retrieve")
@pytest.mark.django_db
def test_customer_add_payment_method(a_retrieve, a_update, l_create, customer, api_client):
api_client.force_authenticate(customer.owner)
data = {
"source": "fkdsla;jfioewni3o2ndsa",
"email": "[email protected]",
}
new_card = get_mock_resource("Card")
updated_data = data.copy()
updated_data.pop("source")
updated_data["default_source"] = new_card
a_retrieve.return_value = get_mock_resource("Customer")
l_create.return_value = new_card
a_update.return_value = get_mock_resource("Customer", **updated_data)
uri = reverse("rf_stripe:customer-detail", kwargs={"pk": customer.pk})
response = api_client.patch(uri, data=data, format="json")
customer.refresh_from_db()
assert response.status_code == 200, response.data
assert 0 < models.Card.objects.filter(owner=customer.owner).count()
assert customer.source["email"] == data["email"]
@pytest.mark.django_db
def test_options(customer, api_client):
api_client.force_authenticate(customer.owner)
uri = reverse("rf_stripe:customer-list")
response = api_client.options(uri)
assert response.status_code == 200, response.data<|fim▁end|> |
customer_retrieve.return_value = get_mock_resource("Customer") |
<|file_name|>zz_generated_certificateregistrationprovider_client.go<|end_file_name|><|fim▁begin|>//go:build go1.16
// +build go1.16
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for license information.
// Code generated by Microsoft (R) AutoRest Code Generator.
// Changes may cause incorrect behavior and will be lost if the code is regenerated.
package armappservice
import (
"context"
"github.com/Azure/azure-sdk-for-go/sdk/azcore"
"github.com/Azure/azure-sdk-for-go/sdk/azcore/arm"
armruntime "github.com/Azure/azure-sdk-for-go/sdk/azcore/arm/runtime"
"github.com/Azure/azure-sdk-for-go/sdk/azcore/policy"
"github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime"
"net/http"
)
// CertificateRegistrationProviderClient contains the methods for the CertificateRegistrationProvider group.
// Don't use this type directly, use NewCertificateRegistrationProviderClient() instead.
type CertificateRegistrationProviderClient struct {
host string
pl runtime.Pipeline
}
// NewCertificateRegistrationProviderClient creates a new instance of CertificateRegistrationProviderClient with the specified values.
// credential - used to authorize requests. Usually a credential from azidentity.
// options - pass nil to accept the default values.
func NewCertificateRegistrationProviderClient(credential azcore.TokenCredential, options *arm.ClientOptions) *CertificateRegistrationProviderClient {
if options == nil {
options = &arm.ClientOptions{}
}
ep := options.Endpoint
if len(ep) == 0 {
ep = arm.AzurePublicCloud
}
client := &CertificateRegistrationProviderClient{
host: string(ep),
pl: armruntime.NewPipeline(moduleName, moduleVersion, credential, runtime.PipelineOptions{}, options),<|fim▁hole|> }
return client
}
// ListOperations - Description for Implements Csm operations Api to exposes the list of available Csm Apis under the resource
// provider
// If the operation fails it returns an *azcore.ResponseError type.
// options - CertificateRegistrationProviderClientListOperationsOptions contains the optional parameters for the CertificateRegistrationProviderClient.ListOperations
// method.
func (client *CertificateRegistrationProviderClient) ListOperations(options *CertificateRegistrationProviderClientListOperationsOptions) *CertificateRegistrationProviderClientListOperationsPager {
return &CertificateRegistrationProviderClientListOperationsPager{
client: client,
requester: func(ctx context.Context) (*policy.Request, error) {
return client.listOperationsCreateRequest(ctx, options)
},
advancer: func(ctx context.Context, resp CertificateRegistrationProviderClientListOperationsResponse) (*policy.Request, error) {
return runtime.NewRequest(ctx, http.MethodGet, *resp.CsmOperationCollection.NextLink)
},
}
}
// listOperationsCreateRequest creates the ListOperations request.
func (client *CertificateRegistrationProviderClient) listOperationsCreateRequest(ctx context.Context, options *CertificateRegistrationProviderClientListOperationsOptions) (*policy.Request, error) {
urlPath := "/providers/Microsoft.CertificateRegistration/operations"
req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.host, urlPath))
if err != nil {
return nil, err
}
reqQP := req.Raw().URL.Query()
reqQP.Set("api-version", "2021-03-01")
req.Raw().URL.RawQuery = reqQP.Encode()
req.Raw().Header.Set("Accept", "application/json")
return req, nil
}
// listOperationsHandleResponse handles the ListOperations response.
func (client *CertificateRegistrationProviderClient) listOperationsHandleResponse(resp *http.Response) (CertificateRegistrationProviderClientListOperationsResponse, error) {
result := CertificateRegistrationProviderClientListOperationsResponse{RawResponse: resp}
if err := runtime.UnmarshalAsJSON(resp, &result.CsmOperationCollection); err != nil {
return CertificateRegistrationProviderClientListOperationsResponse{}, err
}
return result, nil
}<|fim▁end|> | |
<|file_name|>SomeInterface.java<|end_file_name|><|fim▁begin|><|fim▁hole|>package eas.com;
public interface SomeInterface {
String someMethod(String param1, String param2, String param3, String param4);
}<|fim▁end|> | |
<|file_name|>CircularLayout.py<|end_file_name|><|fim▁begin|># CircularLayout.py
# Copyright (C) 2009 Matthias Treder
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program 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 General Public License for more details.
#
# You should have received a copy of the GNU General Public License along
# with this program; if not, write to the Free Software Foundation, Inc.,
# 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
"""
Implements a circular layout. All elements are placed on
a circle with a given radius in pixels. The first element
is placed on the top. The next elements are placed in
clockwise fashion. <|fim▁hole|>if you do not want it to be placed on the top.
"""
import math
class CircularLayout(object):
def __init__(self, nr_elements=20, radius=200, start= - math.pi / 2):
self.positions = []
step = 2 * math.pi / nr_elements
for i in range(nr_elements):
phi = start + i * step
x = round (radius * math.cos(phi))
y = round (radius * math.sin(phi))
self.positions.append((x, y))<|fim▁end|> |
Provide the number of elements (nr_elements) and the radius
(radius) when creating an intance of this layout. You can
also provide the angular position of the first element (start) |
<|file_name|>trader.py<|end_file_name|><|fim▁begin|><|fim▁hole|># -*- coding: utf-8 -*-
import os
import time
import yaml
import logging
import threading
from ybk.lighttrade.sysframe import Client as SysframeClient
log = logging.getLogger('trader')
configfile = open(os.path.join(os.path.dirname(__file__), 'trading.yaml'), encoding='utf-8')
config = yaml.load(configfile)
try:
accountfile = open(
os.path.join(os.path.dirname(__file__), 'accounts.yaml'))
account = yaml.load(accountfile)
except:
account = {}
lock = threading.RLock()
class Trader(object):
""" 交易调度 """
traders = {}
def __init__(self, exchange, username=None, password=None):
""" 登陆并缓存Trader Object """
with lock:
d = config[exchange]
if d['system'] == 'sysframe':
Client = SysframeClient
elif d['system'] == 'winner':
raise NotImplementedError
if username is None:
u = account[exchange][0]
username = u['username']
password = u['password']
if d.get('disabled'):
raise ValueError('该交易所被禁止')
signature = (exchange, username, password)
if signature not in self.traders:
if not isinstance(d['tradeweb_url'], list):
d['tradeweb_url'] = [d['tradeweb_url']]
self.client = Client(front_url=d['front_url'],
tradeweb_url=d['tradeweb_url'])
setattr(self.client, 'exchange', exchange)
self.client.login(username, password)
self.traders[signature] = self
else:
old = self.traders[signature]
self.client = old.client
self.client.keep_alive()
def __getattr__(self, key):
if key in self.__dict__:
return self.__dict__[key]
else:
return getattr(self.client, key)
@property
def server_time(self):
t0 = time.time()
return t0 + self.client.time_offset + self.client.latency * 3
if __name__ == '__main__':
pass<|fim▁end|> | #!/usr/bin/env python |
<|file_name|>i18n.py<|end_file_name|><|fim▁begin|>import re
from django.template import Node, Variable, VariableNode
from django.template import TemplateSyntaxError, TokenParser, Library
from django.template import TOKEN_TEXT, TOKEN_VAR
from django.template.base import _render_value_in_context
from django.utils import translation
from django.utils.encoding import force_unicode
from django.template.defaulttags import token_kwargs
register = Library()
class GetAvailableLanguagesNode(Node):
def __init__(self, variable):
self.variable = variable
def render(self, context):
from django.conf import settings
context[self.variable] = [(k, translation.ugettext(v)) for k, v in settings.LANGUAGES]
return ''
class GetLanguageInfoNode(Node):
def __init__(self, lang_code, variable):
self.lang_code = Variable(lang_code)
self.variable = variable
def render(self, context):
lang_code = self.lang_code.resolve(context)
context[self.variable] = translation.get_language_info(lang_code)
return ''
class GetLanguageInfoListNode(Node):
def __init__(self, languages, variable):
self.languages = Variable(languages)
self.variable = variable
def get_language_info(self, language):
# ``language`` is either a language code string or a sequence
# with the language code as its first item
if len(language[0]) > 1:
return translation.get_language_info(language[0])
else:
return translation.get_language_info(str(language))
def render(self, context):
langs = self.languages.resolve(context)
context[self.variable] = [self.get_language_info(lang) for lang in langs]
return ''
class GetCurrentLanguageNode(Node):
def __init__(self, variable):
self.variable = variable
def render(self, context):
context[self.variable] = translation.get_language()
return ''
class GetCurrentLanguageBidiNode(Node):
def __init__(self, variable):
self.variable = variable
def render(self, context):
context[self.variable] = translation.get_language_bidi()
return ''
class TranslateNode(Node):
def __init__(self, filter_expression, noop):
self.noop = noop
self.filter_expression = filter_expression
if isinstance(self.filter_expression.var, basestring):
self.filter_expression.var = Variable(u"'%s'" % self.filter_expression.var)
def render(self, context):
self.filter_expression.var.translate = not self.noop
output = self.filter_expression.resolve(context)
return _render_value_in_context(output, context)
class BlockTranslateNode(Node):
def __init__(self, extra_context, singular, plural=None, countervar=None,
counter=None):
self.extra_context = extra_context
self.singular = singular
self.plural = plural
self.countervar = countervar
self.counter = counter
def render_token_list(self, tokens):
result = []
vars = []
for token in tokens:
if token.token_type == TOKEN_TEXT:
result.append(token.contents)
elif token.token_type == TOKEN_VAR:
result.append(u'%%(%s)s' % token.contents)
vars.append(token.contents)
return ''.join(result), vars
def render(self, context):
tmp_context = {}
for var, val in self.extra_context.items():
tmp_context[var] = val.resolve(context)
# Update() works like a push(), so corresponding context.pop() is at
# the end of function
context.update(tmp_context)
singular, vars = self.render_token_list(self.singular)
if self.plural and self.countervar and self.counter:
count = self.counter.resolve(context)
context[self.countervar] = count
plural, plural_vars = self.render_token_list(self.plural)
result = translation.ungettext(singular, plural, count)
vars.extend(plural_vars)
else:
result = translation.ugettext(singular)
# Escape all isolated '%' before substituting in the context.
result = re.sub(u'%(?!\()', u'%%', result)
data = dict([(v, _render_value_in_context(context[v], context)) for v in vars])
context.pop()
return result % data
def do_get_available_languages(parser, token):
"""
This will store a list of available languages
in the context.
Usage::
{% get_available_languages as languages %}
{% for language in languages %}
...
{% endfor %}
This will just pull the LANGUAGES setting from
your setting file (or the default settings) and
put it into the named variable.
"""
args = token.contents.split()
if len(args) != 3 or args[1] != 'as':
raise TemplateSyntaxError("'get_available_languages' requires 'as variable' (got %r)" % args)
return GetAvailableLanguagesNode(args[2])
def do_get_language_info(parser, token):
"""
This will store the language information dictionary for the given language
code in a context variable.
Usage::
{% get_language_info for LANGUAGE_CODE as l %}
{{ l.code }}
{{ l.name }}
{{ l.name_local }}
{{ l.bidi|yesno:"bi-directional,uni-directional" }}
"""
args = token.contents.split()
if len(args) != 5 or args[1] != 'for' or args[3] != 'as':
raise TemplateSyntaxError("'%s' requires 'for string as variable' (got %r)" % (args[0], args[1:]))
return GetLanguageInfoNode(args[2], args[4])
def do_get_language_info_list(parser, token):
"""
This will store a list of language information dictionaries for the given
language codes in a context variable. The language codes can be specified
either as a list of strings or a settings.LANGUAGES style tuple (or any
sequence of sequences whose first items are language codes).
Usage::
{% get_language_info_list for LANGUAGES as langs %}
{% for l in langs %}
{{ l.code }}
{{ l.name }}
{{ l.name_local }}
{{ l.bidi|yesno:"bi-directional,uni-directional" }}
{% endfor %}
"""
args = token.contents.split()
if len(args) != 5 or args[1] != 'for' or args[3] != 'as':
raise TemplateSyntaxError("'%s' requires 'for sequence as variable' (got %r)" % (args[0], args[1:]))
return GetLanguageInfoListNode(args[2], args[4])
def language_name(lang_code):
return translation.get_language_info(lang_code)['name']
def language_name_local(lang_code):
return translation.get_language_info(lang_code)['name_local']
def language_bidi(lang_code):
return translation.get_language_info(lang_code)['bidi']
def do_get_current_language(parser, token):
"""
This will store the current language in the context.
Usage::
{% get_current_language as language %}
This will fetch the currently active language and
put it's value into the ``language`` context
variable.
"""
args = token.contents.split()
if len(args) != 3 or args[1] != 'as':
raise TemplateSyntaxError("'get_current_language' requires 'as variable' (got %r)" % args)
return GetCurrentLanguageNode(args[2])
def do_get_current_language_bidi(parser, token):
"""
This will store the current language layout in the context.
Usage::
{% get_current_language_bidi as bidi %}
This will fetch the currently active language's layout and
put it's value into the ``bidi`` context variable.
True indicates right-to-left layout, otherwise left-to-right
"""
args = token.contents.split()
if len(args) != 3 or args[1] != 'as':
raise TemplateSyntaxError("'get_current_language_bidi' requires 'as variable' (got %r)" % args)
return GetCurrentLanguageBidiNode(args[2])
def do_translate(parser, token):
"""
This will mark a string for translation and will
translate the string for the current language.
Usage::
{% trans "this is a test" %}
This will mark the string for translation so it will
be pulled out by mark-messages.py into the .po files
and will run the string through the translation engine.
There is a second form::
{% trans "this is a test" noop %}
This will only mark for translation, but will return
the string unchanged. Use it when you need to store
values into forms that should be translated later on.
You can use variables instead of constant strings
to translate stuff you marked somewhere else::
{% trans variable %}
This will just try to translate the contents of
the variable ``variable``. Make sure that the string
in there is something that is in the .po file.
"""
class TranslateParser(TokenParser):
def top(self):
value = self.value()
# Backwards Compatiblity fix:
# FilterExpression does not support single-quoted strings,
# so we make a cheap localized fix in order to maintain
# backwards compatibility with existing uses of ``trans``
# where single quote use is supported.
if value[0] == "'":
pos = None
m = re.match("^'([^']+)'(\|.*$)",value)
if m:
value = '"%s"%s' % (m.group(1).replace('"','\\"'),m.group(2))
elif value[-1] == "'":
value = '"%s"' % value[1:-1].replace('"','\\"')
if self.more():
if self.tag() == 'noop':
noop = True
else:
raise TemplateSyntaxError("only option for 'trans' is 'noop'")
else:
noop = False
return (value, noop)
value, noop = TranslateParser(token.contents).top()
return TranslateNode(parser.compile_filter(value), noop)
def do_block_translate(parser, token):
"""
This will translate a block of text with parameters.
Usage::
{% blocktrans with bar=foo|filter boo=baz|filter %}
This is {{ bar }} and {{ boo }}.
{% endblocktrans %}
Additionally, this supports pluralization::
{% blocktrans count count=var|length %}
There is {{ count }} object.
{% plural %}
There are {{ count }} objects.
{% endblocktrans %}
This is much like ngettext, only in template syntax.
The "var as value" legacy format is still supported::
{% blocktrans with foo|filter as bar and baz|filter as boo %}
{% blocktrans count var|length as count %}
"""
bits = token.split_contents()
options = {}
remaining_bits = bits[1:]
while remaining_bits:
option = remaining_bits.pop(0)<|fim▁hole|> if option in options:
raise TemplateSyntaxError('The %r option was specified more '
'than once.' % option)
if option == 'with':
value = token_kwargs(remaining_bits, parser, support_legacy=True)
if not value:
raise TemplateSyntaxError('"with" in %r tag needs at least '
'one keyword argument.' % bits[0])
elif option == 'count':
value = token_kwargs(remaining_bits, parser, support_legacy=True)
if len(value) != 1:
raise TemplateSyntaxError('"count" in %r tag expected exactly '
'one keyword argument.' % bits[0])
else:
raise TemplateSyntaxError('Unknown argument for %r tag: %r.' %
(bits[0], option))
options[option] = value
if 'count' in options:
countervar, counter = options['count'].items()[0]
else:
countervar, counter = None, None
extra_context = options.get('with', {})
singular = []
plural = []
while parser.tokens:
token = parser.next_token()
if token.token_type in (TOKEN_VAR, TOKEN_TEXT):
singular.append(token)
else:
break
if countervar and counter:
if token.contents.strip() != 'plural':
raise TemplateSyntaxError("'blocktrans' doesn't allow other block tags inside it")
while parser.tokens:
token = parser.next_token()
if token.token_type in (TOKEN_VAR, TOKEN_TEXT):
plural.append(token)
else:
break
if token.contents.strip() != 'endblocktrans':
raise TemplateSyntaxError("'blocktrans' doesn't allow other block tags (seen %r) inside it" % token.contents)
return BlockTranslateNode(extra_context, singular, plural, countervar,
counter)
register.tag('get_available_languages', do_get_available_languages)
register.tag('get_language_info', do_get_language_info)
register.tag('get_language_info_list', do_get_language_info_list)
register.tag('get_current_language', do_get_current_language)
register.tag('get_current_language_bidi', do_get_current_language_bidi)
register.tag('trans', do_translate)
register.tag('blocktrans', do_block_translate)
register.filter(language_name)
register.filter(language_name_local)
register.filter(language_bidi)<|fim▁end|> | |
<|file_name|>XAxis.tsx<|end_file_name|><|fim▁begin|>import { extent } from 'd3-array';
import { ScaleBand } from 'd3-scale';
import React, { FC } from 'react';
import { buildTicks } from '../utils/axis';
import { isOfType } from '../utils/isOfType';
import textWrap from '../utils/svgTextWrap';
import { defaultPadding } from './Bars/Bars';
import {
buildScale,
defaultPath,
defaultTickFormat,
ELabelOrientation,
IAxis,
TAxisValue,
} from './YAxis';
const positionTick = (value: TAxisValue, scale: any, i: number, inverse: boolean = false, width = 10) => {
const offset = isOfType<ScaleBand<any>>(scale, 'paddingInner')
? scale.bandwidth() / 2
: 0;
let v = isOfType<ScaleBand<any>>(scale, 'paddingInner')
? Number(scale(String(i))) + offset
: scale(value);
if (inverse) {
v = width - v;
}
return `(${v}, 0)`
}
const XAxis: FC<IAxis> = ({
labelFormat,
values = [],
tickSize = 2,
width,
height,
path,
top = 0,
left = 0,
scale = 'band',<|fim▁hole|> inverse = false,
}) => {
if (scale === 'linear' && values.length > 0 && typeof values[0] === 'string') {
throw new Error('Linear axis can not accept string values');
}
if (scale === 'band' && !padding) {
console.warn('band scale provided without padding settings');
}
const Scale = buildScale({
domain,
length: width,
padding,
values,
scale,
range: [0, width],
});
const transform = `${left}, ${top}`;
const pathD = `M0,0 L${width},0`;
const axisPath = { ...defaultPath, ...(path ?? {}) };
const { fill, opacity, stroke, strokeOpacity, strokeWidth } = axisPath;
const d = Scale.domain() as [number, number];
const ticks = buildTicks(scale, values, d);
return (
<g className="x-axis"
transform={`translate(${transform})`}
fill="none"
fontSize="10"
fontFamily="sans-serif"
textAnchor="middle">
<path className="domain"
stroke={stroke}
d={pathD}
fill={fill}
opacity={opacity}
shapeRendering="auto"
strokeOpacity={strokeOpacity}
strokeWidth={strokeWidth}
></path>
{
ticks.map((v, i) => {
const tickOffset = positionTick(v, Scale, i, inverse, width);
const label = scale === 'band' ? String(values[i]) : String(v);
const thisFormat = typeof tickFormat === 'function' ? tickFormat(label, i) : tickFormat;
const tickLabel = labelFormat ? labelFormat('x', label, i) : label
const textArray: string[] = textWrap(tickLabel, height, { 'font-size': thisFormat.fontSize });
return (
<g
aria-hidden={scale !== 'band'}
role={scale === 'band' ? 'row' : ''}
key={`x-axis-${v}.${label}.${i}`}
className="tick"
opacity="1"
textAnchor="middle"
transform={`translate${tickOffset}`}>
<line stroke={stroke}
x1={0}
y2={`${tickSize}`}
fill="none"
opacity={opacity}
shapeRendering="auto"
strokeOpacity="1"
strokeWidth="1">
</line>
{ textArray.map((txt, j) => {
const dx = textArray.length === 1 ? 0 : (textArray.length / 2 * 20) - (20 * j) - 10;
const dy = textArray.length === 1 ? 20 : (20 * j) + 20;
return <g key={j}>
<text
role={scale === 'band' ? 'columnheader' : ''}
fill={thisFormat.stroke}
fontSize={thisFormat.fontSize}
textAnchor={labelOrientation === ELabelOrientation.HORIZONTAL ? 'middle' : 'start'}
writingMode={labelOrientation === ELabelOrientation.HORIZONTAL ? 'horizontal-tb' : 'vertical-lr'}
height={height}
dy={labelOrientation === ELabelOrientation.HORIZONTAL ? dy : '20'}
dx={labelOrientation === ELabelOrientation.HORIZONTAL ? '0' : dx}>
{txt}
</text>
</g>
})}
</g>
)
})
}
</g>
)
}
export default XAxis;<|fim▁end|> | domain,
padding = defaultPadding,
tickFormat = defaultTickFormat,
labelOrientation = ELabelOrientation.HORIZONTAL, |
<|file_name|>markstress.py<|end_file_name|><|fim▁begin|>### This program intends to combine same GSHF in citation tree, and sort them according to the first letter of title;
### Author: Ye Gao
### Date: 2017-11-7
import csv
file = open('NodeCheckList.csv', 'rb')
reader = csv.reader(file)
NodeCheckList = list(reader)
file.close()
#print NodeCheckList
FirstRow = NodeCheckList.pop(0)
FirstRow[8] = 'Frequency'
# convert cited time from string to integer;
for element in NodeCheckList:<|fim▁hole|>SortYear = sorted(NodeCheckList, key=lambda l:l[3], reverse=True)
SortCiteTimes = sorted(NodeCheckList, key=lambda l:l[2], reverse=True)
print SortYear
NodeStressList = []
for element in NodeCheckList:
if (int(element[7]) == 0) or (int(element[7]) == 1) or (int(element[7]) == 2):
NodeStressList.append(element)
SortTitle = sorted(NodeStressList, key=lambda l:l[4], reverse=False)
SortTitle = [FirstRow] + SortTitle
title = ""
CombineTitle = []
for element in SortTitle:
if element[4] != title:
CombineTitle.append(element)
else:
CombineTitle[-1][1] += '|' + element[1]
title = element[4]
# save result list to NodeStressList.csv;
file = open('NodeStressList.csv','wb')
for i in CombineTitle:
for j in i:
file.write(str(j))
file.write(',')
file.write('\n')
file.close()<|fim▁end|> | if element[2] != "":
element[2] = int(element[2])
|
<|file_name|>file.go<|end_file_name|><|fim▁begin|>// Copyright 2013 Beego Authors
// Copyright 2014 The Macaron Authors
//
// Licensed under the Apache License, Version 2.0 (the "License"): you may
// not use this file except in compliance with the License. You may obtain
// a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
// WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
// License for the specific language governing permissions and limitations
// under the License.
package cache
import (
"crypto/md5"
"encoding/hex"
"fmt"
"io/ioutil"
"log"
"os"
"path/filepath"
"sync"
"time"
"github.com/Unknwon/com"
"gopkg.in/macaron.v1"
)
// Item represents a cache item.
type Item struct {
Val interface{}
Created int64
Expire int64
}
func (item *Item) hasExpired() bool {
return item.Expire > 0 &&
(time.Now().Unix()-item.Created) >= item.Expire
}
// FileCacher represents a file cache adapter implementation.
type FileCacher struct {
lock sync.Mutex
rootPath string
interval int // GC interval.
}
// NewFileCacher creates and returns a new file cacher.
func NewFileCacher() *FileCacher {
return &FileCacher{}
}
func (c *FileCacher) filepath(key string) string {
m := md5.Sum([]byte(key))
hash := hex.EncodeToString(m[:])
return filepath.Join(c.rootPath, string(hash[0]), string(hash[1]), hash)
}
// Put puts value into cache with key and expire time.
// If expired is 0, it will not be deleted by GC.
func (c *FileCacher) Put(key string, val interface{}, expire int64) error {
filename := c.filepath(key)
item := &Item{val, time.Now().Unix(), expire}
data, err := EncodeGob(item)
if err != nil {
return err
}
os.MkdirAll(filepath.Dir(filename), os.ModePerm)
return ioutil.WriteFile(filename, data, os.ModePerm)
}
func (c *FileCacher) read(key string) (*Item, error) {
filename := c.filepath(key)
data, err := ioutil.ReadFile(filename)
if err != nil {
return nil, err
}
item := new(Item)
return item, DecodeGob(data, item)
}
// Get gets cached value by given key.
func (c *FileCacher) Get(key string) interface{} {
item, err := c.read(key)
if err != nil {
return nil
}
if item.hasExpired() {
os.Remove(c.filepath(key))
return nil
}
return item.Val
}
// Delete deletes cached value by given key.
func (c *FileCacher) Delete(key string) error {
return os.Remove(c.filepath(key))
}
// Incr increases cached int-type value by given key as a counter.
func (c *FileCacher) Incr(key string) error {<|fim▁hole|> if err != nil {
return err
}
item.Val, err = Incr(item.Val)
if err != nil {
return err
}
return c.Put(key, item.Val, item.Expire)
}
// Decrease cached int value.
func (c *FileCacher) Decr(key string) error {
item, err := c.read(key)
if err != nil {
return err
}
item.Val, err = Decr(item.Val)
if err != nil {
return err
}
return c.Put(key, item.Val, item.Expire)
}
// IsExist returns true if cached value exists.
func (c *FileCacher) IsExist(key string) bool {
return com.IsExist(c.filepath(key))
}
// Flush deletes all cached data.
func (c *FileCacher) Flush() error {
return os.RemoveAll(c.rootPath)
}
func (c *FileCacher) startGC() {
c.lock.Lock()
defer c.lock.Unlock()
if c.interval < 1 {
return
}
if err := filepath.Walk(c.rootPath, func(path string, fi os.FileInfo, err error) error {
if err != nil {
return fmt.Errorf("Walk: %v", err)
}
if fi.IsDir() {
return nil
}
data, err := ioutil.ReadFile(path)
if err != nil && !os.IsNotExist(err) {
fmt.Errorf("ReadFile: %v", err)
}
item := new(Item)
if err = DecodeGob(data, item); err != nil {
return err
}
if item.hasExpired() {
if err = os.Remove(path); err != nil && !os.IsNotExist(err) {
return fmt.Errorf("Remove: %v", err)
}
}
return nil
}); err != nil {
log.Printf("error garbage collecting cache files: %v", err)
}
time.AfterFunc(time.Duration(c.interval)*time.Second, func() { c.startGC() })
}
// StartAndGC starts GC routine based on config string settings.
func (c *FileCacher) StartAndGC(opt Options) error {
c.lock.Lock()
c.rootPath = opt.AdapterConfig
c.interval = opt.Interval
if !filepath.IsAbs(c.rootPath) {
c.rootPath = filepath.Join(macaron.Root, c.rootPath)
}
c.lock.Unlock()
if err := os.MkdirAll(c.rootPath, os.ModePerm); err != nil {
return err
}
go c.startGC()
return nil
}
func init() {
Register("file", NewFileCacher())
}<|fim▁end|> | item, err := c.read(key) |
<|file_name|>list.module.ts<|end_file_name|><|fim▁begin|>// (C) Copyright 2015 Martin Dougiamas
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
import { NgModule } from '@angular/core';
import { IonicPageModule } from 'ionic-angular';
import { TranslateModule } from '@ngx-translate/core';
import { CoreDirectivesModule } from '@directives/directives.module';
import { AddonNotesListPage } from './list';
import { AddonNotesComponentsModule } from '../../components/components.module';
@NgModule({
declarations: [
AddonNotesListPage
],
imports: [
CoreDirectivesModule,<|fim▁hole|> IonicPageModule.forChild(AddonNotesListPage),
TranslateModule.forChild()
]
})
export class AddonNotesListPageModule {}<|fim▁end|> | AddonNotesComponentsModule, |
<|file_name|>fixed_bug_11.rs<|end_file_name|><|fim▁begin|>/*!
* # Expected behaviour:
* The top cube will fall asleep while the bottom cube goes right at constant speed.
*
* # Symptoms:
* Bothe cube fall asleep at some point.
*
* # Cause:
* There was no way of customizing the deactivation threshold.
*
* # Solution:
* Rigid bodies now have a `set_deactivation_threshold` method to set the threshold to a
* user-defined value, or to prevent completely any deactivation (by setting None as the
* threshold).
*
* # Limitations of the solution:
*/
extern crate nalgebra as na;
extern crate ncollide;
extern crate nphysics;
extern crate nphysics_testbed2d;
use na::{Vec2, Translation};
use ncollide::shape::Cuboid;<|fim▁hole|>use nphysics::object::RigidBody;
use nphysics_testbed2d::Testbed;
fn main() {
/*
* World
*/
let mut world = World::new();
world.set_gravity(Vec2::new(0.0, 0.0));
/*
* Create the box that will be deactivated.
*/
let rad = 1.0;
let geom = Cuboid::new(Vec2::new(rad, rad));
let mut rb = RigidBody::new_dynamic(geom, 1.0, 0.3, 0.5);
rb.set_lin_vel(Vec2::new(0.99, 0.0));
world.add_body(rb.clone());
/*
* Create the box that will not be deactivated.
*/
rb.set_deactivation_threshold(Some(0.5));
rb.append_translation(&Vec2::new(0.0, 3.0));
world.add_body(rb);
/*
* Set up the testbed.
*/
let mut testbed = Testbed::new(world);
testbed.run();
}<|fim▁end|> | use nphysics::world::World; |
<|file_name|>env.go<|end_file_name|><|fim▁begin|>package app
import (
"os"
"strings"
)
type Environment struct {
Env string
Port string
}
func (this *App) defaultEnv() Environment {
return Environment{
Env: "development",
Port: "5000",<|fim▁hole|>}
func envMap() map[string]string {
environ := os.Environ()
env := make(map[string]string)
for _, v := range environ {
pair := strings.SplitN(v, "=", 2)
env[pair[0]] = pair[1]
}
return env
}<|fim▁end|> | } |
<|file_name|>subscription_log.py<|end_file_name|><|fim▁begin|><|fim▁hole|> _name = 'saas_portal.subscription_log'
_order = 'id desc'
client_id = fields.Many2one('saas_portal.client', 'Client')
expiration = fields.Datetime('Previous expiration')
expiration_new = fields.Datetime('New expiration')
reason = fields.Text('Reason')<|fim▁end|> | from odoo import fields, models
class SaasSubscriptionLog(models.Model): |
<|file_name|>interest.py<|end_file_name|><|fim▁begin|>import os.path, sys
sys.path.append(os.path.join(os.path.dirname(os.path.realpath(__file__)), os.pardir))
import json
import falcon
import urllib
import uuid
import settings
import requests
from geopy.geocoders import Nominatim
import geopy.distance
from geopy.distance import vincenty
import datetime
radius = []
radius_maps = []
#geoJSON template to create radius (polygon) on geojson.io
geoJSON_template = {
"type": "FeatureCollection",
"features": [
{
"type": "Feature",
"properties": {},
"geometry": {
"type": "Polygon",
"coordinates": [
]
}
}
]
}
class interest(object):
global radius
interested = {}
#radius = []i
def proximity_to_others(self, my_coordinates):
if radius:
for x in radius:
radius_center = (x['center'][0],x['center'][1])
my_coordinates = (my_coordinates[0], my_coordinates[1])
distance = vincenty(radius_center, my_coordinates).kilometers
print("Proximity distance")
print(distance)
return distance, x["center"]
else:
return 0, []
def geojson_io_prox(self, resp, my_coordinates, user_name):
global radius
distance = 0
radius = []
try:
distance,radius = self.proximity_to_others(my_coordinates)
except Exception as e:
print(e)
if not distance or distance < 1:
points = []<|fim▁hole|> points.append(d.destination(point=start, bearing=x))
print("\n\n POINTS")
print("\n\n")
radius_dict = {
'center': my_coordinates,
'radius': points,
'people': [user_name,],
'created_date': datetime.datetime.utcnow().strftime("%a %b %d %H:%M:%S %Z %Y")
}
radius.append(radius_dict)
print("\n\n RADIUS: ")
print(radius)
print("\n\n")
else:
for x in radius:
if x["center"] == radius:
x['people'].append(
{'name': user_name,
'coordinates':
my_coordinates}
)
def proximity(self,req, resp, my_coordinates, user_name):
# Works out user/client proximity to mytransport API stops
# Works on a radius of 1km. Assumption on average walk time
global radius_maps
google_map_url = "http://www.google.com/maps/place/"
query_params = {"point":"{},{}".format(my_coordinates[0], my_coordinates[1]),
"radius":"1000"}
endpoint ="api/stops"
headers = {"Authorization": "Bearer {}".format(settings.ACCESS_TOKEN)}
request = requests.get("{}/{}".format(settings.API_URL,endpoint),
params=query_params,
headers=headers)
print("Response from api/stops")
print(request.status_code)
response_data = request.json()
print(type(response_data))
if not response_data:
resp.status = falcon.HTTP_200
your_radius_map = ""
for x in radius_maps:
if x["center"] == my_coordinates:
your_radius_map = x["geoJSON_url"]
messge_dict = {'message' :
"No stops in your area, adding you to interest area", "maps": your_radius_map}
resp.body = json.dumps(messge_dict)
return False
else:
map_list = []
message_dict = {"message":"", "maps":[]}
for x in response_data:
print(x)
if 'geometry' in x:
coordinates = x["geometry"]["coordinates"]
map_list.append("{}{},{}".format(google_map_url,
coordinates[1],
coordinates[0]))
message_dict["maps"] = map_list
if message_dict:
message_dict["message"] = """You have existing stops within 1km
of your location"""
else:
message_dict["messsage"] = """You\shave no existing stops nearby,
we will combine your interest in a stop with others in the area"""
resp.body = json.dumps(message_dict)
resp.status = falcon.HTTP_200
return True
#return True
def geopy_coordinates(self, address,resp):
try:
geolocator = Nominatim()
location = geolocator.geocode(address)
if location.latitude and location.longitude:
return [location.latitude, location.longitude]
except Exception as e:
print(e)
resp.body = """{'message':'Bad address,
try being more specific and try agai'}"""
resp.status = falcon.HTTP_400
def on_get(self, req, resp):
resp_dict = {"message":"Post request needed with GeoLocation data"}
resp.body = json.dumps(resp_dict)
resp.status = falcon.HTTP_200
def on_post(self, req, resp):
# Main API method, post the following
'''
POST Request
data type: JSON
Required: name, address or coordinates
data format : {
"name" : "Yourname",
"address" : "Your number and street address, province, etc"
"geometry" : { "coordinates" : ["x", "y"] }
'''
global radius_maps
global radius
print(req.headers)
user_name = ""
post_data = json.load(req.stream)
print(post_data)
if "name" in post_data:
user_name = post_data["name"]
print("Username IF statement")
print(user_name)
if "geometry" in post_data:
if not self.proximity(req,resp, post_data["geometry"]["coordinates"],user_name):
self.geojson_io_prox(resp, post_data["geometry"]["coordinates"],user_name)
elif post_data["address"]:
if "address" in post_data:
my_coordinates = self.geopy_coordinates(post_data["address"],resp)
print("BASED ON ADDRESS")
proximity = self.proximity(req, resp, my_coordinates, user_name)
print("PROXIMITY")
print(proximity)
if proximity == False:
print("NO routes")
self.geojson_io_prox(resp,my_coordinates, user_name)
else:
falcon.HTTPMissingParam
resp_dict = { 'message' :
'Please supply a address or coordinates (long,lat)'}
# json.dumps allows proper formating of message
resp.body = json.dumps(resp_dict)
print("Current Radius")
print(radius)
radius_list = []
radius_maps = []
for x in radius:
for y in x['radius']:
radius_list.append([y[1],y[0]])
radius_list.append([x['radius'][0][1],x['radius'][0][0]])
geoJSON_template['features'][0]['geometry']['coordinates'].append(radius_list)
radius_maps.append( {
'center': x['center'],
'geoJSON': geoJSON_template,
'geoJSON_url' : "http://geojson.io/#map=5/{}/{}&data=data:application/json,{}".format(
x['center'][1], x['center'][0], urllib.quote(json.dumps(geoJSON_template).encode()) )
}
)
#resp.body
print(radius_maps)<|fim▁end|> | start = geopy.Point(my_coordinates[0], my_coordinates[1])
d = geopy.distance.VincentyDistance(kilometers = 1)
for x in range(0,360, 10): |
<|file_name|>find_median.py<|end_file_name|><|fim▁begin|>'''
Find the median element in an unsorted array
'''<|fim▁hole|>import heapq
def find_median(arr):
# O(n)
heapq.heapify(arr)
num_elements = len(arr)
if num_elements % 2 != 0:
return arr[(num_elements + 1)/2 - 1]
else:
return (arr[num_elements/2 - 1] + arr[num_elements/2 + 1 - 1])/2.0
assert find_median([1, -1, 2, 3, 4]) == 2
assert find_median([1, -1, 2, 3, 4, 5]) == 2.5<|fim▁end|> | |
<|file_name|>models.py<|end_file_name|><|fim▁begin|>from django.db import models
# Create your models here.<|fim▁hole|> ('Pertama', 'Perekayasa Pertama'),
('Muda', 'Perekayasa Muda'),
('Madya', 'Perekayasa Madya'),
('Utama', 'Perekayasa Utama'),
)
nip = models.CharField(max_length=50, verbose_name='NIP')
pendidikan = models.CharField(max_length=150, verbose_name='Pendidikan')
instansi = models.TextField(verbose_name='Nama Lengkap Unit')
instansi_kode = models.CharField(max_length=20, verbose_name='Singkatan Unit')
satuan = models.TextField(verbose_name='Nama Lengkap Satuan kerja', blank=True)
kantor = models.TextField(verbose_name='Nama Lengkap Kantor', blank=True)
pangkat = models.TextField(verbose_name='Pangkat/Golongan Ruang/TMT')
jabatan = models.CharField(max_length=150, verbose_name='Jabatan')
jenjang = models.CharField(max_length=10, verbose_name='Jenjang Perekayasa', choices=PILIHAN_JENJANG, default=awal)
user = models.ForeignKey('auth.User', verbose_name='Personil', on_delete=models.CASCADE)
class Meta:
verbose_name_plural = 'Profil'
def __str__(self):
return self.nip<|fim▁end|> | class Profil(models.Model):
awal = ''
PILIHAN_JENJANG = (
(awal, '----'), |
<|file_name|>syslog_json.py<|end_file_name|><|fim▁begin|># (c) 2017 Ansible Project
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
# Make coding more python3-ish
from __future__ import (absolute_import, division, print_function)
__metaclass__ = type
DOCUMENTATION = '''
callback: syslog_json
callback_type: notification
requirements:
- whitelist in configuration
short_description: sends JSON events to syslog
version_added: "1.9"
description:
- This plugin logs ansible-playbook and ansible runs to a syslog server in JSON format
- Before 2.9 only environment variables were available for configuration
options:
server:
description: syslog server that will receive the event
env:
- name: SYSLOG_SERVER
default: localhost
ini:
- section: callback_syslog_json
key: syslog_server
port:
description: port on which the syslog server is listening
env:
- name: SYSLOG_PORT
default: 514
ini:
- section: callback_syslog_json
key: syslog_port
facility:
description: syslog facility to log as
env:
- name: SYSLOG_FACILITY
default: user
ini:
- section: callback_syslog_json
key: syslog_facility
'''
import os<|fim▁hole|>import json
import logging
import logging.handlers
import socket
from ansible.plugins.callback import CallbackBase
class CallbackModule(CallbackBase):
"""
logs ansible-playbook and ansible runs to a syslog server in json format
"""
CALLBACK_VERSION = 2.0
CALLBACK_TYPE = 'aggregate'
CALLBACK_NAME = 'syslog_json'
CALLBACK_NEEDS_WHITELIST = True
def __init__(self):
super(CallbackModule, self).__init__()
self.set_options()
syslog_host = self.get_option("server")
syslog_port = int(self.get_option("port"))
syslog_facility = self.get_option("facility")
self.logger = logging.getLogger('ansible logger')
self.logger.setLevel(logging.DEBUG)
self.handler = logging.handlers.SysLogHandler(
address=(syslog_host, syslog_port),
facility=syslog_facility
)
self.logger.addHandler(self.handler)
self.hostname = socket.gethostname()
def runner_on_failed(self, host, res, ignore_errors=False):
self.logger.error('%s ansible-command: task execution FAILED; host: %s; message: %s', self.hostname, host, self._dump_results(res))
def runner_on_ok(self, host, res):
self.logger.info('%s ansible-command: task execution OK; host: %s; message: %s', self.hostname, host, self._dump_results(res))
def runner_on_skipped(self, host, item=None):
self.logger.info('%s ansible-command: task execution SKIPPED; host: %s; message: %s', self.hostname, host, 'skipped')
def runner_on_unreachable(self, host, res):
self.logger.error('%s ansible-command: task execution UNREACHABLE; host: %s; message: %s', self.hostname, host, self._dump_results(res))
def runner_on_async_failed(self, host, res, jid):
self.logger.error('%s ansible-command: task execution FAILED; host: %s; message: %s', self.hostname, host, self._dump_results(res))
def playbook_on_import_for_host(self, host, imported_file):
self.logger.info('%s ansible-command: playbook IMPORTED; host: %s; message: imported file %s', self.hostname, host, imported_file)
def playbook_on_not_import_for_host(self, host, missing_file):
self.logger.info('%s ansible-command: playbook NOT IMPORTED; host: %s; message: missing file %s', self.hostname, host, missing_file)<|fim▁end|> | |
<|file_name|>widgets.py<|end_file_name|><|fim▁begin|>from decimal import Decimal
from django import forms
from django.template.loader import render_to_string
from django.template.defaultfilters import slugify
class BaseWidget(forms.TextInput):
"""
Base widget. Do not use this directly.
"""
template = None
instance = None
def get_parent_id(self, name, attrs):
final_attrs = self.build_attrs(attrs, type=self.input_type, name=name)
return final_attrs['id']
def get_widget_id(self, prefix, name, key=''):
if self.instance:
opts = self.instance._meta
widget_id = '%s-%s-%s_%s-%s' % (prefix, name, opts.app_label, opts.module_name, self.instance.pk)
else:
widget_id = '%s-%s' % (prefix, name)<|fim▁hole|> widget_id = '%s_%s' % (widget_id, slugify(key))
return widget_id
def get_values(self, min_value, max_value, step=1):
decimal_step = Decimal(str(step))
value = Decimal(str(min_value))
while value <= max_value:
yield value
value += decimal_step
class SliderWidget(BaseWidget):
"""
Slider widget.
In order to use this widget you must load the jQuery.ui slider
javascript.
This widget triggers the following javascript events:
- *slider_change* with the vote value as argument
(fired when the user changes his vote)
- *slider_delete* without arguments
(fired when the user deletes his vote)
It's easy to bind these events using jQuery, e.g.::
$(document).bind('slider_change', function(event, value) {
alert('New vote: ' + value);
});
"""
def __init__(self, min_value, max_value, step, instance=None,
can_delete_vote=True, key='', read_only=False, default='',
template='ratings/slider_widget.html', attrs=None):
"""
The argument *default* is used when the initial value is None.
"""
super(SliderWidget, self).__init__(attrs)
self.min_value = min_value
self.max_value = max_value
self.step = step
self.instance = instance
self.can_delete_vote = can_delete_vote
self.read_only = read_only
self.default = default
self.template = template
self.key = key
def get_context(self, name, value, attrs=None):
# here we convert *min_value*, *max_value*, *step* and *value*
# to string to avoid odd behaviours of Django localization
# in the template (and, for backward compatibility we do not
# want to use the *unlocalize* filter)
attrs['type'] = 'hidden'
return {
'min_value': str(self.min_value),
'max_value': str(self.max_value),
'step': str(self.step),
'can_delete_vote': self.can_delete_vote,
'read_only': self.read_only,
'default': self.default,
'parent': super(SliderWidget, self).render(name, value, attrs),
'parent_id': self.get_parent_id(name, attrs),
'value': str(value),
'has_value': bool(value),
'slider_id': self.get_widget_id('slider', name, self.key),
'label_id': 'slider-label-%s' % name,
'remove_id': 'slider-remove-%s' % name,
}
def render(self, name, value, attrs=None):
context = self.get_context(name, value, attrs or {})
return render_to_string(self.template, context)
class StarWidget(BaseWidget):
"""
Starrating widget.
In order to use this widget you must download the
jQuery Star Rating Plugin available at
http://www.fyneworks.com/jquery/star-rating/#tab-Download
and then load the required javascripts and css, e.g.::
<link href="/path/to/jquery.rating.css" rel="stylesheet" type="text/css" />
<script type="text/javascript" src="/path/to/jquery.MetaData.js"></script>
<script type="text/javascript" src="/path/to/jquery.rating.js"></script>
This widget triggers the following javascript events:
- *star_change* with the vote value as argument
(fired when the user changes his vote)
- *star_delete* without arguments
(fired when the user deletes his vote)
It's easy to bind these events using jQuery, e.g.::
$(document).bind('star_change', function(event, value) {
alert('New vote: ' + value);
});
"""
def __init__(self, min_value, max_value, step, instance=None,
can_delete_vote=True, key='', read_only=False,
template='ratings/star_widget.html', attrs=None):
super(StarWidget, self).__init__(attrs)
self.min_value = min_value
self.max_value = max_value
self.step = step
self.instance = instance
self.can_delete_vote = can_delete_vote
self.read_only = read_only
self.template = template
self.key = key
def get_context(self, name, value, attrs=None):
# here we convert *min_value*, *max_value* and *step*
# to string to avoid odd behaviours of Django localization
# in the template (and, for backward compatibility we do not
# want to use the *unlocalize* filter)
attrs['type'] = 'hidden'
split_value = int(1 / self.step)
if split_value == 1:
values = range(1, self.max_value+1)
split = u''
else:
values = self.get_values(self.min_value, self.max_value, self.step)
split = u' {split:%d}' % split_value
return {
'min_value': str(self.min_value),
'max_value': str(self.max_value),
'step': str(self.step),
'can_delete_vote': self.can_delete_vote,
'read_only': self.read_only,
'values': values,
'split': split,
'parent': super(StarWidget, self).render(name, value, attrs),
'parent_id': self.get_parent_id(name, attrs),
'value': self._get_value(value, split_value),
'star_id': self.get_widget_id('star', name, self.key),
}
def _get_value(self, original, split):
if original:
value = round(original * split) / split
return Decimal(str(value))
def render(self, name, value, attrs=None):
context = self.get_context(name, value, attrs or {})
return render_to_string(self.template, context)
class LikeWidget(BaseWidget):
def __init__(self, min_value, max_value, instance=None,
can_delete_vote=True, template='ratings/like_widget.html', attrs=None):
super(LikeWidget, self).__init__(attrs)
self.min_value = min_value
self.max_value = max_value
self.instance = instance
self.can_delete_vote = can_delete_vote
self.template = template
def get_context(self, name, value, attrs=None):
# here we convert *min_value*, *max_value* and *step*
# to string to avoid odd behaviours of Django localization
# in the template (and, for backward compatibility we do not
# want to use the *unlocalize* filter)
attrs['type'] = 'hidden'
return {
'min_value': str(self.min_value),
'max_value': str(self.max_value),
'can_delete_vote': self.can_delete_vote,
'parent': super(LikeWidget, self).render(name, value, attrs),
'parent_id': self.get_parent_id(name, attrs),
'value': str(value),
'like_id': self.get_widget_id('like', name),
}
def render(self, name, value, attrs=None):
context = self.get_context(name, value, attrs or {})
return render_to_string(self.template, context)<|fim▁end|> | if key: |
<|file_name|>index.js<|end_file_name|><|fim▁begin|>'use strict';
const { messages, ruleName } = require('..');
testRule({
ruleName,
config: [
{
border: 2,
'/^margin/': 1,
},
],
accept: [
{
code: 'a { margin: 0; }',
},
{
code: 'a { margin: 1px; }',
},
{
code: 'a { margin: var(--foo); }',
description: 'deals with CSS variables',
},
{
code: 'a { margin: 1px /* 3px */; }',
description: 'ignore values in comments',
},
{
code: 'a { margin-inline: 1px; }',
},
{
code: 'a { margin: ; }',
},
{
code: 'a { border: 1px; }',
},
{
code: 'a { border: 1px solid; }',
},
{
code: 'a { transition: margin-right 2s ease-in-out; }',
description: 'irrelevant shorthand',
},
],
reject: [
{
code: 'a { margin: 1px 2px; }',
message: messages.rejected('margin', 1),
line: 1,
column: 5,
},
{<|fim▁hole|> code: 'a { margin-inline: 1px 2px; }',
message: messages.rejected('margin-inline', 1),
line: 1,
column: 5,
},
{
code: 'a { margin: var(--foo) var(--bar); }',
message: messages.rejected('margin', 1),
line: 1,
column: 5,
description: 'deals with CSS variables',
},
{
code: 'a { margin: 1px 2px 3px 4px; }',
message: messages.rejected('margin', 1),
line: 1,
column: 5,
},
{
code: 'a { margin: 0 0 0 0; }',
message: messages.rejected('margin', 1),
line: 1,
column: 5,
},
{
code: 'a { border: 1px solid blue; }',
message: messages.rejected('border', 2),
line: 1,
column: 5,
},
],
});<|fim▁end|> | |
<|file_name|>unwind.rs<|end_file_name|><|fim▁begin|>// taken from https://github.com/thepowersgang/rust-barebones-kernel
<|fim▁hole|> // 'args' will print to the formatted string passed to panic!
log!("file='{}', line={} :: {}", file, line, args);
loop {}
}
#[lang="stack_exhausted"]
#[no_mangle]
pub extern "C" fn __morestack() -> ! {
loop {}
}
#[allow(non_camel_case_types)]
#[repr(C)]
#[derive(Clone,Copy)]
pub enum _Unwind_Reason_Code {
_URC_NO_REASON = 0,
_URC_FOREIGN_EXCEPTION_CAUGHT = 1,
_URC_FATAL_PHASE2_ERROR = 2,
_URC_FATAL_PHASE1_ERROR = 3,
_URC_NORMAL_STOP = 4,
_URC_END_OF_STACK = 5,
_URC_HANDLER_FOUND = 6,
_URC_INSTALL_CONTEXT = 7,
_URC_CONTINUE_UNWIND = 8,
}
#[allow(non_camel_case_types)]
#[derive(Clone,Copy)]
pub struct _Unwind_Context;
#[allow(non_camel_case_types)]
pub type _Unwind_Action = u32;
static _UA_SEARCH_PHASE: _Unwind_Action = 1;
#[allow(non_camel_case_types)]
#[repr(C)]
#[derive(Clone,Copy)]
#[allow(raw_pointer_derive)]
pub struct _Unwind_Exception {
exception_class: u64,
exception_cleanup: fn(_Unwind_Reason_Code, *const _Unwind_Exception),
private: [u64; 2],
}
#[lang="eh_personality"]
#[no_mangle]
pub extern "C" fn rust_eh_personality(_version: isize,
_actions: _Unwind_Action,
_exception_class: u64,
_exception_object: &_Unwind_Exception,
_context: &_Unwind_Context)
-> _Unwind_Reason_Code {
loop {}
}
#[no_mangle]
#[allow(non_snake_case)]
pub extern "C" fn _Unwind_Resume() {
loop {}
}<|fim▁end|> | #[lang="panic_fmt"]
#[no_mangle]
pub extern "C" fn rust_begin_unwind(args: ::core::fmt::Arguments, file: &str, line: usize) -> ! { |
<|file_name|>test_annotation.py<|end_file_name|><|fim▁begin|># Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY<|fim▁hole|># specific language governing permissions and limitations
# under the License.
"""Unit tests for annotations."""
import tvm
from tvm import relay
import pytest
def test_on_device_via_string():
x = relay.Var("x")
call = relay.annotation.on_device(x, "cuda")
assert isinstance(call, relay.Call)
assert len(call.args) == 1
assert call.args[0] == x
assert call.attrs.virtual_device.device_type_int == 2 # ie kDLCUDA
assert call.attrs.virtual_device.virtual_device_id == 0
assert call.attrs.virtual_device.target is None
assert call.attrs.virtual_device.memory_scope == ""
assert call.attrs.constrain_body
assert not call.attrs.constrain_result
def test_on_device_via_device():
x = relay.Var("x")
call = relay.annotation.on_device(x, tvm.device("cpu"))
assert call.attrs.virtual_device.device_type_int == 1 # ie kDLCPU
def test_on_device_invalid_device():
x = relay.Var("x")
pytest.raises(ValueError, lambda: relay.annotation.on_device(x, "bogus"))
def test_on_device_fixed():
x = relay.Var("x")
call = relay.annotation.on_device(x, "cuda", constrain_result=True)
assert call.attrs.virtual_device.device_type_int == 2 # ie kDLCUDA
assert call.attrs.constrain_body
assert call.attrs.constrain_result
def test_on_device_free():
x = relay.Var("x")
call = relay.annotation.on_device(x, "cuda", constrain_result=False, constrain_body=False)
assert call.attrs.virtual_device.device_type_int == -1 # ie kInvalidDeviceType
assert not call.attrs.constrain_body
assert not call.attrs.constrain_result
def test_function_on_device():
x = relay.Var("x")
y = relay.Var("y")
f = relay.Function([x, y], relay.add(x, y))
func = relay.annotation.function_on_device(f, ["cpu", "cuda"], "cuda")
assert isinstance(func, relay.Function)
assert len(func.attrs["param_virtual_devices"]) == 2
assert func.attrs["param_virtual_devices"][0].device_type_int == 1 # ie kDLCPU
assert func.attrs["param_virtual_devices"][1].device_type_int == 2 # ie kDLCUDA
assert func.virtual_device_.device_type_int == 2 # ie KDLCUDA
if __name__ == "__main__":
import sys
sys.exit(pytest.main([__file__] + sys.argv[1:]))<|fim▁end|> | # KIND, either express or implied. See the License for the |
<|file_name|>test_example_app.py<|end_file_name|><|fim▁begin|>import tornado.testing
from testexample import ExampleApp
class TestExampleApp(tornado.testing.AsyncHTTPTestCase,
tornado.testing.LogTrapTestCase):
def get_app(self):
return ExampleApp()
def test_home(self):
response = self.fetch('/')
self.assertEqual(response.code, 200)
<|fim▁hole|> response = self.fetch('/ticker')
self.assertEqual(response.code, 200)<|fim▁end|> | def test_ticker(self): |
<|file_name|>twitch.d.ts<|end_file_name|><|fim▁begin|>declare module "twitch" {
export interface Links {
next?: string;
self: string;
last?: string;
channel?: string;
}
export interface FollowsResponse {
_links: Links;
_total: number;
follows: Follow[];
}
export interface Follow {
created_at: string;
_links: Links;
notifications: boolean;
channel: Channel;
}
export interface Channel {
mature: boolean,
status: string,
broadcaster_language: string,
<|fim▁hole|> _id: number;
name: string,
created_at:string,
updated_at: string,
logo: string,
banner: string,
video_banner: string,
background: string,
profile_banner: string,
profile_banner_background_color: string,
partner: true,
url: string,
views: number;
followers: number;
}
export interface StreamsResponse {
_links: Links;
_total: number;
streams: Stream[];
}
export interface Stream {
_links: Links;
game: string,
viewers: number,
average_fps: number,
delay: number,
video_height: number,
is_playlist: boolean,
created_at: string,
_id: number,
channel: Channel;
preview: StreamPreviews;
}
export interface StreamPreviews {
small: string,
medium: string,
large: string,
templat: string,
}
}<|fim▁end|> | display_name: string,
game: string,
delay: number;
language: string,
|
<|file_name|>__init__.py<|end_file_name|><|fim▁begin|>from .fetch import FetchParser
from .json_ld import JsonLdParser
from .lom import LomParser
from .lrmi import LrmiParser<|fim▁hole|>from .nsdl_dc import NsdlDcParser
__all__ = [
'FetchParser',
'JsonLdParser',
'LomParser',
'LrmiParser',
'NsdlDcParser',
]<|fim▁end|> | |
<|file_name|>test_educollections.py<|end_file_name|><|fim▁begin|>from educollections import ArrayList
def print_list_state(lst):
print('Size is', lst.size())
print('Contents are', lst)<|fim▁hole|>print('Capacity is', arr.capacity())
print_list_state(arr)
for i in range(10):
print('Prepend', i)
arr.prepend(i)
print_list_state(arr)
for i in range(10):
print('Item at index', i, 'is', arr.get(i))
print_list_state(arr)
for i in range(10):
print('Assign index', i, 'with', 10 - i)
arr.set(i, 10 - i)
print_list_state(arr)
arr.clear()
print_list_state(arr)
for i in range(10):
print('Append', i)
arr.append(i)
print_list_state(arr)
for i in [9, 4, 1, 6, 3, 0, 0, 0, 1, 0]:
item = arr.remove(i);
print('Removed', item, 'from index', i)
print_list_state(arr)
arr.clear()
print_list_state(arr)
for i in range(5):
print('Append', i)
arr.append(i)
print_list_state(arr)
for i in [2, 3, 0, 7, 8]:
print('Insert', i + 10, 'at index', i)
arr.insert(i, i + 10)
print_list_state(arr)<|fim▁end|> | print()
arr = ArrayList(10) |
<|file_name|>PasswordValidator.js<|end_file_name|><|fim▁begin|>define(
({
nomatchMessage: "Lozinke se ne podudaraju.",
badPasswordMessage: "Neispravna lozinka."<|fim▁hole|>})
);<|fim▁end|> | |
<|file_name|>base_renderer.py<|end_file_name|><|fim▁begin|>"""
Copyright (c) 2013 Timon Wong
Permission is hereby granted, free of charge, to any person obtaining a copy of
this software and associated documentation files (the "Software"), to deal in
the Software without restriction, including without limitation the rights to
use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
of the Software, and to permit persons to whom the Software is furnished to do
so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
"""
from __future__ import print_function
import locale
import os
import subprocess
import sys
import tempfile
PY3K = sys.version_info >= (3, 0, 0)
class MarkupRenderer(object):
def __init__(self):
self.renderer_options = {}
def load_settings(self, global_setting, renderer_options):
self.renderer_options = renderer_options
@classmethod
def is_enabled(cls, filename, syntax):
return False
def render(self, text, **kwargs):
raise NotImplementedError()
class InputMethod(object):
STDIN = 1
TEMPFILE = 2
FILE = 3
class CommandlineRenderer(MarkupRenderer):
def __init__(self, input_method=InputMethod.STDIN, executable=None, args=[]):
super(CommandlineRenderer, self).__init__()
self.input_method = input_method
self.executable = executable
self.args = args
def pre_process_encoding(self, text, **kwargs):
return text.encode('utf-8')
def pre_process(self, text, **kwargs):
return text
def post_process(self, rendered_text, **kwargs):
return rendered_text
def post_process_encoding(self, rendered_text, **kwargs):
return rendered_text.decode('utf-8')
def render(self, text, **kwargs):
text = self.pre_process_encoding(text, **kwargs)
text = self.pre_process(text, **kwargs)
text = self.executable_check(text, kwargs['filename'])
text = self.post_process_encoding(text, **kwargs)
return self.post_process(text, **kwargs)
def executable_check(self, text, filename):
tempfile_ = None
result = ''
try:
args = [self.get_executable()]
if self.input_method == InputMethod.STDIN:
args.extend(self.get_args())
elif self.input_method == InputMethod.TEMPFILE:
_, ext = os.path.splitext(filename)
tempfile_ = tempfile.NamedTemporaryFile(suffix=ext)
tempfile_.write(text)
tempfile_.flush()
args.extend(self.get_args(filename=tempfile_.name()))
text = None
elif self.input_method == InputMethod.FILE:
args.extend(self.get_args(filename=filename))
text = None
else:
return u''
proc = subprocess.Popen(args, stdin=subprocess.PIPE,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
startupinfo=self.get_startupinfo())
result, errdata = proc.communicate(text)
if len(errdata) > 0:
print(errdata)
finally:
if tempfile_ is not None:
tempfile_.close() # Also delete file
return result.strip()
<|fim▁hole|> # [PY2K] On Windows, popen won't support unicode args
if isinstance(self.executable, unicode):
encoding = locale.getpreferredencoding()
return self.executable.encode(encoding)
return self.executable
def get_args(self, filename=None):
if not PY3K and os.name == 'nt':
# [PY2K] On Windows, popen won't support unicode args
encoding = locale.getpreferredencoding()
args = [arg if isinstance(arg, str) else arg.encode(encoding) for arg in self.args]
else:
args = self.args
return [arg.format(filename=filename) for arg in args]
def get_startupinfo(self):
if os.name != 'nt':
return None
info = subprocess.STARTUPINFO()
info.dwFlags |= subprocess.STARTF_USESHOWWINDOW
info.wShowWindow = subprocess.SW_HIDE
return info
def renderer(renderer_type):
renderer_type.IS_VALID_RENDERER__ = True
return renderer_type<|fim▁end|> | def get_executable(self):
if not PY3K and os.name == 'nt': |
<|file_name|>reader.rs<|end_file_name|><|fim▁begin|><|fim▁hole|><|fim▁end|> | extern crate webservices; |
<|file_name|>boss_lorekeeper_polkelt.cpp<|end_file_name|><|fim▁begin|>/*
* Copyright (C) 2010-2013 Project SkyFire <http://www.projectskyfire.org/>
* Copyright (C) 2010-2013 Oregon <http://www.oregoncore.com/>
* Copyright (C) 2006-2008 ScriptDev2 <https://scriptdev2.svn.sourceforge.net/>
* Copyright (C) 2008-2013 TrinityCore <http://www.trinitycore.org/>
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License as published by the
* Free Software Foundation; either version 2 of the License, or (at your
* option) any later version.
*
* This program 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 General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License along
* with this program. If not, see <http://www.gnu.org/licenses/>.
*/
/* ScriptData
SDName: Boss_Lorekeeper_Polkelt
SD%Complete: 100
SDComment:
SDCategory: Scholomance
EndScriptData */
#include "ScriptPCH.h"
#include "scholomance.h"
#define SPELL_VOLATILEINFECTION 24928
#define SPELL_DARKPLAGUE 18270
#define SPELL_CORROSIVEACID 23313
#define SPELL_NOXIOUSCATALYST 18151
struct boss_lorekeeperpolkeltAI : public ScriptedAI
{
boss_lorekeeperpolkeltAI(Creature *c) : ScriptedAI(c) {}
uint32 VolatileInfection_Timer;
uint32 Darkplague_Timer;
uint32 CorrosiveAcid_Timer;
uint32 NoxiousCatalyst_Timer;
void Reset()
{
VolatileInfection_Timer = 38000;
Darkplague_Timer = 8000;
CorrosiveAcid_Timer = 45000;
NoxiousCatalyst_Timer = 35000;
}
void JustDied(Unit * /*killer*/)
{
ScriptedInstance *instance = me->GetInstanceScript();
if (instance)
{
instance->SetData(DATA_LOREKEEPERPOLKELT_DEATH, 0);
if (instance->GetData(TYPE_GANDLING) == IN_PROGRESS)
me->SummonCreature(1853, 180.73f, -9.43856f, 75.507f, 1.61399f, TEMPSUMMON_DEAD_DESPAWN, 0);
}
}
void EnterCombat(Unit * /*who*/)
{
}
void UpdateAI(const uint32 diff)
{
if (!UpdateVictim())
return;
//VolatileInfection_Timer
if (VolatileInfection_Timer <= diff)
{
DoCast(me->getVictim(), SPELL_VOLATILEINFECTION);
VolatileInfection_Timer = 32000;
} else VolatileInfection_Timer -= diff;
//Darkplague_Timer
if (Darkplague_Timer <= diff)
{
DoCast(me->getVictim(), SPELL_DARKPLAGUE);
Darkplague_Timer = 8000;
} else Darkplague_Timer -= diff;
//CorrosiveAcid_Timer
if (CorrosiveAcid_Timer <= diff)
{
DoCast(me->getVictim(), SPELL_CORROSIVEACID);
CorrosiveAcid_Timer = 25000;
} else CorrosiveAcid_Timer -= diff;
//NoxiousCatalyst_Timer
if (NoxiousCatalyst_Timer <= diff)
{
DoCast(me->getVictim(), SPELL_NOXIOUSCATALYST);
NoxiousCatalyst_Timer = 38000;
} else NoxiousCatalyst_Timer -= diff;
DoMeleeAttackIfReady();
}<|fim▁hole|>}
void AddSC_boss_lorekeeperpolkelt()
{
Script *newscript;
newscript = new Script;
newscript->Name = "boss_lorekeeper_polkelt";
newscript->GetAI = &GetAI_boss_lorekeeperpolkelt;
newscript->RegisterSelf();
}<|fim▁end|> | };
CreatureAI* GetAI_boss_lorekeeperpolkelt(Creature* creature)
{
return new boss_lorekeeperpolkeltAI (creature); |
<|file_name|>mod.rs<|end_file_name|><|fim▁begin|>// Copyright 2012-2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
//! The code to do lexical region resolution.
use infer::region_constraints::Constraint;
use infer::region_constraints::GenericKind;
use infer::region_constraints::RegionConstraintData;
use infer::region_constraints::VarInfos;
use infer::region_constraints::VerifyBound;
use infer::RegionVariableOrigin;
use infer::SubregionOrigin;
use middle::free_region::RegionRelations;
use rustc_data_structures::fx::FxHashSet;
use rustc_data_structures::graph::implementation::{
Direction, Graph, NodeIndex, INCOMING, OUTGOING,
};
use rustc_data_structures::indexed_vec::{Idx, IndexVec};
use std::fmt;
use std::u32;
use ty::fold::TypeFoldable;
use ty::{self, Ty, TyCtxt};
use ty::{ReEarlyBound, ReEmpty, ReErased, ReFree, ReStatic};
use ty::{ReLateBound, ReScope, RePlaceholder, ReVar};
use ty::{Region, RegionVid};
mod graphviz;
/// This function performs lexical region resolution given a complete
/// set of constraints and variable origins. It performs a fixed-point
/// iteration to find region values which satisfy all constraints,
/// assuming such values can be found. It returns the final values of
/// all the variables as well as a set of errors that must be reported.
pub fn resolve<'tcx>(
region_rels: &RegionRelations<'_, '_, 'tcx>,
var_infos: VarInfos,
data: RegionConstraintData<'tcx>,
) -> (
LexicalRegionResolutions<'tcx>,
Vec<RegionResolutionError<'tcx>>,
) {
debug!("RegionConstraintData: resolve_regions()");
let mut errors = vec![];
let mut resolver = LexicalResolver {
region_rels,
var_infos,
data,
};
let values = resolver.infer_variable_values(&mut errors);
(values, errors)
}
/// Contains the result of lexical region resolution. Offers methods
/// to lookup up the final value of a region variable.
pub struct LexicalRegionResolutions<'tcx> {
values: IndexVec<RegionVid, VarValue<'tcx>>,
error_region: ty::Region<'tcx>,
}
#[derive(Copy, Clone, Debug)]
enum VarValue<'tcx> {
Value(Region<'tcx>),
ErrorValue,
}
#[derive(Clone, Debug)]
pub enum RegionResolutionError<'tcx> {
/// `ConcreteFailure(o, a, b)`:
///
/// `o` requires that `a <= b`, but this does not hold
ConcreteFailure(SubregionOrigin<'tcx>, Region<'tcx>, Region<'tcx>),
/// `GenericBoundFailure(p, s, a)
///
/// The parameter/associated-type `p` must be known to outlive the lifetime
/// `a` (but none of the known bounds are sufficient).
GenericBoundFailure(SubregionOrigin<'tcx>, GenericKind<'tcx>, Region<'tcx>),
/// `SubSupConflict(v, sub_origin, sub_r, sup_origin, sup_r)`:
///
/// Could not infer a value for `v` because `sub_r <= v` (due to
/// `sub_origin`) but `v <= sup_r` (due to `sup_origin`) and
/// `sub_r <= sup_r` does not hold.
SubSupConflict(
RegionVariableOrigin,
SubregionOrigin<'tcx>,
Region<'tcx>,
SubregionOrigin<'tcx>,
Region<'tcx>,
),
}
struct RegionAndOrigin<'tcx> {
region: Region<'tcx>,
origin: SubregionOrigin<'tcx>,
}
type RegionGraph<'tcx> = Graph<(), Constraint<'tcx>>;
struct LexicalResolver<'cx, 'gcx: 'tcx, 'tcx: 'cx> {
region_rels: &'cx RegionRelations<'cx, 'gcx, 'tcx>,
var_infos: VarInfos,
data: RegionConstraintData<'tcx>,
}
impl<'cx, 'gcx, 'tcx> LexicalResolver<'cx, 'gcx, 'tcx> {
fn tcx(&self) -> TyCtxt<'cx, 'gcx, 'tcx> {
self.region_rels.tcx
}
fn infer_variable_values(
&mut self,
errors: &mut Vec<RegionResolutionError<'tcx>>,
) -> LexicalRegionResolutions<'tcx> {
let mut var_data = self.construct_var_data(self.tcx());
// Dorky hack to cause `dump_constraints` to only get called
// if debug mode is enabled:
debug!(
"----() End constraint listing (context={:?}) {:?}---",
self.region_rels.context,
self.dump_constraints(self.region_rels)
);
graphviz::maybe_print_constraints_for(&self.data, self.region_rels);
let graph = self.construct_graph();
self.expand_givens(&graph);
self.expansion(&mut var_data);
self.collect_errors(&mut var_data, errors);
self.collect_var_errors(&var_data, &graph, errors);
var_data
}
fn num_vars(&self) -> usize {
self.var_infos.len()
}
/// Initially, the value for all variables is set to `'empty`, the
/// empty region. The `expansion` phase will grow this larger.
fn construct_var_data(&self, tcx: TyCtxt<'_, '_, 'tcx>) -> LexicalRegionResolutions<'tcx> {
LexicalRegionResolutions {
error_region: tcx.types.re_static,
values: IndexVec::from_elem_n(VarValue::Value(tcx.types.re_empty), self.num_vars())
}
}
fn dump_constraints(&self, free_regions: &RegionRelations<'_, '_, 'tcx>) {
debug!(
"----() Start constraint listing (context={:?}) ()----",
free_regions.context
);
for (idx, (constraint, _)) in self.data.constraints.iter().enumerate() {
debug!("Constraint {} => {:?}", idx, constraint);
}
}
fn expand_givens(&mut self, graph: &RegionGraph<'_>) {
// Givens are a kind of horrible hack to account for
// constraints like 'c <= '0 that are known to hold due to
// closure signatures (see the comment above on the `givens`
// field). They should go away. But until they do, the role
// of this fn is to account for the transitive nature:
//
// Given 'c <= '0
// and '0 <= '1
// then 'c <= '1
let seeds: Vec<_> = self.data.givens.iter().cloned().collect();
for (r, vid) in seeds {
// While all things transitively reachable in the graph
// from the variable (`'0` in the example above).
let seed_index = NodeIndex(vid.index() as usize);
for succ_index in graph.depth_traverse(seed_index, OUTGOING) {
let succ_index = succ_index.0;
// The first N nodes correspond to the region
// variables. Other nodes correspond to constant
// regions.
if succ_index < self.num_vars() {
let succ_vid = RegionVid::new(succ_index);
// Add `'c <= '1`.
self.data.givens.insert((r, succ_vid));
}
}
}
}
fn expansion(&self, var_values: &mut LexicalRegionResolutions<'tcx>) {
self.iterate_until_fixed_point("Expansion", |constraint, origin| {
debug!("expansion: constraint={:?} origin={:?}", constraint, origin);
match *constraint {
Constraint::RegSubVar(a_region, b_vid) => {
let b_data = var_values.value_mut(b_vid);
self.expand_node(a_region, b_vid, b_data)
}
Constraint::VarSubVar(a_vid, b_vid) => match *var_values.value(a_vid) {
VarValue::ErrorValue => false,
VarValue::Value(a_region) => {
let b_node = var_values.value_mut(b_vid);
self.expand_node(a_region, b_vid, b_node)
}
},
Constraint::RegSubReg(..) | Constraint::VarSubReg(..) => {
// These constraints are checked after expansion
// is done, in `collect_errors`.
false
}
}
})
}
fn expand_node(
&self,
a_region: Region<'tcx>,
b_vid: RegionVid,
b_data: &mut VarValue<'tcx>,
) -> bool {
debug!("expand_node({:?}, {:?} == {:?})", a_region, b_vid, b_data);
// Check if this relationship is implied by a given.
match *a_region {
ty::ReEarlyBound(_) | ty::ReFree(_) => if self.data.givens.contains(&(a_region, b_vid))
{
debug!("given");
return false;
},
_ => {}
}
match *b_data {
VarValue::Value(cur_region) => {
let lub = self.lub_concrete_regions(a_region, cur_region);
if lub == cur_region {
return false;
}
debug!(
"Expanding value of {:?} from {:?} to {:?}",
b_vid, cur_region, lub
);
*b_data = VarValue::Value(lub);
return true;
}
VarValue::ErrorValue => {
return false;
}
}
}
fn lub_concrete_regions(&self, a: Region<'tcx>, b: Region<'tcx>) -> Region<'tcx> {
let tcx = self.tcx();
match (a, b) {
(&ty::ReClosureBound(..), _)
| (_, &ty::ReClosureBound(..))
| (&ReLateBound(..), _)
| (_, &ReLateBound(..))
| (&ReErased, _)
| (_, &ReErased) => {
bug!("cannot relate region: LUB({:?}, {:?})", a, b);
}
(r @ &ReStatic, _) | (_, r @ &ReStatic) => {
r // nothing lives longer than static
}
(&ReEmpty, r) | (r, &ReEmpty) => {
r // everything lives longer than empty
}
(&ReVar(v_id), _) | (_, &ReVar(v_id)) => {
span_bug!(
self.var_infos[v_id].origin.span(),
"lub_concrete_regions invoked with non-concrete \
regions: {:?}, {:?}",
a,
b
);
}
(&ReEarlyBound(_), &ReScope(s_id))
| (&ReScope(s_id), &ReEarlyBound(_))
| (&ReFree(_), &ReScope(s_id))
| (&ReScope(s_id), &ReFree(_)) => {
// A "free" region can be interpreted as "some region
// at least as big as fr.scope". So, we can
// reasonably compare free regions and scopes:
let fr_scope = match (a, b) {
(&ReEarlyBound(ref br), _) | (_, &ReEarlyBound(ref br)) => self.region_rels
.region_scope_tree
.early_free_scope(self.tcx(), br),
(&ReFree(ref fr), _) | (_, &ReFree(ref fr)) => self.region_rels
.region_scope_tree
.free_scope(self.tcx(), fr),
_ => bug!(),
};
let r_id = self.region_rels
.region_scope_tree
.nearest_common_ancestor(fr_scope, s_id);
if r_id == fr_scope {
// if the free region's scope `fr.scope` is bigger than
// the scope region `s_id`, then the LUB is the free
// region itself:
match (a, b) {
(_, &ReScope(_)) => return a,
(&ReScope(_), _) => return b,
_ => bug!(),
}
}
// otherwise, we don't know what the free region is,
// so we must conservatively say the LUB is static:
tcx.types.re_static
}
(&ReScope(a_id), &ReScope(b_id)) => {
// The region corresponding to an outer block is a
// subtype of the region corresponding to an inner
// block.
let lub = self.region_rels
.region_scope_tree
.nearest_common_ancestor(a_id, b_id);
tcx.mk_region(ReScope(lub))
}
(&ReEarlyBound(_), &ReEarlyBound(_))
| (&ReFree(_), &ReEarlyBound(_))
| (&ReEarlyBound(_), &ReFree(_))
| (&ReFree(_), &ReFree(_)) => self.region_rels.lub_free_regions(a, b),
// For these types, we cannot define any additional
// relationship:
(&RePlaceholder(..), _) | (_, &RePlaceholder(..)) => if a == b {
a
} else {
tcx.types.re_static
},
}
}
/// After expansion is complete, go and check upper bounds (i.e.,
/// cases where the region cannot grow larger than a fixed point)
/// and check that they are satisfied.
fn collect_errors(
&self,
var_data: &mut LexicalRegionResolutions<'tcx>,
errors: &mut Vec<RegionResolutionError<'tcx>>,
) {
for (constraint, origin) in &self.data.constraints {
debug!(
"collect_errors: constraint={:?} origin={:?}",
constraint, origin
);
match *constraint {
Constraint::RegSubVar(..) | Constraint::VarSubVar(..) => {
// Expansion will ensure that these constraints hold. Ignore.
}
Constraint::RegSubReg(sub, sup) => {
if self.region_rels.is_subregion_of(sub, sup) {
continue;
}
debug!(
"collect_errors: region error at {:?}: \
cannot verify that {:?} <= {:?}",
origin, sub, sup
);
errors.push(RegionResolutionError::ConcreteFailure(
(*origin).clone(),
sub,
sup,
));
}
Constraint::VarSubReg(a_vid, b_region) => {
let a_data = var_data.value_mut(a_vid);
debug!("contraction: {:?} == {:?}, {:?}", a_vid, a_data, b_region);
let a_region = match *a_data {
VarValue::ErrorValue => continue,
VarValue::Value(a_region) => a_region,
};
// Do not report these errors immediately:
// instead, set the variable value to error and
// collect them later.
if !self.region_rels.is_subregion_of(a_region, b_region) {
debug!(
"collect_errors: region error at {:?}: \
cannot verify that {:?}={:?} <= {:?}",
origin, a_vid, a_region, b_region
);
*a_data = VarValue::ErrorValue;
}
}
}
}
for verify in &self.data.verifys {
debug!("collect_errors: verify={:?}", verify);
let sub = var_data.normalize(self.tcx(), verify.region);
// This was an inference variable which didn't get
// constrained, therefore it can be assume to hold.
if let ty::ReEmpty = *sub {
continue;
}
let verify_kind_ty = verify.kind.to_ty(self.tcx());
if self.bound_is_met(&verify.bound, var_data, verify_kind_ty, sub) {
continue;
}
debug!(
"collect_errors: region error at {:?}: \
cannot verify that {:?} <= {:?}",
verify.origin, verify.region, verify.bound
);
errors.push(RegionResolutionError::GenericBoundFailure(
verify.origin.clone(),
verify.kind.clone(),
sub,
));
}
}
/// Go over the variables that were declared to be error variables
/// and create a `RegionResolutionError` for each of them.
fn collect_var_errors(
&self,
var_data: &LexicalRegionResolutions<'tcx>,
graph: &RegionGraph<'tcx>,
errors: &mut Vec<RegionResolutionError<'tcx>>,
) {
debug!("collect_var_errors");
// This is the best way that I have found to suppress
// duplicate and related errors. Basically we keep a set of
// flags for every node. Whenever an error occurs, we will
// walk some portion of the graph looking to find pairs of
// conflicting regions to report to the user. As we walk, we
// trip the flags from false to true, and if we find that
// we've already reported an error involving any particular
// node we just stop and don't report the current error. The
// idea is to report errors that derive from independent
// regions of the graph, but not those that derive from
// overlapping locations.
let mut dup_vec = vec![u32::MAX; self.num_vars()];
for (node_vid, value) in var_data.values.iter_enumerated() {
match *value {
VarValue::Value(_) => { /* Inference successful */ }
VarValue::ErrorValue => {
/* Inference impossible, this value contains
inconsistent constraints.
I think that in this case we should report an
error now---unlike the case above, we can't
wait to see whether the user needs the result
of this variable. The reason is that the mere
existence of this variable implies that the
region graph is inconsistent, whether or not it
is used.
For example, we may have created a region
variable that is the GLB of two other regions
which do not have a GLB. Even if that variable
is not used, it implies that those two regions
*should* have a GLB.
At least I think this is true. It may be that
the mere existence of a conflict in a region variable
that is not used is not a problem, so if this rule
starts to create problems we'll have to revisit
this portion of the code and think hard about it. =) */
self.collect_error_for_expanding_node(graph, &mut dup_vec, node_vid, errors);
}
}
}
}
fn construct_graph(&self) -> RegionGraph<'tcx> {
let num_vars = self.num_vars();
let mut graph = Graph::new();
for _ in 0..num_vars {
graph.add_node(());
}
// Issue #30438: two distinct dummy nodes, one for incoming
// edges (dummy_source) and another for outgoing edges
// (dummy_sink). In `dummy -> a -> b -> dummy`, using one
// dummy node leads one to think (erroneously) there exists a
// path from `b` to `a`. Two dummy nodes sidesteps the issue.
let dummy_source = graph.add_node(());
let dummy_sink = graph.add_node(());
for (constraint, _) in &self.data.constraints {
match *constraint {
Constraint::VarSubVar(a_id, b_id) => {
graph.add_edge(
NodeIndex(a_id.index() as usize),
NodeIndex(b_id.index() as usize),
*constraint,
);
}
Constraint::RegSubVar(_, b_id) => {
graph.add_edge(dummy_source, NodeIndex(b_id.index() as usize), *constraint);
}
Constraint::VarSubReg(a_id, _) => {
graph.add_edge(NodeIndex(a_id.index() as usize), dummy_sink, *constraint);
}
Constraint::RegSubReg(..) => {
// this would be an edge from `dummy_source` to
// `dummy_sink`; just ignore it.
}
}
}
return graph;
}
fn collect_error_for_expanding_node(
&self,
graph: &RegionGraph<'tcx>,
dup_vec: &mut [u32],
node_idx: RegionVid,
errors: &mut Vec<RegionResolutionError<'tcx>>,
) {
// Errors in expanding nodes result from a lower-bound that is
// not contained by an upper-bound.
let (mut lower_bounds, lower_dup) =
self.collect_concrete_regions(graph, node_idx, INCOMING, dup_vec);
let (mut upper_bounds, upper_dup) =
self.collect_concrete_regions(graph, node_idx, OUTGOING, dup_vec);
if lower_dup || upper_dup {
return;
}
// We place free regions first because we are special casing
// SubSupConflict(ReFree, ReFree) when reporting error, and so
// the user will more likely get a specific suggestion.
fn region_order_key(x: &RegionAndOrigin<'_>) -> u8 {
match *x.region {
ReEarlyBound(_) => 0,
ReFree(_) => 1,
_ => 2,
}
}
lower_bounds.sort_by_key(region_order_key);
upper_bounds.sort_by_key(region_order_key);
for lower_bound in &lower_bounds {
for upper_bound in &upper_bounds {
if !self.region_rels
.is_subregion_of(lower_bound.region, upper_bound.region)
{
let origin = self.var_infos[node_idx].origin.clone();
debug!(
"region inference error at {:?} for {:?}: SubSupConflict sub: {:?} \
sup: {:?}",
origin, node_idx, lower_bound.region, upper_bound.region
);
errors.push(RegionResolutionError::SubSupConflict(
origin,
lower_bound.origin.clone(),
lower_bound.region,
upper_bound.origin.clone(),
upper_bound.region,
));<|fim▁hole|> }
}
span_bug!(
self.var_infos[node_idx].origin.span(),
"collect_error_for_expanding_node() could not find \
error for var {:?}, lower_bounds={:?}, \
upper_bounds={:?}",
node_idx,
lower_bounds,
upper_bounds
);
}
fn collect_concrete_regions(
&self,
graph: &RegionGraph<'tcx>,
orig_node_idx: RegionVid,
dir: Direction,
dup_vec: &mut [u32],
) -> (Vec<RegionAndOrigin<'tcx>>, bool) {
struct WalkState<'tcx> {
set: FxHashSet<RegionVid>,
stack: Vec<RegionVid>,
result: Vec<RegionAndOrigin<'tcx>>,
dup_found: bool,
}
let mut state = WalkState {
set: Default::default(),
stack: vec![orig_node_idx],
result: Vec::new(),
dup_found: false,
};
state.set.insert(orig_node_idx);
// to start off the process, walk the source node in the
// direction specified
process_edges(&self.data, &mut state, graph, orig_node_idx, dir);
while !state.stack.is_empty() {
let node_idx = state.stack.pop().unwrap();
// check whether we've visited this node on some previous walk
if dup_vec[node_idx.index() as usize] == u32::MAX {
dup_vec[node_idx.index() as usize] = orig_node_idx.index() as u32;
} else if dup_vec[node_idx.index() as usize] != orig_node_idx.index() as u32 {
state.dup_found = true;
}
debug!(
"collect_concrete_regions(orig_node_idx={:?}, node_idx={:?})",
orig_node_idx, node_idx
);
process_edges(&self.data, &mut state, graph, node_idx, dir);
}
let WalkState {
result, dup_found, ..
} = state;
return (result, dup_found);
fn process_edges<'tcx>(
this: &RegionConstraintData<'tcx>,
state: &mut WalkState<'tcx>,
graph: &RegionGraph<'tcx>,
source_vid: RegionVid,
dir: Direction,
) {
debug!("process_edges(source_vid={:?}, dir={:?})", source_vid, dir);
let source_node_index = NodeIndex(source_vid.index() as usize);
for (_, edge) in graph.adjacent_edges(source_node_index, dir) {
match edge.data {
Constraint::VarSubVar(from_vid, to_vid) => {
let opp_vid = if from_vid == source_vid {
to_vid
} else {
from_vid
};
if state.set.insert(opp_vid) {
state.stack.push(opp_vid);
}
}
Constraint::RegSubVar(region, _) | Constraint::VarSubReg(_, region) => {
state.result.push(RegionAndOrigin {
region,
origin: this.constraints.get(&edge.data).unwrap().clone(),
});
}
Constraint::RegSubReg(..) => panic!(
"cannot reach reg-sub-reg edge in region inference \
post-processing"
),
}
}
}
}
fn iterate_until_fixed_point<F>(&self, tag: &str, mut body: F)
where
F: FnMut(&Constraint<'tcx>, &SubregionOrigin<'tcx>) -> bool,
{
let mut iteration = 0;
let mut changed = true;
while changed {
changed = false;
iteration += 1;
debug!("---- {} Iteration {}{}", "#", tag, iteration);
for (constraint, origin) in &self.data.constraints {
let edge_changed = body(constraint, origin);
if edge_changed {
debug!("Updated due to constraint {:?}", constraint);
changed = true;
}
}
}
debug!("---- {} Complete after {} iteration(s)", tag, iteration);
}
fn bound_is_met(
&self,
bound: &VerifyBound<'tcx>,
var_values: &LexicalRegionResolutions<'tcx>,
generic_ty: Ty<'tcx>,
min: ty::Region<'tcx>,
) -> bool {
match bound {
VerifyBound::IfEq(k, b) => {
(var_values.normalize(self.region_rels.tcx, *k) == generic_ty)
&& self.bound_is_met(b, var_values, generic_ty, min)
}
VerifyBound::OutlivedBy(r) =>
self.region_rels.is_subregion_of(
min,
var_values.normalize(self.tcx(), r),
),
VerifyBound::AnyBound(bs) => bs.iter()
.any(|b| self.bound_is_met(b, var_values, generic_ty, min)),
VerifyBound::AllBounds(bs) => bs.iter()
.all(|b| self.bound_is_met(b, var_values, generic_ty, min)),
}
}
}
impl<'tcx> fmt::Debug for RegionAndOrigin<'tcx> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "RegionAndOrigin({:?},{:?})", self.region, self.origin)
}
}
impl<'tcx> LexicalRegionResolutions<'tcx> {
fn normalize<T>(&self, tcx: TyCtxt<'_, '_, 'tcx>, value: T) -> T
where
T: TypeFoldable<'tcx>,
{
tcx.fold_regions(&value, &mut false, |r, _db| match r {
ty::ReVar(rid) => self.resolve_var(*rid),
_ => r,
})
}
fn value(&self, rid: RegionVid) -> &VarValue<'tcx> {
&self.values[rid]
}
fn value_mut(&mut self, rid: RegionVid) -> &mut VarValue<'tcx> {
&mut self.values[rid]
}
pub fn resolve_var(&self, rid: RegionVid) -> ty::Region<'tcx> {
let result = match self.values[rid] {
VarValue::Value(r) => r,
VarValue::ErrorValue => self.error_region,
};
debug!("resolve_var({:?}) = {:?}", rid, result);
result
}
}<|fim▁end|> | return;
} |
<|file_name|>UserTest.java<|end_file_name|><|fim▁begin|><|fim▁hole|> public void testGetUserId() throws Exception {
}
public void testSetUserId() throws Exception {
}
public void testGetPassword() throws Exception {
}
public void testSetPassword() throws Exception {
}
}<|fim▁end|> | package org.craftercms.studio.api.dto;
public class UserTest { |
<|file_name|>cmd_server_suite_test.go<|end_file_name|><|fim▁begin|>package cmdserver_test
import (
"testing"
. "github.com/onsi/ginkgo"
. "github.com/onsi/gomega"
)<|fim▁hole|>func TestCmdServer(t *testing.T) {
RegisterFailHandler(Fail)
RunSpecs(t, "CmdServer Suite")
}<|fim▁end|> | |
<|file_name|>connectors_local.py<|end_file_name|><|fim▁begin|>import time
from threading import Thread
import threading
from wtfj_ids import *
from wtfj_utils import *
class Printer:
''' Opens a new output window and prints messages sent to it '''
def __init__(self,header=''):
self._header = header
def send(self,string):
print(self._header+string)
class Console:
''' Allows user to enter commands '''
def __init__(self,prompt='[$] '):
self._prompt = prompt
self._at = ''
def poll(self,wait_s=None,uid=None):
try:
prompt = str(self._at)+str(self._prompt)
msg = raw_input(prompt)
if msg == '':
self._at = ''
return []
if msg[0] == '@':
self._at = msg.split()[0]+' '
else:
msg = self._at+msg
return [msg]
except Exception as e:
print(repr(e))
return []
def subscribe(self,*uids):
pass
class Script:
''' Runs a script passed as a list, default frequency = 1000Hz '''
def __init__(self,msgs):
self._msgs = msgs
self._index = 0
self._period = 0.001
self._pid = 'SCRIPT'
def poll(self,wait_s=None,uid=None):
period = self._period if wait_s is None else wait_s
time.sleep(period)
try:
msg = self._msgs[self._index]
print(self._pid+' SEND > '+msg)
self._index += 1
return [msg]
except IndexError:
return []
def subscribe(self,*uids):
for uid in uids:
if uid is not None:
if uid[0] is '@': assert uid[1:] in get_attr(Uid)
else: assert uid in get_attr(Uid)
return self
def load(self,msg_array):
self._msgs += msg_array
return self
def set_period(self,period):
self._period = period
return self
def run(self):
t = threading.current_thread()
self._pid = str(t.ident)+' '+str(t.name)
while len(self.poll()) > 0: pass
def run_async(self):
Thread(target=self.run).start()
if __name__ == '__main__':
Printer('A simple printer: ').send('Just printing a msg to current_thread')<|fim▁hole|> script = [
'@other_uid topic data',
'@other_uid topic',
'uid topic data',
'uid topic'
]
async = ['async topic '+str(n) for n in [1,2,3,4,5,6,7,8,9,0]]
async2 = ['async2 topic '+str(n) for n in [1,2,3,4,5,6,7,8,9,0]]
Script(script).set_period(1).run()
Script(async).set_period(0.15).run_async()
Script(async2).set_period(0.2).run_async()<|fim▁end|> | |
<|file_name|>apns_sender.go<|end_file_name|><|fim▁begin|>package apns
import (
"errors"
"github.com/cosminrentea/gobbler/server/connector"
"github.com/jpillora/backoff"
"github.com/sideshow/apns2"
"net"
"time"
)
const (
// deviceIDKey is the key name set on the route params to identify the application
deviceIDKey = "device_token"
userIDKey = "user_id"
)
var (
errPusherInvalidParams = errors.New("Invalid parameters of APNS Pusher")
ErrRetryFailed = errors.New("Retry failed")
)
type sender struct {
client Pusher
appTopic string
}
<|fim▁hole|> logger.WithField("error", err.Error()).Error("APNS Pusher creation error")
return nil, err
}
return NewSenderUsingPusher(pusher, *config.AppTopic)
}
func NewSenderUsingPusher(pusher Pusher, appTopic string) (connector.Sender, error) {
if pusher == nil || appTopic == "" {
return nil, errPusherInvalidParams
}
return &sender{
client: pusher,
appTopic: appTopic,
}, nil
}
func (s sender) Send(request connector.Request) (interface{}, error) {
l := logger.WithField("correlation_id", request.Message().CorrelationID())
deviceToken := request.Subscriber().Route().Get(deviceIDKey)
l.WithField("deviceToken", deviceToken).Info("Trying to push a message to APNS")
push := func() (interface{}, error) {
return s.client.Push(&apns2.Notification{
Priority: apns2.PriorityHigh,
Topic: s.appTopic,
DeviceToken: deviceToken,
Payload: request.Message().Body,
})
}
withRetry := &retryable{
Backoff: backoff.Backoff{
Min: 1 * time.Second,
Max: 10 * time.Second,
Factor: 2,
Jitter: true,
},
maxTries: 3,
}
result, err := withRetry.execute(push)
if err != nil && err == ErrRetryFailed {
if closable, ok := s.client.(closable); ok {
l.Warn("Close TLS and retry again")
mTotalSendRetryCloseTLS.Add(1)
pSendRetryCloseTLS.Inc()
closable.CloseTLS()
return push()
} else {
mTotalSendRetryUnrecoverable.Add(1)
pSendRetryUnrecoverable.Inc()
l.Error("Cannot Close TLS. Unrecoverable state")
}
}
return result, err
}
type retryable struct {
backoff.Backoff
maxTries int
}
func (r *retryable) execute(op func() (interface{}, error)) (interface{}, error) {
tryCounter := 0
for {
tryCounter++
result, opError := op()
// retry on network errors
if _, ok := opError.(net.Error); ok {
mTotalSendNetworkErrors.Add(1)
pSendNetworkErrors.Inc()
if tryCounter >= r.maxTries {
return "", ErrRetryFailed
}
d := r.Duration()
logger.WithField("error", opError.Error()).Warn("Retry in ", d)
time.Sleep(d)
continue
} else {
return result, opError
}
}
}<|fim▁end|> | func NewSender(config Config) (connector.Sender, error) {
pusher, err := newPusher(config)
if err != nil { |
<|file_name|>0025_auto_20160616_1637.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*-
# Generated by Django 1.9.7 on 2016-06-16 16:37
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('pushkin', '0024_authparam_secret'),
]
operations = [
migrations.AlterField(<|fim▁hole|> name='arguments',
field=models.ManyToManyField(blank=True, null=True, to='pushkin.CommandArgument'),
),
]<|fim▁end|> | model_name='command', |
<|file_name|>webpack.config.js<|end_file_name|><|fim▁begin|><|fim▁hole|>
module.exports = {
entry: "./public/App.js",
output: {
filename: "bundle.js",
path: path.resolve(__dirname, "public")
}
};<|fim▁end|> | var path = require("path"); |
<|file_name|>Link.js<|end_file_name|><|fim▁begin|>'use strict';
exports.__esModule = true;
var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; };
var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; };
var _react = require('react');
var _react2 = _interopRequireDefault(_react);
var _Broadcasts = require('./Broadcasts');
var _PropTypes = require('./PropTypes');
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function _objectWithoutProperties(obj, keys) { var target = {}; for (var i in obj) { if (keys.indexOf(i) >= 0) continue; if (!Object.prototype.hasOwnProperty.call(obj, i)) continue; target[i] = obj[i]; } return target; }
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }
function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }
var Link = function (_React$Component) {
_inherits(Link, _React$Component);
function Link() {
var _temp, _this, _ret;
_classCallCheck(this, Link);
for (var _len = arguments.length, args = Array(_len), _key = 0; _key < _len; _key++) {
args[_key] = arguments[_key];
}
return _ret = (_temp = (_this = _possibleConstructorReturn(this, _React$Component.call.apply(_React$Component, [this].concat(args))), _this), _this.handleClick = function (event) {
if (_this.props.onClick) _this.props.onClick(event);
if (!event.defaultPrevented && // onClick prevented default
!_this.props.target && // let browser handle "target=_blank" etc.
!isModifiedEvent(event) && isLeftClickEvent(event)) {
event.preventDefault();
_this.handleTransition();
}
}, _this.handleTransition = function () {
var router = _this.context.router;
var _this$props = _this.props,
to = _this$props.to,
replace = _this$props.replace;
var navigate = replace ? router.replaceWith : router.transitionTo;
navigate(to);
}, _temp), _possibleConstructorReturn(_this, _ret);
}
Link.prototype.render = function render() {
var _this2 = this;
var router = this.context.router;
var _props = this.props,
to = _props.to,
style = _props.style,
activeStyle = _props.activeStyle,
className = _props.className,
activeClassName = _props.activeClassName,
getIsActive = _props.isActive,
activeOnlyWhenExact = _props.activeOnlyWhenExact,
replace = _props.replace,
children = _props.children,
rest = _objectWithoutProperties(_props, ['to', 'style', 'activeStyle', 'className', 'activeClassName', 'isActive', 'activeOnlyWhenExact', 'replace', 'children']);
return _react2.default.createElement(
_Broadcasts.LocationSubscriber,
null,
function (location) {
var isActive = getIsActive(location, createLocationDescriptor(to), _this2.props);
// If children is a function, we are using a Function as Children Component
// so useful values will be passed down to the children function.
if (typeof children == 'function') {
return children({
isActive: isActive,
location: location,
href: router ? router.createHref(to) : to,
onClick: _this2.handleClick,
transition: _this2.handleTransition
});
}
// Maybe we should use <Match> here? Not sure how the custom `isActive`
// prop would shake out, also, this check happens a LOT so maybe its good
// to optimize here w/ a faster isActive check, so we'd need to benchmark
// any attempt at changing to use <Match>
return _react2.default.createElement('a', _extends({}, rest, {
href: router ? router.createHref(to) : to,
onClick: _this2.handleClick,
style: isActive ? _extends({}, style, activeStyle) : style,
className: isActive ? [className, activeClassName].join(' ').trim() : className,
children: children
}));
}
);
};
return Link;
}(_react2.default.Component);
Link.defaultProps = {
replace: false,
activeOnlyWhenExact: false,
className: '',
activeClassName: '',
style: {},
activeStyle: {},
isActive: function isActive(location, to, props) {
return pathIsActive(to.pathname, location.pathname, props.activeOnlyWhenExact) && queryIsActive(to.query, location.query);
}
};
Link.contextTypes = {
router: _PropTypes.routerContext.isRequired
};
if (process.env.NODE_ENV !== 'production') {
Link.propTypes = {
to: _react.PropTypes.oneOfType([_react.PropTypes.string, _react.PropTypes.object]).isRequired,
replace: _react.PropTypes.bool,
activeStyle: _react.PropTypes.object,
activeClassName: _react.PropTypes.string,
activeOnlyWhenExact: _react.PropTypes.bool,
isActive: _react.PropTypes.func,
children: _react.PropTypes.oneOfType([_react.PropTypes.node, _react.PropTypes.func]),
// props we have to deal with but aren't necessarily
// part of the Link API
style: _react.PropTypes.object,
className: _react.PropTypes.string,
target: _react.PropTypes.string,
onClick: _react.PropTypes.func
};
}<|fim▁hole|>var createLocationDescriptor = function createLocationDescriptor(to) {
return (typeof to === 'undefined' ? 'undefined' : _typeof(to)) === 'object' ? to : { pathname: to };
};
var pathIsActive = function pathIsActive(to, pathname, activeOnlyWhenExact) {
return activeOnlyWhenExact ? pathname === to : pathname.indexOf(to) === 0;
};
var queryIsActive = function queryIsActive(query, activeQuery) {
if (activeQuery == null) return query == null;
if (query == null) return true;
return deepEqual(query, activeQuery);
};
var isLeftClickEvent = function isLeftClickEvent(event) {
return event.button === 0;
};
var isModifiedEvent = function isModifiedEvent(event) {
return !!(event.metaKey || event.altKey || event.ctrlKey || event.shiftKey);
};
var deepEqual = function deepEqual(a, b) {
if (a == b) return true;
if (a == null || b == null) return false;
if (Array.isArray(a)) {
return Array.isArray(b) && a.length === b.length && a.every(function (item, index) {
return deepEqual(item, b[index]);
});
}
if ((typeof a === 'undefined' ? 'undefined' : _typeof(a)) === 'object') {
for (var p in a) {
if (!Object.prototype.hasOwnProperty.call(a, p)) {
continue;
}
if (a[p] === undefined) {
if (b[p] !== undefined) {
return false;
}
} else if (!Object.prototype.hasOwnProperty.call(b, p)) {
return false;
} else if (!deepEqual(a[p], b[p])) {
return false;
}
}
return true;
}
return String(a) === String(b);
};
exports.default = Link;<|fim▁end|> |
// we should probably use LocationUtils.createLocationDescriptor |
<|file_name|>analyticsdata_v1beta_generated_beta_analytics_data_batch_run_pivot_reports_async.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*-
# Copyright 2022 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
# Generated code. DO NOT EDIT!
#
# Snippet for BatchRunPivotReports
# NOTE: This snippet has been automatically generated for illustrative purposes only.
# It may require modifications to work in your environment.
# To install the latest published package dependency, execute the following:
# python3 -m pip install google-analytics-data
# [START analyticsdata_v1beta_generated_BetaAnalyticsData_BatchRunPivotReports_async]
from google.analytics import data_v1beta
async def sample_batch_run_pivot_reports():
# Create a client
client = data_v1beta.BetaAnalyticsDataAsyncClient()
# Initialize request argument(s)
request = data_v1beta.BatchRunPivotReportsRequest(
)
# Make the request
response = await client.batch_run_pivot_reports(request=request)
# Handle the response<|fim▁hole|> print(response)
# [END analyticsdata_v1beta_generated_BetaAnalyticsData_BatchRunPivotReports_async]<|fim▁end|> | |
<|file_name|>tileinfo.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python
"""Print out a report about whats in a vectortile
Usage:
tileinfo.py [options] [SOURCE]
Options:
--srcformat=SRC_FORMAT Source file format: (tile | json)
--indent=INT|None JSON indentation level. Defaults to 4. Use 'None' to disable.
-h --help Show this screen.
--version Show version.
-q --quiet be quiet
"""
import json
import sys
from docopt import docopt
from vectortile import Tile
def info(data, cols):
"""
Compute min/max for all registered columns.
Parameters
----------
data : list
List of points from tile.
cols : list
List of columns from tile header.
Returns
-------
dict
{
column: {
min: value,
max: value
}
}
"""
stats = {c['name']: [] for c in cols}
for point in data:
for c, v in point.items():
stats[c].append(v)
return {n: {'min': min(v), 'max': max(v)} for n, v in stats.items()}
def main():
"""
Get an info report for a tile. Format is same as input tile but with
min/max values for values under 'data'.
"""
arguments = docopt(__doc__, version='tileinfo 0.1')
src_name = arguments['SOURCE']
src_format = arguments['--srcformat']
indent = arguments['--indent']
if isinstance(indent, str) and indent.lower() == 'none':
indent = None
elif isinstance(indent, str):
indent = int(indent)<|fim▁hole|>
# Guess input format if not given
if src_format is None:
if '.json' == f.name[-5:]:
src_format = 'json'
else:
src_format = 'tile'
if src_format == 'tile':
header, data = Tile(f.read()).unpack()
else:
header = json.loads(f.read())
data = header.pop('data')
# Generate the info report
report = info(data, header['cols'])
# Merge report with other tile attributes
out = {k: v for k, v in header.items() if k != 'data'}
out['data'] = {}
for field, vals in report.items():
out['data'][field + '_min'] = vals['min']
out['data'][field + '_max'] = vals['max']
print(json.dumps(out, indent=indent, sort_keys=True))
if __name__ == '__main__':
sys.exit(main())<|fim▁end|> | else:
indent = 4
with sys.stdin if src_name in ('-', None) else open(src_name, 'rb') as f: |
<|file_name|>views.py<|end_file_name|><|fim▁begin|>from rest_framework.decorators import api_view
from django.shortcuts import get_object_or_404
from rest_framework.response import Response
from rest_framework import status
from .models import Person
from .serializers import PersonSerializer
@api_view(['GET', 'DELETE', 'PUT'])
def get_delete_update_person(request, fstname):
person = get_object_or_404(Person, firstname=fstname)
# get details of a single person
if request.method == 'GET':
serializer = PersonSerializer(person)
return Response(serializer.data)
# delete a single person
elif request.method == 'DELETE':
person.delete()
return Response(status=status.HTTP_204_NO_CONTENT)<|fim▁hole|> # update details of a single person
elif request.method == 'PUT':
serializer = PersonSerializer(person, data=request.data)
if serializer.is_valid():
serializer.save()
return Response(serializer.data, status=status.HTTP_204_NO_CONTENT)
return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
@api_view(['GET', 'POST'])
def get_post_people(request):
# get all people
if request.method == 'GET':
people = Person.objects.all()
serializer = PersonSerializer(people, many=True)
return Response(serializer.data)
# insert a new record for a person
elif request.method == 'POST':
data = {
'firstname': request.data.get('firstname'),
'lastname': request.data.get('lastname'),
'country': request.data.get('country'),
'email': request.data.get('email'),
'phone': request.data.get('phone'),
'occupation_field': request.data.get('occupation_field'),
'occupation': request.data.get('occupation'),
'birthdate': request.data.get('birthdate'),
'description': request.data.get('description')
}
serializer = PersonSerializer(data=data)
if serializer.is_valid():
serializer.save()
return Response(serializer.data, status=status.HTTP_201_CREATED)
return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)<|fim▁end|> | |
<|file_name|>brief.js<|end_file_name|><|fim▁begin|>finApp.directive('brief', function () {<|fim▁hole|> controllerAs: 'bfc'
};
});<|fim▁end|> | return {
restrict: 'E',
templateUrl: 'views/directives/brief.html',
controller: 'BriefController', |
<|file_name|>091 image parent alpha.js<|end_file_name|><|fim▁begin|>var config = {
type: Phaser.WEBGL,
parent: 'phaser-example',
scene: {
preload: preload,
create: create
}
};
var game = new Phaser.Game(config);
function preload() {
<|fim▁hole|> this.load.image('bunny', 'assets/sprites/bunny.png');
}
function create() {
var parent = this.add.image(0, 0, 'bunny');
var child = this.add.image(100, 100, 'bunny');
parent.alpha = 0.5;
}<|fim▁end|> | |
<|file_name|>fetch.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python
# Copyright 2021 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
# This is generated, do not edit. Update BuildConfigGenerator.groovy and
# 3ppFetch.template instead.
from __future__ import print_function
import argparse
import json
import os
_FILE_URL = 'https://dl.google.com/dl/android/maven2/com/google/firebase/firebase-messaging/21.0.1/firebase-messaging-21.0.1.aar'
_FILE_NAME = 'firebase-messaging-21.0.1.aar'
_FILE_VERSION = '21.0.1'
def do_latest():
print(_FILE_VERSION)
def get_download_url(version):
if _FILE_URL.endswith('.jar'):
ext = '.jar'
elif _FILE_URL.endswith('.aar'):
ext = '.aar'
else:
raise Exception('Unsupported extension for %s' % _FILE_URL)
partial_manifest = {
'url': [_FILE_URL],
'name': [_FILE_NAME],
'ext': ext,
}
print(json.dumps(partial_manifest))
def main():
ap = argparse.ArgumentParser()
sub = ap.add_subparsers()<|fim▁hole|>
download = sub.add_parser("get_url")
download.set_defaults(
func=lambda _opts: get_download_url(os.environ['_3PP_VERSION']))
opts = ap.parse_args()
opts.func(opts)
if __name__ == '__main__':
main()<|fim▁end|> |
latest = sub.add_parser("latest")
latest.set_defaults(func=lambda _opts: do_latest()) |
<|file_name|>functions.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*-
# Pluma External Tools plugin
# Copyright (C) 2005-2006 Steve Frécinaux <[email protected]>
# Copyright (C) 2012-2021 MATE Developers
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program 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 General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
import os
from gi.repository import Gio, Gdk, Gtk, GtkSource, Pluma
from .outputpanel import OutputPanel
from .capture import *
def default(val, d):
if val is not None:
return val
else:
return d
def current_word(document):
piter = document.get_iter_at_mark(document.get_insert())
start = piter.copy()
if not piter.starts_word() and (piter.inside_word() or piter.ends_word()):
start.backward_word_start()
if not piter.ends_word() and piter.inside_word():
piter.forward_word_end()
return (start, piter)
# ==== Capture related functions ====
def run_external_tool(window, panel, node):
# Configure capture environment
try:
cwd = os.getcwd()
except OSError:
cwd = os.getenv('HOME');
capture = Capture(node.command, cwd)
capture.env = os.environ.copy()
capture.set_env(PLUMA_CWD = cwd)
view = window.get_active_view()
if view is not None:
# Environment vars relative to current document
document = view.get_buffer()
uri = document.get_uri()
# Current line number
piter = document.get_iter_at_mark(document.get_insert())
capture.set_env(PLUMA_CURRENT_LINE_NUMBER=str(piter.get_line() + 1))
# Current line text
piter.set_line_offset(0)
end = piter.copy()
if not end.ends_line():
end.forward_to_line_end()
capture.set_env(PLUMA_CURRENT_LINE=piter.get_text(end))
# Selected text (only if input is not selection)
if node.input != 'selection' and node.input != 'selection-document':
bounds = document.get_selection_bounds()
if bounds:
capture.set_env(PLUMA_SELECTED_TEXT=bounds[0].get_text(bounds[1]))
bounds = current_word(document)
capture.set_env(PLUMA_CURRENT_WORD=bounds[0].get_text(bounds[1]))
capture.set_env(PLUMA_CURRENT_DOCUMENT_TYPE=document.get_mime_type())
if uri is not None:
gfile = Gio.file_new_for_uri(uri)
scheme = gfile.get_uri_scheme()
name = os.path.basename(uri)
capture.set_env(PLUMA_CURRENT_DOCUMENT_URI = uri,
PLUMA_CURRENT_DOCUMENT_NAME = name,
PLUMA_CURRENT_DOCUMENT_SCHEME = scheme)
if Pluma.utils_uri_has_file_scheme(uri):
path = gfile.get_path()
cwd = os.path.dirname(path)
capture.set_cwd(cwd)
capture.set_env(PLUMA_CURRENT_DOCUMENT_PATH = path,
PLUMA_CURRENT_DOCUMENT_DIR = cwd)
documents_uri = [doc.get_uri()
for doc in window.get_documents()
if doc.get_uri() is not None]
documents_path = [Gio.file_new_for_uri(uri).get_path()
for uri in documents_uri
if Pluma.utils_uri_has_file_scheme(uri)]
capture.set_env(PLUMA_DOCUMENTS_URI = ' '.join(documents_uri),
PLUMA_DOCUMENTS_PATH = ' '.join(documents_path))
flags = capture.CAPTURE_BOTH
if not node.has_hash_bang():
flags |= capture.CAPTURE_NEEDS_SHELL
capture.set_flags(flags)
# Get input text
input_type = node.input
output_type = node.output
# Clear the panel
panel.clear()
if output_type == 'output-panel':
panel.show()
# Assign the error output to the output panel
panel.set_process(capture)
if input_type != 'nothing' and view is not None:
if input_type == 'document':
start, end = document.get_bounds()
elif input_type == 'selection' or input_type == 'selection-document':
try:
start, end = document.get_selection_bounds()
except ValueError:
if input_type == 'selection-document':
start, end = document.get_bounds()
if output_type == 'replace-selection':
document.select_range(start, end)
else:
start = document.get_iter_at_mark(document.get_insert())
end = start.copy()
elif input_type == 'line':
start = document.get_iter_at_mark(document.get_insert())
end = start.copy()
if not start.starts_line():
start.set_line_offset(0)
if not end.ends_line():
end.forward_to_line_end()
elif input_type == 'word':
start = document.get_iter_at_mark(document.get_insert())
end = start.copy()
if not start.inside_word():
panel.write(_('You must be inside a word to run this command'),
panel.command_tag)
return
if not start.starts_word():
start.backward_word_start()
if not end.ends_word():
end.forward_word_end()
input_text = document.get_text(start, end, False)
capture.set_input(input_text)
# Assign the standard output to the chosen "file"
if output_type == 'new-document':
tab = window.create_tab(True)
view = tab.get_view()
document = tab.get_document()
pos = document.get_start_iter()
capture.connect('stdout-line', capture_stdout_line_document, document, pos)
document.begin_user_action()
view.set_editable(False)
view.set_cursor_visible(False)
elif output_type != 'output-panel' and output_type != 'nothing' and view is not None:
document.begin_user_action()
view.set_editable(False)
view.set_cursor_visible(False)
if output_type == 'insert':
pos = document.get_iter_at_mark(document.get_mark('insert'))
elif output_type == 'replace-selection':
document.delete_selection(False, False)
pos = document.get_iter_at_mark(document.get_mark('insert'))
elif output_type == 'replace-document':
document.set_text('')
pos = document.get_end_iter()
else:
pos = document.get_end_iter()
capture.connect('stdout-line', capture_stdout_line_document, document, pos)
elif output_type != 'nothing':
capture.connect('stdout-line', capture_stdout_line_panel, panel)
document.begin_user_action()
capture.connect('stderr-line', capture_stderr_line_panel, panel)
capture.connect('begin-execute', capture_begin_execute_panel, panel, view, node.name)
capture.connect('end-execute', capture_end_execute_panel, panel, view, output_type)
# Run the command
capture.execute()
if output_type != 'nothing':
document.end_user_action()
class MultipleDocumentsSaver:
def __init__(self, window, panel, docs, node):
self._window = window
self._panel = panel
self._node = node
self._error = False
self._counter = len(docs)
self._signal_ids = {}
self._counter = 0
signals = {}
for doc in docs:
signals[doc] = doc.connect('saving', self.on_document_saving)
Pluma.commands_save_document(window, doc)
doc.disconnect(signals[doc])
def on_document_saving(self, doc, size, total_size):
self._counter += 1
self._signal_ids[doc] = doc.connect('saved', self.on_document_saved)
def on_document_saved(self, doc, error):
if error:
self._error = True
doc.disconnect(self._signal_ids[doc])
del self._signal_ids[doc]
self._counter -= 1
if self._counter == 0 and not self._error:
run_external_tool(self._window, self._panel, self._node)
def capture_menu_action(action, window, panel, node):
if node.save_files == 'document' and window.get_active_document():<|fim▁hole|> MultipleDocumentsSaver(window, panel, window.get_documents(), node)
return
run_external_tool(window, panel, node)
def capture_stderr_line_panel(capture, line, panel):
if not panel.visible():
panel.show()
panel.write(line, panel.error_tag)
def capture_begin_execute_panel(capture, panel, view, label):
view.get_window(Gtk.TextWindowType.TEXT).set_cursor(Gdk.Cursor.new(Gdk.CursorType.WATCH))
panel['stop'].set_sensitive(True)
panel.clear()
panel.write(_("Running tool:"), panel.italic_tag);
panel.write(" %s\n\n" % label, panel.bold_tag);
def capture_end_execute_panel(capture, exit_code, panel, view, output_type):
panel['stop'].set_sensitive(False)
if output_type in ('new-document','replace-document'):
doc = view.get_buffer()
start = doc.get_start_iter()
end = start.copy()
end.forward_chars(300)
mtype, uncertain = Gio.content_type_guess(None, doc.get_text(start, end, False).encode('utf-8'))
lmanager = GtkSource.LanguageManager.get_default()
language = lmanager.guess_language(doc.get_uri(), mtype)
if language is not None:
doc.set_language(language)
view.get_window(Gtk.TextWindowType.TEXT).set_cursor(Gdk.Cursor.new(Gdk.CursorType.XTERM))
view.set_cursor_visible(True)
view.set_editable(True)
if exit_code == 0:
panel.write("\n" + _("Done.") + "\n", panel.italic_tag)
else:
panel.write("\n" + _("Exited") + ":", panel.italic_tag)
panel.write(" %d\n" % exit_code, panel.bold_tag)
def capture_stdout_line_panel(capture, line, panel):
panel.write(line)
def capture_stdout_line_document(capture, line, document, pos):
document.insert(pos, line)
# ex:ts=4:et:<|fim▁end|> | MultipleDocumentsSaver(window, panel, [window.get_active_document()], node)
return
elif node.save_files == 'all': |
<|file_name|>htmlselectelement.rs<|end_file_name|><|fim▁begin|>/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
use dom::attr::Attr;
use dom::bindings::codegen::Bindings::HTMLOptionElementBinding::HTMLOptionElementMethods;
use dom::bindings::codegen::Bindings::HTMLSelectElementBinding;
use dom::bindings::codegen::Bindings::HTMLSelectElementBinding::HTMLSelectElementMethods;
use dom::bindings::codegen::UnionTypes::HTMLElementOrLong;
use dom::bindings::codegen::UnionTypes::HTMLOptionElementOrHTMLOptGroupElement;
use dom::bindings::inheritance::Castable;
use dom::bindings::js::Root;
use dom::bindings::str::DOMString;
use dom::document::Document;
use dom::element::{AttributeMutation, Element};
use dom::htmlelement::HTMLElement;
use dom::htmlfieldsetelement::HTMLFieldSetElement;
use dom::htmlformelement::{FormDatumValue, FormControl, FormDatum, HTMLFormElement};
use dom::htmloptionelement::HTMLOptionElement;
use dom::node::{Node, UnbindContext, window_from_node};
use dom::nodelist::NodeList;
use dom::validation::Validatable;
use dom::validitystate::ValidityState;
use dom::virtualmethods::VirtualMethods;
use string_cache::Atom;
use style::attr::AttrValue;
use style::element_state::*;
#[dom_struct]
pub struct HTMLSelectElement {
htmlelement: HTMLElement
}
static DEFAULT_SELECT_SIZE: u32 = 0;
impl HTMLSelectElement {
fn new_inherited(localName: Atom,
prefix: Option<DOMString>,
document: &Document) -> HTMLSelectElement {
HTMLSelectElement {
htmlelement:
HTMLElement::new_inherited_with_state(IN_ENABLED_STATE,
localName, prefix, document)
}
}
#[allow(unrooted_must_root)]
pub fn new(localName: Atom,
prefix: Option<DOMString>,
document: &Document) -> Root<HTMLSelectElement> {
let element = HTMLSelectElement::new_inherited(localName, prefix, document);
Node::reflect_node(box element, document, HTMLSelectElementBinding::Wrap)
}
// https://html.spec.whatwg.org/multipage/#ask-for-a-reset
pub fn ask_for_reset(&self) {
if self.Multiple() {
return;
}
let mut first_enabled: Option<Root<HTMLOptionElement>> = None;
let mut last_selected: Option<Root<HTMLOptionElement>> = None;
let node = self.upcast::<Node>();
for opt in node.traverse_preorder().filter_map(Root::downcast::<HTMLOptionElement>) {
if opt.Selected() {
opt.set_selectedness(false);
last_selected = Some(Root::from_ref(opt.r()));
}
let element = opt.upcast::<Element>();
if first_enabled.is_none() && !element.disabled_state() {
first_enabled = Some(Root::from_ref(opt.r()));
}
}
if let Some(last_selected) = last_selected {
last_selected.set_selectedness(true);
} else {
if self.display_size() == 1 {
if let Some(first_enabled) = first_enabled {
first_enabled.set_selectedness(true);
}
}
}
}
pub fn push_form_data(&self, data_set: &mut Vec<FormDatum>) {
let node = self.upcast::<Node>();
if self.Name().is_empty() {
return;<|fim▁hole|> let element = opt.upcast::<Element>();
if opt.Selected() && element.enabled_state() {
data_set.push(FormDatum {
ty: self.Type(),
name: self.Name(),
value: FormDatumValue::String(opt.Value())
});
}
}
}
// https://html.spec.whatwg.org/multipage/#concept-select-pick
pub fn pick_option(&self, picked: &HTMLOptionElement) {
if !self.Multiple() {
let node = self.upcast::<Node>();
let picked = picked.upcast();
for opt in node.traverse_preorder().filter_map(Root::downcast::<HTMLOptionElement>) {
if opt.upcast::<HTMLElement>() != picked {
opt.set_selectedness(false);
}
}
}
}
// https://html.spec.whatwg.org/multipage/#concept-select-size
fn display_size(&self) -> u32 {
if self.Size() == 0 {
if self.Multiple() {
4
} else {
1
}
} else {
self.Size()
}
}
}
impl HTMLSelectElementMethods for HTMLSelectElement {
// https://html.spec.whatwg.org/multipage/#dom-cva-validity
fn Validity(&self) -> Root<ValidityState> {
let window = window_from_node(self);
ValidityState::new(window.r(), self.upcast())
}
// Note: this function currently only exists for union.html.
// https://html.spec.whatwg.org/multipage/#dom-select-add
fn Add(&self, _element: HTMLOptionElementOrHTMLOptGroupElement, _before: Option<HTMLElementOrLong>) {
}
// https://html.spec.whatwg.org/multipage/#dom-fe-disabled
make_bool_getter!(Disabled, "disabled");
// https://html.spec.whatwg.org/multipage/#dom-fe-disabled
make_bool_setter!(SetDisabled, "disabled");
// https://html.spec.whatwg.org/multipage/#dom-fae-form
fn GetForm(&self) -> Option<Root<HTMLFormElement>> {
self.form_owner()
}
// https://html.spec.whatwg.org/multipage/#dom-select-multiple
make_bool_getter!(Multiple, "multiple");
// https://html.spec.whatwg.org/multipage/#dom-select-multiple
make_bool_setter!(SetMultiple, "multiple");
// https://html.spec.whatwg.org/multipage/#dom-fe-name
make_getter!(Name, "name");
// https://html.spec.whatwg.org/multipage/#dom-fe-name
make_setter!(SetName, "name");
// https://html.spec.whatwg.org/multipage/#dom-select-size
make_uint_getter!(Size, "size", DEFAULT_SELECT_SIZE);
// https://html.spec.whatwg.org/multipage/#dom-select-size
make_uint_setter!(SetSize, "size", DEFAULT_SELECT_SIZE);
// https://html.spec.whatwg.org/multipage/#dom-select-type
fn Type(&self) -> DOMString {
DOMString::from(if self.Multiple() {
"select-multiple"
} else {
"select-one"
})
}
// https://html.spec.whatwg.org/multipage/#dom-lfe-labels
fn Labels(&self) -> Root<NodeList> {
self.upcast::<HTMLElement>().labels()
}
}
impl VirtualMethods for HTMLSelectElement {
fn super_type(&self) -> Option<&VirtualMethods> {
Some(self.upcast::<HTMLElement>() as &VirtualMethods)
}
fn attribute_mutated(&self, attr: &Attr, mutation: AttributeMutation) {
self.super_type().unwrap().attribute_mutated(attr, mutation);
if attr.local_name() == &atom!("disabled") {
let el = self.upcast::<Element>();
match mutation {
AttributeMutation::Set(_) => {
el.set_disabled_state(true);
el.set_enabled_state(false);
},
AttributeMutation::Removed => {
el.set_disabled_state(false);
el.set_enabled_state(true);
el.check_ancestors_disabled_state_for_form_control();
}
}
}
}
fn bind_to_tree(&self, tree_in_doc: bool) {
if let Some(ref s) = self.super_type() {
s.bind_to_tree(tree_in_doc);
}
self.upcast::<Element>().check_ancestors_disabled_state_for_form_control();
}
fn unbind_from_tree(&self, context: &UnbindContext) {
self.super_type().unwrap().unbind_from_tree(context);
let node = self.upcast::<Node>();
let el = self.upcast::<Element>();
if node.ancestors().any(|ancestor| ancestor.is::<HTMLFieldSetElement>()) {
el.check_ancestors_disabled_state_for_form_control();
} else {
el.check_disabled_attribute();
}
}
fn parse_plain_attribute(&self, local_name: &Atom, value: DOMString) -> AttrValue {
match *local_name {
atom!("size") => AttrValue::from_u32(value.into(), DEFAULT_SELECT_SIZE),
_ => self.super_type().unwrap().parse_plain_attribute(local_name, value),
}
}
}
impl FormControl for HTMLSelectElement {}
impl Validatable for HTMLSelectElement {}<|fim▁end|> | }
for opt in node.traverse_preorder().filter_map(Root::downcast::<HTMLOptionElement>) { |
<|file_name|>compare_crud_spec.ts<|end_file_name|><|fim▁begin|>/*
* Copyright 2019 ThoughtWorks, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import {ApiResult, SuccessResponse} from "helpers/api_request_builder";
import {SparkRoutes} from "helpers/spark_routes";
import {Comparison} from "../compare";
import {ComparisonCRUD} from "../compare_crud";
import {ComparisonData} from "./test_data";
describe('CompareCrudSpec', () => {
beforeEach(() => jasmine.Ajax.install());
afterEach(() => jasmine.Ajax.uninstall());
it('should get the difference between the two counters for the given pipeline', (done) => {
const apiPath = SparkRoutes.comparePipelines("pipeline1", 1, 3);
jasmine.Ajax.stubRequest(apiPath).andReturn(comparisonResponse());
const onResponse = jasmine.createSpy().and.callFake((response: ApiResult<any>) => {
const responseJSON = response.unwrap() as SuccessResponse<any>;
const object = (responseJSON.body as Comparison);
expect(object.pipelineName).toEqual("pipeline1");
expect(object.fromCounter).toEqual(1);
expect(object.toCounter).toEqual(3);<|fim▁hole|> done();
});
ComparisonCRUD.getDifference("pipeline1", 1, 3).then(onResponse);
const request = jasmine.Ajax.requests.mostRecent();
expect(request.url).toEqual(apiPath);
expect(request.method).toEqual("GET");
expect(request.requestHeaders.Accept).toEqual("application/vnd.go.cd.v1+json");
});
});
function comparisonResponse() {
return {
status: 200,
responseHeaders: {
"Content-Type": "application/vnd.go.cd.v1+json; charset=utf-8",
"ETag": "some-etag"
},
responseText: JSON.stringify(ComparisonData.compare())
};
}<|fim▁end|> | |
<|file_name|>sep.py<|end_file_name|><|fim▁begin|>from outsourcer import Code
from . import utils
from .base import Expression
from .constants import BREAK, POS, RESULT, STATUS
class Sep(Expression):
num_blocks = 2
def __init__(
self,<|fim▁hole|> expr,
separator,
discard_separators=True,
allow_trailer=False,
allow_empty=True,
):
self.expr = expr
self.separator = separator
self.discard_separators = discard_separators
self.allow_trailer = allow_trailer
self.allow_empty = allow_empty
def __str__(self):
op = '/?' if self.allow_trailer else '//'
return utils.infix_str(self.expr, op, self.separator)
def operand_string(self):
return f'({self})'
def always_succeeds(self):
return self.allow_empty
def _compile(self, out):
staging = out.var('staging', [])
checkpoint = out.var('checkpoint', POS)
with out.WHILE(True):
with utils.if_fails(out, self.expr):
# If we're not discarding separators, and if we're also not
# allowing a trailing separator, then we need to pop the last
# separator off of our list.
if not self.discard_separators and not self.allow_trailer:
# But only pop if staging is not empty.
with out.IF(staging):
out += staging.pop()
out += BREAK
out += staging.append(RESULT)
out += checkpoint << POS
with utils.if_fails(out, self.separator):
out += BREAK
if not self.discard_separators:
out += staging.append(RESULT)
if self.allow_trailer:
out += checkpoint << POS
success = [
RESULT << staging,
POS << checkpoint,
STATUS << True,
]
if self.allow_empty:
out.extend(success)
else:
with out.IF(staging):
out.extend(success)<|fim▁end|> | |
<|file_name|>test_mysqldb.py<|end_file_name|><|fim▁begin|>import sys
import pytest
from opentracing.ext import tags
from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker
from opentracing_instrumentation.client_hooks import mysqldb as mysqldb_hooks
from opentracing_instrumentation.request_context import span_in_context
from .sql_common import metadata, User
SKIP_REASON_PYTHON_3 = 'MySQLdb is not compatible with Python 3'
SKIP_REASON_CONNECTION = 'MySQL is not running or cannot connect'
MYSQL_CONNECTION_STRING = 'mysql://[email protected]/test'
@pytest.fixture
def session():
Session = sessionmaker()
engine = create_engine(MYSQL_CONNECTION_STRING)
Session.configure(bind=engine)
metadata.create_all(engine)
try:
yield Session()
except:
pass
@pytest.fixture(autouse=True, scope='module')
def patch_sqlalchemy():
mysqldb_hooks.install_patches()
try:
yield
finally:
mysqldb_hooks.reset_patches()
<|fim▁hole|> pass
return True
except:
return False
def assert_span(span, operation, parent=None):
assert span.operation_name == 'MySQLdb:' + operation
assert span.tags.get(tags.SPAN_KIND) == tags.SPAN_KIND_RPC_CLIENT
if parent:
assert span.parent_id == parent.context.span_id
assert span.context.trace_id == parent.context.trace_id
else:
assert span.parent_id is None
@pytest.mark.skipif(not is_mysql_running(), reason=SKIP_REASON_CONNECTION)
@pytest.mark.skipif(sys.version_info.major == 3, reason=SKIP_REASON_PYTHON_3)
def test_db(tracer, session):
root_span = tracer.start_span('root-span')
# span recording works for regular operations within a context only
with span_in_context(root_span):
user = User(name='user', fullname='User', password='password')
session.add(user)
session.commit()
spans = tracer.recorder.get_spans()
assert len(spans) == 4
connect_span, insert_span, commit_span, rollback_span = spans
assert_span(connect_span, 'Connect')
assert_span(insert_span, 'INSERT', root_span)
assert_span(commit_span, 'commit', root_span)
assert_span(rollback_span, 'rollback', root_span)<|fim▁end|> | def is_mysql_running():
try:
import MySQLdb
with MySQLdb.connect(host='127.0.0.1', user='root'): |
<|file_name|>InspectorClientGtk.cpp<|end_file_name|><|fim▁begin|>/*
* Copyright (C) 2008, 2012 Gustavo Noronha Silva
* Copyright (C) 2010 Collabora Ltd.
*
* 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, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
#include "config.h"
#include "InspectorClientGtk.h"
#include "FileSystem.h"
#include "Frame.h"
#include "InspectorController.h"
#include "NotImplemented.h"
#include "Page.h"
#include "PlatformString.h"
#include "webkitversion.h"
#include "webkitwebinspector.h"
#include "webkitwebinspectorprivate.h"
#include "webkitwebview.h"
#include "webkitwebviewprivate.h"
#include <wtf/text/CString.h>
using namespace WebCore;
namespace WebKit {
static void notifyWebViewDestroyed(WebKitWebView* webView, InspectorFrontendClient* inspectorFrontendClient)
{
inspectorFrontendClient->destroyInspectorWindow(true);
}
namespace {
class InspectorFrontendSettingsGtk : public InspectorFrontendClientLocal::Settings {
public:
virtual ~InspectorFrontendSettingsGtk() { }
private:
virtual String getProperty(const String& name)
{
notImplemented();
return String();
}
virtual void setProperty(const String& name, const String& value)
{
notImplemented();
}
};
} // namespace
InspectorClient::InspectorClient(WebKitWebView* webView)
: m_inspectedWebView(webView)
, m_frontendPage(0)
, m_frontendClient(0)
{}
InspectorClient::~InspectorClient()
{
if (m_frontendClient) {
m_frontendClient->disconnectInspectorClient();
m_frontendClient = 0;
}
}
void InspectorClient::inspectorDestroyed()
{
closeInspectorFrontend();
delete this;
}
void InspectorClient::openInspectorFrontend(InspectorController* controller)
{
// This g_object_get will ref the inspector. We're not doing an
// unref if this method succeeds because the inspector object must
// be alive even after the inspected WebView is destroyed - the
// close-window and destroy signals still need to be
// emitted.
WebKitWebInspector* webInspector = 0;
g_object_get(m_inspectedWebView, "web-inspector", &webInspector, NULL);
ASSERT(webInspector);
WebKitWebView* inspectorWebView = 0;
g_signal_emit_by_name(webInspector, "inspect-web-view", m_inspectedWebView, &inspectorWebView);
if (!inspectorWebView) {
g_object_unref(webInspector);
return;
}
webkit_web_inspector_set_web_view(webInspector, inspectorWebView);
GOwnPtr<gchar> inspectorPath(g_build_filename(inspectorFilesPath(), "inspector.html", NULL));
GOwnPtr<gchar> inspectorURI(g_filename_to_uri(inspectorPath.get(), 0, 0));
webkit_web_view_load_uri(inspectorWebView, inspectorURI.get());
gtk_widget_show(GTK_WIDGET(inspectorWebView));
m_frontendPage = core(inspectorWebView);
OwnPtr<InspectorFrontendClient> frontendClient = adoptPtr(new InspectorFrontendClient(m_inspectedWebView, inspectorWebView, webInspector, m_frontendPage, this));
m_frontendClient = frontendClient.get();
m_frontendPage->inspectorController()->setInspectorFrontendClient(frontendClient.release());
// The inspector must be in it's own PageGroup to avoid deadlock while debugging.
m_frontendPage->setGroupName("");
}
void InspectorClient::closeInspectorFrontend()
{
if (m_frontendClient)
m_frontendClient->destroyInspectorWindow(false);
}
void InspectorClient::bringFrontendToFront()
{
m_frontendClient->bringToFront();
}
void InspectorClient::releaseFrontendPage()
{
m_frontendPage = 0;
m_frontendClient = 0;
}
void InspectorClient::highlight()
{
hideHighlight();
}
void InspectorClient::hideHighlight()
{
// FIXME: we should be able to only invalidate the actual rects of
// the new and old nodes. We need to track the nodes, and take the
// actual highlight size into account when calculating the damage
// rect.
gtk_widget_queue_draw(GTK_WIDGET(m_inspectedWebView));
}
bool InspectorClient::sendMessageToFrontend(const String& message)
{
return doDispatchMessageOnFrontendPage(m_frontendPage, message);
}
const char* InspectorClient::inspectorFilesPath()
{
if (m_inspectorFilesPath)
m_inspectorFilesPath.get();
const char* environmentPath = getenv("WEBKIT_INSPECTOR_PATH");
if (environmentPath && g_file_test(environmentPath, G_FILE_TEST_IS_DIR))
m_inspectorFilesPath.set(g_strdup(environmentPath));
else
m_inspectorFilesPath.set(g_build_filename(sharedResourcesPath().data(), "webinspector", NULL));
return m_inspectorFilesPath.get();
}
InspectorFrontendClient::InspectorFrontendClient(WebKitWebView* inspectedWebView, WebKitWebView* inspectorWebView, WebKitWebInspector* webInspector, Page* inspectorPage, InspectorClient* inspectorClient)
: InspectorFrontendClientLocal(core(inspectedWebView)->inspectorController(), inspectorPage, adoptPtr(new InspectorFrontendSettingsGtk()))
, m_inspectorWebView(inspectorWebView)
, m_inspectedWebView(inspectedWebView)
, m_webInspector(webInspector)
, m_inspectorClient(inspectorClient)
{
g_signal_connect(m_inspectorWebView, "destroy",
G_CALLBACK(notifyWebViewDestroyed), (gpointer)this);
}
InspectorFrontendClient::~InspectorFrontendClient()
{
if (m_inspectorClient) {
m_inspectorClient->releaseFrontendPage();
m_inspectorClient = 0;
}
ASSERT(!m_webInspector);
}
void InspectorFrontendClient::destroyInspectorWindow(bool notifyInspectorController)
{
if (!m_webInspector)
return;
GRefPtr<WebKitWebInspector> webInspector = adoptGRef(m_webInspector.leakRef());
if (m_inspectorWebView) {
g_signal_handlers_disconnect_by_func(m_inspectorWebView, reinterpret_cast<gpointer>(notifyWebViewDestroyed), this);
m_inspectorWebView = 0;
}
if (notifyInspectorController)
core(m_inspectedWebView)->inspectorController()->disconnectFrontend();
if (m_inspectorClient)
m_inspectorClient->releaseFrontendPage();
gboolean handled = FALSE;
g_signal_emit_by_name(webInspector.get(), "close-window", &handled);
ASSERT(handled);
// Please do not use member variables here because InspectorFrontendClient object pointed by 'this'
// has been implicitly deleted by "close-window" function.
}
String InspectorFrontendClient::localizedStringsURL()
{
GOwnPtr<gchar> stringsPath(g_build_filename(m_inspectorClient->inspectorFilesPath(), "localizedStrings.js", NULL));
GOwnPtr<gchar> stringsURI(g_filename_to_uri(stringsPath.get(), 0, 0));
// FIXME: support l10n of localizedStrings.js
return String::fromUTF8(stringsURI.get());
}
String InspectorFrontendClient::hiddenPanels()
{
notImplemented();
return String();
}
void InspectorFrontendClient::bringToFront()
{
if (!m_inspectorWebView)
return;
gboolean handled = FALSE;
g_signal_emit_by_name(m_webInspector.get(), "show-window", &handled);
}
void InspectorFrontendClient::closeWindow()
{
destroyInspectorWindow(true);
}
void InspectorFrontendClient::attachWindow()
{
if (!m_inspectorWebView)
return;
gboolean handled = FALSE;
g_signal_emit_by_name(m_webInspector.get(), "attach-window", &handled);
}<|fim▁hole|>void InspectorFrontendClient::detachWindow()
{
if (!m_inspectorWebView)
return;
gboolean handled = FALSE;
g_signal_emit_by_name(m_webInspector.get(), "detach-window", &handled);
}
void InspectorFrontendClient::setAttachedWindowHeight(unsigned height)
{
notImplemented();
}
void InspectorFrontendClient::inspectedURLChanged(const String& newURL)
{
if (!m_inspectorWebView)
return;
webkit_web_inspector_set_inspected_uri(m_webInspector.get(), newURL.utf8().data());
}
}<|fim▁end|> | |
<|file_name|>cloudmailru.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*-
'''
Specto Add-on
Copyright (C) 2015 lambda
<|fim▁hole|> This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program 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 General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
'''
import re,json,urllib
from resources.lib.libraries import client
def resolve(url):
try:
try:
v = url.split('public')[-1]
r = client.request(url)
r = re.sub(r'[^\x00-\x7F]+', ' ', r)
tok = re.findall('"tokens"\s*:\s*{\s*"download"\s*:\s*"([^"]+)', r)[0]
url = re.findall('"weblink_get"\s*:\s*\[.+?"url"\s*:\s*"([^"]+)', r)[0]
url = '%s%s?key=%s' % (url, v, tok)
print("u",url)
return url
except:
return
except:
return<|fim▁end|> | |
<|file_name|>Robot.py<|end_file_name|><|fim▁begin|>import constants as c
from gui.windows import VideoStream
import socket
import cv2
import urllib
import numpy as np
class Robot(object):
def __init__(self, connection):
self.connection = connection
""" @type : Connections.ConnectionProcessEnd.RobotConnection """
self.socket = None
self.stream = None
self.bytes = None
self.window = None
self.psychopy_disabled = None
self.stream_enabled = None
self.target_to_command = None
self.connection.waitMessages(self.start, self.exit, self.update, self.setup, self.sendMessage, poll=0)
<|fim▁hole|> while True:
self.update()
message = self.connection.receiveMessageInstant()
if message is not None:
if isinstance(message, int):
self.sendMessage(self.target_to_command[message])
elif message in c.ROBOT_COMMANDS:
self.sendMessage(message)
elif isinstance(message, basestring):
return message
else:
print("Robot message: " + str(message))
def updateVideo(self):
if self.stream_enabled:
if self.stream is not None:
self.bytes += self.stream.read(1024)
a = self.bytes.find('\xff\xd8')
b = self.bytes.find('\xff\xd9')
if a != -1 and b != -1:
jpg = self.bytes[a:b+2]
self.bytes = self.bytes[b+2:]
i = cv2.imdecode(np.fromstring(jpg, dtype=np.uint8), cv2.CV_LOAD_IMAGE_COLOR)
if self.psychopy_disabled is not None:
if self.psychopy_disabled:
self.window.updateStream(i)
else:
self.connection.sendMessage(i)
def updateWindow(self):
if self.window is not None:
self.window.update()
def exitWindow(self):
if self.window is not None:
self.window.exitFlag = True
self.window.exit()
def update(self):
self.updateVideo()
self.updateWindow()
def exit(self):
self.exitWindow()
self.connection.close()
def sendRobotMessage(self, message):
try: # seems like PiTank closes the socket after receiving message
robot_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
robot_socket.connect(("192.168.42.1", 12345))
robot_socket.send(message)
except Exception, e:
print("Could not send message to robot (did you click setup? Is PiTank switched on and computer connected to PiTank?): " + str(e))
def sendMessage(self, message):
if message in c.ROBOT_COMMANDS:
self.sendRobotMessage(message)
else:
print("Unknown message in Robot: " + str(message))
def psychopyDisabled(self, options):
return options[c.DISABLE] == 1
def streamEnabled(self, options):
return options[c.ROBOT_STREAM] == 1
def getTargetToCommand(self, options):
return {
options[c.ROBOT_OPTION_FORWARD]: c.MOVE_FORWARD,
options[c.ROBOT_OPTION_BACKWARD]: c.MOVE_BACKWARD,
options[c.ROBOT_OPTION_LEFT]: c.MOVE_LEFT,
options[c.ROBOT_OPTION_RIGHT]: c.MOVE_RIGHT,
options[c.ROBOT_OPTION_STOP]: c.MOVE_STOP
}
def setup(self):
options = self.connection.receiveMessageBlock()
self.exitWindow()
self.stream_enabled = self.streamEnabled(options[c.DATA_ROBOT])
self.target_to_command = self.getTargetToCommand(options[c.DATA_ROBOT])
if self.stream_enabled:
self.psychopy_disabled = self.psychopyDisabled(options[c.DATA_BACKGROUND])
if self.psychopy_disabled:
self.window = VideoStream.StreamWindow()
self.window.setup()
else:
self.window = None
else:
self.window = None
try:
self.stream = urllib.urlopen("http://192.168.42.1:8080/?action=stream")
self.bytes = ""
return c.SUCCESS_MESSAGE
except Exception, e:
print("Error: " + str(e))
return c.FAIL_MESSAGE<|fim▁end|> | def start(self): |
<|file_name|>login.js<|end_file_name|><|fim▁begin|>var userData = [
{'fName':'Justin', 'lName' : 'Gil', 'age': 70, 'gender': 'M', 'phone': '949-111-1111', 'profilePic': '../pix/justin.jpeg', 'city' : 'San Diego', 'add' : '55 Serenity'
, 'Bio': 'I like soccer and long walks on the beach.', 'userIndex' : 1, 'username': 'justin', 'password': 'lol', 'state' : 'CA', 'zip' : '92092'},
{'fName':'Momin', 'lName' : 'Khan', 'age': 60, 'gender': 'M', 'phone': '949-111-1312', 'profilePic': '../pix/momin.jpeg', 'city' : 'Carlsbad', 'add' : '23 Rollings'
, 'Bio': 'I like soccer and long walks on the beach.', 'userIndex' : 2, 'username': 'momin', 'password': 'lol', 'state' : 'CA', 'zip' : '92312'},
{'fName':'Scott', 'lName' : 'Chen', 'age': 50, 'gender': 'M', 'phone': '949-111-1113', 'profilePic': '../pix/scott.jpeg', 'city' : 'Oceanside', 'add' : '35 Jasmin'
, 'Bio': 'I like soccer and long walks on the beach.', 'userIndex' : 3, 'username': 'scott', 'password': 'lol', 'state' : 'CA', 'zip' : '42092'},
{'fName':'Charles', 'lName' : 'Chen', 'age': 72, 'gender': 'M', 'phone': '949-111-1114', 'profilePic': '../pix/charles.jpeg', 'city' : 'Coronado', 'add' : '388 Rose',
'Bio': 'I like soccer and long walks on the beach.', 'userIndex' : 4, 'username': 'charles', 'password': 'lol', 'state' : 'CA', 'zip' : '52092'}
]
localStorage.setItem('userDataLocalStorage', JSON.stringify(userData));
<|fim▁hole|>
$(function () {
var invalidAccountWarning = document.getElementById("invalid_account_warning");
invalidAccountWarning.style.display = "none";
});
$("#login").click(function() {
var invalidAccountWarning = document.getElementById("invalid_account_warning");
invalidAccountWarning.style.display = "none";
var username = document.getElementById("inputted_username").value;
var password = document.getElementById("inputted_password").value;
var loggedInUserIndex = 0;
for (var i = 0; i < userData.length; i++) {
var currData = userData[i];
if(username == currData.username && password == currData.password)
loggedInUserIndex = currData.userIndex;
}
if(loggedInUserIndex != 0) {
localStorage.setItem('loggedInUserIndex', loggedInUserIndex);
console.log(loggedInUserIndex);
window.location.href = 'home.html';
}
else {
invalidAccountWarning.style.display = "block";
}
});<|fim▁end|> | |
<|file_name|>difference.py<|end_file_name|><|fim▁begin|>"""
Boolean geometry difference of solids.
"""
from __future__ import absolute_import
#Init has to be imported first because it has code to workaround the python bug where relative imports don't work if the module is imported as a main module.
import __init__
from fabmetheus_utilities.geometry.geometry_utilities import boolean_solid
from fabmetheus_utilities.geometry.geometry_utilities import evaluate
from fabmetheus_utilities.geometry.solids import group
__author__ = 'Enrique Perez ([email protected])'
__credits__ = 'Nophead <http://hydraraptor.blogspot.com/>\nArt of Illusion <http://www.artofillusion.org/>'
__date__ = '$Date: 2008/21/04 $'
__license__ = 'GNU Affero General Public License http://www.gnu.org/licenses/agpl.html'
def convertElementNode(elementNode, geometryOutput):
"Convert the xml element to a difference xml element."
group.convertContainerElementNode(elementNode, geometryOutput, Difference())
def getNewDerivation(elementNode):
'Get new derivation.'
return evaluate.EmptyObject(elementNode)
<|fim▁hole|> "Process the xml element."
evaluate.processArchivable(Difference, elementNode)
class Difference( boolean_solid.BooleanSolid ):
"A difference object."
def getLoopsFromObjectLoopsList(self, importRadius, visibleObjectLoopsList):
"Get loops from visible object loops list."
return self.getDifference(importRadius, visibleObjectLoopsList)
def getXMLLocalName(self):
"Get xml class name."
return self.__class__.__name__.lower()<|fim▁end|> | def processElementNode(elementNode): |
<|file_name|>try_except3.py<|end_file_name|><|fim▁begin|>#####################################################################################
#<|fim▁hole|># copy of the license can be found in the License.html file at the root of this distribution. If
# you cannot locate the Apache License, Version 2.0, please send an email to
# [email protected]. By using this source code in any fashion, you are agreeing to be bound
# by the terms of the Apache License, Version 2.0.
#
# You must not remove this notice, or any other, from this software.
#
#
#####################################################################################
from common import runtests
from .shared import try_except_maker3
from .shared import setGenerator, test_exceptions
setGenerator(try_except_maker3)
runtests(test_exceptions)<|fim▁end|> | # Copyright (c) Microsoft Corporation. All rights reserved.
#
# This source code is subject to terms and conditions of the Apache License, Version 2.0. A |
<|file_name|>twitter_client.rs<|end_file_name|><|fim▁begin|>use std::io::Read;
use oauthcli::SignatureMethod::HmacSha1;
use oauthcli::OAuthAuthorizationHeaderBuilder;
use serde_json;
use serde_json::Value;
use reqwest::{Client, Url, StatusCode, Response};
use reqwest::header::{HeaderValue, AUTHORIZATION};
const API_URL: &'static str = "https://api.twitter.com/1.1/statuses/update.json";
pub struct TwitterClient {
consumer_key: String,
consumer_secret: String,
access_key: String,
access_secret: String,
client: Client,
}
#[derive(PartialEq, Eq, Debug, Clone)]
pub enum TwitterError {
Duplicated,
RateLimitExceeded,
InvalidTweet,
InvalidResponse,
Network,
Unauthorized,
Unknown(String),
}
impl TwitterClient {
pub fn new(consumer_key: String, consumer_secret: String, access_key: String, access_secret: String) -> TwitterClient
{
TwitterClient {
consumer_key: consumer_key,
consumer_secret: consumer_secret,
access_key: access_key,
access_secret: access_secret,
client: Client::new(),
}
}
pub fn is_valid(&self) -> bool
{
// TODO: implement token validation
true
}
fn post(&self, url: &str, args: Vec<(&str, &str)>) -> Result<Response, ()>
{
let mut req = self.client.post(url);
req = req.form(&args);
let oauth_header = OAuthAuthorizationHeaderBuilder::new(
"POST",
&Url::parse(url).expect("must be a valid url string"),
&self.consumer_key,
&self.consumer_secret,
HmacSha1)
.token(&self.access_key, &self.access_secret)
.request_parameters(args.into_iter())
.finish_for_twitter()
.to_string();
req.header(AUTHORIZATION, &oauth_header).send().map_err(|_| ())
}
pub fn update_status(&self, message: &str, in_reply_to: Option<u64>)
-> Result<u64, TwitterError>
{
let prev = in_reply_to.map(|i| i.to_string());
let mut args = vec![("status", message)];
if let Some(prev) = prev.as_ref() {
args.push(("in_reply_to_status_id", prev));
}
let mut response = self.post(API_URL, args).map_err(|_| TwitterError::Network)?;
match response.status() {
StatusCode::FORBIDDEN => {
let mut body = String::new();
response.read_to_string(&mut body).map_err(|_| TwitterError::Network)?;
let json: Option<Value> = serde_json::from_str(&body).ok();
let id = json.and_then(|json| json["errors"][0]["code"].as_i64());
match id {
Some(186) => Err(TwitterError::InvalidTweet),
Some(187) => Err(TwitterError::Duplicated),
_ => Err(TwitterError::Unknown(body))
}
},
StatusCode::OK => {
let mut body = String::new();
response.read_to_string(&mut body).map_err(|_| TwitterError::Network)?;
<|fim▁hole|> let id = json["id"].as_u64().ok_or(TwitterError::InvalidResponse)?;
Ok(id)
},
StatusCode::TOO_MANY_REQUESTS => Err(TwitterError::RateLimitExceeded),
StatusCode::UNAUTHORIZED => Err(TwitterError::Unauthorized),
_ => Err(TwitterError::Unknown(format!("unknown status: {}", response.status())))
}
}
}<|fim▁end|> | let json: Value =
serde_json::from_str(&body).map_err(|_| TwitterError::InvalidResponse)?; |
<|file_name|>order.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*-
from __future__ import unicode_literals
from six import with_metaclass
from decimal import Decimal
from django.core.exceptions import ImproperlyConfigured, PermissionDenied
from django.db import models, transaction
from django.db.models.aggregates import Sum
from django.utils.encoding import python_2_unicode_compatible
from django.utils.module_loading import import_string
from django.utils.functional import cached_property
from django.utils.translation import ugettext_lazy as _, pgettext_lazy, get_language_from_request
from django.utils.six.moves.urllib.parse import urljoin
from jsonfield.fields import JSONField
from ipware.ip import get_ip
from django_fsm import FSMField, transition
from cms.models import Page
from shop import settings as shop_settings
from shop.models.cart import CartItemModel
from shop.money.fields import MoneyField, MoneyMaker
from .product import BaseProduct
from . import deferred
class OrderManager(models.Manager):
@transaction.atomic
def create_from_cart(self, cart, request):
"""
This creates a new Order object with all its OrderItems using the current Cart object
with its Cart Items. Whenever on Order Item is created from a Cart Item, that item is
removed from the Cart.
"""
cart.update(request)
order = self.model(customer=cart.customer, currency=cart.total.currency,
_subtotal=Decimal(0), _total=Decimal(0), stored_request=self.stored_request(request))
order.get_or_assign_number()
order.save()
order.customer.get_or_assign_number()
for cart_item in cart.items.all():
cart_item.update(request)
order_item = OrderItemModel(order=order)
try:
order_item.populate_from_cart_item(cart_item, request)
order_item.save()
cart_item.delete()
except CartItemModel.DoesNotExist:
pass
order.populate_from_cart(cart, request)
order.save()
return order
def stored_request(self, request):
"""
Extract useful information about the request to be used for emulating a Django request
during offline rendering.
"""
return {
'language': get_language_from_request(request),
'absolute_base_uri': request.build_absolute_uri('/'),
'remote_ip': get_ip(request),
'user_agent': request.META.get('HTTP_USER_AGENT'),
}
def filter_from_request(self, request):
"""
Return a queryset containing the orders for the customer associated with the given
request object.
"""
if request.customer.is_visitor():
msg = _("Only signed in customers can view their orders")
raise PermissionDenied(msg)
return self.get_queryset().filter(customer=request.customer).order_by('-updated_at',)
def get_summary_url(self):
"""
Returns the URL of the page with the list view for all orders related to the current customer
"""
if not hasattr(self, '_summary_url'):
try:
page = Page.objects.public().get(reverse_id='shop-order')
except Page.DoesNotExist:
page = Page.objects.public().filter(application_urls='OrderApp').first()
finally:
self._summary_url = page and page.get_absolute_url() or 'cms-page-with--reverse_id=shop-order--does-not-exist/'
return self._summary_url
def get_latest_url(self):
"""
Returns the URL of the page with the detail view for the latest order related to the
current customer. This normally is the thank-you view.
"""
try:
return Page.objects.public().get(reverse_id='shop-order-last').get_absolute_url()
except Page.DoesNotExist:
pass # TODO: could be retrieved by last order
return 'cms-page-with--reverse_id=shop-order-last--does-not-exist/'
class WorkflowMixinMetaclass(deferred.ForeignKeyBuilder):
"""
Add configured Workflow mixin classes to `OrderModel` and `OrderPayment` to customize
all kinds of state transitions in a pluggable manner.
"""
def __new__(cls, name, bases, attrs):
if 'BaseOrder' in (b.__name__ for b in bases):
bases = tuple(import_string(mc) for mc in shop_settings.ORDER_WORKFLOWS) + bases
# merge the dicts of TRANSITION_TARGETS
attrs.update(_transition_targets={}, _auto_transitions={})
for b in reversed(bases):
TRANSITION_TARGETS = getattr(b, 'TRANSITION_TARGETS', {})
delattr(b, 'TRANSITION_TARGETS')<|fim▁hole|> raise ImproperlyConfigured(msg.format(b.__name__, ', '.join(TRANSITION_TARGETS.keys())))
attrs['_transition_targets'].update(TRANSITION_TARGETS)
attrs['_auto_transitions'].update(cls.add_to_auto_transitions(b))
Model = super(WorkflowMixinMetaclass, cls).__new__(cls, name, bases, attrs)
return Model
@staticmethod
def add_to_auto_transitions(base):
result = {}
for name, method in base.__dict__.items():
if callable(method) and hasattr(method, '_django_fsm'):
for name, transition in method._django_fsm.transitions.items():
if transition.custom.get('auto'):
result.update({name: method})
return result
@python_2_unicode_compatible
class BaseOrder(with_metaclass(WorkflowMixinMetaclass, models.Model)):
"""
An Order is the "in process" counterpart of the shopping cart, which freezes the state of the
cart on the moment of purchase. It also holds stuff like the shipping and billing addresses,
and keeps all the additional entities, as determined by the cart modifiers.
"""
TRANSITION_TARGETS = {
'new': _("New order without content"),
'created': _("Order freshly created"),
'payment_confirmed': _("Payment confirmed"),
}
decimalfield_kwargs = {
'max_digits': 30,
'decimal_places': 2,
}
decimal_exp = Decimal('.' + '0' * decimalfield_kwargs['decimal_places'])
customer = deferred.ForeignKey('BaseCustomer', verbose_name=_("Customer"), related_name='orders')
status = FSMField(default='new', protected=True, verbose_name=_("Status"))
currency = models.CharField(max_length=7, editable=False,
help_text=_("Currency in which this order was concluded"))
_subtotal = models.DecimalField(_("Subtotal"), **decimalfield_kwargs)
_total = models.DecimalField(_("Total"), **decimalfield_kwargs)
created_at = models.DateTimeField(_("Created at"), auto_now_add=True)
updated_at = models.DateTimeField(_("Updated at"), auto_now=True)
extra = JSONField(verbose_name=_("Extra fields"), default={},
help_text=_("Arbitrary information for this order object on the moment of purchase."))
stored_request = JSONField(default={},
help_text=_("Parts of the Request objects on the moment of purchase."))
objects = OrderManager()
class Meta:
abstract = True
def __str__(self):
return self.get_number()
def __repr__(self):
return "<{}(pk={})>".format(self.__class__.__name__, self.pk)
def get_or_assign_number(self):
"""
Hook to get or to assign the order number. It shall be invoked, every time an Order
object is created. If you prefer to use an order number which differs from the primary
key, then override this method.
"""
return self.get_number()
def get_number(self):
"""
Hook to get the order number.
"""
return str(self.id)
@cached_property
def subtotal(self):
"""
The summed up amount for all ordered items excluding extra order lines.
"""
return MoneyMaker(self.currency)(self._subtotal)
@cached_property
def total(self):
"""
The final total to charge for this order.
"""
return MoneyMaker(self.currency)(self._total)
@classmethod
def round_amount(cls, amount):
if amount.is_finite():
return Decimal(amount).quantize(cls.decimal_exp)
def get_absolute_url(self):
"""
Returns the URL for the detail view of this order
"""
return urljoin(OrderModel.objects.get_summary_url(), str(self.id))
@transition(field=status, source='new', target='created')
def populate_from_cart(self, cart, request):
"""
Populate the order object with the fields from the given cart. Override this method,
in case a customized cart has some fields which have to be transfered to the cart.
"""
self._subtotal = Decimal(cart.subtotal)
self._total = Decimal(cart.total)
self.extra = dict(cart.extra)
self.extra.update(rows=[(modifier, extra_row.data) for modifier, extra_row in cart.extra_rows.items()])
def save(self, **kwargs):
"""
Before saving the Order object to the database, round the total to the given decimal_places
"""
auto_transition = self._auto_transitions.get(self.status)
if callable(auto_transition):
auto_transition(self)
self._subtotal = BaseOrder.round_amount(self._subtotal)
self._total = BaseOrder.round_amount(self._total)
super(BaseOrder, self).save(**kwargs)
@cached_property
def amount_paid(self):
"""
The amount paid is the sum of related orderpayments
"""
amount = self.orderpayment_set.aggregate(amount=Sum('amount'))['amount']
if amount is None:
amount = MoneyMaker(self.currency)()
return amount
@property
def outstanding_amount(self):
"""
Return the outstanding amount paid for this order
"""
return self.total - self.amount_paid
def is_fully_paid(self):
return self.amount_paid >= self.total
@transition(field='status', source='*', target='payment_confirmed', conditions=[is_fully_paid])
def acknowledge_payment(self, by=None):
"""
Change status to `payment_confirmed`. This status code is known globally and can be used
by all external plugins to check, if an Order object has been fully paid.
"""
@classmethod
def get_transition_name(cls, target):
"""Return the human readable name for a given transition target"""
return cls._transition_targets.get(target, target)
def status_name(self):
"""Return the human readable name for the current transition state"""
return self._transition_targets.get(self.status, self.status)
status_name.short_description = pgettext_lazy('order_models', "State")
OrderModel = deferred.MaterializedModel(BaseOrder)
class OrderPayment(with_metaclass(deferred.ForeignKeyBuilder, models.Model)):
"""
A model to hold received payments for a given order.
"""
order = deferred.ForeignKey(BaseOrder, verbose_name=_("Order"))
amount = MoneyField(_("Amount paid"),
help_text=_("How much was paid with this particular transfer."))
transaction_id = models.CharField(_("Transaction ID"), max_length=255,
help_text=_("The transaction processor's reference"))
created_at = models.DateTimeField(_("Received at"), auto_now_add=True)
payment_method = models.CharField(_("Payment method"), max_length=50,
help_text=_("The payment backend used to process the purchase"))
class Meta:
verbose_name = pgettext_lazy('order_models', "Order payment")
verbose_name_plural = pgettext_lazy('order_models', "Order payments")
@python_2_unicode_compatible
class BaseOrderItem(with_metaclass(deferred.ForeignKeyBuilder, models.Model)):
"""
An item for an order.
"""
order = deferred.ForeignKey(BaseOrder, related_name='items', verbose_name=_("Order"))
product_name = models.CharField(_("Product name"), max_length=255, null=True, blank=True,
help_text=_("Product name at the moment of purchase."))
product_code = models.CharField(_("Product code"), max_length=255, null=True, blank=True,
help_text=_("Product code at the moment of purchase."))
product = deferred.ForeignKey(BaseProduct, null=True, blank=True, on_delete=models.SET_NULL,
verbose_name=_("Product"))
_unit_price = models.DecimalField(_("Unit price"), null=True, # may be NaN
help_text=_("Products unit price at the moment of purchase."), **BaseOrder.decimalfield_kwargs)
_line_total = models.DecimalField(_("Line Total"), null=True, # may be NaN
help_text=_("Line total on the invoice at the moment of purchase."), **BaseOrder.decimalfield_kwargs)
extra = JSONField(verbose_name=_("Extra fields"), default={},
help_text=_("Arbitrary information for this order item"))
class Meta:
abstract = True
verbose_name = _("Order item")
verbose_name_plural = _("Order items")
def __str__(self):
return self.product_name
@classmethod
def perform_model_checks(cls):
try:
cart_field = [f for f in CartItemModel._meta.fields if f.attname == 'quantity'][0]
order_field = [f for f in cls._meta.fields if f.attname == 'quantity'][0]
if order_field.get_internal_type() != cart_field.get_internal_type():
msg = "Field `{}.quantity` must be of one same type `{}.quantity`."
raise ImproperlyConfigured(msg.format(cls.__name__, CartItemModel.__name__))
except IndexError:
msg = "Class `{}` must implement a field named `quantity`."
raise ImproperlyConfigured(msg.format(cls.__name__))
@property
def unit_price(self):
return MoneyMaker(self.order.currency)(self._unit_price)
@property
def line_total(self):
return MoneyMaker(self.order.currency)(self._line_total)
def populate_from_cart_item(self, cart_item, request):
"""
From a given cart item, populate the current order item.
If the operation was successful, the given item shall be removed from the cart.
If a CartItem.DoesNotExist exception is raised, discard the order item.
"""
if cart_item.quantity == 0:
raise CartItemModel.DoesNotExist("Cart Item is on the Wish List")
self.product = cart_item.product
# for historical integrity, store the product's name and price at the moment of purchase
self.product_name = cart_item.product.product_name
self._unit_price = Decimal(cart_item.product.get_price(request))
self._line_total = Decimal(cart_item.line_total)
self.quantity = cart_item.quantity
self.extra = dict(cart_item.extra)
extra_rows = [(modifier, extra_row.data) for modifier, extra_row in cart_item.extra_rows.items()]
self.extra.update(rows=extra_rows)
def save(self, *args, **kwargs):
"""
Before saving the OrderItem object to the database, round the amounts to the given decimal places
"""
self._unit_price = BaseOrder.round_amount(self._unit_price)
self._line_total = BaseOrder.round_amount(self._line_total)
super(BaseOrderItem, self).save(*args, **kwargs)
OrderItemModel = deferred.MaterializedModel(BaseOrderItem)<|fim▁end|> | if set(TRANSITION_TARGETS.keys()).intersection(attrs['_transition_targets']):
msg = "Mixin class {} already contains a transition named '{}'" |
<|file_name|>ForceTorqueSensorHandle.java<|end_file_name|><|fim▁begin|>package us.ihmc.rosControl.wholeRobot;
public interface ForceTorqueSensorHandle
{
double getTz();
double getTy();
double getTx();
double getFz();
double getFy();
double getFx();<|fim▁hole|>}<|fim▁end|> |
String getName();
|
<|file_name|>sensor.rs<|end_file_name|><|fim▁begin|>extern crate libbeaglebone;
<|fim▁hole|>use std::thread;
use std::time::Duration;
fn main() {
// Create a new ADC object using AIN-0 and a scaling factor of 0.
let sensor = ADC::new(AIN_0, 0.0);
// Read from the ADC object every 50ms 100 times, and print out the value.
for _ in 1..101 {
println!("{}", sensor.read().unwrap());
thread::sleep(Duration::from_millis(50));
}
}<|fim▁end|> | use libbeaglebone::prelude::*; |
<|file_name|>keyframes_rule.rs<|end_file_name|><|fim▁begin|>/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
//! Keyframes: https://drafts.csswg.org/css-animations/#keyframes
use cssparser::{parse_one_rule, DeclarationListParser, DeclarationParser, SourceLocation, Token};
use cssparser::{AtRuleParser, CowRcStr, Parser, ParserInput, QualifiedRuleParser, RuleListParser};
use error_reporting::ContextualParseError;
use parser::ParserContext;
use properties::longhands::transition_timing_function::single_value::SpecifiedValue as SpecifiedTimingFunction;
use properties::LonghandIdSet;
use properties::{Importance, PropertyDeclaration};
use properties::{LonghandId, PropertyDeclarationBlock, PropertyId};
use properties::{PropertyDeclarationId, SourcePropertyDeclaration};
use servo_arc::Arc;
use shared_lock::{DeepCloneParams, DeepCloneWithLock, SharedRwLock, SharedRwLockReadGuard};
use shared_lock::{Locked, ToCssWithGuard};
use std::fmt::{self, Write};
use str::CssStringWriter;
use style_traits::{CssWriter, ParseError, ParsingMode, StyleParseErrorKind, ToCss};
use stylesheets::rule_parser::VendorPrefix;
use stylesheets::{CssRuleType, StylesheetContents};
use values::{serialize_percentage, KeyframesName};
/// A [`@keyframes`][keyframes] rule.
///
/// [keyframes]: https://drafts.csswg.org/css-animations/#keyframes
#[derive(Debug)]
pub struct KeyframesRule {
/// The name of the current animation.
pub name: KeyframesName,<|fim▁hole|> /// Vendor prefix type the @keyframes has.
pub vendor_prefix: Option<VendorPrefix>,
/// The line and column of the rule's source code.
pub source_location: SourceLocation,
}
impl ToCssWithGuard for KeyframesRule {
// Serialization of KeyframesRule is not specced.
fn to_css(&self, guard: &SharedRwLockReadGuard, dest: &mut CssStringWriter) -> fmt::Result {
dest.write_str("@keyframes ")?;
self.name.to_css(&mut CssWriter::new(dest))?;
dest.write_str(" {")?;
let iter = self.keyframes.iter();
for lock in iter {
dest.write_str("\n")?;
let keyframe = lock.read_with(&guard);
keyframe.to_css(guard, dest)?;
}
dest.write_str("\n}")
}
}
impl KeyframesRule {
/// Returns the index of the last keyframe that matches the given selector.
/// If the selector is not valid, or no keyframe is found, returns None.
///
/// Related spec:
/// <https://drafts.csswg.org/css-animations-1/#interface-csskeyframesrule-findrule>
pub fn find_rule(&self, guard: &SharedRwLockReadGuard, selector: &str) -> Option<usize> {
let mut input = ParserInput::new(selector);
if let Ok(selector) = Parser::new(&mut input).parse_entirely(KeyframeSelector::parse) {
for (i, keyframe) in self.keyframes.iter().enumerate().rev() {
if keyframe.read_with(guard).selector == selector {
return Some(i);
}
}
}
None
}
}
impl DeepCloneWithLock for KeyframesRule {
fn deep_clone_with_lock(
&self,
lock: &SharedRwLock,
guard: &SharedRwLockReadGuard,
params: &DeepCloneParams,
) -> Self {
KeyframesRule {
name: self.name.clone(),
keyframes: self
.keyframes
.iter()
.map(|x| {
Arc::new(
lock.wrap(x.read_with(guard).deep_clone_with_lock(lock, guard, params)),
)
})
.collect(),
vendor_prefix: self.vendor_prefix.clone(),
source_location: self.source_location.clone(),
}
}
}
/// A number from 0 to 1, indicating the percentage of the animation when this
/// keyframe should run.
#[derive(Clone, Copy, Debug, MallocSizeOf, PartialEq, PartialOrd)]
pub struct KeyframePercentage(pub f32);
impl ::std::cmp::Ord for KeyframePercentage {
#[inline]
fn cmp(&self, other: &Self) -> ::std::cmp::Ordering {
// We know we have a number from 0 to 1, so unwrap() here is safe.
self.0.partial_cmp(&other.0).unwrap()
}
}
impl ::std::cmp::Eq for KeyframePercentage {}
impl ToCss for KeyframePercentage {
fn to_css<W>(&self, dest: &mut CssWriter<W>) -> fmt::Result
where
W: Write,
{
serialize_percentage(self.0, dest)
}
}
impl KeyframePercentage {
/// Trivially constructs a new `KeyframePercentage`.
#[inline]
pub fn new(value: f32) -> KeyframePercentage {
debug_assert!(value >= 0. && value <= 1.);
KeyframePercentage(value)
}
fn parse<'i, 't>(input: &mut Parser<'i, 't>) -> Result<KeyframePercentage, ParseError<'i>> {
let token = input.next()?.clone();
match token {
Token::Ident(ref identifier) if identifier.as_ref().eq_ignore_ascii_case("from") => {
Ok(KeyframePercentage::new(0.))
},
Token::Ident(ref identifier) if identifier.as_ref().eq_ignore_ascii_case("to") => {
Ok(KeyframePercentage::new(1.))
},
Token::Percentage {
unit_value: percentage,
..
}
if percentage >= 0. && percentage <= 1. =>
{
Ok(KeyframePercentage::new(percentage))
},
_ => Err(input.new_unexpected_token_error(token)),
}
}
}
/// A keyframes selector is a list of percentages or from/to symbols, which are
/// converted at parse time to percentages.
#[css(comma)]
#[derive(Clone, Debug, Eq, PartialEq, ToCss)]
pub struct KeyframeSelector(#[css(iterable)] Vec<KeyframePercentage>);
impl KeyframeSelector {
/// Return the list of percentages this selector contains.
#[inline]
pub fn percentages(&self) -> &[KeyframePercentage] {
&self.0
}
/// A dummy public function so we can write a unit test for this.
pub fn new_for_unit_testing(percentages: Vec<KeyframePercentage>) -> KeyframeSelector {
KeyframeSelector(percentages)
}
/// Parse a keyframe selector from CSS input.
pub fn parse<'i, 't>(input: &mut Parser<'i, 't>) -> Result<Self, ParseError<'i>> {
input
.parse_comma_separated(KeyframePercentage::parse)
.map(KeyframeSelector)
}
}
/// A keyframe.
#[derive(Debug)]
pub struct Keyframe {
/// The selector this keyframe was specified from.
pub selector: KeyframeSelector,
/// The declaration block that was declared inside this keyframe.
///
/// Note that `!important` rules in keyframes don't apply, but we keep this
/// `Arc` just for convenience.
pub block: Arc<Locked<PropertyDeclarationBlock>>,
/// The line and column of the rule's source code.
pub source_location: SourceLocation,
}
impl ToCssWithGuard for Keyframe {
fn to_css(&self, guard: &SharedRwLockReadGuard, dest: &mut CssStringWriter) -> fmt::Result {
self.selector.to_css(&mut CssWriter::new(dest))?;
dest.write_str(" { ")?;
self.block.read_with(guard).to_css(dest)?;
dest.write_str(" }")?;
Ok(())
}
}
impl Keyframe {
/// Parse a CSS keyframe.
pub fn parse<'i>(
css: &'i str,
parent_stylesheet_contents: &StylesheetContents,
lock: &SharedRwLock,
) -> Result<Arc<Locked<Self>>, ParseError<'i>> {
let url_data = parent_stylesheet_contents.url_data.read();
let namespaces = parent_stylesheet_contents.namespaces.read();
let mut context = ParserContext::new(
parent_stylesheet_contents.origin,
&url_data,
Some(CssRuleType::Keyframe),
ParsingMode::DEFAULT,
parent_stylesheet_contents.quirks_mode,
None,
None,
);
context.namespaces = Some(&*namespaces);
let mut input = ParserInput::new(css);
let mut input = Parser::new(&mut input);
let mut declarations = SourcePropertyDeclaration::new();
let mut rule_parser = KeyframeListParser {
context: &context,
shared_lock: &lock,
declarations: &mut declarations,
};
parse_one_rule(&mut input, &mut rule_parser)
}
}
impl DeepCloneWithLock for Keyframe {
/// Deep clones this Keyframe.
fn deep_clone_with_lock(
&self,
lock: &SharedRwLock,
guard: &SharedRwLockReadGuard,
_params: &DeepCloneParams,
) -> Keyframe {
Keyframe {
selector: self.selector.clone(),
block: Arc::new(lock.wrap(self.block.read_with(guard).clone())),
source_location: self.source_location.clone(),
}
}
}
/// A keyframes step value. This can be a synthetised keyframes animation, that
/// is, one autogenerated from the current computed values, or a list of
/// declarations to apply.
///
/// TODO: Find a better name for this?
#[derive(Clone, Debug, MallocSizeOf)]
pub enum KeyframesStepValue {
/// A step formed by a declaration block specified by the CSS.
Declarations {
/// The declaration block per se.
#[cfg_attr(
feature = "gecko",
ignore_malloc_size_of = "XXX: Primary ref, measure if DMD says it's worthwhile"
)]
#[cfg_attr(feature = "servo", ignore_malloc_size_of = "Arc")]
block: Arc<Locked<PropertyDeclarationBlock>>,
},
/// A synthetic step computed from the current computed values at the time
/// of the animation.
ComputedValues,
}
/// A single step from a keyframe animation.
#[derive(Clone, Debug, MallocSizeOf)]
pub struct KeyframesStep {
/// The percentage of the animation duration when this step starts.
pub start_percentage: KeyframePercentage,
/// Declarations that will determine the final style during the step, or
/// `ComputedValues` if this is an autogenerated step.
pub value: KeyframesStepValue,
/// Wether a animation-timing-function declaration exists in the list of
/// declarations.
///
/// This is used to know when to override the keyframe animation style.
pub declared_timing_function: bool,
}
impl KeyframesStep {
#[inline]
fn new(
percentage: KeyframePercentage,
value: KeyframesStepValue,
guard: &SharedRwLockReadGuard,
) -> Self {
let declared_timing_function = match value {
KeyframesStepValue::Declarations { ref block } => block
.read_with(guard)
.declarations()
.iter()
.any(|prop_decl| match *prop_decl {
PropertyDeclaration::AnimationTimingFunction(..) => true,
_ => false,
}),
_ => false,
};
KeyframesStep {
start_percentage: percentage,
value: value,
declared_timing_function: declared_timing_function,
}
}
/// Return specified TransitionTimingFunction if this KeyframesSteps has 'animation-timing-function'.
pub fn get_animation_timing_function(
&self,
guard: &SharedRwLockReadGuard,
) -> Option<SpecifiedTimingFunction> {
if !self.declared_timing_function {
return None;
}
match self.value {
KeyframesStepValue::Declarations { ref block } => {
let guard = block.read_with(guard);
let (declaration, _) = guard
.get(PropertyDeclarationId::Longhand(
LonghandId::AnimationTimingFunction,
))
.unwrap();
match *declaration {
PropertyDeclaration::AnimationTimingFunction(ref value) => {
// Use the first value.
Some(value.0[0])
},
PropertyDeclaration::CSSWideKeyword(..) => None,
PropertyDeclaration::WithVariables(..) => None,
_ => panic!(),
}
},
KeyframesStepValue::ComputedValues => {
panic!("Shouldn't happen to set animation-timing-function in missing keyframes")
},
}
}
}
/// This structure represents a list of animation steps computed from the list
/// of keyframes, in order.
///
/// It only takes into account animable properties.
#[derive(Clone, Debug, MallocSizeOf)]
pub struct KeyframesAnimation {
/// The difference steps of the animation.
pub steps: Vec<KeyframesStep>,
/// The properties that change in this animation.
pub properties_changed: LonghandIdSet,
/// Vendor prefix type the @keyframes has.
pub vendor_prefix: Option<VendorPrefix>,
}
/// Get all the animated properties in a keyframes animation.
fn get_animated_properties(
keyframes: &[Arc<Locked<Keyframe>>],
guard: &SharedRwLockReadGuard,
) -> LonghandIdSet {
let mut ret = LonghandIdSet::new();
// NB: declarations are already deduplicated, so we don't have to check for
// it here.
for keyframe in keyframes {
let keyframe = keyframe.read_with(&guard);
let block = keyframe.block.read_with(guard);
// CSS Animations spec clearly defines that properties with !important
// in keyframe rules are invalid and ignored, but it's still ambiguous
// whether we should drop the !important properties or retain the
// properties when they are set via CSSOM. So we assume there might
// be properties with !important in keyframe rules here.
// See the spec issue https://github.com/w3c/csswg-drafts/issues/1824
for declaration in block.normal_declaration_iter() {
let longhand_id = match declaration.id() {
PropertyDeclarationId::Longhand(id) => id,
_ => continue,
};
if longhand_id == LonghandId::Display {
continue;
}
if !longhand_id.is_animatable() {
continue;
}
ret.insert(longhand_id);
}
}
ret
}
impl KeyframesAnimation {
/// Create a keyframes animation from a given list of keyframes.
///
/// This will return a keyframe animation with empty steps and
/// properties_changed if the list of keyframes is empty, or there are no
/// animated properties obtained from the keyframes.
///
/// Otherwise, this will compute and sort the steps used for the animation,
/// and return the animation object.
pub fn from_keyframes(
keyframes: &[Arc<Locked<Keyframe>>],
vendor_prefix: Option<VendorPrefix>,
guard: &SharedRwLockReadGuard,
) -> Self {
let mut result = KeyframesAnimation {
steps: vec![],
properties_changed: LonghandIdSet::new(),
vendor_prefix,
};
if keyframes.is_empty() {
return result;
}
result.properties_changed = get_animated_properties(keyframes, guard);
if result.properties_changed.is_empty() {
return result;
}
for keyframe in keyframes {
let keyframe = keyframe.read_with(&guard);
for percentage in keyframe.selector.0.iter() {
result.steps.push(KeyframesStep::new(
*percentage,
KeyframesStepValue::Declarations {
block: keyframe.block.clone(),
},
guard,
));
}
}
// Sort by the start percentage, so we can easily find a frame.
result.steps.sort_by_key(|step| step.start_percentage);
// Prepend autogenerated keyframes if appropriate.
if result.steps[0].start_percentage.0 != 0. {
result.steps.insert(
0,
KeyframesStep::new(
KeyframePercentage::new(0.),
KeyframesStepValue::ComputedValues,
guard,
),
);
}
if result.steps.last().unwrap().start_percentage.0 != 1. {
result.steps.push(KeyframesStep::new(
KeyframePercentage::new(1.),
KeyframesStepValue::ComputedValues,
guard,
));
}
result
}
}
/// Parses a keyframes list, like:
/// 0%, 50% {
/// width: 50%;
/// }
///
/// 40%, 60%, 100% {
/// width: 100%;
/// }
struct KeyframeListParser<'a> {
context: &'a ParserContext<'a>,
shared_lock: &'a SharedRwLock,
declarations: &'a mut SourcePropertyDeclaration,
}
/// Parses a keyframe list from CSS input.
pub fn parse_keyframe_list(
context: &ParserContext,
input: &mut Parser,
shared_lock: &SharedRwLock,
) -> Vec<Arc<Locked<Keyframe>>> {
debug_assert!(
context.namespaces.is_some(),
"Parsing a keyframe list from a context without namespaces?"
);
let mut declarations = SourcePropertyDeclaration::new();
RuleListParser::new_for_nested_rule(
input,
KeyframeListParser {
context: context,
shared_lock: shared_lock,
declarations: &mut declarations,
},
)
.filter_map(Result::ok)
.collect()
}
impl<'a, 'i> AtRuleParser<'i> for KeyframeListParser<'a> {
type PreludeNoBlock = ();
type PreludeBlock = ();
type AtRule = Arc<Locked<Keyframe>>;
type Error = StyleParseErrorKind<'i>;
}
impl<'a, 'i> QualifiedRuleParser<'i> for KeyframeListParser<'a> {
type Prelude = KeyframeSelector;
type QualifiedRule = Arc<Locked<Keyframe>>;
type Error = StyleParseErrorKind<'i>;
fn parse_prelude<'t>(
&mut self,
input: &mut Parser<'i, 't>,
) -> Result<Self::Prelude, ParseError<'i>> {
let start_position = input.position();
KeyframeSelector::parse(input).map_err(|e| {
let location = e.location;
let error = ContextualParseError::InvalidKeyframeRule(
input.slice_from(start_position),
e.clone(),
);
self.context.log_css_error(location, error);
e
})
}
fn parse_block<'t>(
&mut self,
selector: Self::Prelude,
source_location: SourceLocation,
input: &mut Parser<'i, 't>,
) -> Result<Self::QualifiedRule, ParseError<'i>> {
let context = ParserContext::new_with_rule_type(
self.context,
CssRuleType::Keyframe,
self.context.namespaces.unwrap(),
);
let parser = KeyframeDeclarationParser {
context: &context,
declarations: self.declarations,
};
let mut iter = DeclarationListParser::new(input, parser);
let mut block = PropertyDeclarationBlock::new();
while let Some(declaration) = iter.next() {
match declaration {
Ok(()) => {
block.extend(iter.parser.declarations.drain(), Importance::Normal);
},
Err((error, slice)) => {
iter.parser.declarations.clear();
let location = error.location;
let error =
ContextualParseError::UnsupportedKeyframePropertyDeclaration(slice, error);
context.log_css_error(location, error);
},
}
// `parse_important` is not called here, `!important` is not allowed in keyframe blocks.
}
Ok(Arc::new(self.shared_lock.wrap(Keyframe {
selector,
block: Arc::new(self.shared_lock.wrap(block)),
source_location,
})))
}
}
struct KeyframeDeclarationParser<'a, 'b: 'a> {
context: &'a ParserContext<'b>,
declarations: &'a mut SourcePropertyDeclaration,
}
/// Default methods reject all at rules.
impl<'a, 'b, 'i> AtRuleParser<'i> for KeyframeDeclarationParser<'a, 'b> {
type PreludeNoBlock = ();
type PreludeBlock = ();
type AtRule = ();
type Error = StyleParseErrorKind<'i>;
}
impl<'a, 'b, 'i> DeclarationParser<'i> for KeyframeDeclarationParser<'a, 'b> {
type Declaration = ();
type Error = StyleParseErrorKind<'i>;
fn parse_value<'t>(
&mut self,
name: CowRcStr<'i>,
input: &mut Parser<'i, 't>,
) -> Result<(), ParseError<'i>> {
let id = match PropertyId::parse(&name, self.context) {
Ok(id) => id,
Err(()) => {
return Err(input.new_custom_error(StyleParseErrorKind::UnknownProperty(name)))
},
};
// TODO(emilio): Shouldn't this use parse_entirely?
PropertyDeclaration::parse_into(self.declarations, id, self.context, input)?;
// In case there is still unparsed text in the declaration, we should
// roll back.
input.expect_exhausted()?;
Ok(())
}
}<|fim▁end|> | /// The keyframes specified for this CSS rule.
pub keyframes: Vec<Arc<Locked<Keyframe>>>, |
<|file_name|>fastica_lz.py<|end_file_name|><|fim▁begin|># coding: utf-8
# In[ ]:
import numpy as np
import numexpr as ne
def sym_decorrelation_ne(W):
""" Symmetric decorrelation """
K = np.dot(W, W.T)
s, u = np.linalg.eigh(K)
return (u @ np.diag(1.0/np.sqrt(s)) @ u.T) @ W
# logcosh
def g_logcosh_ne(wx,alpha):
"""derivatives of logcosh"""
return ne.evaluate('tanh(alpha * wx)')
def gprime_logcosh_ne(wx,alpha):
"""second derivatives of logcosh"""
return alpha * (1-ne.evaluate('tanh(alpha*wx)**2'))
# exp
def g_exp_ne(wx,alpha):
"""derivatives of exp"""
return ne.evaluate('wx * exp(-wx**2/2)')
def gprime_exp_ne(wx,alpha):
"""second derivatives of exp"""
return (1-np.square(wx)) * ne.evaluate('exp(-wx**2/2)')
def fastica_s(X, f,alpha=None,n_comp=None,maxit=200, tol=1e-04):
n,p = X.shape
#check if n_comp is valid
if n_comp is None:
n_comp = min(n,p)
elif n_comp > min(n,p):
print("n_comp is too large")
n_comp = min(n,p)
#centering
#by subtracting the mean of each column of X (array).
X = X - X.mean(axis=0)[None,:]
X = X.T
#whitening
s = np.linalg.svd(X @ (X.T) / n)
D = np.diag(1/np.sqrt(s[1]))
k = D @ (s[0].T)
k = k[:n_comp,:]
X1 = k @ X
# initial random weght vector
w_init = np.random.normal(size=(n_comp, n_comp))
W = sym_decorrelation_ne(w_init)
lim = 1
it = 0
# The FastICA algorithm
while lim > tol and it < maxit :
wx = W @ X1
if f =="logcosh":
gwx = g_logcosh_ne(wx,alpha)
g_wx = gprime_logcosh_ne(wx,alpha)
elif f =="exp":
gwx = g_exp_ne(wx,alpha)
g_wx = gprimeg_exp_ne(wx,alpha)
else:
print("doesn't support this approximation negentropy function")
W1 = np.dot(gwx,X1.T)/X1.shape[1] - np.dot(np.diag(g_wx.mean(axis=1)),W)<|fim▁hole|> lim = np.max(np.abs(np.abs(np.diag(W1 @ W.T))) - 1.0)
W = W1
S = W @ X1
#A = np.linalg.inv(W @ k)
return{'X':X1.T,'S':S.T}<|fim▁end|> | W1 = sym_decorrelation_ne(W1)
it = it +1 |
<|file_name|>textpad.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*-
#Ege Öz
from PyQt4 import QtCore, QtGui
import sys,os
try:
_fromUtf8 = QtCore.QString.fromUtf8
except AttributeError:
def _fromUtf8(s):
return s
try:
_encoding = QtGui.QApplication.UnicodeUTF8
def _translate(context, text, disambig):
return QtGui.QApplication.translate(context, text, disambig, _encoding)
except AttributeError:
def _translate(context, text, disambig):
return QtGui.QApplication.translate(context, text, disambig)
class Ui_MainWindow(object):
def setupUi(self, MainWindow):
MainWindow.setObjectName(_fromUtf8("MainWindow"))
MainWindow.resize(661, 440)
icon = QtGui.QIcon.fromTheme(_fromUtf8("text"))
MainWindow.setWindowIcon(icon)
self.centralwidget = QtGui.QWidget(MainWindow)
self.centralwidget.setObjectName(_fromUtf8("centralwidget"))
self.gridLayout = QtGui.QGridLayout(self.centralwidget)
self.gridLayout.setObjectName(_fromUtf8("gridLayout"))
self.textEdit = QtGui.QTextEdit(self.centralwidget)
self.textEdit.setObjectName(_fromUtf8("textEdit"))
font = QtGui.QFont()
font.setFamily(_fromUtf8("Monospace"))
self.textEdit.setFont(font)
self.gridLayout.addWidget(self.textEdit, 0, 0, 1, 1)
MainWindow.setCentralWidget(self.centralwidget)
self.menubar = QtGui.QMenuBar(MainWindow)
self.menubar.setGeometry(QtCore.QRect(0, 0, 661, 20))
self.menubar.setObjectName(_fromUtf8("menubar"))
self.menuFile = QtGui.QMenu(self.menubar)
self.menuFile.setObjectName(_fromUtf8("menuFile"))
self.menuHelp = QtGui.QMenu(self.menubar)
self.menuHelp.setObjectName(_fromUtf8("menuHelp"))
MainWindow.setMenuBar(self.menubar)
self.statusbar = QtGui.QStatusBar(MainWindow)
self.statusbar.setObjectName(_fromUtf8("statusbar"))
MainWindow.setStatusBar(self.statusbar)
self.actionNew = QtGui.QAction(MainWindow)
self.actionNew.setObjectName(_fromUtf8("actionNew"))
self.actionOpen = QtGui.QAction(MainWindow)
self.actionOpen.setObjectName(_fromUtf8("actionOpen"))
self.actionSave = QtGui.QAction(MainWindow)
self.actionSave.setObjectName(_fromUtf8("actionSave"))
self.actionSaveAs = QtGui.QAction(MainWindow)
self.actionSaveAs.setObjectName(_fromUtf8("actionSaveAs"))
self.actionExit = QtGui.QAction(MainWindow)
self.actionExit.setObjectName(_fromUtf8("actionExit"))
self.actionAbout = QtGui.QAction(MainWindow)
self.actionAbout.setObjectName(_fromUtf8("actionAbout"))
self.menuFile.addAction(self.actionNew)
self.menuFile.addAction(self.actionOpen)
self.menuFile.addAction(self.actionSave)
self.menuFile.addAction(self.actionSaveAs)
self.menuFile.addSeparator()
self.menuFile.addAction(self.actionExit)
self.menuHelp.addAction(self.actionAbout)
self.menubar.addAction(self.menuFile.menuAction())
self.menubar.addAction(self.menuHelp.menuAction())
self.actionExit.triggered.connect(self.exitt)
self.actionSave.triggered.connect(self.kaydet)
self.actionSaveAs.triggered.connect(self.fkaydet)
self.actionOpen.triggered.connect(self.ac)
self.actionAbout.triggered.connect(self.hakkinda)
self.actionNew.triggered.connect(self.yeni)
self.retranslateUi(MainWindow)
QtCore.QMetaObject.connectSlotsByName(MainWindow)
def hakkinda(self):
QtGui.QMessageBox.about(None, "About", "Ege Öz 2014")
def yeni(self):
self.textEdit.clear()
def ac(self):
self.afilename = QtGui.QFileDialog.getOpenFileName(None, "Open File", "",os.getenv("USER"))
f=open (self.afilename,"r")
data=f.read()
self.textEdit.setText(data)
f.close()
self.statusbar.showMessage("File opened.")
def kaydet(self):
f=open (self.afilename,"w")
f.write(self.textEdit.toPlainText())
f.close()
self.statusbar.showMessage("File saved.")
def fkaydet(self):
filename = QtGui.QFileDialog.getSaveFileName(None, "Save File", "",os.getenv("USER"))
data=self.textEdit.toPlainText()
f= open (filename,"w")
f.write(data)
f.close()
self.statusbar.showMessage("File saved.")
def exitt(self):
sys.exit()
def retranslateUi(self, MainWindow):
MainWindow.setWindowTitle(_translate("MainWindow", "TextPad", None))
self.menuFile.setTitle(_translate("MainWindow", "File", None))
self.menuHelp.setTitle(_translate("MainWindow", "Help", None))
self.actionNew.setText(_translate("MainWindow", "New", None))
self.actionOpen.setText(_translate("MainWindow", "Open", None))
self.actionSave.setText(_translate("MainWindow", "Save", None))
self.actionSaveAs.setText(_translate("MainWindow", "Save As", None))
self.actionExit.setText(_translate("MainWindow", "Exit", None))
self.actionAbout.setText(_translate("MainWindow", "About", None))
<|fim▁hole|> import sys
app = QtGui.QApplication(sys.argv)
MainWindow = QtGui.QMainWindow()
ui = Ui_MainWindow()
ui.setupUi(MainWindow)
MainWindow.show()
sys.exit(app.exec_())<|fim▁end|> | if __name__ == "__main__": |
<|file_name|>Client.cpp<|end_file_name|><|fim▁begin|>// **********************************************************************
//
// Copyright (c) 2003-2016 ZeroC, Inc. All rights reserved.
//
// **********************************************************************
#include <Ice/Ice.h>
#include <IceGrid/IceGrid.h>
#include <Hello.h>
using namespace std;
using namespace Demo;
class HelloClient : public Ice::Application
{
public:
HelloClient();
virtual int run(int, char*[]);
private:
void menu();
void usage();
};
int
main(int argc, char* argv[])
{
HelloClient app;
return app.main(argc, argv, "config.client");
}
HelloClient::HelloClient() :
//
// Since this is an interactive demo we don't want any signal
// handling.
//
Ice::Application(Ice::NoSignalHandling)
{
}
int
HelloClient::run(int argc, char* argv[])
{
if(argc > 2)
{
usage();
return EXIT_FAILURE;
}
bool addContext = false;
if(argc == 2)
{
if(string(argv[1]) == "--context")
{
addContext = true;
}
else
{
usage();
return EXIT_FAILURE;
}
}
//
// Add the context entry that allows the client to use the locator
//
if(addContext)
{
Ice::LocatorPrx locator = communicator()->getDefaultLocator();
Ice::Context ctx;
ctx["SECRET"] = "LetMeIn";
communicator()->setDefaultLocator(locator->ice_context(ctx));
}<|fim▁hole|> // Now we try to connect to the object with the `hello' identity.
//
HelloPrx hello = HelloPrx::checkedCast(communicator()->stringToProxy("hello"));
if(!hello)
{
cerr << argv[0] << ": couldn't find a `hello' object." << endl;
return EXIT_FAILURE;
}
menu();
char c = 'x';
do
{
try
{
cout << "==> ";
cin >> c;
if(c == 't')
{
hello->sayHello();
}
else if(c == 't')
{
hello->sayHello();
}
else if(c == 's')
{
hello->shutdown();
}
else if(c == 'x')
{
// Nothing to do
}
else if(c == '?')
{
menu();
}
else
{
cout << "unknown command `" << c << "'" << endl;
menu();
}
}
catch(const Ice::Exception& ex)
{
cerr << ex << endl;
}
}
while(cin.good() && c != 'x');
return EXIT_SUCCESS;
}
void
HelloClient::menu()
{
cout <<
"usage:\n"
"t: send greeting\n"
"s: shutdown server\n"
"x: exit\n"
"?: help\n";
}
void
HelloClient::usage()
{
cerr << "Usage: " << appName() << " [--context]" << endl;
}<|fim▁end|> |
// |
<|file_name|>expr-if-unique.rs<|end_file_name|><|fim▁begin|>// run-pass
// Tests for if as expressions returning boxed types<|fim▁hole|>fn test_box() {
let rs: Box<_> = if true { Box::new(100) } else { Box::new(101) };
assert_eq!(*rs, 100);
}
pub fn main() { test_box(); }<|fim▁end|> | |
<|file_name|>l-calc_ja.ts<|end_file_name|><|fim▁begin|><?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE TS>
<TS version="2.1" language="ja_JP">
<context>
<name>XDGDesktopList</name>
<message>
<location filename="../../../core/libLumina/LuminaXDG.cpp" line="608"/>
<source>Multimedia</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../../../core/libLumina/LuminaXDG.cpp" line="609"/>
<source>Development</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../../../core/libLumina/LuminaXDG.cpp" line="610"/>
<source>Education</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../../../core/libLumina/LuminaXDG.cpp" line="611"/>
<source>Games</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../../../core/libLumina/LuminaXDG.cpp" line="612"/>
<source>Graphics</source><|fim▁hole|> <location filename="../../../core/libLumina/LuminaXDG.cpp" line="613"/>
<source>Network</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../../../core/libLumina/LuminaXDG.cpp" line="614"/>
<source>Office</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../../../core/libLumina/LuminaXDG.cpp" line="615"/>
<source>Science</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../../../core/libLumina/LuminaXDG.cpp" line="616"/>
<source>Settings</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../../../core/libLumina/LuminaXDG.cpp" line="617"/>
<source>System</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../../../core/libLumina/LuminaXDG.cpp" line="618"/>
<source>Utility</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../../../core/libLumina/LuminaXDG.cpp" line="619"/>
<source>Wine</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../../../core/libLumina/LuminaXDG.cpp" line="620"/>
<source>Unsorted</source>
<translation type="unfinished"></translation>
</message>
</context>
<context>
<name>mainUI</name>
<message>
<location filename="../mainUI.ui" line="14"/>
<location filename="../mainUI.cpp" line="53"/>
<source>Calculator</source>
<translation>電卓</translation>
</message>
<message>
<location filename="../mainUI.ui" line="657"/>
<source>Advanced Operations</source>
<translation>高度な計算</translation>
</message>
<message>
<location filename="../mainUI.cpp" line="83"/>
<source>Percentage %1</source>
<translation>パーセント %1</translation>
</message>
<message>
<location filename="../mainUI.cpp" line="85"/>
<source>Power %1</source>
<translation>べき乗 %1</translation>
</message>
<message>
<location filename="../mainUI.cpp" line="87"/>
<source>Base-10 Exponential %1</source>
<translation>10が底の指数関数 %1</translation>
</message>
<message>
<location filename="../mainUI.cpp" line="89"/>
<source>Exponential %1</source>
<translation>指数関数 %1</translation>
</message>
<message>
<location filename="../mainUI.cpp" line="91"/>
<source>Constant Pi %1</source>
<translation>円周率π %1</translation>
</message>
<message>
<location filename="../mainUI.cpp" line="94"/>
<source>Square Root %1</source>
<translation>平方根 %1</translation>
</message>
<message>
<location filename="../mainUI.cpp" line="96"/>
<source>Logarithm %1</source>
<translation>対数 %1</translation>
</message>
<message>
<location filename="../mainUI.cpp" line="98"/>
<source>Natural Log %1</source>
<translation>自然対数 %1</translation>
</message>
<message>
<location filename="../mainUI.cpp" line="101"/>
<source>Sine %1</source>
<translation>正弦 %1</translation>
</message>
<message>
<location filename="../mainUI.cpp" line="103"/>
<source>Cosine %1</source>
<translation>余弦 %1</translation>
</message>
<message>
<location filename="../mainUI.cpp" line="105"/>
<source>Tangent %1</source>
<translation>正接 %1</translation>
</message>
<message>
<location filename="../mainUI.cpp" line="108"/>
<source>Arc Sine %1</source>
<translation>逆正弦 %1</translation>
</message>
<message>
<location filename="../mainUI.cpp" line="110"/>
<source>Arc Cosine %1</source>
<translation>逆余弦 %1</translation>
</message>
<message>
<location filename="../mainUI.cpp" line="112"/>
<source>Arc Tangent %1</source>
<translation>逆正接 %1</translation>
</message>
<message>
<location filename="../mainUI.cpp" line="115"/>
<source>Hyperbolic Sine %1</source>
<translation>双曲線正弦 %1</translation>
</message>
<message>
<location filename="../mainUI.cpp" line="117"/>
<source>Hyperbolic Cosine %1</source>
<translation>双曲線余弦 %1</translation>
</message>
<message>
<location filename="../mainUI.cpp" line="119"/>
<source>Hyperbolic Tangent %1</source>
<translation>双曲線正接 %1</translation>
</message>
<message>
<location filename="../mainUI.cpp" line="182"/>
<source>Save Calculator History</source>
<translation>計算履歴を保存</translation>
</message>
</context>
</TS><|fim▁end|> | <translation type="unfinished"></translation>
</message>
<message> |
<|file_name|>Nederlands.nl.ts<|end_file_name|><|fim▁begin|><?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE TS>
<TS version="2.1" language="nl_NL">
<context>
<name>CMS50Serial</name>
<message>
<location filename="../sleepyhead/oximetry.cpp" line="471"/>
<source>Processing...</source>
<translation>Verwerken...</translation>
</message>
<message>
<location filename="../sleepyhead/oximetry.cpp" line="488"/>
<source>Question</source>
<translation>Vraag</translation>
</message>
<message>
<location filename="../sleepyhead/oximetry.cpp" line="488"/>
<source>Did you remember to start your oximeter recording at exactly the same time you started your CPAP machine?</source>
<translation>Heb je eraan gedacht om de oxymeter precies gelijk met je CPAP te starten?</translation>
</message>
<message>
<location filename="../sleepyhead/oximetry.cpp" line="499"/>
<location filename="../sleepyhead/oximetry.cpp" line="505"/>
<source>Information</source>
<translation>Informatie</translation>
</message>
<message>
<location filename="../sleepyhead/oximetry.cpp" line="499"/>
<source>The most recent CPAP Session time has been selected as the start of your oximetry session.
If you forgot to import todays CPAP data first, go and do that now, then import again from your oximeter.</source>
<translation>Het begin van de laatste CPAP sessie is gekozen als start voor je oxymetrie sessie.
Als je bent vergeten om eerst de CPAP data te importeren, doe dat dan nu eerst en dan opnieuw de oxymeter.</translation>
</message>
<message>
<location filename="../sleepyhead/oximetry.cpp" line="505"/>
<source>No valid start time was provided for this oximeter session. You will likely have to adjust your oximeter sessions start time before saving.</source>
<translation>Er is geen geldige starttijd voor deze oxymetrie sessie. Pas de starttijd aan voordat je het opslaat.</translation>
</message>
<message>
<location filename="../sleepyhead/oximetry.cpp" line="738"/>
<source>Please Wait, Importing...</source>
<translation>Even wachten, import loopt...</translation>
</message>
<message>
<location filename="../sleepyhead/oximetry.cpp" line="782"/>
<source>Import Failed. Wait for oximeter and try again.</source>
<translation>Import mislukt, Wacht tot de oxymeter klaar is en probeer het opnieuw.</translation>
</message>
<message>
<location filename="../sleepyhead/oximetry.cpp" line="955"/>
<source>Import Failed</source>
<translation>Import mislukt</translation>
</message>
<message>
<location filename="../sleepyhead/oximetry.cpp" line="959"/>
<source>Set Oximeter to Upload</source>
<translation>Start Upload op de oxymeter</translation>
</message>
</context>
<context>
<name>Daily</name>
<message>
<location filename="../sleepyhead/daily.ui" line="20"/>
<source>Form</source>
<translatorcomment>Staat bovenaan het venster hierboven</translatorcomment>
<translation>Pagina</translation>
</message>
<message>
<location filename="../sleepyhead/daily.ui" line="97"/>
<source>Go to the previous day</source>
<translation>Ga naar de vorige dag met gegevens</translation>
</message>
<message>
<location filename="../sleepyhead/daily.ui" line="116"/>
<source>Prev</source>
<translatorcomment>Niet gezien</translatorcomment>
<translation>Vorige dag</translation>
</message>
<message>
<location filename="../sleepyhead/daily.ui" line="154"/>
<source>Show or hide the calender</source>
<translation>Kalender aan/uit zetten</translation>
</message>
<message>
<location filename="../sleepyhead/daily.ui" line="177"/>
<source>...</source>
<translation>...</translation>
</message>
<message>
<location filename="../sleepyhead/daily.ui" line="217"/>
<source>Go to the next day</source>
<translation>Ga naar de volgende dag met gegevens</translation>
</message>
<message>
<location filename="../sleepyhead/daily.ui" line="239"/>
<source>Next</source>
<translatorcomment>Niet gezien</translatorcomment>
<translation>Volgende</translation>
</message>
<message>
<location filename="../sleepyhead/daily.ui" line="277"/>
<source>Go to the most recent day with data records</source>
<translatorcomment>WJG: compacter</translatorcomment>
<translation>Ga naar de laatste dag met gegevens</translation>
</message>
<message>
<source>Details</source>
<translation type="obsolete">Details</translation>
</message>
<message>
<source>about:blank</source>
<translatorcomment>Niet gezien</translatorcomment>
<translation type="obsolete">about:blank</translation>
</message>
<message>
<location filename="../sleepyhead/daily.ui" line="420"/>
<source>Events</source>
<translatorcomment>WJG: Zou 'Apneus' niet beter zijn dan Gebeurtenissen'? Want dat is wat hier geteld wordt en het past beter op de ruimte van het tabje.
AK: Nee, er zijn ook andere gebeurtenissen: snurken, RERA, enz. Misschien 'evenementen' of 'incidenten'?</translatorcomment>
<translation>Incidenten</translation>
</message>
<message>
<location filename="../sleepyhead/daily.ui" line="479"/>
<source>View Size</source>
<translatorcomment>Onder INCIDENTEN
Misschien is 'Zoomniveau' beter?</translatorcomment>
<translation>Beeldgrootte</translation>
</message>
<message>
<location filename="../sleepyhead/daily.ui" line="524"/>
<location filename="../sleepyhead/daily.ui" line="939"/>
<source>Notes</source>
<translatorcomment>WJG: Is compacter, past beter op tabje
In verband met de koppeling met Bladwijzers, lijkt me 'Notities' beter.</translatorcomment>
<translation>Notities</translation>
</message>
<message>
<location filename="../sleepyhead/daily.ui" line="578"/>
<source>Journal</source>
<translatorcomment>WJG: is gebruikelijker</translatorcomment>
<translation>Dagboek</translation>
</message>
<message>
<location filename="../sleepyhead/daily.ui" line="664"/>
<source>Small</source>
<translation>Klein</translation>
</message>
<message>
<location filename="../sleepyhead/daily.ui" line="669"/>
<source>Medium</source>
<translation>Medium</translation>
</message>
<message>
<location filename="../sleepyhead/daily.ui" line="674"/>
<source>Big</source>
<translation>Groot</translation>
</message>
<message>
<location filename="../sleepyhead/daily.ui" line="644"/>
<source>Color</source>
<translation>Kleur</translation>
</message>
<message>
<location filename="../sleepyhead/daily.ui" line="603"/>
<source> i </source>
<translation> i </translation>
</message>
<message>
<location filename="../sleepyhead/daily.ui" line="606"/>
<source>Ctrl+I</source>
<translatorcomment>Toetsenbord combinatie voor cursief</translatorcomment>
<translation>Ctrl+I</translation>
</message>
<message>
<location filename="../sleepyhead/daily.ui" line="634"/>
<source>u</source>
<translation>u</translation>
</message>
<message>
<location filename="../sleepyhead/daily.ui" line="619"/>
<source>B</source>
<translation>B</translation>
</message>
<message>
<location filename="../sleepyhead/daily.ui" line="622"/>
<source>Ctrl+B</source>
<translatorcomment>Toetsenbord combinatie voor vet</translatorcomment>
<translation>Ctrl+B</translation>
</message>
<message>
<location filename="../sleepyhead/daily.ui" line="733"/>
<source>Zombie</source>
<translation>Zombie</translation>
</message>
<message>
<location filename="../sleepyhead/daily.ui" line="746"/>
<source>I'm feeling...</source>
<translation>Ik voel me ...</translation>
</message>
<message>
<location filename="../sleepyhead/daily.ui" line="762"/>
<source>Weight</source>
<translation>Gewicht</translation>
</message>
<message>
<location filename="../sleepyhead/daily.ui" line="836"/>
<source>Awesome</source>
<translation>Fantastisch</translation>
</message>
<message>
<location filename="../sleepyhead/daily.ui" line="874"/>
<source>B.M.I.</source>
<translatorcomment>zonder puntjes?</translatorcomment>
<translation>BMI</translation>
</message>
<message>
<location filename="../sleepyhead/daily.ui" line="890"/>
<source>Bookmarks</source>
<translation>Bladwijzers</translation>
</message>
<message>
<location filename="../sleepyhead/daily.ui" line="911"/>
<source>Add Bookmark</source>
<translation>Bladwijzer toevoegen</translation>
</message>
<message>
<location filename="../sleepyhead/daily.ui" line="934"/>
<source>Starts</source>
<translatorcomment>WJG: er wordt een punt in de tijd mee aangegeven vanaf wanneer je opmerkingen wilt plaatsen</translatorcomment>
<translation>Vanaf</translation>
</message>
<message>
<location filename="../sleepyhead/daily.ui" line="947"/>
<source>Remove Bookmark</source>
<translation>Bladwijzer verwijderen</translation>
</message>
<message>
<location filename="../sleepyhead/daily.ui" line="997"/>
<source>Zoom fully out</source>
<translation>Volledig uitzoomen</translation>
</message>
<message>
<location filename="../sleepyhead/daily.ui" line="1016"/>
<source>100%</source>
<translation>100%</translation>
</message>
<message>
<location filename="../sleepyhead/daily.ui" line="1026"/>
<source>Reset the graph heights to uniform sizes</source>
<translation>Maak de grafiekhoogtes weer gelijk</translation>
</message>
<message>
<location filename="../sleepyhead/daily.ui" line="1045"/>
<source>Reset</source>
<translation>Reset hoogtes</translation>
</message>
<message>
<location filename="../sleepyhead/daily.ui" line="1106"/>
<source>Drop down this list to show/hide available graphs.</source>
<translatorcomment>WJG: In het Engels ook nogal omslachtig
AK: Wellicht 'beschikbare' ook weglaten, is verwarrend, want de eerste is gelijk een (belangrijke) keuze</translatorcomment>
<translation>Toon/verberg grafieken.</translation>
</message>
<message>
<source>Flow Rate</source>
<translatorcomment>AK: Afgekort wegens ruimtegebrek</translatorcomment>
<translation type="obsolete">Stroomsnelh.</translation>
</message>
<message>
<source>RDI</source>
<translatorcomment>WJG: Wat is RDI?
AK: Respiratory Disturbance Index, iets van Respironics</translatorcomment>
<translation type="obsolete">RDI</translation>
</message>
<message>
<source>AHI</source>
<translation type="obsolete">AHI</translation>
</message>
<message>
<source>Mask Pressure</source>
<translation type="obsolete">Maskerdruk</translation>
</message>
<message>
<source>Pressure</source>
<translation type="obsolete">Druk</translation>
</message>
<message>
<source>Leak</source>
<translation type="obsolete">Lek</translation>
</message>
<message>
<source>Snore</source>
<translation type="obsolete">Snurken</translation>
</message>
<message>
<source>Resp. Rate</source>
<translatorcomment>Afgekort wegens ruimtegebrek</translatorcomment>
<translation type="obsolete">Ademtempo</translation>
</message>
<message>
<source>Tidal Volume</source>
<translation type="obsolete">Teugvolume</translation>
</message>
<message>
<source>Minute Vent.</source>
<translation type="obsolete">Minuutventilatie</translation>
</message>
<message>
<source>Flow Limitation</source>
<translatorcomment>Staat in: Instellingen-Grafieken</translatorcomment>
<translation type="obsolete">Stroombeperk.</translation>
</message>
<message>
<source>Pat. Trig. Breath</source>
<translatorcomment>WJG: te lang, past niet
AK: Heeel moeilijk!</translatorcomment>
<translation type="obsolete">Pat. Veroorz. Ademh.</translation>
</message>
<message>
<source>Resp. Event</source>
<translatorcomment>WJG: Zie 'event'
AK: zie mijn opmerking bij 'event'</translatorcomment>
<translation type="obsolete">Incident</translation>
</message>
<message>
<source>Insp. Time</source>
<translatorcomment>Staat in: Instellingen-Grafieken</translatorcomment>
<translation type="obsolete">Inademtijd</translation>
</message>
<message>
<source>Exp. Time</source>
<translatorcomment>Staat in: Instellingen-Grafieken</translatorcomment>
<translation type="obsolete">Uitademtijd</translation>
</message>
<message>
<source>IE</source>
<translatorcomment>WJG: wat is IE?
AK: Bij een BIPAP Verhouding Inhalatie- Exhalatietijd, dus I/E</translatorcomment>
<translation type="obsolete">I/E</translation>
</message>
<message>
<source>Sleep Stage</source>
<translatorcomment>Staat in: Instellingen-Grafieken</translatorcomment>
<translation type="obsolete">Slaapfase</translation>
</message>
<message>
<location filename="../sleepyhead/daily.cpp" line="169"/>
<source>Breakdown</source>
<translatorcomment>Niet gezien</translatorcomment>
<translation>Verdeling</translation>
</message>
<message>
<location filename="../sleepyhead/daily.cpp" line="169"/>
<source>events</source>
<translation>incidenten</translation>
</message>
<message>
<source>H</source>
<translatorcomment>Letters in de cirkelgrafiek</translatorcomment>
<translation type="obsolete">H</translation>
</message>
<message>
<source>A</source>
<translatorcomment>Letters in de cirkelgrafiek</translatorcomment>
<translation type="obsolete">A</translation>
</message>
<message>
<source>OA</source>
<translatorcomment>Letters in de cirkelgrafiek</translatorcomment>
<translation type="obsolete">OA</translation>
</message>
<message>
<source>CA</source>
<translatorcomment>Letters in de cirkelgrafiek
CA is Clear Airway, wat gelijk staat met Centrale Apneu</translatorcomment>
<translation type="obsolete">CA</translation>
</message>
<message>
<source>RE</source>
<translatorcomment>Letters in de cirkelgrafiek</translatorcomment>
<translation type="obsolete">RE</translation>
</message>
<message>
<source>NR</source>
<translatorcomment>Letters in de cirkelgrafiek</translatorcomment>
<translation type="obsolete">NR</translation>
</message>
<message>
<source>FL</source>
<translatorcomment>Letters in de cirkelgrafiek</translatorcomment>
<translation type="obsolete">FL</translation>
</message>
<message>
<source>PB</source>
<translatorcomment>Letters in de cirkelgrafiek</translatorcomment>
<translation type="obsolete">PB</translation>
</message>
<message>
<source>E</source>
<translatorcomment>Letters in de cirkelgrafiek</translatorcomment>
<translation type="obsolete">E</translation>
</message>
<message>
<source>L</source>
<translatorcomment>Letters in de cirkelgrafiek</translatorcomment>
<translation type="obsolete">L</translation>
</message>
<message>
<source>NRI</source>
<translatorcomment>Letters in de cirkelgrafiek</translatorcomment>
<translation type="obsolete">NRI</translation>
</message>
<message>
<source>VS</source>
<translatorcomment>Letters in de cirkelgrafiek</translatorcomment>
<translation type="obsolete">VS</translation>
</message>
<message>
<source>VS2</source>
<translatorcomment>Letters in de cirkelgrafiek</translatorcomment>
<translation type="obsolete">VS2</translation>
</message>
<message>
<source>UF1</source>
<translatorcomment>Letters in de cirkelgrafiek</translatorcomment>
<translation type="obsolete">UF1</translation>
</message>
<message>
<source>UF2</source>
<translatorcomment>Letters in de cirkelgrafiek</translatorcomment>
<translation type="obsolete">UF2</translation>
</message>
<message>
<source>UF3</source>
<translatorcomment>Letters in de cirkelgrafiek</translatorcomment>
<translation type="obsolete">UF3</translation>
</message>
<message>
<location filename="../sleepyhead/daily.cpp" line="214"/>
<source>Selection AHI</source>
<translation>Selectie AHI</translation>
</message>
<message>
<source>CSR</source>
<translation type="obsolete">CSR</translation>
</message>
<message>
<source>PR</source>
<translation type="obsolete">PR</translation>
</message>
<message>
<location filename="../sleepyhead/daily.cpp" line="238"/>
<source>U1</source>
<translation>U1</translation>
</message>
<message>
<location filename="../sleepyhead/daily.cpp" line="239"/>
<source>U2</source>
<translation>U2</translation>
</message>
<message>
<location filename="../sleepyhead/daily.cpp" line="240"/>
<source>U3</source>
<translation>U3</translation>
</message>
<message>
<source>O2</source>
<translation type="obsolete">O2</translation>
</message>
<message>
<location filename="../sleepyhead/daily.cpp" line="318"/>
<location filename="../sleepyhead/daily.cpp" line="319"/>
<location filename="../sleepyhead/daily.cpp" line="329"/>
<location filename="../sleepyhead/daily.cpp" line="330"/>
<source>Events/hour</source>
<translation>Incidenten/uur</translation>
</message>
<message>
<source>PD</source>
<translation type="obsolete">PD</translation>
</message>
<message>
<source>No Data</source>
<translation type="obsolete">Geen gegevens</translation>
</message>
<message>
<location filename="../sleepyhead/daily.cpp" line="473"/>
<source>No %1 events are recorded this day</source>
<translation>Er zijn vandaag geen %1 incidenten geweest</translation>
</message>
<message>
<location filename="../sleepyhead/daily.cpp" line="569"/>
<source>%1 event</source>
<translation>%1 incident</translation>
</message>
<message>
<location filename="../sleepyhead/daily.cpp" line="570"/>
<source>%1 events</source>
<translation>%1 incidenten</translation>
</message>
<message>
<location filename="../sleepyhead/daily.cpp" line="924"/>
<source>PAP Mode: %1<br/></source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../sleepyhead/daily.cpp" line="1164"/>
<source>Oximetry data exists for this day, but its timestamps are too different, so the Graphs will not be linked.</source>
<translatorcomment>WJG: spelling oxymetrie (zie Van Dale)
AK: mee eens</translatorcomment>
<translation>Oxymetriegegevens beschikbaar, maar de tijden verschillen teveel: de grafieken worden niet verbonden.</translation>
</message>
<message>
<location filename="../sleepyhead/daily.cpp" line="1219"/>
<source>No Graphs :(</source>
<translation>Geen grafieken :(</translation>
</message>
<message>
<source>CPAP</source>
<translation type="obsolete">CPAP</translation>
</message>
<message>
<source>APAP</source>
<translation type="obsolete">APAP</translation>
</message>
<message>
<source>Bi-Level</source>
<translation type="obsolete">BiPAP</translation>
</message>
<message>
<source>ASV</source>
<translatorcomment>Adaptieve ventilatie-instelling ASI?
AK: Hmmm ASV=Adaptive Servo-Ventilation
Maar het is een vierde soort apparaat, tegen Centrale Apneus</translatorcomment>
<translation type="vanished">ASV</translation>
</message>
<message>
<source>Unknown</source>
<translation type="obsolete">Onbekend</translation>
</message>
<message>
<source>Date</source>
<translation type="obsolete">Datum</translation>
</message>
<message>
<location filename="../sleepyhead/daily.cpp" line="1123"/>
<source>Sleep</source>
<translation>Start</translation>
</message>
<message>
<location filename="../sleepyhead/daily.cpp" line="1123"/>
<source>Wake</source>
<translation>Einde</translation>
</message>
<message>
<source>Hypopnea</source>
<translation type="obsolete">Hypopneu (H)</translation>
</message>
<message>
<source>Apnea</source>
<translation type="obsolete">Onbekende apneu (A)</translation>
</message>
<message>
<source>Obstructive</source>
<translatorcomment>AK: nee,Obstructieve is bijv.nw. bij apneu
Toch ief, staat in de tabel</translatorcomment>
<translation type="obsolete">Obstructieve apneu (OA)</translation>
</message>
<message>
<source>Flow Limit</source>
<translatorcomment>AK: Inderdaad, bedoeld wordt een herkende vermindering in luchtstroom, hij gebruikt Flow Limit en -Limitation door elkaar</translatorcomment>
<translation type="obsolete">Stroombeperking (FL)</translation>
</message>
<message>
<source>Clear Airway</source>
<translation type="obsolete">Open luchtweg of Centrale apneu (CA)</translation>
</message>
<message>
<source>User Flags</source>
<translation type="obsolete">Gebruikers vlag (UF)</translation>
</message>
<message>
<source>RERA</source>
<translation type="obsolete">RERA (RE)</translation>
</message>
<message>
<source>VSnore</source>
<translation type="obsolete">VSnore (VS)</translation>
</message>
<message>
<source>VSnore2</source>
<translation type="obsolete">VSnore2</translation>
</message>
<message>
<source>PB/CSR</source>
<translation type="obsolete">PA(PB)/CSR</translation>
</message>
<message>
<source>Exh&nbsp;Puff</source>
<translation type="obsolete">Exh&nbsp;Pufje</translation>
</message>
<message>
<location filename="../sleepyhead/daily.cpp" line="1293"/>
<source>Event Breakdown</source>
<translation>Verdeling incidenten</translation>
</message>
<message>
<location filename="../sleepyhead/daily.cpp" line="1320"/>
<source>Sessions all off!</source>
<translatorcomment>Niet gevonden</translatorcomment>
<translation>Alle sessies uit!</translation>
</message>
<message>
<location filename="../sleepyhead/daily.cpp" line="1321"/>
<source>Sessions exist for this day but are switched off.</source>
<translation>Er zijn wel sessies, maar die staan uit.</translation>
</message>
<message>
<location filename="../sleepyhead/daily.cpp" line="1323"/>
<source>Impossibly short session</source>
<translation>Onmogelijk korte sessie</translation>
</message>
<message>
<location filename="../sleepyhead/daily.cpp" line="1324"/>
<source>Zero hours??</source>
<translation>Nul uren???</translation>
</message>
<message>
<location filename="../sleepyhead/daily.cpp" line="1327"/>
<source>BRICK :(</source>
<translatorcomment>Arie: Als er niets uit komt is het echt fout
Volgens mij zit er een foutje in deze string: dat eerste ( hoort er niet in dacht ik...
Oh, dat is een smiley ;-)</translatorcomment>
<translation>BAKSTEEN :(</translation>
</message>
<message>
<source>Sorry, your machine does not record data.</source>
<translatorcomment>WJG: machine = groter; apparaat gebruikelijker voor dit soort toestellen (zie Van Dale - apparaat, waarbij beademingsapparaat genoemd wordt</translatorcomment>
<translation type="obsolete">Sorry, je apparaat bewaart geen gegevens.</translation>
</message>
<message>
<location filename="../sleepyhead/daily.cpp" line="1329"/>
<source>Complain to your Equipment Provider!</source>
<translation>Klaag bij je leverancier!</translation>
</message><|fim▁hole|> <message>
<location filename="../sleepyhead/daily.cpp" line="1009"/>
<location filename="../sleepyhead/daily.cpp" line="1010"/>
<source>Avg</source>
<translation>Gem.</translation>
</message>
<message>
<location filename="../sleepyhead/daily.cpp" line="1011"/>
<source>Med</source>
<translation>Med.</translation>
</message>
<message>
<location filename="../sleepyhead/daily.cpp" line="1016"/>
<source>Statistics</source>
<translation>Statistieken</translation>
</message>
<message>
<source>Channel</source>
<translation type="obsolete">Kanaal</translation>
</message>
<message>
<source>Min</source>
<translation type="obsolete">Min.</translation>
</message>
<message>
<location filename="../sleepyhead/daily.cpp" line="1021"/>
<source>%1%</source>
<translation>%1%</translation>
</message>
<message>
<source>Max</source>
<translation type="obsolete">Max.</translation>
</message>
<message>
<location filename="../sleepyhead/daily.cpp" line="1094"/>
<source><b>Please Note:</b> This day just contains summary data, only limited information is available .</source>
<translation><b>Let op:</b> Deze dag heeft alleen overzichtsgegevens; alleen beperkte informatie dus.</translation>
</message>
<message>
<location filename="../sleepyhead/daily.cpp" line="1346"/>
<source>No data available</source>
<translation>Geen gegevens beschikbaar</translation>
</message>
<message>
<location filename="../sleepyhead/daily.cpp" line="880"/>
<source>Oximeter Information</source>
<translation>Oxymeterinformatie</translation>
</message>
<message>
<location filename="../sleepyhead/daily.cpp" line="156"/>
<source>Int. Pulse</source>
<translation>Int. polsslag</translation>
</message>
<message>
<location filename="../sleepyhead/daily.cpp" line="157"/>
<source>Int. SpO2</source>
<translation>Int. SpO2</translation>
</message>
<message>
<location filename="../sleepyhead/daily.cpp" line="784"/>
<source>Duration</source>
<translation>Tijdsduur</translation>
</message>
<message>
<location filename="../sleepyhead/daily.cpp" line="796"/>
<source>Oximetery Sessions</source>
<translation>Oxymetrie sessies</translation>
</message>
<message>
<location filename="../sleepyhead/daily.cpp" line="803"/>
<source>Unknown Session</source>
<translation>Onbekende sessie</translation>
</message>
<message>
<location filename="../sleepyhead/daily.cpp" line="884"/>
<source>SpO2 Desaturations</source>
<translatorcomment>WJG: hoofdletter D?</translatorcomment>
<translation>SpO2 desaturaties</translation>
</message>
<message>
<location filename="../sleepyhead/daily.cpp" line="885"/>
<source>Pulse Change events</source>
<translatorcomment>AK: Oei! Bedoeld worden plotselinge, kortdurende wijzigingen in de polsslag. Maar hoe maak je dat kort?</translatorcomment>
<translation>Polsslag incidenten</translation>
</message>
<message>
<location filename="../sleepyhead/daily.cpp" line="886"/>
<source>SpO2 Baseline Used</source>
<translatorcomment>WJG: hoofdletter B?</translatorcomment>
<translation>SpO2 basislijn gebruikt</translation>
</message>
<message>
<location filename="../sleepyhead/daily.cpp" line="851"/>
<source>Machine Settings</source>
<translation>Apparaatinstellingen</translation>
</message>
<message>
<source>Pr. Relief</source>
<translation type="obsolete">Drukvermindering</translation>
</message>
<message>
<source>Humidifier</source>
<translation type="obsolete">Bevochtiger</translation>
</message>
<message>
<location filename="../sleepyhead/daily.cpp" line="765"/>
<source>Session Information</source>
<translation>Sessie-informatie</translation>
</message>
<message>
<source>SessionID</source>
<translation type="obsolete">Sessienummer</translation>
</message>
<message>
<source>On</source>
<translatorcomment>is een schakelaar, beneuwd of het past...</translatorcomment>
<translation type="obsolete">aan/uit</translation>
</message>
<message>
<source>Start</source>
<translation type="obsolete">Start</translation>
</message>
<message>
<source>End</source>
<translation type="obsolete">Einde</translation>
</message>
<message>
<location filename="../sleepyhead/daily.cpp" line="793"/>
<source>CPAP Sessions</source>
<translation>CPAP-sessies</translation>
</message>
<message>
<source>Oximetry Sessions</source>
<translation type="obsolete">Oxymetriesessies</translation>
</message>
<message>
<source>Oximeter</source>
<translation type="obsolete">Oxymeter</translation>
</message>
<message>
<location filename="../sleepyhead/daily.cpp" line="799"/>
<source>Sleep Stage Sessions</source>
<translation>Slaapfasesessies</translation>
</message>
<message>
<location filename="../sleepyhead/daily.cpp" line="841"/>
<source>One or more waveform record for this session had faulty source data. Some waveform overlay points may not match up correctly.</source>
<translatorcomment>WJG: tikfout</translatorcomment>
<translation>Een of meer golfvormgegevens had foutieve brongegevens. Sommige kunnen niet goed aansluiten.</translation>
</message>
<message>
<source>PAP Setting</source>
<translation type="vanished">Instelling PAP</translation>
</message>
<message>
<location filename="../sleepyhead/daily.cpp" line="1328"/>
<source>Sorry, your machine only provides compliance data.</source>
<translation>Sorry, jouw apparaat geeft uitsluitend gegevens over compliantie.</translation>
</message>
<message>
<location filename="../sleepyhead/daily.cpp" line="1614"/>
<source>Pick a Colour</source>
<translation>Kies een kleur</translation>
</message>
<message>
<location filename="../sleepyhead/daily.cpp" line="1865"/>
<source>This bookmarked is in a currently disabled area..</source>
<translation>Deze bladwijzer staat in een uitgeschakeld gebied..</translation>
</message>
<message>
<location filename="../sleepyhead/daily.cpp" line="1883"/>
<source>Bookmark at %1</source>
<translation>Bladwijzer bij %1</translation>
</message>
<message>
<location filename="../sleepyhead/daily.cpp" line="2093"/>
<source>Show all graphs</source>
<translation>Toon alle grafieken</translation>
</message>
<message>
<location filename="../sleepyhead/daily.cpp" line="2099"/>
<source>No Graphs On!</source>
<translation>Alle grafieken staan uit!</translation>
</message>
<message>
<location filename="../sleepyhead/daily.cpp" line="2110"/>
<source>Hide all graphs</source>
<translation>Verberg alle grafieken</translation>
</message>
</context>
<context>
<name>ExportCSV</name>
<message>
<location filename="../sleepyhead/exportcsv.ui" line="14"/>
<source>Export as CSV</source>
<translation>Exporteer naar .csv bestand</translation>
</message>
<message>
<location filename="../sleepyhead/exportcsv.ui" line="24"/>
<source>Dates:</source>
<translation>Periode:</translation>
</message>
<message>
<location filename="../sleepyhead/exportcsv.ui" line="37"/>
<source>Resolution:</source>
<translation>Resolutie:</translation>
</message>
<message>
<location filename="../sleepyhead/exportcsv.ui" line="46"/>
<source>Details</source>
<translation>Details</translation>
</message>
<message>
<location filename="../sleepyhead/exportcsv.ui" line="53"/>
<source>Sessions</source>
<translation>Sessies</translation>
</message>
<message>
<location filename="../sleepyhead/exportcsv.ui" line="60"/>
<source>Daily</source>
<translation>Dagelijks</translation>
</message>
<message>
<location filename="../sleepyhead/exportcsv.ui" line="85"/>
<source>Filename:</source>
<translation>Bestandsnaam:</translation>
</message>
<message>
<location filename="../sleepyhead/exportcsv.ui" line="107"/>
<source>Cancel</source>
<translation>Annuleren</translation>
</message>
<message>
<location filename="../sleepyhead/exportcsv.ui" line="114"/>
<source>Export</source>
<translation>Exporteren</translation>
</message>
<message>
<location filename="../sleepyhead/exportcsv.ui" line="131"/>
<source>Start:</source>
<translation>Start:</translation>
</message>
<message>
<location filename="../sleepyhead/exportcsv.ui" line="154"/>
<source>End:</source>
<translation>Einde:</translation>
</message>
<message>
<location filename="../sleepyhead/exportcsv.ui" line="192"/>
<source>Quick Range:</source>
<translation>Snelkeuze:</translation>
</message>
<message>
<location filename="../sleepyhead/exportcsv.ui" line="200"/>
<location filename="../sleepyhead/exportcsv.cpp" line="59"/>
<location filename="../sleepyhead/exportcsv.cpp" line="113"/>
<source>Most Recent Day</source>
<translatorcomment>WJG: zie ook bij Daily</translatorcomment>
<translation>Meest recente dag</translation>
</message>
<message>
<location filename="../sleepyhead/exportcsv.ui" line="205"/>
<location filename="../sleepyhead/exportcsv.cpp" line="116"/>
<source>Last Week</source>
<translation>Afgelopen week</translation>
</message>
<message>
<location filename="../sleepyhead/exportcsv.ui" line="210"/>
<location filename="../sleepyhead/exportcsv.cpp" line="119"/>
<source>Last Fortnight</source>
<translation>Afgelopen twee weken</translation>
</message>
<message>
<location filename="../sleepyhead/exportcsv.ui" line="215"/>
<location filename="../sleepyhead/exportcsv.cpp" line="122"/>
<source>Last Month</source>
<translation>Afgelopen maand</translation>
</message>
<message>
<location filename="../sleepyhead/exportcsv.ui" line="220"/>
<location filename="../sleepyhead/exportcsv.cpp" line="125"/>
<source>Last 6 Months</source>
<translation>Afgelopen halfjaar</translation>
</message>
<message>
<location filename="../sleepyhead/exportcsv.ui" line="225"/>
<location filename="../sleepyhead/exportcsv.cpp" line="128"/>
<source>Last Year</source>
<translatorcomment>AK: Bij vorig jaar denk ik nu aan 2012. Bedoeld wordt een jaar voor gisteren.... Dat is toch afgelopen jaar?</translatorcomment>
<translation>Afgelopen jaar</translation>
</message>
<message>
<location filename="../sleepyhead/exportcsv.ui" line="230"/>
<location filename="../sleepyhead/exportcsv.cpp" line="110"/>
<source>Everything</source>
<translation>Alles</translation>
</message>
<message>
<location filename="../sleepyhead/exportcsv.ui" line="235"/>
<location filename="../sleepyhead/exportcsv.cpp" line="99"/>
<source>Custom</source>
<translation>Zelf kiezen</translation>
</message>
<message>
<location filename="../sleepyhead/exportcsv.ui" line="248"/>
<source>...</source>
<translation>...</translation>
</message>
<message>
<location filename="../sleepyhead/exportcsv.cpp" line="72"/>
<source>SleepyHead_</source>
<translation>SleepyHead_</translation>
</message>
<message>
<location filename="../sleepyhead/exportcsv.cpp" line="75"/>
<source>Details_</source>
<translation>Details_</translation>
</message>
<message>
<location filename="../sleepyhead/exportcsv.cpp" line="76"/>
<source>Sessions_</source>
<translatorcomment>WJG: Engels is meervoud
AK: Wat betekent het streepje erachter?
Het zit in de bestandsnaam, het streepje is een spatie</translatorcomment>
<translation>Sessies_</translation>
</message>
<message>
<location filename="../sleepyhead/exportcsv.cpp" line="77"/>
<source>Summary_</source>
<translation>Overzicht_</translation>
</message>
<message>
<location filename="../sleepyhead/exportcsv.cpp" line="82"/>
<source>Select file to export to</source>
<translation>Kies exportbestand</translation>
</message>
<message>
<location filename="../sleepyhead/exportcsv.cpp" line="82"/>
<source>CSV Files (*.csv)</source>
<translatorcomment>bestandstype</translatorcomment>
<translation>CSV bestanden (*.csv)</translation>
</message>
<message>
<location filename="../sleepyhead/exportcsv.cpp" line="186"/>
<source>DateTime</source>
<translation>Datum-Tijd</translation>
</message>
<message>
<location filename="../sleepyhead/exportcsv.cpp" line="186"/>
<location filename="../sleepyhead/exportcsv.cpp" line="191"/>
<source>Session</source>
<translation>Sessie</translation>
</message>
<message>
<location filename="../sleepyhead/exportcsv.cpp" line="186"/>
<source>Event</source>
<translation>Incident</translation>
</message>
<message>
<location filename="../sleepyhead/exportcsv.cpp" line="186"/>
<source>Data/Duration</source>
<translation>Gegevens/duur</translation>
</message>
<message>
<location filename="../sleepyhead/exportcsv.cpp" line="189"/>
<location filename="../sleepyhead/exportcsv.cpp" line="191"/>
<source>Date</source>
<translation>Datum</translation>
</message>
<message>
<location filename="../sleepyhead/exportcsv.cpp" line="189"/>
<source>Session Count</source>
<translation>Aantal sessies</translation>
</message>
<message>
<location filename="../sleepyhead/exportcsv.cpp" line="189"/>
<location filename="../sleepyhead/exportcsv.cpp" line="191"/>
<source>Start</source>
<translation>Start</translation>
</message>
<message>
<location filename="../sleepyhead/exportcsv.cpp" line="189"/>
<location filename="../sleepyhead/exportcsv.cpp" line="191"/>
<source>End</source>
<translation>Einde</translation>
</message>
<message>
<location filename="../sleepyhead/exportcsv.cpp" line="189"/>
<location filename="../sleepyhead/exportcsv.cpp" line="191"/>
<source>Total Time</source>
<translation>Totale tijdsduur</translation>
</message>
<message>
<location filename="../sleepyhead/exportcsv.cpp" line="189"/>
<location filename="../sleepyhead/exportcsv.cpp" line="191"/>
<source>AHI</source>
<translation>AHI</translation>
</message>
<message>
<location filename="../sleepyhead/exportcsv.cpp" line="194"/>
<source> Count</source>
<translation> Aantal</translation>
</message>
<message>
<location filename="../sleepyhead/exportcsv.cpp" line="196"/>
<source> Avg</source>
<translation> Gem.</translation>
</message>
<message>
<location filename="../sleepyhead/exportcsv.cpp" line="198"/>
<source> %1%</source>
<translation> %1%</translation>
</message>
</context>
<context>
<name>MainWindow</name>
<message>
<location filename="../sleepyhead/mainwindow.ui" line="26"/>
<source>SleepyHead</source>
<translatorcomment>AK: Ik ben van mening dat we de naam niet moeten vertalen</translatorcomment>
<translation>SleepyHead</translation>
</message>
<message>
<location filename="../sleepyhead/mainwindow.ui" line="103"/>
<source>&Statistics</source>
<translation>&Statistieken</translation>
</message>
<message>
<location filename="../sleepyhead/mainwindow.ui" line="125"/>
<location filename="../sleepyhead/mainwindow.ui" line="2029"/>
<location filename="../sleepyhead/mainwindow.ui" line="2086"/>
<source>about:blank</source>
<translation>about:blank</translation>
</message>
<message>
<location filename="../sleepyhead/mainwindow.ui" line="140"/>
<source>&Help Browser</source>
<translatorcomment>AK: Volgens mij brengt dit je naar: "Over SleepyHead".
20/9 WJG: is dat niet gewoon wat er helemaal boven in de menubalk staat,ongeacht waar je in het programma bent?
AK: klopt</translatorcomment>
<translation>&Over SleepyHead</translation>
</message>
<message>
<location filename="../sleepyhead/mainwindow.ui" line="208"/>
<location filename="../sleepyhead/mainwindow.ui" line="228"/>
<location filename="../sleepyhead/mainwindow.ui" line="248"/>
<location filename="../sleepyhead/mainwindow.ui" line="1911"/>
<source>...</source>
<translation>...</translation>
</message>
<message>
<location filename="../sleepyhead/mainwindow.ui" line="297"/>
<source>qrc:/docs/index.html</source>
<translatorcomment>geen idee!</translatorcomment>
<translation>qrc:/docs/index.html</translation>
</message>
<message>
<location filename="../sleepyhead/mainwindow.ui" line="585"/>
<source>&Navigation</source>
<translation>&Navigatie</translation>
</message>
<message>
<location filename="../sleepyhead/mainwindow.ui" line="612"/>
<source>Statistics</source>
<translation>Statistieken</translation>
</message>
<message>
<location filename="../sleepyhead/mainwindow.ui" line="662"/>
<source>Daily</source>
<translation>Dagelijks</translation>
</message>
<message>
<location filename="../sleepyhead/mainwindow.ui" line="706"/>
<source>Overview</source>
<translation>Overzicht</translation>
</message>
<message>
<location filename="../sleepyhead/mainwindow.ui" line="750"/>
<source>Oximetry</source>
<translation>Oxymetrie</translation>
</message>
<message>
<location filename="../sleepyhead/mainwindow.ui" line="800"/>
<source>Import</source>
<translation>Gegevens
importeren</translation>
</message>
<message>
<location filename="../sleepyhead/mainwindow.ui" line="850"/>
<source>Help</source>
<translation>Over SleepyHead</translation>
</message>
<message>
<location filename="../sleepyhead/mainwindow.ui" line="972"/>
<source>&Bookmarks</source>
<translatorcomment>AK: Beter B&ladwijzers en &Bestand</translatorcomment>
<translation>B&ladwijzers</translation>
</message>
<message>
<location filename="../sleepyhead/mainwindow.ui" line="2056"/>
<source>&Records</source>
<translation>&Erelijst</translation>
</message>
<message>
<location filename="../sleepyhead/mainwindow.ui" line="2115"/>
<source>&File</source>
<translatorcomment>WJG: Onderstreepte letter kan geen B zijn, is al gebruikt bij Bladwijzers
AK: Dan zou ik het andersom doen: B&ladwijzers</translatorcomment>
<translation>&Bestand</translation>
</message>
<message>
<location filename="../sleepyhead/mainwindow.ui" line="2131"/>
<source>&View</source>
<translation>&Weergave</translation>
</message>
<message>
<location filename="../sleepyhead/mainwindow.ui" line="2148"/>
<source>&Help</source>
<translation>&Help</translation>
</message>
<message>
<location filename="../sleepyhead/mainwindow.ui" line="2164"/>
<source>&Data</source>
<translation>&Gegevens</translation>
</message>
<message>
<location filename="../sleepyhead/mainwindow.ui" line="2168"/>
<source>&Advanced</source>
<translation>Ge&avanceerd</translation>
</message>
<message>
<location filename="../sleepyhead/mainwindow.ui" line="2172"/>
<source>&Purge CPAP Data</source>
<translatorcomment>WJG: W is al gebruikt bij Weergave</translatorcomment>
<translation>Wis &CPAP gegevens</translation>
</message>
<message>
<location filename="../sleepyhead/mainwindow.ui" line="2196"/>
<source>&Import Data</source>
<translation>Gegevens &importeren</translation>
</message>
<message>
<location filename="../sleepyhead/mainwindow.ui" line="2199"/>
<source>Shift+F2</source>
<translation>Shift+F2</translation>
</message>
<message>
<location filename="../sleepyhead/mainwindow.ui" line="2204"/>
<source>&Preferences</source>
<translatorcomment>WJG: i is al gebruikt bij Gegevens importeren</translatorcomment>
<translation>I&nstellingen</translation>
</message>
<message>
<location filename="../sleepyhead/mainwindow.ui" line="2209"/>
<source>&Profiles</source>
<translation>&Profielen</translation>
</message>
<message>
<location filename="../sleepyhead/mainwindow.ui" line="2214"/>
<location filename="../sleepyhead/mainwindow.cpp" line="171"/>
<source>E&xit</source>
<translation>E&xit</translation>
</message>
<message>
<location filename="../sleepyhead/mainwindow.ui" line="2219"/>
<source>View &Daily</source>
<translatorcomment>20/9 WJG: aangepast na compilatie</translatorcomment>
<translation>&Dagweergave</translation>
</message>
<message>
<location filename="../sleepyhead/mainwindow.ui" line="2222"/>
<source>F5</source>
<translation>F5</translation>
</message>
<message>
<location filename="../sleepyhead/mainwindow.ui" line="2227"/>
<source>View &Overview</source>
<translation>&Overzichtpagina</translation>
</message>
<message>
<location filename="../sleepyhead/mainwindow.ui" line="2230"/>
<source>F6</source>
<translation>F6</translation>
</message>
<message>
<location filename="../sleepyhead/mainwindow.ui" line="2235"/>
<source>View &Welcome</source>
<translatorcomment>WJG: Om de al gebruikte W te omzeilen
AK: Waar staat dat Welkomst-/Startscherm???
20/9 WJG: Goeie vraag, waarschijnlijk dateert dat nog uit een oudere versie en heeft Mark dat niet opgeruimd?</translatorcomment>
<translation variants="yes">
<lengthvariant>&Welkomstscherm</lengthvariant>
<lengthvariant>&Startscherm</lengthvariant>
</translation>
</message>
<message>
<location filename="../sleepyhead/mainwindow.ui" line="2238"/>
<location filename="../sleepyhead/mainwindow.ui" line="2379"/>
<source>F4</source>
<translation>F4</translation>
</message>
<message>
<location filename="../sleepyhead/mainwindow.ui" line="2243"/>
<source>-</source>
<translation>-</translation>
</message>
<message>
<location filename="../sleepyhead/mainwindow.ui" line="2246"/>
<source>Ctrl+Tab</source>
<translation>Ctrl+Tab</translation>
</message>
<message>
<location filename="../sleepyhead/mainwindow.ui" line="2254"/>
<source>Use &AntiAliasing</source>
<translation>Gebruik &AntiAliasing</translation>
</message>
<message>
<location filename="../sleepyhead/mainwindow.ui" line="2259"/>
<source>&About SleepyHead</source>
<translatorcomment>WJG: O is al gebruikt</translatorcomment>
<translation>Over &SleepyHead</translation>
</message>
<message>
<location filename="../sleepyhead/mainwindow.ui" line="2267"/>
<source>&Fullscreen Toggle</source>
<translation>&Volledig scherm aan/uit</translation>
</message>
<message>
<location filename="../sleepyhead/mainwindow.ui" line="2270"/>
<source>F11</source>
<translation>F11</translation>
</message>
<message>
<location filename="../sleepyhead/mainwindow.ui" line="2278"/>
<source>Show Debug Pane</source>
<translation>Foutopsporingsvenster</translation>
</message>
<message>
<location filename="../sleepyhead/mainwindow.ui" line="2283"/>
<source>&Reset Graph Layout</source>
<translation>&Reset alle grafieken</translation>
</message>
<message>
<location filename="../sleepyhead/mainwindow.ui" line="2288"/>
<location filename="../sleepyhead/mainwindow.cpp" line="169"/>
<source>Check for &Updates</source>
<translation>Zoek naar &updates</translation>
</message>
<message>
<location filename="../sleepyhead/mainwindow.ui" line="2293"/>
<source>Take &Screenshot</source>
<translation>&Schermopname maken</translation>
</message>
<message>
<location filename="../sleepyhead/mainwindow.ui" line="2296"/>
<source>F12</source>
<translation>F12</translation>
</message>
<message>
<location filename="../sleepyhead/mainwindow.ui" line="2301"/>
<source>View O&ximetry</source>
<translation>O&xymetrievenster</translation>
</message>
<message>
<location filename="../sleepyhead/mainwindow.ui" line="2304"/>
<source>F7</source>
<translation>F7</translation>
</message>
<message>
<location filename="../sleepyhead/mainwindow.ui" line="2309"/>
<source>Print &Report</source>
<translation>&Rapport afdrukken</translation>
</message>
<message>
<location filename="../sleepyhead/mainwindow.ui" line="2314"/>
<source>&Edit Profile</source>
<translation>Profiel &aanpassen</translation>
</message>
<message>
<location filename="../sleepyhead/mainwindow.ui" line="2322"/>
<source>&Link Graph Groups</source>
<translation>Grafiekgroepen &koppelen</translation>
</message>
<message>
<location filename="../sleepyhead/mainwindow.ui" line="2327"/>
<source>Exp&ort</source>
<translation>Exp&orteer</translation>
</message>
<message>
<location filename="../sleepyhead/mainwindow.ui" line="2332"/>
<source>Online Users &Guide</source>
<translation>Online &gebruiksaanwijzing</translation>
</message>
<message>
<location filename="../sleepyhead/mainwindow.ui" line="2337"/>
<source>&Frequently Asked Questions</source>
<translation>&FAQ</translation>
</message>
<message>
<location filename="../sleepyhead/mainwindow.ui" line="2342"/>
<source>&Rebuild Oximetry Indices</source>
<translation>Oxymetrie-indexen &herstellen</translation>
</message>
<message>
<location filename="../sleepyhead/mainwindow.ui" line="2347"/>
<source>Change &User</source>
<translation>Ander &profiel</translation>
</message>
<message>
<location filename="../sleepyhead/mainwindow.ui" line="2352"/>
<source>&Current Selected Day</source>
<translation>&Geselecteerde dag</translation>
</message>
<message>
<location filename="../sleepyhead/mainwindow.ui" line="2357"/>
<source>All data for current CPAP machine</source>
<translation>Alle gegevens van dit apparaat</translation>
</message>
<message>
<location filename="../sleepyhead/mainwindow.ui" line="2368"/>
<source>Right &Sidebar</source>
<translation>&Rechter zijbalk aan/uit</translation>
</message>
<message>
<location filename="../sleepyhead/mainwindow.ui" line="2371"/>
<source>F8</source>
<translation>F8</translation>
</message>
<message>
<location filename="../sleepyhead/mainwindow.ui" line="2376"/>
<source>View S&ummary</source>
<translation>&Statistiekpagina</translation>
</message>
<message>
<location filename="../sleepyhead/mainwindow.ui" line="2384"/>
<source>Import &ZEO Data</source>
<translation>Importeer &ZEO gegevens</translation>
</message>
<message>
<location filename="../sleepyhead/mainwindow.ui" line="2389"/>
<source>Import RemStar &MSeries Data</source>
<translation>Importeer RemStar &M-series gegevens</translation>
</message>
<message>
<location filename="../sleepyhead/mainwindow.ui" line="2394"/>
<source>&Support SleepyHead Development</source>
<translation>&Help bij ontwikkeling SleepyHead</translation>
</message>
<message>
<location filename="../sleepyhead/mainwindow.ui" line="2399"/>
<source>Sleep Disorder Terms &Glossary</source>
<translation>&Woordenlijst slaapaandoeningen</translation>
</message>
<message>
<location filename="../sleepyhead/mainwindow.ui" line="2404"/>
<source>Change &Language</source>
<translation>Wijzig &Taal</translation>
</message>
<message>
<location filename="../sleepyhead/mainwindow.ui" line="2409"/>
<source>Change &Data Folder</source>
<translation>Wijzig &Gegevensmap</translation>
</message>
<message>
<location filename="../sleepyhead/mainwindow.cpp" line="242"/>
<source>Loading Data</source>
<translation>Gegevens laden</translation>
</message>
<message>
<location filename="../sleepyhead/mainwindow.cpp" line="368"/>
<source>Importing Data</source>
<translation>Gegevens importeren</translation>
</message>
<message>
<source>RDI</source>
<translation type="obsolete">RDI</translation>
</message>
<message>
<source>AHI</source>
<translation type="obsolete">AHI</translation>
</message>
<message>
<source>No CPAP data available.</source>
<translation type="obsolete">Geen CPAP-gegevens beschikbaar.</translation>
</message>
<message>
<source>%1 day of CPAP Data, on %2.</source>
<translation type="obsolete">Dag %1 van CPAP-gegevens, op %2.</translation>
</message>
<message>
<source>%1 days of CPAP Data, between %2 and %3</source>
<translation type="obsolete">%1 dagen met CPAP-gegevens, tussen %2 en %3</translation>
</message>
<message>
<source>Details</source>
<translation type="obsolete">Details</translation>
</message>
<message>
<source>Most Recent</source>
<translation type="obsolete">Laatste ingelezen dag</translation>
</message>
<message>
<source>Last 7 Days</source>
<translatorcomment>WJG: hoeft niet per se een week te zijn?</translatorcomment>
<translation type="obsolete">Afgelopen 7 dagen</translation>
</message>
<message>
<source>Last 30 Days</source>
<translation type="obsolete">Afgelopen 30 dagen</translation>
</message>
<message>
<source>Last 6 months</source>
<translation type="obsolete">Afgelopen 6 maanden</translation>
</message>
<message>
<source>Last Year</source>
<translatorcomment>AK: Zie mijn eerdere opmerking</translatorcomment>
<translation type="obsolete">Afgelopen jaar</translation>
</message>
<message>
<source>RERA Index</source>
<translation type="obsolete">RERA-index</translation>
</message>
<message>
<source>Flow Limit Index</source>
<translatorcomment>En wat wordt de afkorting?
AK: SBI</translatorcomment>
<translation type="obsolete">Stroom Beperking Index
(FLI)</translation>
</message>
<message>
<source>Hours per Night</source>
<translation type="obsolete">Uren per nacht</translation>
</message>
<message>
<source>Min EPAP</source>
<translation type="obsolete">Min. EPAP</translation>
</message>
<message>
<source>%1% EPAP</source>
<translation type="obsolete">%1% EPAP</translation>
</message>
<message>
<source>Max IPAP</source>
<translation type="obsolete">Max. IPAP</translation>
</message>
<message>
<source>%1% IPAP</source>
<translation type="obsolete">%1% IPAP</translation>
</message>
<message>
<source>Average Pressure</source>
<translation type="obsolete">Gemiddelde druk</translation>
</message>
<message>
<source>%1% Pressure</source>
<translation type="obsolete">%1% Druk</translation>
</message>
<message>
<source>Pressure</source>
<translation type="obsolete">Druk</translation>
</message>
<message>
<source>Average %1</source>
<translation type="obsolete">Gemiddelde %1</translation>
</message>
<message>
<source>%1% %2</source>
<translation type="obsolete">%1% %2</translation>
</message>
<message>
<source>Oximetry Summary</source>
<translation type="obsolete">Oxymetrie overzicht</translation>
</message>
<message>
<source>%1 day of Oximetry Data, on %2.</source>
<translation type="obsolete">%1 dag van oxymetriegegevens, op %2</translation>
</message>
<message>
<source>%1 days of Oximetry Data, between %2 and %3</source>
<translation type="obsolete">%1 dagen van oxymetrie-gegevens, tussen %2 en %3</translation>
</message>
<message>
<source>Average SpO2</source>
<translation type="obsolete">Gemiddelde SpO2</translation>
</message>
<message>
<source>Minimum SpO2</source>
<translation type="obsolete">Minimum SpO2</translation>
</message>
<message>
<source>SpO2 Events / Hour</source>
<translatorcomment>Dit zijn echt geen apneus, hoor...</translatorcomment>
<translation type="obsolete">SpO2 incidenten per uur</translation>
</message>
<message>
<source>% of time in SpO2 Events</source>
<translation type="obsolete">Tijd in SpO2 incidenten</translation>
</message>
<message>
<source>Average Pulse Rate</source>
<translation type="obsolete">Gemiddelde polsslag</translation>
</message>
<message>
<source>Minimum Pulse Rate</source>
<translation type="obsolete">Minumum polsslag</translation>
</message>
<message>
<source>Maximum Pulse Rate</source>
<translation type="obsolete">Maximum polsslag</translation>
</message>
<message>
<source>Pulse Change Events / Hour</source>
<translatorcomment>Het gaat om veranderingen als incident</translatorcomment>
<translation type="obsolete">Polsslagincidenten per uur</translation>
</message>
<message>
<source>Usage Information</source>
<translatorcomment>Dit staat onder "records"</translatorcomment>
<translation type="obsolete">Gebruiksinformatie</translation>
</message>
<message>
<source>Total Days</source>
<translation type="obsolete">Totaal aantal dagen</translation>
</message>
<message>
<source>Compliant Days</source>
<translation type="obsolete">Therapietrouw-dagen</translation>
</message>
<message>
<source>Days AHI &gt;5.0</source>
<translation type="obsolete">Dagen met AHI &gt 5,0</translation>
</message>
<message>
<source>Best&nbsp;%1</source>
<translation type="obsolete">Beste &nbsp;%1</translation>
</message>
<message>
<source>Worst&nbsp;%1</source>
<translation type="obsolete">Slechtste &nbsp;%1</translation>
</message>
<message>
<source>CPAP</source>
<translation type="obsolete">CPAP</translation>
</message>
<message>
<source>APAP</source>
<translation type="obsolete">APAP</translation>
</message>
<message>
<source>Bi-Level</source>
<translation type="obsolete">BiPAP</translation>
</message>
<message>
<source>ST/ASV</source>
<translatorcomment>Adaptieve ventilatie-instelling ASI?</translatorcomment>
<translation type="obsolete">ST/ASV</translation>
</message>
<message>
<source>Best RX Setting</source>
<translation type="obsolete">Beste Rx instelling</translation>
</message>
<message>
<source>Mode</source>
<translation type="obsolete">Modus</translation>
</message>
<message>
<source>Worst RX Setting</source>
<translation type="obsolete">Slechtste Rx instelling</translation>
</message>
<message>
<source>EPAP</source>
<translation type="obsolete">EPAP</translation>
</message>
<message>
<source>IPAPLo</source>
<translation type="obsolete">IPAP laag</translation>
</message>
<message>
<source>IPAPHi</source>
<translation type="obsolete">IPAP hoog</translation>
</message>
<message>
<source>PS Min</source>
<translation type="obsolete">PS min.</translation>
</message>
<message>
<source>PS Max</source>
<translation type="obsolete">PS max.</translation>
</message>
<message>
<source>IPAP</source>
<translation type="obsolete">IPAP</translation>
</message>
<message>
<source>PS</source>
<translation type="obsolete">PS</translation>
</message>
<message>
<source>Min Pres.</source>
<translation type="obsolete">Min. druk</translation>
</message>
<message>
<source>Max Pres.</source>
<translation type="obsolete">Max. druk</translation>
</message>
<message>
<source>First</source>
<translation type="obsolete">Eerste dag</translation>
</message>
<message>
<source>Last</source>
<translation type="obsolete">Laatste dag</translation>
</message>
<message>
<source>Days</source>
<translation type="obsolete">Dagen</translation>
</message>
<message>
<source>FL</source>
<translation type="obsolete">FL</translation>
</message>
<message>
<source>Machine</source>
<translation type="obsolete">Apparaat</translation>
</message>
<message>
<source>Pr. Rel.</source>
<translation type="obsolete">Drukvermindering</translation>
</message>
<message>
<source>%5 %1% EPAP=%2<br/>%3% IPAP=%4</source>
<translation type="obsolete">%5 %1% EPAP=%2<br/>%3% IPAP=%4</translation>
</message>
<message>
<source>%3 %1% Pressure=%2</source>
<translation type="obsolete">%3 %1% Druk=%2</translation>
</message>
<message>
<source>Brand</source>
<translation type="obsolete">Merk</translation>
</message>
<message>
<source>Model</source>
<translation type="obsolete">Type</translation>
</message>
<message>
<source>Serial</source>
<translation type="obsolete">Serienummer</translation>
</message>
<message>
<source>First Use</source>
<translation type="obsolete">Eerste gebruik</translation>
</message>
<message>
<source>Last Use</source>
<translation type="obsolete">Laatste gebruik</translation>
</message>
<message>
<location filename="../sleepyhead/mainwindow.cpp" line="582"/>
<source>Loading</source>
<translation>Laden...</translation>
</message>
<message>
<source><html><body><div align='center'><h2>SleepyHead v%1.%2.%3-%4 (%8)</h2>Build Date: %5 %6<br/>%7<br/>Data Folder: %9<hr>Copyright &copy;2011 Mark Watkins (jedimark) <br>
<a href='http://sleepyhead.sourceforge.net'>http://sleepyhead.sourceforge.net</a> <hr>This software is released under the GNU Public License <br><i>This software comes with absolutely no warranty, either express of implied. It comes with no guarantee of fitness for any particular purpose. No guarantees are made regarding the accuracy of any data this program displays.</div></body></html></source>
<translatorcomment>WJG: juridische terminologie aangepast. Klopt de Nederlandse downloadsite?
AK: De site wijzigt niet, is een algemene verwijzing. De vertaling wordt tzt in het standaard programma opgenomen, als taalkeuze.</translatorcomment>
<translation type="obsolete"><html><body><div align='center'><h2>SleepyHead v%1.%2.%3-%4 (%8)</h2>Build Date: %5 %6<br/>%7<br/>Data Folder: %9<hr>Copyright &copy;2011 Mark Watkins (jedimark) <br>
<a href='http://sleepyhead.sourceforge.net'>http://sleepyhead.sourceforge.net</a> <hr>Deze software is vrijgegeven onder de GNU Public License <br> <i> Deze software sluit elke vorm van aansprakelijkheid uit, zowel expliciet als impliciet. Het wordt geleverd zonder waarborg voor geschiktheid voor een bepaald doel. Er zijn geen garanties met betrekking tot de juistheid van de gegevens die dit programma toont.</div></body></html></translation>
</message>
<message>
<source>About SleepyHead</source>
<translation type="obsolete">Over SleepyHead</translation>
</message>
<message>
<source>There are no graphs visible to print</source>
<translation type="obsolete">Geen zichtbare grafieken om af te drukken</translation>
</message>
<message>
<source>Bookmarks</source>
<translation type="obsolete">Bladwijzers</translation>
</message>
<message>
<source>Would you like to show bookmarked areas in this report?</source>
<translation type="obsolete">Wil je gebieden met bladwijzer in dit rapport tonen?</translation>
</message>
<message>
<source>This make take some time to complete..
Please don't touch anything until it's done.</source>
<translation type="obsolete">Dit kan even duren...
Alsjeblieft niets aanraken tot ik klaar ben!</translation>
</message>
<message>
<source>Printing %1 Report</source>
<translation type="obsolete">Rapport %1 afdrukken</translation>
</message>
<message>
<source>%1 Report</source>
<translation type="obsolete">%1 Rapport</translation>
</message>
<message>
<source>Name: %1, %2
</source>
<translation type="obsolete">Naam: %1, %2
</translation>
</message>
<message>
<source>DOB: %1
</source>
<translation type="obsolete">Geboortedatum: %1
</translation>
</message>
<message>
<source>Patient ID: %1
</source>
<translation type="obsolete">Patientnr.: %1
</translation>
</message>
<message>
<source>Phone: %1
</source>
<translation type="obsolete">Telefoon: %1
</translation>
</message>
<message>
<source>Email: %1
</source>
<translation type="obsolete">E-mail: %1
</translation>
</message>
<message>
<source>
Address:
%1</source>
<translation type="obsolete">
Adres:
%1</translation>
</message>
<message>
<source>Mask Time: </source>
<translation type="obsolete">Maskertijd: </translation>
</message>
<message>
<source>Bedtime: </source>
<translation type="obsolete">Gaan slapen:</translation>
</message>
<message>
<source>Wake-up: </source>
<translation type="obsolete">Opgestaan: </translation>
</message>
<message>
<source>Machine: </source>
<translation type="obsolete">Apparaaat: </translation>
</message>
<message>
<source>
Mode: </source>
<translation type="obsolete">
Modus: </translation>
</message>
<message>
<source>ASV</source>
<translatorcomment>Adaptieve ventilatie-instelling ASI?</translatorcomment>
<translation type="obsolete">ASV</translation>
</message>
<message>
<source>Unknown</source>
<translation type="obsolete">Onbekend</translation>
</message>
<message>
<source>RDI %1
</source>
<translation type="obsolete">RDI %1
</translation>
</message>
<message>
<source>AHI %1
</source>
<translation type="obsolete">AHI %1
</translation>
</message>
<message>
<source>AI=%1 HI=%2 CAI=%3 </source>
<translation type="obsolete">AI=%1 HI=%2 CAI=%3 </translation>
</message>
<message>
<source>REI=%1 VSI=%2 FLI=%3 PB/CSR=%4%</source>
<translation type="obsolete">REI=%1 VSI=%2 FLI=%3 PB/CSR=%4%</translation>
</message>
<message>
<source>UAI=%1 </source>
<translation type="obsolete">UAI=%1 </translation>
</message>
<message>
<source>NRI=%1 LKI=%2 EPI=%3</source>
<translation type="obsolete">NRI=%1 LKI=%2 EPI=%3</translation>
</message>
<message>
<source>Weight %1 </source>
<translation type="obsolete">Gewicht %1</translation>
</message>
<message>
<source>BMI %1 </source>
<translation type="obsolete">BMI %1 </translation>
</message>
<message>
<source>Zombie %1/10 </source>
<translation type="obsolete">Zombie %1/10 </translation>
</message>
<message>
<source>Reporting from %1 to %2</source>
<translation type="obsolete">Rapport van %1 tot %2</translation>
</message>
<message>
<source>Reporting data goes here</source>
<translation type="obsolete">De rapportgegevens komen hier</translation>
</message>
<message>
<source>Entire Day's Flow Waveform</source>
<translation type="obsolete">Flow golfvorm hele dag</translation>
</message>
<message>
<source>SleepyHead v%1 - http://sleepyhead.sourceforge.net</source>
<translation type="obsolete">SleepyHead v%1 - http://sleepyhead.sourceforge.net</translation>
</message>
<message>
<source>Page %1 of %2</source>
<translation type="obsolete">Pagina %1 van %2</translation>
</message>
<message>
<location filename="../sleepyhead/mainwindow.cpp" line="98"/>
<source>Profile</source>
<translation>Profiel</translation>
</message>
<message>
<location filename="../sleepyhead/mainwindow.cpp" line="119"/>
<source>Welcome</source>
<translation>Welkom</translation>
</message>
<message>
<location filename="../sleepyhead/mainwindow.cpp" line="168"/>
<source>&About</source>
<translation>&Over</translation>
</message>
<message>
<location filename="../sleepyhead/mainwindow.cpp" line="188"/>
<source>Loading...</source>
<translation>Laden...</translation>
</message>
<message>
<location filename="../sleepyhead/mainwindow.cpp" line="285"/>
<source>Access to Import has been blocked while recalculations are in progress.</source>
<translation>Tijden een herberekening kan niet geïmporteerd worden.</translation>
</message>
<message>
<location filename="../sleepyhead/mainwindow.cpp" line="316"/>
<source>Import from where?</source>
<translation>Waar vandaan importeren?</translation>
</message>
<message>
<location filename="../sleepyhead/mainwindow.cpp" line="316"/>
<source>Do you just want to Import from the usual (remembered) locations?
</source>
<translation>Wil je van de gebruikelijke (opgeslagen) lokatie importeren?</translation>
</message>
<message>
<location filename="../sleepyhead/mainwindow.cpp" line="316"/>
<source>The Usual</source>
<translation>Gebruikelijk</translation>
</message>
<message>
<location filename="../sleepyhead/mainwindow.cpp" line="316"/>
<source>New Location</source>
<translation>Nieuw</translation>
</message>
<message>
<location filename="../sleepyhead/mainwindow.cpp" line="316"/>
<source>Cancel</source>
<translation>Annuleren</translation>
</message>
<message>
<location filename="../sleepyhead/mainwindow.cpp" line="385"/>
<source>Remember this Location?</source>
<translation>Deze lokatie bewaren?</translation>
</message>
<message>
<location filename="../sleepyhead/mainwindow.cpp" line="385"/>
<source>Would you like to remember this import location for next time?</source>
<translation>Wil je deze lokatie bewaren voor de volgende keer?</translation>
</message>
<message>
<location filename="../sleepyhead/mainwindow.cpp" line="400"/>
<source>Import Problem
Couldn't find any new Machine Data at the locations given</source>
<translation>Probleem:
Kon geen nieuwe gegevens op de bekende lokaties vinden</translation>
</message>
<message>
<location filename="../sleepyhead/mainwindow.cpp" line="608"/>
<source>Build Date</source>
<translation>Versiedatum</translation>
</message>
<message>
<location filename="../sleepyhead/mainwindow.cpp" line="608"/>
<source>Data Folder Location</source>
<translation>Locatie folder SleepyHeadData</translation>
</message>
<message>
<location filename="../sleepyhead/mainwindow.cpp" line="609"/>
<source>Copyright</source>
<translation>Copyright</translation>
</message>
<message>
<location filename="../sleepyhead/mainwindow.cpp" line="610"/>
<source>This software is released under the GNU Public License v3.0<br/></source>
<translation>De software wordt vrijgegeven onder de GNU Public License v3.0<br/></translation>
</message>
<message>
<location filename="../sleepyhead/mainwindow.cpp" line="611"/>
<source>SleepyHead Project Page</source>
<translation>SleepyHead Project pagina</translation>
</message>
<message>
<location filename="../sleepyhead/mainwindow.cpp" line="612"/>
<source>SleepyHead Wiki</source>
<translation>SleepyHead Wiki</translation>
</message>
<message>
<location filename="../sleepyhead/mainwindow.cpp" line="613"/>
<source>Authors Twitter Feed</source>
<translation>Twitter-feed van de auteur</translation>
</message>
<message>
<location filename="../sleepyhead/mainwindow.cpp" line="615"/>
<source><p>The author wishes to express thanks to James Marshall and Rich Freeman for their assistance with this project.</p></source>
<translation><p>De auteur wil James Marshall en Rich Freeman bedanken voor hun hulp bij dit project</p></translation>
</message>
<message>
<location filename="../sleepyhead/mainwindow.cpp" line="616"/>
<source>This software comes with absolutely no warranty, either express of implied.</source>
<translation>Deze software sluit elke vorm van aansprakelijkheid uit, zowel expliciet als impliciet.</translation>
</message>
<message>
<location filename="../sleepyhead/mainwindow.cpp" line="617"/>
<source>It comes with no guarantee of fitness for any particular purpose.</source>
<translation>Het wordt geleverd zonder waarborg voor geschiktheid voor een bepaald doel.</translation>
</message>
<message>
<location filename="../sleepyhead/mainwindow.cpp" line="618"/>
<source>No guarantees are made regarding the accuracy of any data this program displays.</source>
<translation>Er zijn geen garanties met betrekking tot de juistheid van de gegevens die dit programma toont.</translation>
</message>
<message>
<location filename="../sleepyhead/mainwindow.cpp" line="619"/>
<source>This is NOT medical software, it is merely a research tool that provides a visual interpretation of data recorded by supported devices.</source>
<translation>Dit is GEEN MEDISCHE SOFTWARE, maar meer een onderzoeksgereedschap voor de visuele interpretatie van gegevens uit ondersteunde apparatuur.</translation>
</message>
<message>
<location filename="../sleepyhead/mainwindow.cpp" line="620"/>
<source>This software is NOT suitable for medical diagnosis, CPAP complaince reporting and other similar purposes.</source>
<translation>Deze software is NIET TOEPASBAAR voor medische diagnose, CPAP compliantie rapportage of vergelijkbare doelen.</translation>
</message>
<message>
<location filename="../sleepyhead/mainwindow.cpp" line="621"/>
<source>The author and any associates of his accept NO responsibilty for damages, issues or non-issues resulting from the use or mis-use of this software.</source>
<translation>De auteur en al zijn collegas accepteren GEEN ENKELE AANSPRAKELIJKHEID voor schade, in welke vorm ook, door het gebruik of misbruik van deze software.</translation>
</message>
<message>
<location filename="../sleepyhead/mainwindow.cpp" line="622"/>
<source>Use this software entirely at your own risk.</source>
<translation>Het gebruik van deze software is geheel voor eigen risico.</translation>
</message>
<message>
<location filename="../sleepyhead/mainwindow.cpp" line="623"/>
<source>If you find this free software to be of use, please consider supporting the development efforts by making a paypal donation to the Author</source>
<translation>Wanneer u dit programma de moeite waard vindt, steun dan de ontwikkeling met een PayPal donatie aan de auteur</translation>
</message>
<message>
<location filename="../sleepyhead/mainwindow.cpp" line="684"/>
<source>Access to Preferences has been blocked until recalculation completes.</source>
<translation>Toegang tot de Voorkeuren is geblokkeerd gedurende herberekening.</translation>
</message>
<message>
<location filename="../sleepyhead/mainwindow.cpp" line="713"/>
<source>Question</source>
<translation>Vraag</translation>
</message>
<message>
<location filename="../sleepyhead/mainwindow.cpp" line="713"/>
<source>Do you have a CMS50[x] Oximeter?
One is required to use this section.</source>
<translation>Heeft u een CMS50[x] oxymeter?
Die is vereist voor gebruik van deze sectie.</translation>
</message>
<message>
<location filename="../sleepyhead/mainwindow.cpp" line="768"/>
<source>There was an error saving screenshot to file "%1"</source>
<translation>Er is iets fout gegaan bij het opslaan van een beeldschermafdruk naar het bestand "%1"</translation>
</message>
<message>
<location filename="../sleepyhead/mainwindow.cpp" line="770"/>
<source>Screenshot saved to file "%1"</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../sleepyhead/mainwindow.cpp" line="787"/>
<source>Printing Disabled</source>
<translation>Afdrukken is uitgeschakeld</translation>
</message>
<message>
<location filename="../sleepyhead/mainwindow.cpp" line="787"/>
<source>Please rebuild SleepyHead with Qt 4.8.5 or greater, as printing causes a crash with this version of Qt</source>
<translation></translation>
</message>
<message>
<location filename="../sleepyhead/mainwindow.cpp" line="1087"/>
<location filename="../sleepyhead/mainwindow.cpp" line="1105"/>
<source>Gah!</source>
<translation>Bah!</translation>
</message>
<message>
<location filename="../sleepyhead/mainwindow.cpp" line="1087"/>
<location filename="../sleepyhead/mainwindow.cpp" line="1105"/>
<source>If you can read this, the restart command didn't work. Your going to have to do it yourself manually.</source>
<translation>Als je dit kunt lezen, heeft het herstartcommando niet gewerkt. Je zult het handmatig moeten doen.</translation>
</message>
<message>
<location filename="../sleepyhead/mainwindow.cpp" line="1175"/>
<source>Are you sure?</source>
<translation>Weet je het zeker?</translation>
</message>
<message>
<location filename="../sleepyhead/mainwindow.cpp" line="1175"/>
<source>Are you sure you want to purge all CPAP data for the following machine:
</source>
<translation>Weet je zeker dat je alle CPAP-gegevens wilt wissen van het volgende apparaat:
</translation>
</message>
<message>
<location filename="../sleepyhead/mainwindow.cpp" line="1336"/>
<source>Performance will be degraded during these recalculations.</source>
<translation>Tijdens herberekening gaan de prestaties van de PC achteruit.</translation>
</message>
<message>
<location filename="../sleepyhead/mainwindow.cpp" line="1336"/>
<source>Recalculating Indices</source>
<translation>Herberekening van de indexen</translation>
</message>
<message>
<location filename="../sleepyhead/mainwindow.cpp" line="1347"/>
<source>Loading Event Data</source>
<translation>Incidenten laden</translation>
</message>
<message>
<location filename="../sleepyhead/mainwindow.cpp" line="1349"/>
<location filename="../sleepyhead/mainwindow.cpp" line="1397"/>
<source>Recalculating Summaries</source>
<translation>Opnieuw berekenen</translation>
</message>
<message>
<location filename="../sleepyhead/mainwindow.cpp" line="1407"/>
<source>Restart Required</source>
<translation>Herstart nodig</translation>
</message>
<message>
<location filename="../sleepyhead/mainwindow.cpp" line="1407"/>
<source>Recalculations are complete, the application now needs to restart to display the changes.</source>
<translation>Herberekening voltooid, de applicatie moet nu herstarten om de wijzigingen zichtbaar te maken.</translation>
</message>
<message>
<location filename="../sleepyhead/mainwindow.cpp" line="1411"/>
<source>Recalculations are now complete.</source>
<translation>Herberekening voltooid.</translation>
</message>
<message>
<location filename="../sleepyhead/mainwindow.cpp" line="1411"/>
<source>Task Completed</source>
<translation>Taak voltooid</translation>
</message>
<message>
<location filename="../sleepyhead/mainwindow.cpp" line="1432"/>
<source>There was a problem opening ZEO File: </source>
<translation>Er was een probleem met het openen van het Zeo bestand: </translation>
</message>
<message>
<location filename="../sleepyhead/mainwindow.cpp" line="1435"/>
<source>Zeo CSV Import complete</source>
<translation>Import van het Zeo csv bestand voltooid</translation>
</message>
<message>
<location filename="../sleepyhead/mainwindow.cpp" line="1455"/>
<source>There was a problem opening MSeries block File: </source>
<translation>Er was een probleem bij het openen van het M-Series blokbestand: </translation>
</message>
<message>
<location filename="../sleepyhead/mainwindow.cpp" line="1458"/>
<source>MSeries Import complete</source>
<translation>Import M-Series voltooid</translation>
</message>
</context>
<context>
<name>NewProfile</name>
<message>
<location filename="../sleepyhead/newprofile.ui" line="14"/>
<source>Edit User Profile</source>
<translation>Wijzig gebruikersprofiel</translation>
</message>
<message>
<source>Language</source>
<translation type="obsolete">Taal</translation>
</message>
<message>
<source>English</source>
<translation type="obsolete">English</translation>
</message>
<message>
<source>Data Folder</source>
<translation type="obsolete">Bestandsmap</translation>
</message>
<message>
<source>Shows the directory where SleepyHead data will be stored. </source>
<translation type="obsolete">De gegevens van SleepyHead worden in deze map opgeslagen.</translation>
</message>
<message>
<source>Click here to choose where to store SleepyHead data.</source>
<translatorcomment>Dit is een hulptekst, mag lang zijn.
20/9 WJG: op zich met de redenatie eens, al ben ik er ook voor om hulpteksten zo compact en duidelijk mogelijk te houden.</translatorcomment>
<translation type="obsolete">Kies hier waar SleepyHead gegevens opslaat.</translation>
</message>
<message>
<source>...</source>
<translation type="obsolete">...</translation>
</message>
<message>
<source><!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0//EN" "http://www.w3.org/TR/REC-html40/strict.dtd">
<html><head><meta name="qrichtext" content="1" /><style type="text/css">
p, li { white-space: pre-wrap; }
</style></head><body style=" font-family:'Sans'; font-size:10pt; font-weight:400; font-style:normal;">
<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><span style=" font-weight:600; font-style:italic;">Welcome to SleepyHead</span></p>
<p style="-qt-paragraph-type:empty; margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"></p>
<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;">This software is being designed to help you review data related to your CPAP treatment.</p>
<p style="-qt-paragraph-type:empty; margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"></p>
<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;">It's intended as merely a data viewer, and not a substitute for competent medical guidance from your Doctor. </p>
<p style="-qt-paragraph-type:empty; margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"></p>
<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;">This software has been released freely under the <a href="qrc:/LICENSE.txt"><span style=" text-decoration: underline; color:#0000ff;">GNU Public License</span></a>, and comes with no warranty, and without ANY claims to fitness for any purpose.</p>
<p style="-qt-paragraph-type:empty; margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"></p>
<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;">Accuracy of any data displayed is not and can not be guaranteed. </p>
<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><br />Any reports generated are for PERSONAL USE ONLY, and not fit for compliance purposes.</p>
<p style="-qt-paragraph-type:empty; margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"></p>
<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;">The author will not be held liable for <span style=" text-decoration: underline;">anything</span> related to the use or misuse of this software. </p>
<p style="-qt-paragraph-type:empty; margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"></p>
<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;">Use at your own risk. </p>
<p style="-qt-paragraph-type:empty; margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"></p>
<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;">This software is copyright ©2011 Mark Watkins </p>
<p style="-qt-paragraph-type:empty; margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"></p></body></html></source>
<translation type="obsolete"><!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0//EN" "http://www.w3.org/TR/REC-html40/strict.dtd">
<html><head><meta name="qrichtext" content="1" /><style type="text/css">
p, li { white-space: pre-wrap; }
</style></head><body style=" font-family:'Sans'; font-size:10pt; font-weight:400; font-style:normal;">
<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><span style=" font-weight:600; font-style:italic;">Welkom bij SleepyHead</span></p>
<p style="-qt-paragraph-type:empty; margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"></p>
<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;">Dit programma is ontworpen als hulp bij het beoordelen van de gegevens over je CPAP behandeling.</p>
<p style="-qt-paragraph-type:empty; margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"></p>
<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;">Het is voornamelijk bedoeld om gegevens te bekijken en absoluut geen vervanging van de medische begeleiding door je arts. </p>
<p style="-qt-paragraph-type:empty; margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"></p>
<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;">Deze software is vrijelijk uitgegeven onder de <a href="qrc:/LICENSE.txt"><span style=" text-decoration: underline; color:#0000ff;">GNU Public License</span></a>, en wordt geleverd zonder garantie en zonder enige aanspraak op geschiktheid voor welk doel dan ook.</p>
<p style="-qt-paragraph-type:empty; margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"></p>
<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;">De juistheid van alle weergegeven gegevens is niet en kan niet worden gegarandeerd. </p>
<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><br />Ieder gegenereerd rapport is voor EIGEN GEBRUIK en is niet geschikt om de naleving te beoordelen.</p>
<p style="-qt-paragraph-type:empty; margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"></p>
<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;">De auteur kan niet verantwoordelijk worden gehouden voor <span style=" text-decoration: underline;">alles</span> dat is gerelateerd aan het gebruik of misbruik van deze programmatuur. </p>
<p style="-qt-paragraph-type:empty; margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"></p>
<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;">Gebruik op eigen risico. </p>
<p style="-qt-paragraph-type:empty; margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"></p>
<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;">Auteursrecht software ©2011 Mark Watkins </p>
<p style="-qt-paragraph-type:empty; margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"></p></body></html></translation>
</message>
<message>
<location filename="../sleepyhead/newprofile.ui" line="45"/>
<source>qrc:/docs/intro.html</source>
<translation>qrc:/docs/intro.html</translation>
</message>
<message>
<location filename="../sleepyhead/newprofile.ui" line="58"/>
<source>I agree to all the conditions above.</source>
<translation>Ik ga akkoord met bovengenoemde voorwaarden.</translation>
</message>
<message>
<location filename="../sleepyhead/newprofile.ui" line="90"/>
<source>User Information</source>
<translation>Gebruikersinformatie</translation>
</message>
<message>
<location filename="../sleepyhead/newprofile.ui" line="113"/>
<source>User Name</source>
<translation>Naam gebruiker</translation>
</message>
<message>
<location filename="../sleepyhead/newprofile.ui" line="132"/>
<source>Keep the kids out.. Nothing more.. This isn't meant to be uber security.</source>
<translatorcomment>WJG: Mooi gevonden!</translatorcomment>
<translation>Hou de kinderen erbuiten... niets meer of minder...
Dit is GEEN ECHTE BEVEILIGING.</translation>
</message>
<message>
<location filename="../sleepyhead/newprofile.ui" line="135"/>
<source>Password Protect Profile</source>
<translation>Wachtwoordbeveiliging van het profiel</translation>
</message>
<message>
<location filename="../sleepyhead/newprofile.ui" line="150"/>
<source>Password</source>
<translation>Wachtwoord</translation>
</message>
<message>
<location filename="../sleepyhead/newprofile.ui" line="164"/>
<source>...twice...</source>
<translation>... nog eens ...</translation>
</message>
<message>
<location filename="../sleepyhead/newprofile.ui" line="191"/>
<source>Locale Settings</source>
<translation>Landinstellingen</translation>
</message>
<message>
<location filename="../sleepyhead/newprofile.ui" line="212"/>
<source>Country</source>
<translation>Land</translation>
</message>
<message>
<location filename="../sleepyhead/newprofile.ui" line="231"/>
<source>TimeZone</source>
<translation>Tijdzone</translation>
</message>
<message>
<location filename="../sleepyhead/newprofile.ui" line="270"/>
<source>DST Zone</source>
<translation>Zomertijd</translation>
</message>
<message>
<location filename="../sleepyhead/newprofile.ui" line="290"/>
<source>Personal Information (for reports)</source>
<translation>Persoonlijke informatie (voor rapporten)</translation>
</message>
<message>
<location filename="../sleepyhead/newprofile.ui" line="314"/>
<source>First Name</source>
<translation>Voornaam</translation>
</message>
<message>
<location filename="../sleepyhead/newprofile.ui" line="324"/>
<source>Last Name</source>
<translation>Achternaam</translation>
</message>
<message>
<location filename="../sleepyhead/newprofile.ui" line="334"/>
<source>D.O.B.</source>
<translation>Geboortedatum</translation>
</message>
<message>
<location filename="../sleepyhead/newprofile.ui" line="350"/>
<source>Gender</source>
<translation>Geslacht</translation>
</message>
<message>
<location filename="../sleepyhead/newprofile.ui" line="363"/>
<source>Male</source>
<translation>Man</translation>
</message>
<message>
<location filename="../sleepyhead/newprofile.ui" line="368"/>
<source>Female</source>
<translation>Vrouw</translation>
</message>
<message>
<location filename="../sleepyhead/newprofile.ui" line="384"/>
<source>Height</source>
<translation>Lengte</translation>
</message>
<message>
<location filename="../sleepyhead/newprofile.ui" line="423"/>
<source>metric</source>
<translation>metrisch</translation>
</message>
<message>
<location filename="../sleepyhead/newprofile.ui" line="428"/>
<source>archiac</source>
<translatorcomment>WJG: is grapje van de maker
AK: Ik heb het nu ook door!</translatorcomment>
<translation>archaïsch</translation>
</message>
<message>
<location filename="../sleepyhead/newprofile.ui" line="441"/>
<source>Contact Information</source>
<translation>Contactinformatie</translation>
</message>
<message>
<location filename="../sleepyhead/newprofile.ui" line="468"/>
<location filename="../sleepyhead/newprofile.ui" line="732"/>
<source>Address</source>
<translation>Adres</translation>
</message>
<message>
<location filename="../sleepyhead/newprofile.ui" line="485"/>
<location filename="../sleepyhead/newprofile.ui" line="763"/>
<source>Email</source>
<translation>E-mail</translation>
</message>
<message>
<location filename="../sleepyhead/newprofile.ui" line="495"/>
<location filename="../sleepyhead/newprofile.ui" line="753"/>
<source>Phone</source>
<translation>Telefoon</translation>
</message>
<message>
<location filename="../sleepyhead/newprofile.ui" line="531"/>
<source>CPAP Treatment Information</source>
<translation>Informatie over de behandeling</translation>
</message>
<message>
<location filename="../sleepyhead/newprofile.ui" line="558"/>
<source>Date Diagnosed</source>
<translation>Datum diagnose</translation>
</message>
<message>
<location filename="../sleepyhead/newprofile.ui" line="572"/>
<source>Untreated AHI</source>
<translation>Onbehandelde AHI</translation>
</message>
<message>
<location filename="../sleepyhead/newprofile.ui" line="586"/>
<source>CPAP Mode</source>
<translatorcomment>WJG: klopt dit wel, want Bi-level en APAP zijn in feite geen CPAP-soorten, toch? Ik geef maar wat alternatieven, ook spreekt het wel voor zich en zou je ook 'Soort CPAP' kunnen laten staan.
20/9 WJG: Soort apparaat lijkt me prima!</translatorcomment>
<translation variants="yes">
<lengthvariant>Soort apparaat</lengthvariant>
<lengthvariant></lengthvariant>
<lengthvariant></lengthvariant>
</translation>
</message>
<message>
<location filename="../sleepyhead/newprofile.ui" line="594"/>
<source>CPAP</source>
<translation>CPAP</translation>
</message>
<message>
<location filename="../sleepyhead/newprofile.ui" line="599"/>
<source>APAP</source>
<translation>APAP</translation>
</message>
<message>
<location filename="../sleepyhead/newprofile.ui" line="604"/>
<source>Bi-Level</source>
<translation>Bi-level</translation>
</message>
<message>
<location filename="../sleepyhead/newprofile.ui" line="609"/>
<source>ASV</source>
<translatorcomment>Adaptieve ventilatie-instelling ASI?</translatorcomment>
<translation>ASV</translation>
</message>
<message>
<location filename="../sleepyhead/newprofile.ui" line="617"/>
<source>RX Pressure</source>
<translation>Voorgeschreven druk</translation>
</message>
<message>
<location filename="../sleepyhead/newprofile.ui" line="661"/>
<source>Doctors / Clinic Information</source>
<translation>Specialist/ziekenhuis</translation>
</message>
<message>
<location filename="../sleepyhead/newprofile.ui" line="688"/>
<source>Doctors Name</source>
<translation>Specialist</translation>
</message>
<message>
<location filename="../sleepyhead/newprofile.ui" line="705"/>
<source>Practice Name</source>
<translatorcomment>WJG: zou dit niet bedoeld worden? Bij het adres wordt wel duidelijk welk ziekenhuis het is. Bij mij is de behandeling bij 'Longziekten', misschien heet dat bij een ander ziekenhuis anders?</translatorcomment>
<translation>Afdeling</translation>
</message>
<message>
<location filename="../sleepyhead/newprofile.ui" line="715"/>
<source>Patient ID</source>
<translation>Patient-ID</translation>
</message>
<message>
<location filename="../sleepyhead/newprofile.ui" line="811"/>
<source>SleepyHead</source>
<translation>SleepyHead</translation>
</message>
<message>
<location filename="../sleepyhead/newprofile.ui" line="826"/>
<source>TextLabel</source>
<translation>Tekstlabel</translation>
</message>
<message>
<location filename="../sleepyhead/newprofile.ui" line="887"/>
<source>&Cancel</source>
<translation>&Annuleren</translation>
</message>
<message>
<location filename="../sleepyhead/newprofile.ui" line="903"/>
<source>&Back</source>
<translation>&Terug</translation>
</message>
<message>
<location filename="../sleepyhead/newprofile.ui" line="919"/>
<location filename="../sleepyhead/newprofile.cpp" line="207"/>
<location filename="../sleepyhead/newprofile.cpp" line="215"/>
<source>&Next</source>
<translation>&Volgende</translation>
</message>
<message>
<location filename="../sleepyhead/newprofile.cpp" line="57"/>
<source>Select Country</source>
<translation>Kies land</translation>
</message>
<message>
<location filename="../sleepyhead/newprofile.cpp" line="107"/>
<source>Empty Username</source>
<translation>Geen gebruikernaam</translation>
</message>
<message>
<location filename="../sleepyhead/newprofile.cpp" line="115"/>
<source>Passwords don't match</source>
<translation>Wachtwoorden komen niet overeen</translation>
</message>
<message>
<location filename="../sleepyhead/newprofile.cpp" line="138"/>
<source>Profile Changes</source>
<translation>Profielwijzigingen</translation>
</message>
<message>
<location filename="../sleepyhead/newprofile.cpp" line="138"/>
<source>Accept and save this information?</source>
<translation>Opslaan?</translation>
</message>
<message>
<location filename="../sleepyhead/newprofile.cpp" line="205"/>
<source>&Finish</source>
<translation>&Einde</translation>
</message>
</context>
<context>
<name>Overview</name>
<message>
<location filename="../sleepyhead/overview.ui" line="14"/>
<source>Form</source>
<translation>Formulier</translation>
</message>
<message>
<location filename="../sleepyhead/overview.ui" line="68"/>
<source>Range:</source>
<translation>Bereik:</translation>
</message>
<message>
<location filename="../sleepyhead/overview.ui" line="82"/>
<source>Last Week</source>
<translation>Afgelopen week</translation>
</message>
<message>
<location filename="../sleepyhead/overview.ui" line="87"/>
<source>Last Two Weeks</source>
<translation>Afgelopen twee weken</translation>
</message>
<message>
<location filename="../sleepyhead/overview.ui" line="92"/>
<source>Last Month</source>
<translation>Afgelopen maand</translation>
</message>
<message>
<location filename="../sleepyhead/overview.ui" line="97"/>
<source>Last Two Months</source>
<translation>Afgelopen twee maanden</translation>
</message>
<message>
<location filename="../sleepyhead/overview.ui" line="102"/>
<source>Last Three Months</source>
<translation>Afgelopen drie maanden</translation>
</message>
<message>
<location filename="../sleepyhead/overview.ui" line="107"/>
<source>Last 6 Months</source>
<translation>Afgelopen halfjaar</translation>
</message>
<message>
<location filename="../sleepyhead/overview.ui" line="112"/>
<source>Last Year</source>
<translation>Afgelopen jaar</translation>
</message>
<message>
<location filename="../sleepyhead/overview.ui" line="117"/>
<source>Everything</source>
<translation>Alles</translation>
</message>
<message>
<location filename="../sleepyhead/overview.ui" line="122"/>
<source>Custom</source>
<translation>Zelf kiezen</translation>
</message>
<message>
<location filename="../sleepyhead/overview.ui" line="130"/>
<source>Start:</source>
<translation>Start:</translation>
</message>
<message>
<location filename="../sleepyhead/overview.ui" line="153"/>
<source>End:</source>
<translation>Einde:</translation>
</message>
<message>
<location filename="../sleepyhead/overview.ui" line="176"/>
<source>Reset view to selected date range</source>
<translatorcomment>WJG: is wat preciezer, als het past</translatorcomment>
<translation>Herstel naar geselecteerd datumbereik</translation>
</message>
<message>
<location filename="../sleepyhead/overview.ui" line="195"/>
<location filename="../sleepyhead/overview.ui" line="238"/>
<source>...</source>
<translation>...</translation>
</message>
<message>
<location filename="../sleepyhead/overview.ui" line="219"/>
<source>Toggle Graph Visibility</source>
<translation>Grafieken aan/uit</translation>
</message>
<message>
<location filename="../sleepyhead/overview.ui" line="254"/>
<source>Drop down to see list of graphs to switch on/off.</source>
<translation>Lijst met grafieken om aan/uit te zetten.</translation>
</message>
<message>
<location filename="../sleepyhead/overview.ui" line="258"/>
<source>Graphs</source>
<translation>Grafieken</translation>
</message>
<message>
<source>RDI</source>
<translation type="obsolete">RDI</translation>
</message>
<message>
<source>AHI</source>
<translation type="obsolete">AHI</translation>
</message>
<message>
<location filename="../sleepyhead/overview.cpp" line="102"/>
<source>Apnea
Hypopnea
Index</source>
<translation>Apneu
Hypopneu
Index</translation>
</message>
<message>
<location filename="../sleepyhead/overview.cpp" line="105"/>
<source>Usage</source>
<translation>Gebruik</translation>
</message>
<message>
<location filename="../sleepyhead/overview.cpp" line="105"/>
<source>Usage
(hours)</source>
<translation>Gebruik
(uren)</translation>
</message>
<message>
<source>Flow Limit</source>
<translation type="obsolete">Stroombeperking</translation>
</message>
<message>
<location filename="../sleepyhead/overview.cpp" line="120"/>
<source>Session Times</source>
<translation>Sessietijden</translation>
</message>
<message>
<location filename="../sleepyhead/overview.cpp" line="120"/>
<source>Session Times
(hours)</source>
<translation>Sessietijden
(uren)</translation>
</message>
<message>
<source>Pressure
(cmH2O)</source>
<translation type="obsolete">Druk
(cmWK)</translation>
</message>
<message>
<source>Settings</source>
<translation type="obsolete">Instellingen</translation>
</message>
<message>
<source>Leaks</source>
<translation type="obsolete">Maskerlek</translation>
</message>
<message>
<source>Unintentional Leaks
(L/min)</source>
<translation type="obsolete">Maskerlek
(l/min)</translation>
</message>
<message>
<source>Total Leaks</source>
<translation type="obsolete">Totale lek</translation>
</message>
<message>
<source>Total Leaks
(L/min)</source>
<translation type="obsolete">Totale lek
(l/min)</translation>
</message>
<message>
<location filename="../sleepyhead/overview.cpp" line="100"/>
<source>Respiratory
Disturbance
Index</source>
<translation>Ademhalings
Stoornis
Index (RDI)</translation>
</message>
<message>
<location filename="../sleepyhead/overview.cpp" line="125"/>
<source>% in PB</source>
<translatorcomment>WJG: moet dat niet 'periodieke ademhaling zijn, zie volgende item
AK: Discussie</translatorcomment>
<translation>% in PB</translation>
</message>
<message>
<location filename="../sleepyhead/overview.cpp" line="125"/>
<source>Periodic
Breathing
(% of night)</source>
<translatorcomment>WJG: wat wordt er eigenlijk precies mee bedoeld? Gaat het hier om de reguliere/normale ademhaling, d.w.z. zonder ademstops? Dan zou je 'periodiek beter door 'Reguliere' of 'Normale' kunnen vervangen.
AK: Het is een oscillerende ademhaling, mss is "Cyclische" beter?
20/9: Dat zou dan beter zijn.</translatorcomment>
<translation>Cyclische ademhaling (PB)
(% van de nacht)</translation>
</message>
<message>
<location filename="../sleepyhead/overview.cpp" line="127"/>
<source>Peak RDI</source>
<translatorcomment>AK: Deze niet vertalen? Respiratory Disturbance Index...</translatorcomment>
<translation>Piek RDI</translation>
</message>
<message>
<location filename="../sleepyhead/overview.cpp" line="127"/>
<source>Peak RDI
Shows RDI Clusters
(RDI/hr)</source>
<translatorcomment>WJG: zo'n spellingsdingetje met streepjes en al dan niet aan elkaar schrijven.
AK: Deze niet vertalen? Respiratory Disturbance Index...
20/9 WJG: Als dat gangbaar is om het onvertaald te gebruiken, dan inderdaad laten.</translatorcomment>
<translation>Piek RDI, maakt
RDI-clusters zichtbaar
(RDI/uur)</translation>
</message>
<message>
<location filename="../sleepyhead/overview.cpp" line="129"/>
<source>Peak AHI</source>
<translation>Piek-AHI</translation>
</message>
<message>
<location filename="../sleepyhead/overview.cpp" line="129"/>
<source>Peak AHI
Shows AHI Clusters
(AHI/hr)</source>
<translation>Piek-AHI, maakt
AHI-clusters zichtbaar
(AHI/uur)</translation>
</message>
<message>
<location filename="../sleepyhead/overview.cpp" line="136"/>
<source>
(count)</source>
<translation>
(aantal)</translation>
</message>
<message>
<source>Resp. Rate</source>
<translatorcomment>WJG: afgebroken vanwege beschikbare ruimte</translatorcomment>
<translation type="obsolete">Ademtempo</translation>
</message>
<message>
<location filename="../sleepyhead/overview.cpp" line="131"/>
<source>Respiratory
Rate
(breaths/min)</source>
<translatorcomment>WJG: afbreeksreepje</translatorcomment>
<translation>Ademtempo
(per minuut)</translation>
</message>
<message>
<source>Tidal Volume</source>
<translation type="obsolete">Teugvolume</translation>
</message>
<message>
<location filename="../sleepyhead/overview.cpp" line="132"/>
<source>Tidal
Volume
(ml)</source>
<translatorcomment>WJG: maar misschien past het ook wel zonder afbreking
AK: Ik zie het nergens...
20/9 WJG: Als je met je cursor over de grafiek Tidal Vulume beweegt en op de grafiektitel gaat staan, zie je een geel hulptekstje verschijnen (is bij al die grafieken het geval). De breedte van die gele balonnetjes past zich aan de tekst aan - tot op zekere hoogte.</translatorcomment>
<translation>Teugvolume
(ml)</translation>
</message>
<message>
<source>Minute Vent.</source>
<translatorcomment>WJG: ik weet niet precies wat er getoond wordt, ik ken de waarden niet, maar 'minuutventitlatie' lijkt me niet goed. 'Minute' kan in het Engels ook 'zeer klein, miniem' betekenen, misschien moet het eerder in die richting gezocht worden, in plaats van met tijdeenheden?
AK: Nee, het is The average minute ventilation (tidal volume x rate).
Staat in: Instellingen-Grafieken</translatorcomment>
<translation type="obsolete">Minuutventilatie</translation>
</message>
<message>
<location filename="../sleepyhead/overview.cpp" line="133"/>
<source>Minute
Ventilation
(L/min)</source>
<translatorcomment>WJG: zie vorige</translatorcomment>
<translation>Minuutventilatie
(l/min)</translation>
</message>
<message>
<source>Target Vent.</source>
<translatorcomment>WJG: zit een beetje met het woord 'ventialtie'. Kan ook 'verversing' zijn. Mijn kennis van het lezen van deze grafiek schiet me hier echter te kort.
AK: Ik zie het nergens staan...
20/9 WJG: Is de een na onderste keuze in het dropdown menuutje rechtsonder</translatorcomment>
<translation type="obsolete">Doelventilatie</translation>
</message>
<message>
<location filename="../sleepyhead/overview.cpp" line="134"/>
<source>Target
Ventilation
(L/min)</source>
<translatorcomment>WJG: zie vorige</translatorcomment>
<translation>Doelventilatie
(l/min)</translation>
</message>
<message>
<source>Pat. Trig. Br.</source>
<translatorcomment>Staat in: Instellingen-Grafieken</translatorcomment>
<translation type="obsolete">Pat. geact. teugen</translation>
</message>
<message>
<location filename="../sleepyhead/overview.cpp" line="135"/>
<source>Patient
Triggered
Breaths
(%)</source>
<translatorcomment>WJG: als dit past is dit 'meer' Nederlands</translatorcomment>
<translation>Patient geactiveerde ademhaling
(PTB) (%)</translation>
</message>
<message>
<source>Sessions</source>
<translation type="obsolete">Sessies</translation>
</message>
<message>
<source>Sessions
(count)</source>
<translation type="obsolete">Sessies
(aantal)</translation>
</message>
<message>
<source>Pulse Rate</source>
<translation type="obsolete">Polsslag</translation>
</message>
<message>
<source>Pulse Rate
(bpm)</source>
<translation type="obsolete">Polsslag
(per minuut)</translation>
</message>
<message>
<location filename="../sleepyhead/overview.cpp" line="138"/>
<source>Oxygen Saturation
(%)</source>
<translation>Zuurstofsaturatie
(%)</translation>
</message>
<message>
<location filename="../sleepyhead/overview.cpp" line="141"/>
<source>Body
Mass
Index</source>
<translation>Body Mass Index
(BMI)</translation>
</message>
<message>
<source>Zombie</source>
<translation type="obsolete">Zombie</translation>
</message>
<message>
<location filename="../sleepyhead/overview.cpp" line="142"/>
<source>How you felt
(0-10)</source>
<translation>Hoe je je voelde
(0-10)</translation>
</message>
<message>
<location filename="../sleepyhead/overview.cpp" line="144"/>
<source>Events/Hr</source>
<translation>Incidenten/uur</translation>
</message>
<message>
<location filename="../sleepyhead/overview.cpp" line="159"/>
<source>Zombie Meter</source>
<translation>Zombie-meter</translation>
</message>
<message>
<source>FL</source>
<translation type="obsolete">FL</translation>
</message>
<message>
<location filename="../sleepyhead/overview.cpp" line="216"/>
<source>breaths/min</source>
<translation>teugen/min</translation>
</message>
<message>
<location filename="../sleepyhead/overview.cpp" line="224"/>
<source>L/b</source>
<translation>l/teug</translation>
</message>
<message>
<source>L/m</source>
<translation type="obsolete">l/min</translation>
</message>
<message>
<location filename="../sleepyhead/overview.cpp" line="246"/>
<source>%PTB</source>
<translatorcomment>WJG: patiënt-geactiveerde teugen? Of betekent PTB hier iets anders dan patient triggered breaths
AK: Ik zie het nergens...
Even afwachten</translatorcomment>
<translation>% PTB</translation>
</message>
<message>
<location filename="../sleepyhead/overview.cpp" line="273"/>
<source>% PB</source>
<translatorcomment>WJG: ? zie vorige
AK: Cyclische ademhaling kan niet: CA is al Centrale Apneu...</translatorcomment>
<translation>% Cyclische ademhaling
(PB)</translation>
</message>
<message>
<location filename="../sleepyhead/overview.cpp" line="578"/>
<source>Show all graphs</source>
<translation>Alle grafieken</translation>
</message>
<message>
<location filename="../sleepyhead/overview.cpp" line="584"/>
<source>No Graphs On!</source>
<translation>Grafieken staan uit!</translation>
</message>
<message>
<location filename="../sleepyhead/overview.cpp" line="593"/>
<source>Hide all graphs</source>
<translation>Verberg alle grafieken</translation>
</message>
</context>
<context>
<name>Oximetry</name>
<message>
<location filename="../sleepyhead/oximetry.ui" line="14"/>
<source>Form</source>
<translation>Formulier</translation>
</message>
<message>
<location filename="../sleepyhead/oximetry.ui" line="89"/>
<source>Date</source>
<translation>Datum</translation>
</message>
<message>
<location filename="../sleepyhead/oximetry.ui" line="102"/>
<source>d/MM/yy h:mm:ss AP</source>
<translation>dd/MM/jj uu:mm:ss AP</translation>
</message>
<message>
<location filename="../sleepyhead/oximetry.ui" line="131"/>
<source>R&eset</source>
<translation>R&eset</translation>
</message>
<message>
<location filename="../sleepyhead/oximetry.ui" line="160"/>
<source>SpO2</source>
<translation>SpO2</translation>
</message>
<message>
<location filename="../sleepyhead/oximetry.ui" line="245"/>
<source>Pulse</source>
<translation>Pols</translation>
</message>
<message>
<location filename="../sleepyhead/oximetry.ui" line="346"/>
<source>...</source>
<translation>...</translation>
</message>
<message>
<location filename="../sleepyhead/oximetry.ui" line="366"/>
<source>&Open .spo/R File</source>
<translation>&Open SpO/R bestand</translation>
</message>
<message>
<location filename="../sleepyhead/oximetry.ui" line="385"/>
<source>Serial &Import</source>
<translation>Seriële &import</translation>
</message>
<message>
<location filename="../sleepyhead/oximetry.ui" line="398"/>
<source>&Start Live</source>
<translation>&Start live</translation>
</message>
<message>
<location filename="../sleepyhead/oximetry.ui" line="421"/>
<source>Serial Port</source>
<translation>Seriële poort</translation>
</message>
<message>
<location filename="../sleepyhead/oximetry.ui" line="450"/>
<source>&Rescan Ports</source>
<translation>&Herscan poorten</translation>
</message>
<message>
<location filename="../sleepyhead/oximetry.cpp" line="1043"/>
<source>Control</source>
<translatorcomment>WJG: Ik heb geen oxymeter, kan in SleepyHead niet kijken wat hier bedoeld wordt. 'Control' kan verschillende betekenissen hebben: beheren en checken (contoleren)</translatorcomment>
<translation>Control</translation>
</message>
<message>
<location filename="../sleepyhead/oximetry.cpp" line="1085"/>
<location filename="../sleepyhead/oximetry.cpp" line="1602"/>
<source>No Oximetry Data</source>
<translation>Geen oxymetriegegevens</translation>
</message>
<message>
<location filename="../sleepyhead/oximetry.cpp" line="1183"/>
<source>Connect Oximeter</source>
<translation>Sluit oxymeter aan</translation>
</message>
<message>
<location filename="../sleepyhead/oximetry.cpp" line="1183"/>
<source>Please connect oximeter device</source>
<translation>Sluit aub de oxymeter aan</translation>
</message>
<message>
<location filename="../sleepyhead/oximetry.cpp" line="1235"/>
<source>Device Connected</source>
<translation>Oxymeter aangesloten</translation>
</message>
<message>
<location filename="../sleepyhead/oximetry.cpp" line="1235"/>
<source>Please make sure Oximeter device is in upload mode.</source>
<translation>Zet de oxymeter op UPLOAD</translation>
</message>
<message>
<location filename="../sleepyhead/oximetry.cpp" line="1255"/>
<source>Oximetry live recording has been terminated due to timeout.</source>
<translation>Oxymetrie live-opname is beëindigd vanwege time-out.</translation>
</message>
<message>
<location filename="../sleepyhead/oximetry.cpp" line="1264"/>
<location filename="../sleepyhead/oximetry.cpp" line="1479"/>
<source>&Start</source>
<translation>&Start</translation>
</message>
<message>
<location filename="../sleepyhead/oximetry.cpp" line="1282"/>
<location filename="../sleepyhead/oximetry.cpp" line="1774"/>
<location filename="../sleepyhead/oximetry.cpp" line="1829"/>
<source>Save Session?</source>
<translation>Sessie opslaan?</translation>
</message>
<message>
<location filename="../sleepyhead/oximetry.cpp" line="1282"/>
<source>Creating a new oximetry session will destroy the old one.
Would you like to save it first?</source>
<translation>Een nieuwe oxymetriesessie zal de oude wissen.
Wilt u de oude eerst opslaan?</translation>
</message>
<message>
<location filename="../sleepyhead/oximetry.cpp" line="1282"/>
<location filename="../sleepyhead/oximetry.cpp" line="1774"/>
<location filename="../sleepyhead/oximetry.cpp" line="1829"/>
<source>Save</source>
<translation>Opslaan</translation>
</message>
<message>
<location filename="../sleepyhead/oximetry.cpp" line="1282"/>
<location filename="../sleepyhead/oximetry.cpp" line="1774"/>
<location filename="../sleepyhead/oximetry.cpp" line="1829"/>
<source>Destroy It</source>
<translation>Wissen!</translation>
</message>
<message>
<location filename="../sleepyhead/oximetry.cpp" line="1282"/>
<location filename="../sleepyhead/oximetry.cpp" line="1774"/>
<location filename="../sleepyhead/oximetry.cpp" line="1829"/>
<source>Cancel</source>
<translation>Annuleren</translation>
</message>
<message>
<location filename="../sleepyhead/oximetry.cpp" line="1292"/>
<source>Please Wait</source>
<translation>Even geduld</translation>
</message>
<message>
<location filename="../sleepyhead/oximetry.cpp" line="1309"/>
<source>Oximetry Error!
Something is wrong with the device connection.</source>
<translation>Oxymetrie fout!
Er ging iets fout bij de aansluiting.</translation>
</message>
<message>
<location filename="../sleepyhead/oximetry.cpp" line="1345"/>
<source>&Stop</source>
<translation>&Stop</translation>
</message>
<message>
<location filename="../sleepyhead/oximetry.cpp" line="1431"/>
<source>Oximeter Error
The device has not responded.. Make sure it's switched on.</source>
<translation>Oxymetrie fout!
Het apparaat reageerde niet... staat het wel aan?</translation>
</message>
<message>
<location filename="../sleepyhead/oximetry.cpp" line="1577"/>
<source>Keep This Recording?</source>
<translation>Deze gegevens bewaren?</translation>
</message>
<message>
<location filename="../sleepyhead/oximetry.cpp" line="1577"/>
<source>Would you like to save this oximetery session?</source>
<translation>Wil je deze oxymetie sessie bewaren?</translation>
</message>
<message>
<location filename="../sleepyhead/oximetry.cpp" line="1774"/>
<source>Opening this oximetry file will destroy the current session.
Would you like to keep it?</source>
<translation>De huidige sessie gaat verloren als je dit bestand opent.
Wil je hem bewaren?</translation>
</message>
<message>
<location filename="../sleepyhead/oximetry.cpp" line="1784"/>
<source>Select an oximetry file</source>
<translation>Kies een oxymetrie bestand</translation>
</message>
<message>
<location filename="../sleepyhead/oximetry.cpp" line="1784"/>
<source>Oximetry Files (*.spo *.spoR)</source>
<translation>Oxymetrie bestanden (*.spo, *.spoR)</translation>
</message>
<message>
<location filename="../sleepyhead/oximetry.cpp" line="1798"/>
<source>Couldn't open oximetry file "</source>
<translation>Kon het oxymeter bestand niet openen "</translation>
</message>
<message>
<location filename="../sleepyhead/oximetry.cpp" line="1829"/>
<source>Opening this oximetry session will destroy the unsavedsession in the oximetry tab.
Would you like to store it first?</source>
<translation>Als je deze oxymetie sessie opent, gaat de niet opgeslagen sessie verloren.
Wil je deze eerst opslaan?</translation>
</message>
<message>
<source>Ready</source>
<translation type="obsolete">Klaar</translation>
</message>
<message>
<location filename="../sleepyhead/oximetry.cpp" line="1442"/>
<source>Check Oximeter is Ready</source>
<translatorcomment>WJG: spelling</translatorcomment>
<translation>Controleer of de oxymeter aan staat</translation>
</message>
<message>
<location filename="../sleepyhead/oximetry.cpp" line="1462"/>
<source>Oximeter Error
The device did not respond.. Make sure it's switched on.</source>
<translatorcomment>WJG: ik vermoed een inconsistentie bij de naker van het programma (zie vertaling twee regels hierboven): de werkwoordtijden zijn verschillend, maar de bedoeling zal hetzelfde zijn.</translatorcomment>
<translation>Oxymetriefout!
Het apparaat reageerde niet... staat het wel aan?</translation>
</message>
<message>
<location filename="../sleepyhead/oximetry.cpp" line="1515"/>
<source>Please make sure your oximeter is switched on, and in the right mode to transmit data.</source>
<translation>Controleer of de oxymeter aan staat en op gegevensoverdracht is ingesteld.</translation>
</message>
<message>
<location filename="../sleepyhead/oximetry.cpp" line="1515"/>
<source>Oximeter Error!</source>
<translation>Oxymeterfout!</translation>
</message>
</context>
<context>
<name>PreferencesDialog</name>
<message>
<location filename="../sleepyhead/preferencesdialog.ui" line="23"/>
<source>Preferences</source>
<translation>Instellingen</translation>
</message>
<message>
<location filename="../sleepyhead/preferencesdialog.ui" line="58"/>
<source>&Import</source>
<translation>&Importeer</translation>
</message>
<message>
<location filename="../sleepyhead/preferencesdialog.ui" line="79"/>
<source>Session Settings</source>
<translation>Sessie-instellingen</translation>
</message>
<message>
<location filename="../sleepyhead/preferencesdialog.ui" line="102"/>
<source>Combine Close Sessions </source>
<translation>Combineer nabije sessies</translation>
</message>
<message>
<location filename="../sleepyhead/preferencesdialog.ui" line="112"/>
<location filename="../sleepyhead/preferencesdialog.ui" line="197"/>
<source>Minutes</source>
<translation>Minuten</translation>
</message>
<message>
<location filename="../sleepyhead/preferencesdialog.ui" line="132"/>
<source>Multiple sessions closer together than this value will be kept on the same day.
</source>
<translation>Tijd tussen sessies die tot dezelfde dag gerekend moeten worden.</translation>
</message>
<message>
<location filename="../sleepyhead/preferencesdialog.ui" line="187"/>
<source>Ignore Short Sessions</source>
<translation>Negeer korte sessies</translation>
</message>
<message>
<location filename="../sleepyhead/preferencesdialog.ui" line="211"/>
<source><!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0//EN" "http://www.w3.org/TR/REC-html40/strict.dtd">
<html><head><meta name="qrichtext" content="1" /><style type="text/css">
p, li { white-space: pre-wrap; }
</style></head><body style=" font-family:'Cantarell'; font-size:11pt; font-weight:400; font-style:normal;">
<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;">Sessions shorter in duration than this will not be displayed<span style=" font-style:italic;">.</span></p>
<p style="-qt-paragraph-type:empty; margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px; font-style:italic;"></p></body></html></source>
<translation><!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0//EN" "http://www.w3.org/TR/REC-html40/strict.dtd">
<html><head><meta name="qrichtext" content="1" /><style type="text/css">
p, li { white-space: pre-wrap; }
</style></head><body style=" font-family:'Cantarell'; font-size:11pt; font-weight:400; font-style:normal;">
<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;">Kortere sessies worden niet weergegeven<span style=" font-style:italic;">.</span></p>
<p style="-qt-paragraph-type:empty; margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px; font-style:italic;"></p></body></html></translation>
</message>
<message>
<location filename="../sleepyhead/preferencesdialog.ui" line="252"/>
<source>Day Split Time</source>
<translation>Volgende dag start om </translation>
</message>
<message>
<location filename="../sleepyhead/preferencesdialog.ui" line="262"/>
<source>Sessions starting before this time will go to the previous calendar day.</source>
<translation>Sessies die voor dit tijdstip startten horen bij de vorige dag.</translation>
</message>
<message>
<location filename="../sleepyhead/preferencesdialog.ui" line="282"/>
<source>Keep session data in memory to speed up revisiting days.</source>
<translation>Houd sessiegegevens in geheugen voor hogere snelheid.</translation>
</message>
<message>
<location filename="../sleepyhead/preferencesdialog.ui" line="285"/>
<source>Cache Session Data (uses more system memory)</source>
<translation>Cache sessiegegevens (kost meer geheugen)</translation>
</message>
<message>
<location filename="../sleepyhead/preferencesdialog.ui" line="316"/>
<source>Session Storage Options</source>
<translation>Opties voor sessie-opslag</translation>
</message>
<message>
<location filename="../sleepyhead/preferencesdialog.ui" line="340"/>
<source>This maintains a backup of SD-card data for ResMed machines,
ResMed machines delete high resolution data older than 7 days,
and graph data older than 30 days..
SleepyHead can keep a copy of this data if you ever need to reinstall.
(Highly recomended, unless your short on disk space or don't care about the graph data)</source>
<translatorcomment>WJG: kleine spellingsdingetjes, o.a. de twee hoofdletters in SleepyHead; die Mark is zelf niet altijd consistent, maar het is dan ook geen linguïst
AK: <grin></translatorcomment>
<translation>Dit zorgt voor een back-up van de SD-kaart voor ResMed-apparaten,
ResMed apparaten verwijderen hoge resolutie-gegevens ouder dan 7 dagen,
en grafiekgegevens die ouder zijn dan 30 dagen..
SleepyHead kan een kopie van deze gegevens bewaren voor na een herinstallatie.
(Sterk aanbevolen, tenzij je weinig schijfruimte hebt of niets om grafiekgegevens geeft)</translation>
</message>
<message>
<location filename="../sleepyhead/preferencesdialog.ui" line="349"/>
<source>Create SD Card Backups during Import (only for ResMed so far, highly recommended)</source>
<translation>Maak tijdens importeren een back-up van de SD-kaart (alleen nog voor ResMed, sterk aan te bevelen)</translation>
</message>
<message>
<location filename="../sleepyhead/preferencesdialog.ui" line="356"/>
<source>This makes SleepyHead's data take around half as much space.
But it makes import and day changing take longer..
If you've got a new computer with a small solid state disk, this is a good option.</source>
<translatorcomment>WJG: iets te kort door de bocht in de eerste regel, want de opslag wordt niet langzamer (dat kan ook niet), maar de processen gaan trager
AK: In SSD zit al een disk, dus niet nog eens schijf... En het is niet eens een schijf ;-))
20/9 WJG: De facto heb je natuurlijk gelijk, alleen wordt er in de volksmond wel over een schijf gesproken.
AK: Dank je! Je hebt gelijk...</translatorcomment>
<translation>De grootte van de opslag wordt gehalveerd,
maar maakt het importeren en verwerken trager.
Als je een nieuwe computer met SSD hebt, is dit een goede keuze.</translation>
</message>
<message>
<location filename="../sleepyhead/preferencesdialog.ui" line="361"/>
<source>Compress Session Data (makes SleepyHead data smaller, but day changing slower.)</source>
<translation>Comprimeer sessiegegevens (minder opslagruimte, maar tragere verwerking).</translation>
</message>
<message>
<location filename="../sleepyhead/preferencesdialog.ui" line="368"/>
<source>Compress ResMed (EDF) backups to save disk space.
Backed up EDF files are stored in the .gz format,
which is common on Mac & Linux platforms..
SleepyHead can import from this compressed backup directory natively..
To use with ResScan will require the .gz files to be uncompressed first..</source>
<translation>Comprimeer ResMed (EDF) back-ups om schijfruimte te besparen.
Back-ups van EDF bestanden worden opgeslagen in het gz-formaat,
dat veel gebruikt wordt op Mac & Linux-systemen ..
SleepyHead kan hier rechtstreeks uit importeren,
maar voor ResScan moeten de .gz-bestanden eerst uitgepakt worden.</translation>
</message>
<message>
<location filename="../sleepyhead/preferencesdialog.ui" line="376"/>
<source>Compress SD Card Backups (slower first import, but makes backups smaller)</source>
<translation>Comprimeer SD-kaartback-ups (langzamere eerste import, maar minder opslagruimte nodig)</translation>
</message>
<message>
<location filename="../sleepyhead/preferencesdialog.ui" line="388"/>
<source>The following options affect the amount of disk space SleepyHead uses, and all have an effect on how long import takes.</source>
<translation>De volgende opties hebben effect op de gebruikte schijfruimte en op de snelheid van importeren.</translation>
</message>
<message>
<location filename="../sleepyhead/preferencesdialog.ui" line="398"/>
<source><!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0//EN" "http://www.w3.org/TR/REC-html40/strict.dtd">
<html><head><meta name="qrichtext" content="1" /><style type="text/css">
p, li { white-space: pre-wrap; }
</style></head><body style=" font-family:'Sans'; font-size:10pt; font-weight:400; font-style:normal;">
<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><span style=" font-style:italic;">Changing SD Backup compression options doesn't automatically recompress backup data. </span></p></body></html></source>
<translation><!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0//EN" "http://www.w3.org/TR/REC-html40/strict.dtd">
<html><head><meta name="qrichtext" content="1" /><style type="text/css">
p, li { white-space: pre-wrap; }
</style></head><body style=" font-family:'Sans'; font-size:10pt; font-weight:400; font-style:normal;">
<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><span style=" font-style:italic;">Wijzigen van SD-backupcompressie comprimeert de back-upgegevens niet automatisch opnieuw. </span></p></body></html></translation>
</message>
<message>
<location filename="../sleepyhead/preferencesdialog.ui" line="429"/>
<source>&CPAP</source>
<translation>&Masker en apparaat</translation>
</message>
<message>
<location filename="../sleepyhead/preferencesdialog.ui" line="456"/>
<source>CPAP Mask Information</source>
<translation>Informatie over het masker</translation>
</message>
<message>
<location filename="../sleepyhead/preferencesdialog.ui" line="483"/>
<source>Mask Type</source>
<translation>Soort masker</translation>
</message>
<message>
<location filename="../sleepyhead/preferencesdialog.ui" line="490"/>
<source>Generic mask type. Select the one that's closest to your mask.</source>
<translation>Algemeen maskertype. Kies wat het beste overeenkomt.</translation>
</message>
<message>
<location filename="../sleepyhead/preferencesdialog.ui" line="508"/>
<source>Description</source>
<translation>Beschrijving</translation>
</message>
<message>
<location filename="../sleepyhead/preferencesdialog.ui" line="515"/>
<source>The name of your mask, or at least the name you call it.</source>
<translation>De naam van het masker, of zoals je het noemt.</translation>
</message>
<message>
<location filename="../sleepyhead/preferencesdialog.ui" line="528"/>
<source>Method of unintentional leaks calculation if not provided by your machine.
Note: Statistical Model is experimental.</source>
<translatorcomment>WJG: spreken we de gebruiker met 'u' of 'je' aan? Vaak tutoyeer je, wat gezien de luchtige toon van de teksten ook mijn voorkeur heeft. Denk dat de hele vertaling nog een keer hierop nagelopen moet worden.</translatorcomment>
<translation type="unfinished">Wijze van berekening van maskerlekkag , als het apparaat dat niet zelf doet.
Opmerking: Het statistisch model is experimenteel.</translation>
</message>
<message>
<location filename="../sleepyhead/preferencesdialog.ui" line="533"/>
<source>Mask Profile</source>
<translation>Masker lekprofiel</translation>
</message>
<message>
<location filename="../sleepyhead/preferencesdialog.ui" line="538"/>
<source>Statistical Model</source>
<translation>Statistisch model</translation>
</message>
<message>
<location filename="../sleepyhead/preferencesdialog.ui" line="552"/>
<source>Leak calcs</source>
<translatorcomment>Lekkage?
20/9 WJG: Nergens anders wordt 'lekkage' gebruikt - al zou dat wel een beter woord zijn</translatorcomment>
<translation>Berekening lekkage</translation>
</message>
<message>
<location filename="../sleepyhead/preferencesdialog.ui" line="565"/>
<source>Started Using</source>
<translation>Start gebruik</translation>
</message>
<message>
<location filename="../sleepyhead/preferencesdialog.ui" line="578"/>
<source>The date you started using this mask</source>
<translation>De datum waarop je het masker in gebruik nam</translation>
</message>
<message>
<location filename="../sleepyhead/preferencesdialog.ui" line="594"/>
<source>Leak Profile</source>
<translation>Masker lekprofiel</translation>
</message>
<message>
<location filename="../sleepyhead/preferencesdialog.ui" line="608"/>
<source>Pressure</source>
<translation>Druk</translation>
</message>
<message>
<location filename="../sleepyhead/preferencesdialog.ui" line="613"/>
<source>Leak</source>
<translation>Lekkage</translation>
</message>
<message>
<location filename="../sleepyhead/preferencesdialog.ui" line="626"/>
<source><!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0//EN" "http://www.w3.org/TR/REC-html40/strict.dtd">
<html><head><meta name="qrichtext" content="1" /><style type="text/css">
p, li { white-space: pre-wrap; }
</style></head><body style=" font-family:'Sans'; font-size:10pt; font-weight:400; font-style:italic;">
<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><span style=" font-weight:600; font-style:normal;">Note: </span>Leak profiles currently does not work yet..</p></body></html></source>
<translation><!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0//EN" "http://www.w3.org/TR/REC-html40/strict.dtd">
<html><head><meta name="qrichtext" content="1" /><style type="text/css">
p, li { white-space: pre-wrap; }
</style></head><body style=" font-family:'Sans'; font-size:10pt; font-weight:400; font-style:italic;">
<p align="justify" style="-qt-paragraph-type:empty; margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"></p>
<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><span style=" font-weight:600; font-style:normal;">Let op: </span>Het onderstaande werkt nog niet...</p></body></html></translation>
</message>
<message>
<location filename="../sleepyhead/preferencesdialog.ui" line="655"/>
<source>Shows Respiratory Disturbance Index instead of Apnea/Hypopnea Index (RDI=AHI + RERA)</source>
<translatorcomment>WJG: is voor RDI geen Nederlandse vertaling? Is natuurlijk het probleem met veel van die afkortingen.
AK: Mss later?</translatorcomment>
<translation>Toont Respiratory Disturbance Index ipv Apneu / Hypopneu Index (RDI = AHI + RERA)</translation>
</message>
<message>
<location filename="../sleepyhead/preferencesdialog.ui" line="658"/>
<source>Use RDI instead of AHI (PRS1 only)</source>
<translation>Gebruik RDI in plaats van AHI (alleen bij PRS1)</translation>
</message>
<message>
<location filename="../sleepyhead/preferencesdialog.ui" line="665"/>
<source>Don't show any compliance information</source>
<translatorcomment>WJG: lastige. Ik denk dat het hier gaat om het al dan niet opvolgen van het gebruik. Gaat hier om het aantal uren dat je het masker per nacht gebruikt. Compliance is naleving in de zin van wetten, maar voor ander gebruik zeg je wat anders. 'Opvolgen' is er een voor, maar ik vind dat het allemaal niet zo lekker past. Kortom, hier ben ik niet helemaal uit.
AK: Compliantie is al gebruikelijk,therapietrouw is dè uitdrukking</translatorcomment>
<translation type="unfinished">Toon informatie over therapietrouw</translation>
</message>
<message>
<location filename="../sleepyhead/preferencesdialog.ui" line="668"/>
<source>Show Compliance</source>
<translatorcomment>AK: Het gaat om de juridische term...
20/9 WJG: Dat lijkt me wat sterk... Er zijn toch geen wettelijke sancties verbonden aan het al dan niet gebruiken van je masker?
AK: Zie hier boven</translatorcomment>
<translation>Laat therapietrouw zien</translation>
</message>
<message>
<location filename="../sleepyhead/preferencesdialog.ui" line="698"/>
<source>Regard days with under this usage as "incompliant". 4 hours is usually considered compliant.</source>
<translatorcomment>WJG: bij gebrek aan beter, maar 'niet-compliant' en 'compliant' zijn geen termen die je in Van Dale tegenkomt
Als ze het maar begrijpen, klachten mogen </translatorcomment>
<translation>Beschouw dagen met minder gebruik als "niet-therapietrouw". 4 uur wordt meestal als "therapietrouw" beschouwd .</translation>
</message>
<message>
<location filename="../sleepyhead/preferencesdialog.ui" line="701"/>
<source> hours</source>
<translation> uren</translation>
</message>
<message>
<location filename="../sleepyhead/preferencesdialog.ui" line="723"/>
<source>as over</source>
<translation>indien meer dan </translation>
</message>
<message>
<location filename="../sleepyhead/preferencesdialog.ui" line="730"/>
<source>of usage per night</source>
<translation>gebruik per nacht</translation>
</message>
<message>
<location filename="../sleepyhead/preferencesdialog.ui" line="740"/>
<source>Enable/disable experimental event flagging enhancements.
It allows detecting borderline events, and some the machine missed.
This option must be enabled before import, otherwise a purge is required.</source>
<translation>Zet experimentele incidentmarkeringen aan of uit.
Dat detecteert incidenten 'op het randje' en door het apparaat gemiste incidenten.
Deze optie moet worden aangezet vóór het importeren, anders eerst alles wissen...</translation>
</message>
<message>
<location filename="../sleepyhead/preferencesdialog.ui" line="745"/>
<source>Custom User Event Flagging</source>
<translatorcomment>AK: Het is een keuze van de gebruiker...
20/9 WJG: Oké, maar dan moet het streepje weg.</translatorcomment>
<translation>Aangepaste gebruikers markering</translation>
</message>
<message>
<location filename="../sleepyhead/preferencesdialog.ui" line="775"/>
<source>Flow Restriction</source>
<translatorcomment>AK: Inderdaad, afsluiting is 0%, hier kan je kiezen,
Debietreductie
Debietbeperking
Stroombeperking
Debietbegrenzing
Doorstroombeperking</translatorcomment>
<translation>Debietreductie</translation>
</message>
<message>
<location filename="../sleepyhead/preferencesdialog.ui" line="788"/>
<source>Percentage of restriction in airflow from the median value.
A value of 20% works well for detecting apneas. </source>
<translation>Percentage van de vermindering van de luchtstroom ten opzichte van de mediane waarde.
Een waarde van 20% werkt goed voor het opsporen van apneus.</translation>
</message>
<message>
<location filename="../sleepyhead/preferencesdialog.ui" line="792"/>
<location filename="../sleepyhead/preferencesdialog.ui" line="1274"/>
<source>%</source>
<translation>%</translation>
</message>
<message>
<location filename="../sleepyhead/preferencesdialog.ui" line="826"/>
<source><!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0//EN" "http://www.w3.org/TR/REC-html40/strict.dtd">
<html><head><meta name="qrichtext" content="1" /><style type="text/css">
p, li { white-space: pre-wrap; }
</style></head><body style=" font-family:'Sans'; font-size:10pt; font-weight:400; font-style:italic;">
<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;">Custom flagging is an experimental method of detecting events missed by the machine. They are <span style=" text-decoration: underline;">not</span> included in AHI.</p></body></html></source>
<translation><!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0//EN" "http://www.w3.org/TR/REC-html40/strict.dtd">
<html><head><meta name="qrichtext" content="1" /><style type="text/css">
p, li { white-space: pre-wrap; }
</style></head><body style=" font-family:'Sans'; font-size:10pt; font-weight:400; font-style:italic;">
<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;">Aangepast markeren is een experimentele werkwijze voor het detecteren van incidenten die zijn gemist door het apparaat. Ze worden <span style=" text-decoration: underline;">niet </ span> opgenomen in de AHI.</p></body></html></translation>
</message>
<message>
<location filename="../sleepyhead/preferencesdialog.ui" line="843"/>
<source>Duration of airflow restriction</source>
<translatorcomment>20/9 WJG: Vanaf hier weer verder gegaan</translatorcomment>
<translation>Duur van de vermindering van de luchtstroom</translation>
</message>
<message>
<location filename="../sleepyhead/preferencesdialog.ui" line="846"/>
<location filename="../sleepyhead/preferencesdialog.ui" line="1319"/>
<location filename="../sleepyhead/preferencesdialog.ui" line="1332"/>
<location filename="../sleepyhead/preferencesdialog.ui" line="1355"/>
<source>s</source>
<translation> s</translation>
</message>
<message>
<location filename="../sleepyhead/preferencesdialog.ui" line="859"/>
<source>Event Duration</source>
<translation>Tijdsduur</translation>
</message>
<message>
<location filename="../sleepyhead/preferencesdialog.ui" line="866"/>
<source>Allow duplicates near machine events.</source>
<translatorcomment>20/9 WJG: Maar ik kan deze tekst niet terugvinden op het tabblad CPAP van Preferences
AK: inderdaad, vreemd</translatorcomment>
<translation>Sta duplicaten naast machinegebeurtenissen toe.</translation>
</message>
<message>
<location filename="../sleepyhead/preferencesdialog.ui" line="876"/>
<source>AHI/Hour Graph Settings</source>
<translation>Instelling grafiek AHI/uur</translation>
</message>
<message>
<location filename="../sleepyhead/preferencesdialog.ui" line="909"/>
<source>Window</source>
<translatorcomment>20/9 WJG: past beter in het schermpje en is ook wel duidelijk. Ik kan deze instelling overigens niet wijzigen</translatorcomment>
<translation>Tijdsduur </translation>
</message>
<message>
<location filename="../sleepyhead/preferencesdialog.ui" line="916"/>
<source>Adjusts the amount of data considered for each point in the AHI/Hour graph.
Defaults to 60 minutes.. Highly recommend it's left at this value.</source>
<translation>Regelt de hoeveelheid gegevens die worden beschouwd voor elk punt in de grafiek AHI/uur.
Staat standaard op 60 minuten. Sterk aanbevolen het op deze waarde te laten staan,
anders is het geen AHI/uur meer.</translation>
</message>
<message>
<location filename="../sleepyhead/preferencesdialog.ui" line="920"/>
<source> minutes</source>
<translation> minuten</translation>
</message>
<message>
<location filename="../sleepyhead/preferencesdialog.ui" line="936"/>
<source>Reset the counter to zero at beginning of each (time) window.</source>
<translation type="unfinished">Zet de teller op nul aan het begin van elke periode.</translation>
</message>
<message>
<location filename="../sleepyhead/preferencesdialog.ui" line="939"/>
<source>Zero Reset</source>
<translation>Telkens op nul zetten</translation>
</message>
<message>
<location filename="../sleepyhead/preferencesdialog.ui" line="968"/>
<source>CPAP Clock Drift</source>
<translation>Correctie afwijking klok CPAP</translation>
</message>
<message>
<location filename="../sleepyhead/preferencesdialog.ui" line="975"/>
<source>Don't touch this unless you know your CPAP clock is out.
Try to sync it to your PC's clock (which should be synced to a timeserver)</source>
<translatorcomment>20/9 WJG: beslissing nemen over aanspreekpersoon en dat consistent doorvoeren</translatorcomment>
<translation>Wijzig dit niet, tenzij je zeker weet dat de klok van je CPAP fout staat.
Probeer hem eerst te synchroniseren met de klok van de PC ( niet mogelijk voor PRS1).</translation>
</message>
<message>
<location filename="../sleepyhead/preferencesdialog.ui" line="979"/>
<source> seconds</source>
<translation> seconden</translation>
</message>
<message>
<location filename="../sleepyhead/preferencesdialog.ui" line="998"/>
<source>&Events</source>
<translatorcomment>Deze tab zie ik niet...</translatorcomment>
<translation>&Incidenten</translation>
</message>
<message>
<location filename="../sleepyhead/preferencesdialog.ui" line="1019"/>
<source>Not entirely sure if this will get to live or not..</source>
<translatorcomment>20/9 WJG: Mooi compact</translatorcomment>
<translation>Onzeker of dit ooit gaat werken..</translation>
</message>
<message>
<location filename="../sleepyhead/preferencesdialog.ui" line="1039"/>
<source>Show</source>
<translation>Tonen</translation>
</message>
<message>
<location filename="../sleepyhead/preferencesdialog.ui" line="1047"/>
<source>Colour</source>
<translation>Kleur</translation>
</message>
<message>
<location filename="../sleepyhead/preferencesdialog.ui" line="1055"/>
<source>Event</source>
<translatorcomment>Staat in: Instellingen-Grafieken</translatorcomment>
<translation>Incident</translation>
</message>
<message>
<location filename="../sleepyhead/preferencesdialog.ui" line="1060"/>
<source>ID</source>
<translation>ID</translation>
</message>
<message>
<location filename="../sleepyhead/preferencesdialog.ui" line="1069"/>
<source>Graphs</source>
<translation>Grafieken</translation>
</message>
<message>
<location filename="../sleepyhead/preferencesdialog.ui" line="1092"/>
<source>Search</source>
<translation>Zoeken</translation>
</message>
<message>
<location filename="../sleepyhead/preferencesdialog.ui" line="1099"/>
<source>Filters the graph list. Simply start typing the name of the graph your looking for.</source>
<translation>Filtert de grafiek lijst. Gewoon beginnen met het typen van de naam van de grafiek die je zoekt.</translation>
</message>
<message>
<location filename="../sleepyhead/preferencesdialog.ui" line="1132"/>
<source>&Defaults</source>
<translation>&Standaardinstellingen</translation>
</message>
<message>
<location filename="../sleepyhead/preferencesdialog.ui" line="1139"/>
<source>Double click on the (Y-axis) min/max values to edit them</source>
<translation>Dubbelklik op de min/max waarden om de Y-as te wijzigen</translation>
</message>
<message>
<location filename="../sleepyhead/preferencesdialog.ui" line="1150"/>
<source>&Oximetry</source>
<translation>&Oxymetrie</translation>
</message>
<message>
<location filename="../sleepyhead/preferencesdialog.ui" line="1171"/>
<source>Use Oximetry</source>
<translation>Gebruik oxymeter</translation>
</message>
<message>
<location filename="../sleepyhead/preferencesdialog.ui" line="1201"/>
<source>Type</source>
<translation>Type</translation>
</message>
<message>
<location filename="../sleepyhead/preferencesdialog.ui" line="1215"/>
<source>Contec CMS50</source>
<translation>Contec CMS50</translation>
</message>
<message>
<source>Overpriced ResMed S9 Oximeter</source>
<translation type="obsolete">(Te dure) ResMed S9 oxymeter</translation>
</message>
<message>
<location filename="../sleepyhead/preferencesdialog.ui" line="1229"/>
<source>Tries to forces the oximetry data to link with CPAP when possible.</source>
<translation>Dwingt de oxymetergegevens te koppelen met de CPAP, indien mogelijk.</translation>
</message>
<message>
<location filename="../sleepyhead/preferencesdialog.ui" line="1232"/>
<source>Link Oximetry and CPAP graphs</source>
<translation>Koppel oxymeter met andere grafieken</translation>
</message>
<message>
<location filename="../sleepyhead/preferencesdialog.ui" line="1252"/>
<source>Flag changes in oximetry stats</source>
<translation>Markeer veranderingen in oxymeterstatistieken</translation>
</message>
<message>
<location filename="../sleepyhead/preferencesdialog.ui" line="1264"/>
<source>SPO2</source>
<translation>SpO2</translation>
</message>
<message>
<location filename="../sleepyhead/preferencesdialog.ui" line="1271"/>
<source>Percentage drop in oxygen saturation</source>
<translatorcomment>20/9 WJG: Zuurstof wellicht niet echt nodig?</translatorcomment>
<translation>Percentage daling van zuurstofsaturatie</translation>
</message>
<message>
<location filename="../sleepyhead/preferencesdialog.ui" line="1293"/>
<source>Pulse</source>
<translatorcomment>209/ WJG: Als 't past</translatorcomment>
<translation>Polsslag</translation>
</message>
<message>
<location filename="../sleepyhead/preferencesdialog.ui" line="1300"/>
<source>Sudden change in Pulse Rate of at least this amount</source>
<translation>Plotselinge verandering in polsslag van tenminste deze hoeveelheid</translation>
</message>
<message>
<location filename="../sleepyhead/preferencesdialog.ui" line="1303"/>
<source> bpm</source>
<translatorcomment>20/9 WJG: slagen per minuut</translatorcomment>
<translation> per minuut</translation>
</message>
<message>
<location filename="../sleepyhead/preferencesdialog.ui" line="1316"/>
<source>Minimum duration of drop in oxygen saturation</source>
<translation>Minimale duur van de verlaging</translation>
</message>
<message>
<location filename="../sleepyhead/preferencesdialog.ui" line="1329"/>
<source>Minimum duration of pulse change event.</source>
<translation>Minimale duur van de verandering.</translation>
</message>
<message>
<location filename="../sleepyhead/preferencesdialog.ui" line="1342"/>
<source>Discard chunks under</source>
<translation>Verwaarloos als korter dan </translation>
</message>
<message>
<location filename="../sleepyhead/preferencesdialog.ui" line="1352"/>
<source>Small chunks of oximetry data under this amount will be discarded.</source>
<translation>Kortdurende oxymetrie-incidenten worden verwaarloosd.</translation>
</message>
<message>
<source><!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0//EN" "http://www.w3.org/TR/REC-html40/strict.dtd">
<html><head><meta name="qrichtext" content="1" /><style type="text/css">
p, li { white-space: pre-wrap; }
</style></head><body style=" font-family:'Sans'; font-size:10pt; font-weight:400; font-style:normal;">
<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><span style=" font-weight:600;">Syncing Oximetry and CPAP Data</span></p>
<p align="justify" style="-qt-paragraph-type:empty; margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"></p>
<p align="justify" style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;">CMS50 data imported from SpO2Review (from .spoR files) or the serial import method does <span style=" font-weight:600; text-decoration: underline;">not</span> have the correct timestamp needed to sync.</p>
<p align="justify" style="-qt-paragraph-type:empty; margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"></p>
<p align="justify" style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;">Live view mode (using a serial cable) is one way to acheive an accurate sync on CMS50 oximeters, but does not counter for CPAP clock drift.</p>
<p align="justify" style="-qt-paragraph-type:empty; margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"></p>
<p align="justify" style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;">If you start your Oximeters recording mode at <span style=" font-style:italic;">exactly </span>the same time you start your CPAP machine, you can now also achieve sync. </p>
<p align="justify" style="-qt-paragraph-type:empty; margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"></p>
<p align="justify" style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;">The serial import process takes the starting time from last nights first CPAP session. (Remember to import your CPAP data first!)</p></body></html></source>
<translatorcomment>20/9 WJG: Iets met koppeltekens gedaan en u in je veranderd</translatorcomment>
<translation type="obsolete"><!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0//EN" "http://www.w3.org/TR/REC-html40/strict.dtd">
<html><head><meta name="qrichtext" content="1" /><style type="text/css">
p, li { white-space: pre-wrap; }
</style></head><body style=" font-family:'Sans'; font-size:10pt; font-weight:400; font-style:normal;">
<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><span style=" font-weight:600;">Synchronisatie van oximetrie- en CPAP-gegevens</span></p>
<p align="justify" style="-qt-paragraph-type:empty; margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"></p>
<p align="justify" style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;">De geïmporteerde gegevens van de CMS50 uit SpO2Review (dus uit .spoR bestanden) zowel als de seriële import methode hebben <span style=" font-weight:600; text-decoration: underline;">niet</span> de correcte tijdsaanduiding die voor synchronisatie nodig is.</p>
<p align="justify" style="-qt-paragraph-type:empty; margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"></p>
<p align="justify" style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;">Live view-modus (met een seriële kabel) is een manier om een nauwkeurige synchronisatie op CMS50 oxymeters te bereiken, maar houdt geen rekening met de verlopende CPAP klok.</p>
<p align="justify" style="-qt-paragraph-type:empty; margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"></p>
<p align="justify" style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;">Als de opname van de oxymeter <span style=" font-style:italic;"> precies </span> tegelijk met de CPAP wordt gestart,is er ook synchronisatie bereikt. </p>
<p align="justify" style="-qt-paragraph-type:empty; margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"></p>
<p align="justify" style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;">Het proces van seriële import neemt de starttijd van de eerste CPAP sessie van de afgelopen nacht. (Vergeet niet om eerst de CPAP gegevens te importeren!)</p></body></html></translation>
</message>
<message>
<location filename="../sleepyhead/preferencesdialog.ui" line="1404"/>
<source>&General</source>
<translation>&Algemeen</translation>
</message>
<message>
<location filename="../sleepyhead/preferencesdialog.ui" line="1425"/>
<source>General Settings</source>
<translation>Algemene instellingen</translation>
</message>
<message>
<location filename="../sleepyhead/preferencesdialog.ui" line="1446"/>
<source>Daily view navigation buttons will skip over days without data records</source>
<translation>De navigatieknoppen slaan de dagen zonder gegevens over</translation>
</message>
<message>
<location filename="../sleepyhead/preferencesdialog.ui" line="1449"/>
<source>Skip over Empty Days</source>
<translation>Sla lege dagen over</translation>
</message>
<message>
<location filename="../sleepyhead/preferencesdialog.ui" line="1456"/>
<source>Allow use of multiple CPU cores where available to improve performance.
Mainly affects the importer.</source>
<translation>Gebruik meerdere CPU-cores voor betere prestaties.
Werkt vooral bij importeren.</translation>
</message>
<message>
<location filename="../sleepyhead/preferencesdialog.ui" line="1460"/>
<source>Enable Multithreading</source>
<translation>Multithreading inschakelen</translation>
</message>
<message>
<location filename="../sleepyhead/preferencesdialog.ui" line="1467"/>
<source>Bypass the login screen and load the most recent User Profile</source>
<translation>Sla het inlogscherm over en laad het meest recente gebruikersprofiel</translation>
</message>
<message>
<location filename="../sleepyhead/preferencesdialog.ui" line="1470"/>
<source>Skip Login Screen</source>
<translation>Sla login-scherm over</translation>
</message>
<message>
<location filename="../sleepyhead/preferencesdialog.ui" line="1489"/>
<source>Changes to the following settings needs a restart, but not a recalc.</source>
<translation>Wijzigingen in de volgende instellingen werken pas na een herstart, maar er is geen herberekening nodig.</translation>
</message>
<message>
<location filename="../sleepyhead/preferencesdialog.ui" line="1492"/>
<source>Preferred Calculation Methods</source>
<translation>Voorkeur berekeningsmethoden</translation>
</message>
<message>
<location filename="../sleepyhead/preferencesdialog.ui" line="1519"/>
<source>Middle Calculations</source>
<translation>Gemiddelden</translation>
</message>
<message>
<location filename="../sleepyhead/preferencesdialog.ui" line="1526"/>
<source>Upper Percentile</source>
<translation>Bovenste percentiel</translation>
</message>
<message>
<location filename="../sleepyhead/preferencesdialog.ui" line="1533"/>
<source>For consistancy, ResMed users should use 95% here,
as this is the only value available on summary-only days.</source>
<translatorcomment>20/9 WJG: koppelteken en extra woorje</translatorcomment>
<translation>Voor consistentie moeten ResMed-gebruikers hier 95% instellen,
want dit is de enige waarde die beschikbaar is op de dagen met alleen een samenvatting.</translation>
</message>
<message>
<location filename="../sleepyhead/preferencesdialog.ui" line="1547"/>
<source>Median is recommended for ResMed users.</source>
<translation>Mediaan wordt aanbevolen voor ResMed-gebruikers.</translation>
</message>
<message>
<location filename="../sleepyhead/preferencesdialog.ui" line="1551"/>
<source>Median</source>
<translation>Mediaan</translation>
</message>
<message>
<location filename="../sleepyhead/preferencesdialog.ui" line="1556"/>
<source>Weighted Average</source>
<translation>Gewogen gemiddelde</translation>
</message>
<message>
<location filename="../sleepyhead/preferencesdialog.ui" line="1561"/>
<source>Normal Average</source>
<translation>Normaal gemiddelde</translation>
</message>
<message>
<location filename="../sleepyhead/preferencesdialog.ui" line="1581"/>
<source>ResMed users probably should use 99th Percentile for visual consistency.</source>
<translatorcomment>20/9 WJG: koppelteken en Van Dale zegt 'het' tegen percentiel</translatorcomment>
<translation>ResMed-gebruikers moeten waarschijnlijk het 99e percentiel gebruiken voor visuele consistentie.</translation>
</message>
<message>
<location filename="../sleepyhead/preferencesdialog.ui" line="1585"/>
<source>True Maximum</source>
<translation>Ware maximum</translation>
</message>
<message>
<location filename="../sleepyhead/preferencesdialog.ui" line="1590"/>
<source>99% Percentile</source>
<translation>99% percentiel</translation>
</message>
<message>
<location filename="../sleepyhead/preferencesdialog.ui" line="1598"/>
<source>Maximum Calcs</source>
<translation>Berekening maximum</translation>
</message>
<message>
<location filename="../sleepyhead/preferencesdialog.ui" line="1615"/>
<source>Import Locations</source>
<translatorcomment>20/9 WJG: spelling</translatorcomment>
<translation>Importlocaties</translation>
</message>
<message>
<location filename="../sleepyhead/preferencesdialog.ui" line="1646"/>
<source>Add</source>
<translation>Toevoegen</translation>
</message>
<message>
<location filename="../sleepyhead/preferencesdialog.ui" line="1653"/>
<source>Remove</source>
<translation>Verwijderen</translation>
</message>
<message>
<location filename="../sleepyhead/preferencesdialog.ui" line="1694"/>
<source>Automatically Check For Updates</source>
<translation>Automatisch controleren op updates</translation>
</message>
<message>
<location filename="../sleepyhead/preferencesdialog.ui" line="1711"/>
<source>Check for new version every</source>
<translation>Controleer elke</translation>
</message>
<message>
<location filename="../sleepyhead/preferencesdialog.ui" line="1718"/>
<source>Sourceforge hosts this project for free.. Please be considerate of their resources..</source>
<translation>Sourceforge hosts dit project gratis .. Maak er zorgvuldig gebruik van..</translation>
</message>
<message>
<location filename="../sleepyhead/preferencesdialog.ui" line="1734"/>
<source>days.</source>
<translation>dagen.</translation>
</message>
<message>
<location filename="../sleepyhead/preferencesdialog.ui" line="1799"/>
<source>&Check for Updates now</source>
<translation>Nu &controleren</translation>
</message>
<message>
<location filename="../sleepyhead/preferencesdialog.ui" line="1822"/>
<source>Last Checked For Updates: </source>
<translation>Laatste controle:</translation>
</message>
<message>
<location filename="../sleepyhead/preferencesdialog.ui" line="1835"/>
<source>TextLabel</source>
<translation>Tekstlabel</translation>
</message>
<message>
<location filename="../sleepyhead/preferencesdialog.ui" line="1857"/>
<source><!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0//EN" "http://www.w3.org/TR/REC-html40/strict.dtd">
<html><head><meta name="qrichtext" content="1" /><style type="text/css">
p, li { white-space: pre-wrap; }
</style></head><body style=" font-family:'Sans'; font-size:10pt; font-weight:400; font-style:normal;">
<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;">If your interested in helping test new features and bugfixes early, click here.</p>
<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><span style=" font-style:italic;">But please be warned this will sometimes mean breaky code..</span></p>
<p style="-qt-paragraph-type:empty; margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"></p></body></html></source>
<translatorcomment>20/9 WJG: aanpsreekvorm</translatorcomment>
<translation><!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0//EN" "http://www.w3.org/TR/REC-html40/strict.dtd">
<html><head><meta name="qrichtext" content="1" /><style type="text/css">
p, li { white-space: pre-wrap; }
</style></head><body style=" font-family:'Sans'; font-size:10pt; font-weight:400; font-style:normal;">
<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;">Als je geïnteresseerd bent in het helpen testen van nieuwe features en bugfixes, klik hier.</p>
<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><span style=" font-style:italic;">Maar wees gewaarschuwd: dit zal soms vastlopers betekenen!!</span></p>
<p style="-qt-paragraph-type:empty; margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"></p></body></html></translation>
</message>
<message>
<location filename="../sleepyhead/preferencesdialog.ui" line="1866"/>
<source>I want to try experimental and test builds (Advanced users only please.)</source>
<translation>Ik wil experimentele en testupdates proberen (s.v.p. alleen gevorderde gebruikers!)</translation>
</message>
<message>
<location filename="../sleepyhead/preferencesdialog.ui" line="1890"/>
<source>&Appearance</source>
<translation>&Uiterlijk</translation>
</message>
<message>
<location filename="../sleepyhead/preferencesdialog.ui" line="1922"/>
<source>Graph Settings</source>
<translation>Grafiekinstellingen</translation>
</message>
<message>
<location filename="../sleepyhead/preferencesdialog.ui" line="1929"/>
<source>Bar Tops</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../sleepyhead/preferencesdialog.ui" line="1934"/>
<source>Line Chart</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../sleepyhead/preferencesdialog.ui" line="1942"/>
<source>Overview Linecharts</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../sleepyhead/preferencesdialog.ui" line="1967"/>
<source><html><head/><body><p>This makes scrolling when zoomed in easier on sensitive bidirectional TouchPads</p><p>50ms is recommended value.</p></body></html></source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../sleepyhead/preferencesdialog.ui" line="1995"/>
<source>milliseconds</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../sleepyhead/preferencesdialog.ui" line="2061"/>
<source>Scroll Dampening</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../sleepyhead/preferencesdialog.ui" line="2153"/>
<source>Overlay Flags</source>
<translation>Markeringen</translation>
</message>
<message>
<location filename="../sleepyhead/preferencesdialog.ui" line="2119"/>
<source>The visual method of displaying waveform overlay flags.
</source>
<translation>De visuele methode voor het tonen van markeringen in golfvormgrafieken.</translation>
</message>
<message>
<location filename="../sleepyhead/preferencesdialog.ui" line="2124"/>
<source>Standard Bars</source>
<translation>Standaardbalken</translation>
</message>
<message>
<location filename="../sleepyhead/preferencesdialog.ui" line="2129"/>
<source>Top & Bottom Markers</source>
<translation>Onder en boven</translation>
</message>
<message>
<location filename="../sleepyhead/preferencesdialog.ui" line="2137"/>
<source>Graph Height</source>
<translation>Grafiekhoogte</translation>
</message>
<message>
<location filename="../sleepyhead/preferencesdialog.ui" line="2087"/>
<source>Default display height of graphs in pixels</source>
<translation>Standaardhoogte grafieken in pixels</translation>
</message>
<message>
<location filename="../sleepyhead/preferencesdialog.ui" line="2015"/>
<source>How long you want the tooltips to stay visible.</source>
<translation>Hoe lang moeten de tooltips zichtbaar blijven?</translation>
</message>
<message>
<location filename="../sleepyhead/preferencesdialog.ui" line="1384"/>
<source><!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0//EN" "http://www.w3.org/TR/REC-html40/strict.dtd">
<html><head><meta name="qrichtext" content="1" /><style type="text/css">
p, li { white-space: pre-wrap; }
</style></head><body style=" font-family:'.Lucida Grande UI'; font-size:13pt; font-weight:400; font-style:normal;">
<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><span style=" font-family:'Sans'; font-size:10pt; font-weight:600;">Syncing Oximetry and CPAP Data</span></p>
<p align="justify" style="-qt-paragraph-type:empty; margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px; font-family:'Sans'; font-size:10pt;"><br /></p>
<p align="justify" style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><span style=" font-family:'Sans'; font-size:10pt;">CMS50 data imported from SpO2Review (from .spoR files) or the serial import method does </span><span style=" font-family:'Sans'; font-size:10pt; font-weight:600; text-decoration: underline;">not</span><span style=" font-family:'Sans'; font-size:10pt;"> have the correct timestamp needed to sync.</span></p>
<p align="justify" style="-qt-paragraph-type:empty; margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px; font-family:'Sans'; font-size:10pt;"><br /></p>
<p align="justify" style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><span style=" font-family:'Sans'; font-size:10pt;">Live view mode (using a serial cable) is one way to acheive an accurate sync on CMS50 oximeters, but does not counter for CPAP clock drift.</span></p>
<p align="justify" style="-qt-paragraph-type:empty; margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px; font-family:'Sans'; font-size:10pt;"><br /></p>
<p align="justify" style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><span style=" font-family:'Sans'; font-size:10pt;">If you start your Oximeters recording mode at </span><span style=" font-family:'Sans'; font-size:10pt; font-style:italic;">exactly </span><span style=" font-family:'Sans'; font-size:10pt;">the same time you start your CPAP machine, you can now also achieve sync. </span></p>
<p align="justify" style="-qt-paragraph-type:empty; margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px; font-family:'Sans'; font-size:10pt;"><br /></p>
<p align="justify" style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><span style=" font-family:'Sans'; font-size:10pt;">The serial import process takes the starting time from last nights first CPAP session. (Remember to import your CPAP data first!)</span></p></body></html></source>
<translation><!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0//EN" "http://www.w3.org/TR/REC-html40/strict.dtd">
<html><head><meta name="qrichtext" content="1" /><style type="text/css">
p, li { white-space: pre-wrap; }
</style></head><body style=" font-family:'.Lucida Grande UI'; font-size:13pt; font-weight:400; font-style:normal;">
<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><span style=" font-family:'Sans'; font-size:10pt; font-weight:600;">Synchroniseer oxymetrie en CPAP gegevens</span></p>
<p align="justify" style="-qt-paragraph-type:empty; margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px; font-family:'Sans'; font-size:10pt;"><br /></p>
<p align="justify" style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><span style=" font-family:'Sans'; font-size:10pt;">De CMS50 gegevens, geimporteerd uit SpO2Review (uit .spoR bestanden) en de seriele import methode hebben </span><span style=" font-family:'Sans'; font-size:10pt; font-weight:600; text-decoration: underline;">niet</span><span style=" font-family:'Sans'; font-size:10pt;"> de correcte kloktijd die nodig is voor synchronisatie.</span></p>
<p align="justify" style="-qt-paragraph-type:empty; margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px; font-family:'Sans'; font-size:10pt;"><br /></p>
<p align="justify" style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><span style=" font-family:'Sans'; font-size:10pt;">Live weergave (met een seriele/USB kabel) is een manier om een accurate synchronisatie met CMS50 oxymeters te krijgen, maar helpt ook niet tegen het verlopen van de klok van de CPAP.</span></p>
<p align="justify" style="-qt-paragraph-type:empty; margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px; font-family:'Sans'; font-size:10pt;"><br /></p>
<p align="justify" style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><span style=" font-family:'Sans'; font-size:10pt;">Als je de opname van je oxymeter op </span><span style=" font-family:'Sans'; font-size:10pt; font-style:italic;">precies </span><span style=" font-family:'Sans'; font-size:10pt;">hetzelfde moment start met je CPAP, kun je ook synchroon lopen. </span></p>
<p align="justify" style="-qt-paragraph-type:empty; margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px; font-family:'Sans'; font-size:10pt;"><br /></p>
<p align="justify" style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><span style=" font-family:'Sans'; font-size:10pt;">Het proces van import neemt de starttijd van de eerste CPAP sessie van de vorige nacht. (Vergeet niet om eerst je CPAP gegevens te importeren!)</span></p></body></html></translation>
</message>
<message>
<location filename="../sleepyhead/preferencesdialog.ui" line="2071"/>
<source>Tooltip Timeout</source>
<translation>Tooltip timeout</translation>
</message>
<message>
<location filename="../sleepyhead/preferencesdialog.ui" line="2106"/>
<source>Graph Tooltips</source>
<translation>Grafiek tekstballonnen</translation>
</message>
<message>
<location filename="../sleepyhead/preferencesdialog.ui" line="2188"/>
<source>Other Visual Settings</source>
<translation>Overige visuele instellingen</translation>
</message>
<message>
<location filename="../sleepyhead/preferencesdialog.ui" line="2194"/>
<source>Anti-Aliasing applies smoothing to graph plots..
Certain plots look more attractive with this on.
This also affects printed reports.
Try it and see if you like it.</source>
<translation>Anti-aliasing strijkt de grafieken glad.
Sommige grafieken zien er dan mooier uit.
Dit is ook van invloed op afgedrukte rapporten.
Probeer het en kijk of je het leuk vindt.</translation>
</message>
<message>
<location filename="../sleepyhead/preferencesdialog.ui" line="2201"/>
<source>Use Anti-Aliasing</source>
<translation>Gebruik Anti-aliasing</translation>
</message>
<message>
<location filename="../sleepyhead/preferencesdialog.ui" line="2208"/>
<source>Makes certain plots look more "square waved".</source>
<translation>Zorgt ervoor dat sommige grafieken er hoekiger uitzien.</translation>
</message>
<message>
<location filename="../sleepyhead/preferencesdialog.ui" line="2211"/>
<source>Square Wave Plots</source>
<translation>Hoekige golfgrafieken</translation>
</message>
<message>
<location filename="../sleepyhead/preferencesdialog.ui" line="2218"/>
<source>Allows graphs to be "screenshotted" for display purposes.
The Event Breakdown PIE chart uses this method, as does
the printing code.
Unfortunately some older computers/versions of Qt can cause
this application to be unstable with this feature enabled.</source>
<translatorcomment>20/9 WJG: ietsje duidelijker en past beter in het hulptekstje</translatorcomment>
<translation>Toont grafieken als "screenshots".
Het cirkeldiagram van de incidentgrafiek maakt hiervan gebruik,
net als de afdrukcode.
Helaas veroorzaken sommige oudere computers en versies van Qt
dat hierdoor deze toepassing instabiel wordt.</translation>
</message>
<message>
<location filename="../sleepyhead/preferencesdialog.ui" line="2225"/>
<source>Show event breakdown pie chart</source>
<translation>Toon cirkeldiagram</translation>
</message>
<message>
<location filename="../sleepyhead/preferencesdialog.ui" line="2232"/>
<source><!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0//EN" "http://www.w3.org/TR/REC-html40/strict.dtd">
<html><head><meta name="qrichtext" content="1" /><style type="text/css">
p, li { white-space: pre-wrap; }
</style></head><body style=" font-family:'MS Shell Dlg 2'; font-size:8.25pt; font-weight:400; font-style:normal;">
<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><span style=" font-size:8pt;">Pixmap caching is an graphics acceleration technique. May cause problems with font drawing in graph display area on your platform.</span></p></body></html></source>
<translation><!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0//EN" "http://www.w3.org/TR/REC-html40/strict.dtd">
<html><head><meta name="qrichtext" content="1" /><style type="text/css">
p, li { white-space: pre-wrap; }
</style></head><body style=" font-family:'MS Shell Dlg 2'; font-size:8.25pt; font-weight:400; font-style:normal;">
<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><span style=" font-size:8pt;">Pixmap caching is een graphische versnellingstechniek. Het kan echter wel problemen opleveren met de tekst bij de grafieken, afhankelijk van het computerplatform.</span></p></body></html></translation>
</message>
<message>
<location filename="../sleepyhead/preferencesdialog.ui" line="2239"/>
<source>Use Pixmap Caching</source>
<translation>Gebruik Pixmap Caching</translation>
</message>
<message>
<location filename="../sleepyhead/preferencesdialog.ui" line="2246"/>
<source>Turn on/off the spinning "context" cube.
It really doesn't use that much resources.. :)</source>
<translation>Zet de ronddraaiende kubus aan.
Gebruikt echt niet zoveel geheugen... :)</translation>
</message>
<message>
<location filename="../sleepyhead/preferencesdialog.ui" line="2250"/>
<source>Animations && Fancy Stuff</source>
<translation>Animaties en grappige dingen</translation>
</message>
<message>
<location filename="../sleepyhead/preferencesdialog.ui" line="2257"/>
<source>Whether to allow changing yAxis scales by double clicking on yAxis labels</source>
<translation>Toestaan om de automatische y-as instelling te wijzigen door dubbelklikken op een label</translation>
</message>
<message>
<location filename="../sleepyhead/preferencesdialog.ui" line="2260"/>
<source>Allow YAxis Scaling</source>
<translation>Sta automatische y-as instelling toe</translation>
</message>
<message>
<location filename="../sleepyhead/preferencesdialog.ui" line="2279"/>
<source>Application Fonts</source>
<translation>Tekstinstellingen</translation>
</message>
<message>
<location filename="../sleepyhead/preferencesdialog.ui" line="2314"/>
<source>Font</source>
<translation>Lettertype</translation>
</message>
<message>
<location filename="../sleepyhead/preferencesdialog.ui" line="2333"/>
<source>Size</source>
<translation>Grootte</translation>
</message>
<message>
<location filename="../sleepyhead/preferencesdialog.ui" line="2352"/>
<source>Bold </source>
<translation>Vet</translation>
</message>
<message>
<location filename="../sleepyhead/preferencesdialog.ui" line="2374"/>
<source>Italic</source>
<translation>Cursief</translation>
</message>
<message>
<location filename="../sleepyhead/preferencesdialog.ui" line="2387"/>
<source>Application</source>
<translation>Toepassing</translation>
</message>
<message>
<location filename="../sleepyhead/preferencesdialog.ui" line="2451"/>
<source>Graph Text</source>
<translation>Grafiektekst</translation>
</message>
<message>
<location filename="../sleepyhead/preferencesdialog.ui" line="2512"/>
<source>Graph Titles</source>
<translation>Gafiektitels</translation>
</message>
<message>
<location filename="../sleepyhead/preferencesdialog.ui" line="2573"/>
<source>Big Text</source>
<translation>Grote tekst</translation>
</message>
<message>
<location filename="../sleepyhead/preferencesdialog.ui" line="2634"/>
<source>Details</source>
<translation>Details</translation>
</message>
<message>
<location filename="../sleepyhead/preferencesdialog.ui" line="2691"/>
<source>&Cancel</source>
<translation>&Annuleren</translation>
</message>
<message>
<location filename="../sleepyhead/preferencesdialog.ui" line="2698"/>
<source>&Ok</source>
<translation>&OK</translation>
</message>
<message>
<location filename="../sleepyhead/preferencesdialog.cpp" line="58"/>
<source>Nasal Pillows</source>
<translation>Neuskussens</translation>
</message>
<message>
<location filename="../sleepyhead/preferencesdialog.cpp" line="359"/>
<source>Data Reindex Required</source>
<translation>Gegevens opnieuw indexeren</translation>
</message>
<message>
<location filename="../sleepyhead/preferencesdialog.cpp" line="359"/>
<source>A data reindexing proceedure is required to apply these changes. This operation may take a couple of minutes to complete.
Are you sure you want to make these changes?</source>
<translation>Herindexering van de gegevens is nodig. Dit kan een paar minuten duren.
Weet je zeker dat je deze wijzigingen wilt doorvoeren?</translation>
</message>
<message>
<location filename="../sleepyhead/preferencesdialog.cpp" line="364"/>
<source>Restart Required</source>
<translation>Herstart vereist</translation>
</message>
<message>
<location filename="../sleepyhead/preferencesdialog.cpp" line="364"/>
<source>One or more of the changes you have made will require this application to be restarted,
in order for these changes to come into effect.
Would you like do this now?</source>
<translation>Een of meer wijzigingen vereisen dat SleepyHead opnieuw start, opdat deze veranderingen in werking treden.
Wil je dit nu doen?</translation>
</message>
<message>
<location filename="../sleepyhead/preferencesdialog.cpp" line="560"/>
<source>Add this Location to the Import List</source>
<translation>Voeg deze locatie toe aan de importlijst</translation>
</message>
<message>
<location filename="../sleepyhead/preferencesdialog.cpp" line="678"/>
<source>Daily Graphs</source>
<translation>Dagelijkse grafieken</translation>
</message>
<message>
<location filename="../sleepyhead/preferencesdialog.cpp" line="679"/>
<source>Overview Graphs</source>
<translation>Overzichtgrafieken</translation>
</message>
<message>
<location filename="../sleepyhead/preferencesdialog.cpp" line="691"/>
<source>Graph</source>
<translation>Grafiek</translation>
</message>
<message>
<location filename="../sleepyhead/preferencesdialog.cpp" line="847"/>
<source>This may not be a good idea</source>
<translation>Dit lijkt me niet zo'n goed idee</translation>
</message>
<message>
<location filename="../sleepyhead/preferencesdialog.cpp" line="847"/>
<source>ResMed S9 machines routinely delete certain data from your SD card older than 7 and 30 days (depending on resolution).</source>
<translation>ResMed S9 apparaten wissen bepaalde gegevens van je SD kaart als ze ouder zijn dan 7 en 30 dagen (afhankelijk van de resolutie).</translation>
</message>
<message>
<location filename="../sleepyhead/preferencesdialog.cpp" line="847"/>
<source>If you ever need to reimport this data again (whether in SleepyHead or ResScan) this data won't come back.</source>
<translation>Als je ooit gegevens opnieuw moet inlezen (in SleepyHead of in ResScan), krijg je deze gegevens niet terug.</translation>
</message>
<message>
<location filename="../sleepyhead/preferencesdialog.cpp" line="847"/>
<source>If you need to conserve disk space, please remember to carry out manual backups.</source>
<translation>Als je zuinig moet zijn met schijfruimte, vergeet dan niet om zelf backups te maken.</translation>
</message>
<message>
<location filename="../sleepyhead/preferencesdialog.cpp" line="847"/>
<source>Are you sure you want to disable these backups?</source>
<translation>Weet je zeker dat je deze automatische backups wilt uitschakelen?</translation>
</message>
<message>
<source>Min</source>
<translation type="obsolete">Min.</translation>
</message>
<message>
<source>Max</source>
<translation type="obsolete">Max.</translation>
</message>
<message>
<location filename="../sleepyhead/preferencesdialog.cpp" line="721"/>
<source>N/A</source>
<translation>nvt</translation>
</message>
<message>
<location filename="../sleepyhead/preferencesdialog.cpp" line="752"/>
<source>Oximetry Graphs</source>
<translation>Oxymetriegrafieken</translation>
</message>
<message>
<location filename="../sleepyhead/preferencesdialog.cpp" line="784"/>
<source>Confirmation</source>
<translation>Bevestiging</translation>
</message>
<message>
<location filename="../sleepyhead/preferencesdialog.cpp" line="784"/>
<source>Are you sure you want to reset your graph preferences to the defaults?</source>
<translation>Weet je zeker dat je de grafieken opnieuw wilt instellen op standaardwaarden?</translation>
</message>
</context>
<context>
<name>ProfileSelect</name>
<message>
<location filename="../sleepyhead/profileselect.ui" line="14"/>
<source>Select Profile</source>
<translation>Kies profiel</translation>
</message>
<message>
<location filename="../sleepyhead/profileselect.ui" line="68"/>
<source>Start with the selected user profile.</source>
<translation>Start met het geselecteerde gebruikersprofiel.</translation>
</message>
<message>
<location filename="../sleepyhead/profileselect.ui" line="89"/>
<source>Create a new user profile.</source>
<translation>Maak een nieuw gebruikersprofiel.</translation>
</message>
<message>
<location filename="../sleepyhead/profileselect.ui" line="106"/>
<source>Choose a different SleepyHead data folder.</source>
<translation>Kies een andere SleepyHeadData folder.</translation>
</message>
<message>
<location filename="../sleepyhead/profileselect.ui" line="109"/>
<source>&Different Folder</source>
<translation>&Andere folder</translation>
</message>
<message>
<location filename="../sleepyhead/profileselect.ui" line="136"/>
<source>SleepyHead</source>
<translation>SleepyHead</translation>
</message>
<message>
<location filename="../sleepyhead/profileselect.ui" line="146"/>
<source>[version]</source>
<translation>[versie]</translation>
</message>
<message>
<location filename="../sleepyhead/profileselect.ui" line="169"/>
<source>Click here if you didn't want to start SleepyHead.</source>
<translation>Klik hier als je SleepyHead niet wilt starten.</translation>
</message>
<message>
<location filename="../sleepyhead/profileselect.ui" line="172"/>
<source>&Quit</source>
<translation>&Afsluiten</translation>
</message>
<message>
<location filename="../sleepyhead/profileselect.ui" line="207"/>
<source>Folder:</source>
<translation>Folder:</translation>
</message>
<message>
<location filename="../sleepyhead/profileselect.ui" line="220"/>
<source>The current location of SleepyHead data store.</source>
<translation>De huidige locatie van de SleepyHeadData folder.</translation>
</message>
<message>
<location filename="../sleepyhead/profileselect.ui" line="223"/>
<source>[data directory]</source>
<translation>[gegevens directory]</translation>
</message>
<message>
<location filename="../sleepyhead/profileselect.ui" line="92"/>
<source>New Profile</source>
<translation>Nieuw profiel</translation>
</message>
<message>
<location filename="../sleepyhead/profileselect.ui" line="71"/>
<source>&Select User</source>
<translation>&Selecteer profiel</translation>
</message>
<message>
<location filename="../sleepyhead/profileselect.cpp" line="70"/>
<source>Open Profile</source>
<translation>Open profiel</translation>
</message>
<message>
<location filename="../sleepyhead/profileselect.cpp" line="71"/>
<source>Edit Profile</source>
<translation>Wijzig profiel</translation>
</message>
<message>
<location filename="../sleepyhead/profileselect.cpp" line="73"/>
<source>Delete Profile</source>
<translation>Wis profiel</translation>
</message>
<message>
<location filename="../sleepyhead/profileselect.cpp" line="105"/>
<location filename="../sleepyhead/profileselect.cpp" line="153"/>
<source>Enter Password for %1</source>
<translation>Geef wachtwoord voor %1</translation>
</message>
<message>
<location filename="../sleepyhead/profileselect.cpp" line="120"/>
<location filename="../sleepyhead/profileselect.cpp" line="168"/>
<location filename="../sleepyhead/profileselect.cpp" line="250"/>
<source>Incorrect Password</source>
<translation>Verkeerd wachtwoord</translation>
</message>
<message>
<location filename="../sleepyhead/profileselect.cpp" line="122"/>
<source>You entered the password wrong too many times.</source>
<translation>Je hebt te vaak een verkeerd wachtwoord getypt.</translation>
</message>
<message>
<location filename="../sleepyhead/profileselect.cpp" line="139"/>
<location filename="../sleepyhead/profileselect.cpp" line="140"/>
<location filename="../sleepyhead/profileselect.cpp" line="141"/>
<source>Question</source>
<translation>Vraag</translation>
</message>
<message>
<location filename="../sleepyhead/profileselect.cpp" line="139"/>
<source>Are you sure you want to trash the profile "%1"?</source>
<translation>Weet je zeker dat profiel "%1" moet worden gewist?</translation>
</message>
<message>
<location filename="../sleepyhead/profileselect.cpp" line="140"/>
<source>Double Checking:
Do you really want "%1" profile to be obliterated?</source>
<translation>Echt waar: Wil je echt profiel %1 WISSEN?</translation>
</message>
<message>
<location filename="../sleepyhead/profileselect.cpp" line="141"/>
<source>Okay, I am about to totally OBLITERATE the profile "%1" and all it's contained data..
Don't say you weren't warned. :-p</source>
<translation>OK, ik ga nu het profiel en al de gegevens van "%1"vernietigen..
Zeg niet dat je het niet wist... ;-p</translation>
</message>
<message>
<location filename="../sleepyhead/profileselect.cpp" line="145"/>
<source>WTH???</source>
<translation>Hè????</translation>
</message>
<message>
<location filename="../sleepyhead/profileselect.cpp" line="145"/>
<source>If you can read this you need to delete this profile directory manually (It's under %1)</source>
<translation>Als je dit leest, moet je de profielmap handmatig verwijderen (Hij heet: %1)</translation>
</message>
<message>
<location filename="../sleepyhead/profileselect.cpp" line="170"/>
<source>Meheh... If your trying to delete because you forgot the password, your going the wrong way about it. Read the docs.
Signed: Nasty Programmer</source>
<translation>Hehe... Als je het profiel wilt wissen omdat je het wachtwoord vergeten bent, doe je iets verkeerd: Lees de documentatie.
Ondertekend: Vervelende programmeur</translation>
</message>
<message>
<location filename="../sleepyhead/profileselect.cpp" line="180"/>
<source>Whoops.</source>
<translation>Oeps.</translation>
</message>
<message>
<location filename="../sleepyhead/profileselect.cpp" line="180"/>
<source>There was an error deleting the profile directory.. You need to manually remove %1</source>
<translation>Er ging iets mis bij het wissen. Je moet zelf de map %1 verwijderen</translation>
</message>
<message>
<location filename="../sleepyhead/profileselect.cpp" line="237"/>
<source>Enter Password</source>
<translation>Geef wachtwoord</translation>
</message>
<message>
<location filename="../sleepyhead/profileselect.cpp" line="252"/>
<source>You entered an Incorrect Password too many times. Exiting!</source>
<translation>Je typte te vaak een verkeerd wachtwoord.
Het programma wordt nu afgesloten!</translation>
</message>
</context>
<context>
<name>QObject</name>
<message>
<location filename="../sleepyhead/Graphs/gGraphView.cpp" line="2362"/>
<location filename="../sleepyhead/SleepLib/common.cpp" line="361"/>
<source>No Data</source>
<translation>Geen gegevens</translation>
</message>
<message>
<location filename="../sleepyhead/SleepLib/common.cpp" line="253"/>
<source>cm</source>
<translation>cm</translation>
</message>
<message>
<location filename="../sleepyhead/SleepLib/common.cpp" line="254"/>
<source>"</source>
<translation>inch</translation>
</message>
<message>
<location filename="../sleepyhead/SleepLib/common.cpp" line="255"/>
<source>ft</source>
<translation>ft</translation>
</message>
<message>
<location filename="../sleepyhead/SleepLib/common.cpp" line="256"/>
<source>lb</source>
<translation>lb</translation>
</message>
<message>
<location filename="../sleepyhead/SleepLib/common.cpp" line="257"/>
<source>oz</source>
<translation>oz</translation>
</message>
<message>
<location filename="../sleepyhead/SleepLib/common.cpp" line="258"/>
<source>Kg</source>
<translation>kg</translation>
</message>
<message>
<location filename="../sleepyhead/SleepLib/common.cpp" line="259"/>
<location filename="../sleepyhead/SleepLib/schema.cpp" line="175"/>
<location filename="../sleepyhead/SleepLib/schema.cpp" line="176"/>
<source>cmH2O</source>
<translation>cmWk</translation>
</message>
<message>
<location filename="../sleepyhead/SleepLib/common.cpp" line="260"/>
<source>Hours</source>
<translation>Uren</translation>
</message>
<message>
<location filename="../sleepyhead/SleepLib/common.cpp" line="262"/>
<location filename="../sleepyhead/SleepLib/schema.cpp" line="147"/>
<source>bpm</source>
<translation>slagen per minuut</translation>
</message>
<message>
<location filename="../sleepyhead/SleepLib/common.cpp" line="263"/>
<source>L/m</source>
<translation>l/min</translation>
</message>
<message>
<location filename="../sleepyhead/SleepLib/common.cpp" line="265"/>
<location filename="../sleepyhead/SleepLib/schema.cpp" line="69"/>
<source>Error</source>
<translation>Fout</translation>
</message>
<message>
<location filename="../sleepyhead/SleepLib/common.cpp" line="266"/>
<location filename="../sleepyhead/main.cpp" line="296"/>
<source>Warning</source>
<translation>Waarschuwing</translation>
</message>
<message>
<location filename="../sleepyhead/SleepLib/common.cpp" line="288"/>
<source>Min EPAP</source>
<translation type="unfinished">Min. EPAP</translation>
</message>
<message>
<location filename="../sleepyhead/SleepLib/common.cpp" line="289"/>
<source>Max EPAP</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../sleepyhead/SleepLib/common.cpp" line="291"/>
<source>Min IPAP</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../sleepyhead/SleepLib/common.cpp" line="292"/>
<source>Max IPAP</source>
<translation type="unfinished">Max. IPAP</translation>
</message>
<message>
<location filename="../sleepyhead/SleepLib/common.cpp" line="332"/>
<source>ÇSR</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../sleepyhead/SleepLib/common.cpp" line="393"/>
<location filename="../sleepyhead/SleepLib/common.h" line="78"/>
<source>On</source>
<translation>Aan</translation>
</message>
<message>
<location filename="../sleepyhead/SleepLib/common.cpp" line="394"/>
<location filename="../sleepyhead/SleepLib/common.h" line="79"/>
<source>Off</source>
<translation>Uit</translation>
</message>
<message>
<location filename="../sleepyhead/SleepLib/common.cpp" line="268"/>
<source>BMI</source>
<translation>BMI</translation>
</message>
<message>
<location filename="../sleepyhead/SleepLib/common.cpp" line="269"/>
<source>Weight</source>
<translation>Gewicht</translation>
</message>
<message>
<location filename="../sleepyhead/SleepLib/common.cpp" line="270"/>
<source>Zombie</source>
<translation>Zombie</translation>
</message>
<message>
<location filename="../sleepyhead/SleepLib/common.cpp" line="271"/>
<location filename="../sleepyhead/SleepLib/schema.cpp" line="146"/>
<source>Pulse Rate</source>
<translatorcomment>20/9 WJG: overal gebruiken we polsslag - moeten we daar eigenlijk niet hartslag van maken? Dat lijkt me eigenlijk beter...
Toch maar niet (nog)</translatorcomment>
<translation>Polsslag</translation>
</message>
<message>
<location filename="../sleepyhead/SleepLib/common.cpp" line="272"/>
<location filename="../sleepyhead/SleepLib/schema.cpp" line="147"/>
<source>SpO2</source>
<translation>SpO2</translation>
</message>
<message>
<location filename="../sleepyhead/SleepLib/common.cpp" line="273"/>
<location filename="../sleepyhead/SleepLib/schema.cpp" line="148"/>
<source>Plethy</source>
<translatorcomment>20/9 WJG: Wat is dat?
AK: Het kwam me bekend voor:
plethy definition, meaning, English dictionary, synonym, see also 'plethora',plethoric',plenty',pleat', Reverso dictionary, English definition, English vocabulary.
DAT HAD JIJ TOCH MOETEN WETEN?
Plethysmos = toename
http://www.apneaboard.com/forums/Thread-CMS50D--3956
</translatorcomment>
<translation>Plethy</translation>
</message>
<message>
<location filename="../sleepyhead/SleepLib/common.cpp" line="280"/>
<source>Oximeter</source>
<translation>oxymeter</translation>
</message>
<message>
<location filename="../sleepyhead/SleepLib/common.cpp" line="284"/>
<source>CPAP</source>
<translation>CPAP</translation>
</message>
<message>
<location filename="../sleepyhead/SleepLib/common.cpp" line="285"/>
<source>BiPAP</source>
<translation>BiPAP</translation>
</message>
<message>
<location filename="../sleepyhead/SleepLib/common.cpp" line="286"/>
<source>Bi-Level</source>
<translation>Bi-level</translation>
</message>
<message>
<location filename="../sleepyhead/SleepLib/common.cpp" line="287"/>
<source>EPAP</source>
<translation>EPAP</translation>
</message>
<message>
<location filename="../sleepyhead/SleepLib/common.cpp" line="290"/>
<source>IPAP</source>
<translation>IPAP</translation>
</message>
<message>
<source>IPAPLo</source>
<translation type="vanished">IPAP laag</translation>
</message>
<message>
<source>IPAPHi</source>
<translation type="vanished">IPAP hoog</translation>
</message>
<message>
<location filename="../sleepyhead/SleepLib/common.cpp" line="293"/>
<source>APAP</source>
<translation>APAP</translation>
</message>
<message>
<location filename="../sleepyhead/SleepLib/common.cpp" line="294"/>
<source>ASV</source>
<translation>ASV</translation>
</message>
<message>
<location filename="../sleepyhead/SleepLib/common.cpp" line="295"/>
<source>ST/ASV</source>
<translation>ST/ASV</translation>
</message>
<message>
<location filename="../sleepyhead/SleepLib/common.cpp" line="297"/>
<source>Humidifier</source>
<translation>Bevochtiger</translation>
</message>
<message>
<location filename="../sleepyhead/SleepLib/common.cpp" line="299"/>
<location filename="../sleepyhead/SleepLib/schema.cpp" line="127"/>
<source>H</source>
<translation>H</translation>
</message>
<message>
<location filename="../sleepyhead/SleepLib/common.cpp" line="300"/>
<location filename="../sleepyhead/SleepLib/schema.cpp" line="126"/>
<source>OA</source>
<translation>OA</translation>
</message>
<message>
<location filename="../sleepyhead/SleepLib/common.cpp" line="301"/>
<source>A</source>
<translation>A</translation>
</message>
<message>
<location filename="../sleepyhead/SleepLib/common.cpp" line="302"/>
<location filename="../sleepyhead/SleepLib/schema.cpp" line="125"/>
<source>CA</source>
<translation>CA</translation>
</message>
<message>
<location filename="../sleepyhead/SleepLib/common.cpp" line="303"/>
<location filename="../sleepyhead/SleepLib/schema.cpp" line="129"/>
<source>FL</source>
<translation>FL</translation>
</message>
<message>
<location filename="../sleepyhead/SleepLib/common.cpp" line="304"/>
<source>LE</source>
<translation>LE</translation>
</message>
<message>
<location filename="../sleepyhead/SleepLib/common.cpp" line="305"/>
<location filename="../sleepyhead/SleepLib/schema.cpp" line="136"/>
<source>EP</source>
<translation>EP</translation>
</message>
<message>
<location filename="../sleepyhead/SleepLib/common.cpp" line="306"/>
<location filename="../sleepyhead/SleepLib/schema.cpp" line="131"/>
<source>VS</source>
<translation>VS</translation>
</message>
<message>
<location filename="../sleepyhead/SleepLib/common.cpp" line="307"/>
<location filename="../sleepyhead/SleepLib/schema.cpp" line="132"/>
<source>VS2</source>
<translation>VS2</translation>
</message>
<message>
<location filename="../sleepyhead/SleepLib/common.cpp" line="308"/>
<source>RERA</source>
<translation>RERA (RE)</translation>
</message>
<message>
<location filename="../sleepyhead/SleepLib/common.cpp" line="309"/>
<location filename="../sleepyhead/SleepLib/schema.cpp" line="133"/>
<source>PP</source>
<translation>PP</translation>
</message>
<message>
<location filename="../sleepyhead/SleepLib/common.cpp" line="310"/>
<source>P</source>
<translation>P</translation>
</message>
<message>
<location filename="../sleepyhead/SleepLib/common.cpp" line="311"/>
<location filename="../sleepyhead/SleepLib/schema.cpp" line="130"/>
<source>RE</source>
<translation>RE</translation>
</message>
<message>
<location filename="../sleepyhead/SleepLib/common.cpp" line="312"/>
<location filename="../sleepyhead/SleepLib/schema.cpp" line="135"/>
<source>NR</source>
<translation>NR</translation>
</message>
<message>
<location filename="../sleepyhead/SleepLib/common.cpp" line="313"/>
<source>NRI</source>
<translation>NRI</translation>
</message>
<message>
<location filename="../sleepyhead/SleepLib/common.cpp" line="314"/>
<source>O2</source>
<translation>O2</translation>
</message>
<message>
<location filename="../sleepyhead/SleepLib/common.cpp" line="315"/>
<location filename="../sleepyhead/SleepLib/schema.cpp" line="149"/>
<source>PC</source>
<translation>PC</translation>
</message>
<message>
<location filename="../sleepyhead/SleepLib/common.cpp" line="316"/>
<location filename="../sleepyhead/SleepLib/schema.cpp" line="137"/>
<source>UF1</source>
<translation>UF1</translation>
</message>
<message>
<location filename="../sleepyhead/SleepLib/common.cpp" line="317"/>
<location filename="../sleepyhead/SleepLib/schema.cpp" line="138"/>
<source>UF2</source>
<translation>UF2</translation>
</message>
<message>
<location filename="../sleepyhead/SleepLib/common.cpp" line="318"/>
<location filename="../sleepyhead/SleepLib/schema.cpp" line="139"/>
<source>UF3</source>
<translation>UF3</translation>
</message>
<message>
<location filename="../sleepyhead/SleepLib/common.cpp" line="322"/>
<source>PS</source>
<translation>PS</translation>
</message>
<message>
<location filename="../sleepyhead/SleepLib/common.cpp" line="323"/>
<location filename="../sleepyhead/SleepLib/schema.cpp" line="190"/>
<source>AHI</source>
<translation>AHI</translation>
</message>
<message>
<location filename="../sleepyhead/SleepLib/common.cpp" line="324"/>
<location filename="../sleepyhead/SleepLib/schema.cpp" line="193"/>
<source>RDI</source>
<translation>RDI</translation>
</message>
<message>
<location filename="../sleepyhead/SleepLib/common.cpp" line="325"/>
<source>AI</source>
<translation>AI</translation>
</message>
<message>
<location filename="../sleepyhead/SleepLib/common.cpp" line="326"/>
<source>HI</source>
<translation>HI</translation>
</message>
<message>
<location filename="../sleepyhead/SleepLib/common.cpp" line="327"/>
<source>UAI</source>
<translation>UAI</translation>
</message>
<message>
<location filename="../sleepyhead/SleepLib/common.cpp" line="328"/>
<source>CAI</source>
<translation>CAI</translation>
</message>
<message>
<location filename="../sleepyhead/SleepLib/common.cpp" line="329"/>
<source>FLI</source>
<translation>FLI</translation>
</message>
<message>
<location filename="../sleepyhead/SleepLib/common.cpp" line="330"/>
<source>REI</source>
<translation>REI</translation>
</message>
<message>
<location filename="../sleepyhead/SleepLib/common.cpp" line="331"/>
<source>EPI</source>
<translation>EPI</translation>
</message>
<message>
<source>ÃSR</source>
<translation type="vanished">ÃSR</translation>
</message>
<message>
<location filename="../sleepyhead/SleepLib/common.cpp" line="333"/>
<location filename="../sleepyhead/SleepLib/schema.cpp" line="124"/>
<source>PB</source>
<translation>PB</translation>
</message>
<message>
<location filename="../sleepyhead/SleepLib/common.cpp" line="337"/>
<source>IE</source>
<translation>I/E</translation>
</message>
<message>
<location filename="../sleepyhead/SleepLib/common.cpp" line="338"/>
<location filename="../sleepyhead/SleepLib/schema.cpp" line="185"/>
<source>Insp. Time</source>
<translation>Inademtijd</translation>
</message>
<message>
<location filename="../sleepyhead/SleepLib/common.cpp" line="339"/>
<location filename="../sleepyhead/SleepLib/schema.cpp" line="184"/>
<source>Exp. Time</source>
<translation>Uitademtijd</translation>
</message>
<message>
<location filename="../sleepyhead/SleepLib/common.cpp" line="340"/>
<location filename="../sleepyhead/SleepLib/schema.cpp" line="186"/>
<source>Resp. Event</source>
<translation>Incident</translation>
</message>
<message>
<location filename="../sleepyhead/SleepLib/common.cpp" line="341"/>
<location filename="../sleepyhead/SleepLib/schema.cpp" line="129"/>
<location filename="../sleepyhead/SleepLib/schema.cpp" line="187"/>
<source>Flow Limitation</source>
<translation>Stroombeperking</translation>
</message>
<message>
<location filename="../sleepyhead/SleepLib/common.cpp" line="342"/>
<source>Flow Limit</source>
<translation>Stroombeperking</translation>
</message>
<message>
<location filename="../sleepyhead/SleepLib/common.cpp" line="343"/>
<source>Pat. Trig. Breath</source>
<translation>Pat. Veroorz. Ademh.</translation>
</message>
<message>
<location filename="../sleepyhead/SleepLib/common.cpp" line="344"/>
<source>Tgt. Min. Vent</source>
<translation>Doel min. vent.</translation>
</message>
<message>
<location filename="../sleepyhead/SleepLib/common.cpp" line="345"/>
<location filename="../sleepyhead/SleepLib/schema.cpp" line="188"/>
<source>Target Vent.</source>
<translation>Doelventilatie</translation>
</message>
<message>
<location filename="../sleepyhead/SleepLib/common.cpp" line="346"/>
<location filename="../sleepyhead/SleepLib/schema.cpp" line="179"/>
<source>Minute Vent.</source>
<translation>Minuutventilatie</translation>
</message>
<message>
<location filename="../sleepyhead/SleepLib/common.cpp" line="347"/>
<location filename="../sleepyhead/SleepLib/schema.cpp" line="177"/>
<source>Tidal Volume</source>
<translation>Teugvolume</translation>
</message>
<message>
<location filename="../sleepyhead/SleepLib/common.cpp" line="348"/>
<location filename="../sleepyhead/SleepLib/schema.cpp" line="180"/>
<source>Resp. Rate</source>
<translation>Ademtempo</translation>
</message>
<message>
<location filename="../sleepyhead/SleepLib/common.cpp" line="349"/>
<location filename="../sleepyhead/SleepLib/schema.cpp" line="178"/>
<source>Snore</source>
<translation>Snurken</translation>
</message>
<message>
<location filename="../sleepyhead/SleepLib/common.cpp" line="350"/>
<source>Leak</source>
<translation>Lekkage</translation>
</message>
<message>
<location filename="../sleepyhead/SleepLib/common.cpp" line="351"/>
<source>Leaks</source>
<translation>Maskerlek</translation>
</message>
<message>
<location filename="../sleepyhead/SleepLib/common.cpp" line="352"/>
<location filename="../sleepyhead/SleepLib/schema.cpp" line="191"/>
<source>Total Leaks</source>
<translation>Totale lek</translation>
</message>
<message>
<location filename="../sleepyhead/SleepLib/common.cpp" line="353"/>
<source>Unintentional Leaks</source>
<translation>Onbedoelde lek</translation>
</message>
<message>
<location filename="../sleepyhead/SleepLib/common.cpp" line="354"/>
<source>MaskPressure</source>
<translation>Maskerdruk</translation>
</message>
<message>
<location filename="../sleepyhead/SleepLib/common.cpp" line="355"/>
<location filename="../sleepyhead/SleepLib/schema.cpp" line="174"/>
<source>Flow Rate</source>
<translation>Stroomsnelheid</translation>
</message>
<message>
<location filename="../sleepyhead/SleepLib/common.cpp" line="356"/>
<source>Sleep Stage</source>
<translation>Slaapfase</translation>
</message>
<message>
<location filename="../sleepyhead/SleepLib/common.cpp" line="357"/>
<source>Usage</source>
<translation>Gebruik</translation>
</message>
<message>
<location filename="../sleepyhead/SleepLib/common.cpp" line="358"/>
<source>Sessions</source>
<translation>Sessies</translation>
</message>
<message>
<location filename="../sleepyhead/SleepLib/common.cpp" line="359"/>
<source>Pr. Relief</source>
<translation>Drukvermindering</translation>
</message>
<message>
<location filename="../sleepyhead/SleepLib/common.cpp" line="362"/>
<source>Bookmarks</source>
<translation>Bladwijzers</translation>
</message>
<message>
<location filename="../sleepyhead/SleepLib/common.cpp" line="366"/>
<source>Mode</source>
<translation>Modus</translation>
</message>
<message>
<location filename="../sleepyhead/SleepLib/common.cpp" line="367"/>
<source>Model</source>
<translation>Type</translation>
</message>
<message>
<location filename="../sleepyhead/SleepLib/common.cpp" line="368"/>
<source>Brand</source>
<translation>Merk</translation>
</message>
<message>
<location filename="../sleepyhead/SleepLib/common.cpp" line="369"/>
<source>Serial</source>
<translation>Serienummer</translation>
</message>
<message>
<location filename="../sleepyhead/SleepLib/common.cpp" line="370"/>
<source>Machine</source>
<translation>Apparaat</translation>
</message>
<message>
<location filename="../sleepyhead/SleepLib/common.cpp" line="371"/>
<source>Channel</source>
<translation>Kanaal</translation>
</message>
<message>
<location filename="../sleepyhead/SleepLib/common.cpp" line="372"/>
<source>Settings</source>
<translation>Instellingen</translation>
</message>
<message>
<location filename="../sleepyhead/SleepLib/common.cpp" line="374"/>
<source>Name</source>
<translation>Naam</translation>
</message>
<message>
<location filename="../sleepyhead/SleepLib/common.cpp" line="375"/>
<source>DOB</source>
<translation>Geboortedatum</translation>
</message>
<message>
<location filename="../sleepyhead/SleepLib/common.cpp" line="376"/>
<source>Phone</source>
<translation>Telefoon</translation>
</message>
<message>
<location filename="../sleepyhead/SleepLib/common.cpp" line="377"/>
<source>Address</source>
<translation>Adres</translation>
</message>
<message>
<location filename="../sleepyhead/SleepLib/common.cpp" line="378"/>
<source>Email</source>
<translation>E-mail</translation>
</message>
<message>
<location filename="../sleepyhead/SleepLib/common.cpp" line="379"/>
<source>Patient ID</source>
<translation>Patient-ID</translation>
</message>
<message>
<location filename="../sleepyhead/SleepLib/common.cpp" line="380"/>
<source>Date</source>
<translation>Datum</translation>
</message>
<message>
<location filename="../sleepyhead/SleepLib/common.cpp" line="382"/>
<source>Bedtime</source>
<translation>Gaan slapen</translation>
</message>
<message>
<location filename="../sleepyhead/SleepLib/common.cpp" line="383"/>
<source>Wake-up</source>
<translation>Opgestaan</translation>
</message>
<message>
<location filename="../sleepyhead/SleepLib/common.cpp" line="384"/>
<source>Mask Time</source>
<translation>Maskertijd</translation>
</message>
<message>
<location filename="../sleepyhead/SleepLib/common.cpp" line="385"/>
<source>Unknown</source>
<translation>Onbekend</translation>
</message>
<message>
<location filename="../sleepyhead/SleepLib/common.cpp" line="386"/>
<source>None</source>
<translation>Geen</translation>
</message>
<message>
<location filename="../sleepyhead/SleepLib/common.cpp" line="387"/>
<source>Ready</source>
<translation>Klaar</translation>
</message>
<message>
<location filename="../sleepyhead/SleepLib/common.cpp" line="389"/>
<source>First</source>
<translation>Eerste dag</translation>
</message>
<message>
<location filename="../sleepyhead/SleepLib/common.cpp" line="390"/>
<source>Last</source>
<translation>Laatste dag</translation>
</message>
<message>
<location filename="../sleepyhead/SleepLib/common.cpp" line="391"/>
<source>Start</source>
<translation>Start</translation>
</message>
<message>
<location filename="../sleepyhead/SleepLib/common.cpp" line="392"/>
<source>End</source>
<translation>Einde</translation>
</message>
<message>
<location filename="../sleepyhead/SleepLib/common.cpp" line="396"/>
<source>Min</source>
<translation>Min.</translation>
</message>
<message>
<location filename="../sleepyhead/SleepLib/common.cpp" line="397"/>
<source>Max</source>
<translation>Max.</translation>
</message>
<message>
<location filename="../sleepyhead/SleepLib/common.cpp" line="399"/>
<source>Average</source>
<translation>Gemiddeld</translation>
</message>
<message>
<location filename="../sleepyhead/SleepLib/common.cpp" line="400"/>
<source>Median</source>
<translation>Mediaan</translation>
</message>
<message>
<location filename="../sleepyhead/SleepLib/common.cpp" line="401"/>
<source>Avg</source>
<translation>Gem.</translation>
</message>
<message>
<location filename="../sleepyhead/SleepLib/common.cpp" line="402"/>
<source>W-Avg</source>
<translation>Gew. gem.</translation>
</message>
<message>
<location filename="../sleepyhead/SleepLib/common.cpp" line="274"/>
<source>Pressure</source>
<translation>Druk</translation>
</message>
<message>
<location filename="../sleepyhead/SleepLib/common.cpp" line="276"/>
<source>Daily</source>
<translation>Dagelijks</translation>
</message>
<message>
<location filename="../sleepyhead/SleepLib/common.cpp" line="277"/>
<source>Overview</source>
<translation>Overzicht</translation>
</message>
<message>
<location filename="../sleepyhead/SleepLib/common.cpp" line="278"/>
<source>Oximetry</source>
<translation>Oxymetrie</translation>
</message>
<message>
<location filename="../sleepyhead/SleepLib/common.cpp" line="281"/>
<source>Event Flags</source>
<translation>Markeringen</translation>
</message>
<message>
<location filename="../sleepyhead/SleepLib/preferences.cpp" line="36"/>
<source>Windows User</source>
<translation>Windows-gebruiker</translation>
</message>
<message>
<location filename="../sleepyhead/SleepLib/profiles.cpp" line="107"/>
<source>Software changes have been made that require the reimporting of the following machines data:
</source>
<translation>Door een wijziging in het programma moeten de volgende gegevens van het apparaat opnieuw worden opgehaald:
</translation>
</message>
<message>
<location filename="../sleepyhead/SleepLib/profiles.cpp" line="109"/>
<source>I can automatically purge this data for you, or you can cancel now and continue to run in a previous version.
</source>
<translation>Ik kan automatisch deze gegevens wissen, tenzij je nu afbreekt en de oude versie blijft gebruiken.
</translation>
</message>
<message>
<location filename="../sleepyhead/SleepLib/profiles.cpp" line="110"/>
<source>Would you like me to purge this data this for you so you can run the new version?</source>
<translation>Wil je dat ik de gegevens voor je wis zodat je de nieuwe versie kunt gaan gebruiken?</translation>
</message>
<message>
<location filename="../sleepyhead/SleepLib/profiles.cpp" line="112"/>
<source>Machine Database Changes</source>
<translation>Wijzigingen in de gegevens van het apparaat</translation>
</message>
<message>
<location filename="../sleepyhead/SleepLib/profiles.cpp" line="116"/>
<source>Purge Failed</source>
<translation>Wissen mislukt</translation>
</message>
<message>
<location filename="../sleepyhead/SleepLib/profiles.cpp" line="116"/>
<source>Sorry, I could not purge this data, which means this version of SleepyHead can't start.. SleepyHead's Data folder needs to be removed manually
This folder currently resides at the following location:
</source>
<translation>Sorry, ik kon de gegevens niet wissen, deze versie van SleepyHead kan daardoor niet starten.
De map met gegevens van SleepyHead moet je zelf wissen.
De map vind je op:
</translation>
</message>
<message>
<source>SleepyHead Release Notes</source>
<translation type="obsolete">SleepyHead versie-opmerkingen</translation>
</message>
<message>
<location filename="../sleepyhead/main.cpp" line="101"/>
<source>Release Notes</source>
<translation>Versie-opmerkingen</translation>
</message>
<message>
<location filename="../sleepyhead/main.cpp" line="112"/>
<location filename="../sleepyhead/main.cpp" line="134"/>
<source>&Ok, get on with it..</source>
<translation>&OK, laten we beginnen..</translation>
</message>
<message>
<location filename="../sleepyhead/main.cpp" line="123"/>
<source>SleepyHead Update Notes</source>
<translation>SleepyHead update-opmerkingen</translation>
</message>
<message>
<location filename="../sleepyhead/main.cpp" line="126"/>
<source> Update</source>
<translation>Bijwerken</translation>
</message>
<message>
<location filename="../sleepyhead/main.cpp" line="184"/>
<source>Language</source>
<translation>Taal</translation>
</message>
<message>
<location filename="../sleepyhead/main.cpp" line="274"/>
<source>Question</source>
<translation>Vraag</translation>
</message>
<message>
<location filename="../sleepyhead/main.cpp" line="274"/>
<source>No SleepyHead data folder was found.
Would you like SleepyHead to use the default location for storing its data?
</source>
<translation>Geen SleepyHeadData folder gevonden.
Wil je dat SleepyHead de standaard lokatie gebruikt voor gegevensopslag?
</translation>
</message>
<message>
<location filename="../sleepyhead/main.cpp" line="282"/>
<source>Choose or create new folder for SleepyHead data</source>
<translation>Kies of maak een nieuwe folder voor SleepyHeadData</translation>
</message>
<message>
<location filename="../sleepyhead/main.cpp" line="285"/>
<source>Exiting</source>
<translation>Stoppen</translation>
</message>
<message>
<location filename="../sleepyhead/main.cpp" line="285"/>
<source>As you did not select a data folder, SleepyHead will exit.
Next time you run, you will be asked again.</source>
<translation>Doordat je geen gegevensfolder hebt gekozen, wordt SleepyHead gestopt.
De volgende keer wordt het opnieuw gevraagd.</translation>
</message>
<message>
<location filename="../sleepyhead/main.cpp" line="288"/>
<source>No Directory</source>
<translation>Geen directory</translation>
</message>
<message>
<location filename="../sleepyhead/main.cpp" line="288"/>
<source>You did not select a directory.
SleepyHead will now start with your old one.
</source>
<translation>Je hebt geen directory gekozen.
SleepyHead wordt nu gestart met je oude directory.
</translation>
</message>
<message>
<location filename="../sleepyhead/main.cpp" line="296"/>
<source>The folder you chose is not empty, nor does it already contain valid SleepyHead data.
Are you sure you want to use this folder?
</source>
<translation>De folder die je gekozen hebt is niet leeg, maar bevat ook geen bruikbare SleepyHeadData.
Weet je zeker dat je deze wilt gebruiken?
</translation>
</message>
<message>
<location filename="../sleepyhead/SleepLib/common.cpp" line="363"/>
<source>SleepyHead</source>
<translation>SleepyHead</translation>
</message>
<message>
<location filename="../sleepyhead/preferencesdialog.cpp" line="35"/>
<source>Unspecified</source>
<translation>Niet gespecificeerd</translation>
</message>
<message>
<location filename="../sleepyhead/preferencesdialog.cpp" line="36"/>
<source>Nasal Pillows</source>
<translation>Neuskussens</translation>
</message>
<message>
<location filename="../sleepyhead/preferencesdialog.cpp" line="37"/>
<source>Hybrid F/F Mask</source>
<translation>Hybride volgelaatsmasker</translation>
</message>
<message>
<location filename="../sleepyhead/preferencesdialog.cpp" line="38"/>
<source>Nasal Interface</source>
<translation>Neustussenstuk</translation>
</message>
<message>
<location filename="../sleepyhead/preferencesdialog.cpp" line="39"/>
<source>Full-Face Mask</source>
<translation>Volgelaatsmasker</translation>
</message>
<message>
<location filename="../sleepyhead/SleepLib/loader_plugins/prs1_loader.cpp" line="237"/>
<source>Import Error</source>
<translation>Importfout</translation>
</message>
<message>
<location filename="../sleepyhead/SleepLib/loader_plugins/prs1_loader.cpp" line="237"/>
<source>This Machine Record cannot be imported in this profile.
The Day records overlap with already existing content.</source>
<translation>Deze apparaatgegevens kunnen niet in dit profiel worden geimporteerd.
De gegevens overlappen reeds bestaande gegevens.</translation>
</message>
<message>
<location filename="../sleepyhead/mainwindow.cpp" line="629"/>
<source>About SleepyHead</source>
<translation>Over SleepyHead</translation>
</message>
<message>
<location filename="../sleepyhead/mainwindow.cpp" line="644"/>
<source>&Close</source>
<translation type="unfinished">&Sluiten</translation>
</message>
<message>
<location filename="../sleepyhead/mainwindow.cpp" line="648"/>
<source>&Donate</source>
<translation type="unfinished">&Doneren</translation>
</message>
<message>
<location filename="../sleepyhead/reports.cpp" line="40"/>
<source>There are no graphs visible to print</source>
<translation>Geen zichtbare grafieken om af te drukken</translation>
</message>
<message>
<location filename="../sleepyhead/reports.cpp" line="53"/>
<source>Would you like to show bookmarked areas in this report?</source>
<translation>Wil je gebieden met bladwijzer in dit rapport tonen?</translation>
</message>
<message>
<location filename="../sleepyhead/reports.cpp" line="90"/>
<source>This make take some time to complete..
Please don't touch anything until it's done.</source>
<translation>Dit kan even duren...
Alsjeblieft niets aanraken tot ik klaar ben!</translation>
</message>
<message>
<location filename="../sleepyhead/reports.cpp" line="90"/>
<source>Printing %1 Report</source>
<translation>Rapport %1 afdrukken</translation>
</message>
<message>
<location filename="../sleepyhead/reports.cpp" line="122"/>
<source>%1 Report</source>
<translation>%1 Rapport</translation>
</message>
<message>
<location filename="../sleepyhead/reports.cpp" line="158"/>
<source>: %1 hours, %2 minutes, %3 seconds
</source>
<translation>: %1 uren, %2 minuten, %3 seconden
</translation>
</message>
<message>
<location filename="../sleepyhead/reports.cpp" line="222"/>
<source>RDI %1
</source>
<translation>RDI %1
</translation>
</message>
<message>
<location filename="../sleepyhead/reports.cpp" line="224"/>
<source>AHI %1
</source>
<translation>AHI %1
</translation>
</message>
<message>
<location filename="../sleepyhead/reports.cpp" line="251"/>
<source>AI=%1 HI=%2 CAI=%3 </source>
<translation>AI=%1 HI=%2 CAI=%3 </translation>
</message>
<message>
<location filename="../sleepyhead/reports.cpp" line="253"/>
<source>REI=%1 VSI=%2 FLI=%3 PB/CSR=%4%</source>
<translation>REI=%1 VSI=%2 FLI=%3 PB/CSR=%4%</translation>
</message>
<message>
<location filename="../sleepyhead/reports.cpp" line="257"/>
<source>UAI=%1 </source>
<translation>UAI=%1 </translation>
</message>
<message>
<location filename="../sleepyhead/reports.cpp" line="259"/>
<source>NRI=%1 LKI=%2 EPI=%3</source>
<translation>NRI=%1 LKI=%2 EPI=%3</translation>
</message>
<message>
<location filename="../sleepyhead/reports.cpp" line="310"/>
<source>Reporting from %1 to %2</source>
<translation>Rapport van %1 tot %2</translation>
</message>
<message>
<location filename="../sleepyhead/reports.cpp" line="316"/>
<source>Reporting data goes here</source>
<translation>De rapportgegevens komen hier</translation>
</message>
<message>
<location filename="../sleepyhead/reports.cpp" line="355"/>
<source>Entire Day's Flow Waveform</source>
<translation>Flow golfvorm hele dag</translation>
</message>
<message>
<location filename="../sleepyhead/reports.cpp" line="360"/>
<source>Current Selection</source>
<translation>Huidige selectie</translation>
</message>
<message>
<location filename="../sleepyhead/reports.cpp" line="370"/>
<source>Entire Day</source>
<translation>Gehele dag</translation>
</message>
<message>
<location filename="../sleepyhead/reports.cpp" line="475"/>
<source>SleepyHead v%1 - http://sleepyhead.sourceforge.net</source>
<translation>SleepyHead v%1 - http://sleepyhead.sourceforge.net</translation>
</message>
<message>
<location filename="../sleepyhead/reports.cpp" line="480"/>
<source>Page %1 of %2</source>
<translation>Pagina %1 van %2</translation>
</message>
<message>
<location filename="../sleepyhead/reports.cpp" line="544"/>
<source>SleepyHead has finished sending the job to the printer.</source>
<translation>SleepyHead is klaar met afdrukken </translation>
</message>
<message>
<location filename="../sleepyhead/summary.cpp" line="52"/>
<source>This is an unstable build so expect the possibility things will go wrong.</source>
<translation>Dit is een onstabiele versie, dus je kunt verwachten dat er wat mis gaat.</translation>
</message>
<message>
<location filename="../sleepyhead/summary.cpp" line="53"/>
<source>Please report bugs you find here to SleepyHead's developer mailing list.</source>
<translation type="unfinished">Geef alsjeblieft de fouten door aan de ontwikkelaar van SleepyHead of aan de vertaler: [email protected]</translation>
</message>
<message>
<location filename="../sleepyhead/summary.cpp" line="55"/>
<source>This is a beta software and some functionality may not work as intended yet.</source>
<translation>Dit is een beta programma, sommige funties zouden niet naar verwachting kunnen werken.</translation>
</message>
<message>
<location filename="../sleepyhead/summary.cpp" line="56"/>
<source>Please report any bugs you find to SleepyHead's SourceForge page.</source>
<translation>Geef alle bugs die je vindt op bij de SourceForge pagina van SleepyHead.</translation>
</message>
<message>
<location filename="../sleepyhead/Graphs/gXAxis.cpp" line="57"/>
<source>Jan</source>
<translation>Jan.</translation>
</message>
<message>
<location filename="../sleepyhead/Graphs/gXAxis.cpp" line="57"/>
<source>Feb</source>
<translation>Feb.</translation>
</message>
<message>
<location filename="../sleepyhead/Graphs/gXAxis.cpp" line="57"/>
<source>Mar</source>
<translation>Mrt.</translation>
</message>
<message>
<location filename="../sleepyhead/Graphs/gXAxis.cpp" line="57"/>
<source>Apr</source>
<translation>Apr.</translation>
</message>
<message>
<location filename="../sleepyhead/Graphs/gXAxis.cpp" line="57"/>
<source>May</source>
<translation>Mei</translation>
</message>
<message>
<location filename="../sleepyhead/Graphs/gXAxis.cpp" line="57"/>
<source>Jun</source>
<translation>Jun.</translation>
</message>
<message>
<location filename="../sleepyhead/Graphs/gXAxis.cpp" line="58"/>
<source>Jul</source>
<translation>Jul.</translation>
</message>
<message>
<location filename="../sleepyhead/Graphs/gXAxis.cpp" line="58"/>
<source>Aug</source>
<translation>Aug.</translation>
</message>
<message>
<location filename="../sleepyhead/Graphs/gXAxis.cpp" line="58"/>
<source>Sep</source>
<translation>Sep.</translation>
</message>
<message>
<location filename="../sleepyhead/Graphs/gXAxis.cpp" line="58"/>
<source>Oct</source>
<translation>Okt.</translation>
</message>
<message>
<location filename="../sleepyhead/Graphs/gXAxis.cpp" line="58"/>
<source>Nov</source>
<translation>Nov.</translation>
</message>
<message>
<location filename="../sleepyhead/Graphs/gXAxis.cpp" line="58"/>
<source>Dec</source>
<translation>Dec.</translation>
</message>
<message>
<location filename="../sleepyhead/Graphs/gLineOverlay.cpp" line="275"/>
<source>Events</source>
<translation>Incidenten</translation>
</message>
<message>
<location filename="../sleepyhead/Graphs/gLineOverlay.cpp" line="275"/>
<source>Duration</source>
<translation>Tijdsduur</translation>
</message>
<message>
<location filename="../sleepyhead/Graphs/gLineOverlay.cpp" line="283"/>
<source>(%%1 in events)</source>
<translation>(%%1 in incidenten)</translation>
</message>
<message>
<location filename="../sleepyhead/SleepLib/schema.cpp" line="69"/>
<source>Couldn't parse Channels.xml, this build is seriously borked, no choice but to abort!!</source>
<translation>Kon Channels.xml niet lezen, deze versie is echt brak, geen andere keuze dan om af te breken!</translation>
</message>
<message>
<location filename="../sleepyhead/SleepLib/schema.cpp" line="93"/>
<source>Therapy Pressure</source>
<translation>Therapiedruk</translation>
</message>
<message>
<location filename="../sleepyhead/SleepLib/schema.cpp" line="94"/>
<source>Inspiratory Pressure</source>
<translation>Inademdruk</translation>
</message>
<message>
<location filename="../sleepyhead/SleepLib/schema.cpp" line="95"/>
<source>Lower Inspiratory Pressure</source>
<translation>Laagste inademdruk</translation>
</message>
<message>
<location filename="../sleepyhead/SleepLib/schema.cpp" line="96"/>
<source>Higher Inspiratory Pressure</source>
<translation>Hoogste inademdruk</translation>
</message>
<message>
<location filename="../sleepyhead/SleepLib/schema.cpp" line="97"/>
<source>Expiratory Pressure</source>
<translation>Uitademdruk</translation>
</message>
<message>
<location filename="../sleepyhead/SleepLib/schema.cpp" line="98"/>
<source>Lower Expiratory Pressure</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../sleepyhead/SleepLib/schema.cpp" line="99"/>
<source>Higher Expiratory Pressure</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../sleepyhead/SleepLib/schema.cpp" line="100"/>
<source>Pressure Support</source>
<translation>Drukhulp</translation>
</message>
<message>
<location filename="../sleepyhead/SleepLib/schema.cpp" line="101"/>
<source>PS Min</source>
<translation>PS min.</translation>
</message>
<message>
<location filename="../sleepyhead/SleepLib/schema.cpp" line="101"/>
<source>Pressure Support Minimum</source>
<translation>Minimale drukhulp</translation>
</message>
<message>
<location filename="../sleepyhead/SleepLib/schema.cpp" line="102"/>
<source>PS Max</source>
<translation>PS max.</translation>
</message>
<message>
<location filename="../sleepyhead/SleepLib/schema.cpp" line="102"/>
<source>Pressure Support Maximum</source>
<translation>Maximale drukhulp</translation>
</message>
<message>
<location filename="../sleepyhead/SleepLib/schema.cpp" line="103"/>
<source>Min Pressure</source>
<translation>Minimale druk</translation>
</message>
<message>
<location filename="../sleepyhead/SleepLib/schema.cpp" line="103"/>
<source>Minimum Therapy Pressure</source>
<translation>Minimum therapiedruk</translation>
</message>
<message>
<location filename="../sleepyhead/SleepLib/schema.cpp" line="103"/>
<source>Pr. Min</source>
<translation>Min. druk</translation>
</message>
<message>
<location filename="../sleepyhead/SleepLib/schema.cpp" line="104"/>
<source>Max Pressure</source>
<translation>Max. druk</translation>
</message>
<message>
<location filename="../sleepyhead/SleepLib/schema.cpp" line="104"/>
<source>Maximum Therapy Pressure</source>
<translation>Maximum therapiedruk</translation>
</message>
<message>
<location filename="../sleepyhead/SleepLib/schema.cpp" line="104"/>
<source>Pr. Max</source>
<translation>Max. druk</translation>
</message>
<message>
<location filename="../sleepyhead/SleepLib/schema.cpp" line="105"/>
<source>Ramp Time</source>
<translation>Ramptijd</translation>
</message>
<message>
<location filename="../sleepyhead/SleepLib/schema.cpp" line="105"/>
<source>Ramp Delay Period</source>
<translation>Ramp vertraging</translation>
</message>
<message>
<location filename="../sleepyhead/SleepLib/schema.cpp" line="105"/>
<source>minutes</source>
<translation>minuten</translation>
</message>
<message>
<location filename="../sleepyhead/SleepLib/schema.cpp" line="106"/>
<source>Ramp Pressure</source>
<translation>Rampdruk</translation>
</message>
<message>
<location filename="../sleepyhead/SleepLib/schema.cpp" line="106"/>
<source>Starting Ramp Pressure</source>
<translation>Ramp startdruk</translation>
</message>
<message>
<location filename="../sleepyhead/SleepLib/schema.cpp" line="106"/>
<source>Ramp Pr.</source>
<translation>Rampdr.</translation>
</message>
<message>
<location filename="../sleepyhead/SleepLib/schema.cpp" line="124"/>
<source>Periodic Breathing</source>
<translation>Cyclische ademhaling (PB)</translation>
</message>
<message>
<location filename="../sleepyhead/SleepLib/schema.cpp" line="124"/>
<source>A period of periodic breathing</source>
<translation>Een periode van cyclische ademhaling</translation>
</message>
<message>
<location filename="../sleepyhead/SleepLib/schema.cpp" line="124"/>
<location filename="../sleepyhead/SleepLib/schema.cpp" line="146"/>
<location filename="../sleepyhead/SleepLib/schema.cpp" line="181"/>
<source>%</source>
<translation>%</translation>
</message>
<message>
<location filename="../sleepyhead/SleepLib/schema.cpp" line="125"/>
<source>Clear Airway Apnea</source>
<translation>Open luchtweg apneu (CA)</translation>
</message>
<message>
<location filename="../sleepyhead/SleepLib/schema.cpp" line="125"/>
<source>An apnea where the airway is open</source>
<translation>Een apneu waarbij de luchtweg niet is afgesloten</translation>
</message>
<message>
<location filename="../sleepyhead/SleepLib/schema.cpp" line="125"/>
<location filename="../sleepyhead/SleepLib/schema.cpp" line="126"/>
<location filename="../sleepyhead/SleepLib/schema.cpp" line="127"/>
<location filename="../sleepyhead/SleepLib/schema.cpp" line="128"/>
<location filename="../sleepyhead/SleepLib/schema.cpp" line="129"/>
<location filename="../sleepyhead/SleepLib/schema.cpp" line="130"/>
<location filename="../sleepyhead/SleepLib/schema.cpp" line="131"/>
<location filename="../sleepyhead/SleepLib/schema.cpp" line="132"/>
<location filename="../sleepyhead/SleepLib/schema.cpp" line="133"/>
<location filename="../sleepyhead/SleepLib/schema.cpp" line="134"/>
<location filename="../sleepyhead/SleepLib/schema.cpp" line="135"/>
<location filename="../sleepyhead/SleepLib/schema.cpp" line="136"/>
<location filename="../sleepyhead/SleepLib/schema.cpp" line="137"/>
<location filename="../sleepyhead/SleepLib/schema.cpp" line="138"/>
<location filename="../sleepyhead/SleepLib/schema.cpp" line="139"/>
<location filename="../sleepyhead/SleepLib/schema.cpp" line="149"/>
<location filename="../sleepyhead/SleepLib/schema.cpp" line="150"/>
<source>events/hr</source>
<translation>gebeurtenissen per uur</translation>
</message>
<message>
<location filename="../sleepyhead/SleepLib/schema.cpp" line="126"/>
<source>Obstructive Apnea</source>
<translation>Obstructieve apneu (OA)</translation>
</message>
<message>
<location filename="../sleepyhead/SleepLib/schema.cpp" line="126"/>
<source>An apnea caused by airway obstruction</source>
<translation>Een apneu waarbij de luchtweg is afgesloten</translation>
</message>
<message>
<location filename="../sleepyhead/SleepLib/schema.cpp" line="127"/>
<source>Hypopnea</source>
<translation>Hypopneu (H)</translation>
</message>
<message>
<location filename="../sleepyhead/SleepLib/schema.cpp" line="127"/>
<source>A partially obstructed airway</source>
<translation>Een gedeeltelijk afgesloten luchtweg</translation>
</message>
<message>
<location filename="../sleepyhead/SleepLib/schema.cpp" line="128"/>
<source>Unclassified Apnea</source>
<translation>Onbekende apneu (A)</translation>
</message>
<message>
<location filename="../sleepyhead/SleepLib/schema.cpp" line="128"/>
<source>An apnea that could not fit into a category</source>
<translation>Een apneu die niet traceerbaar was</translation>
</message>
<message>
<location filename="../sleepyhead/SleepLib/schema.cpp" line="128"/>
<source>UA</source>
<translation>UA</translation>
</message>
<message>
<location filename="../sleepyhead/SleepLib/schema.cpp" line="129"/>
<source>An restriction in breathing from normal, causing a flattening of the flow waveform.</source>
<translation>Een abnormale beperking van de ademhaling, waardoor de stroom afvlakte.</translation>
</message>
<message>
<location filename="../sleepyhead/SleepLib/schema.cpp" line="130"/>
<source>Respiratory Effort Related Arousal</source>
<translation>Arousal door ademprobleem (RERA)</translation>
</message>
<message>
<location filename="../sleepyhead/SleepLib/schema.cpp" line="130"/>
<source>An restriction in breathing that causes an either an awakening or sleep disturbance.</source>
<translation>Een stroombeperking die (gedeeltelijk) ontwaken (arousal) veroorzaakt.</translation>
</message>
<message>
<location filename="../sleepyhead/SleepLib/schema.cpp" line="131"/>
<location filename="../sleepyhead/SleepLib/schema.cpp" line="132"/>
<source>Vibratory Snore</source>
<translation>Vibrerend snurken</translation>
</message>
<message>
<location filename="../sleepyhead/SleepLib/schema.cpp" line="131"/>
<source>A vibratory snore</source>
<translation>Een snurk</translation>
</message>
<message>
<location filename="../sleepyhead/SleepLib/schema.cpp" line="132"/>
<source>A vibratory snore as detcted by a System One machine</source>
<translation>System One detecteert vibrerend snurken</translation>
</message>
<message>
<location filename="../sleepyhead/SleepLib/schema.cpp" line="133"/>
<source>Pressure Pulse</source>
<translation>drukpuls</translation>
</message>
<message>
<location filename="../sleepyhead/SleepLib/schema.cpp" line="133"/>
<source>A pulse of pressure 'pinged' to detect a closed airway.</source>
<translation>Een kleine drukgolf waarmee een afgesloten luchtweg wordt gedetecteerd.</translation>
</message>
<message>
<location filename="../sleepyhead/SleepLib/schema.cpp" line="134"/>
<source>Large Leak</source>
<translation>Groot lek</translation>
</message>
<message>
<location filename="../sleepyhead/SleepLib/schema.cpp" line="134"/>
<source>A large mask leak affecting machine performance.</source>
<translation>Dusdanige lekkage dat het apparaat niet meer goed detecteert.</translation>
</message>
<message>
<location filename="../sleepyhead/SleepLib/schema.cpp" line="134"/>
<source>LL</source>
<translation>LL</translation>
</message>
<message>
<location filename="../sleepyhead/SleepLib/schema.cpp" line="135"/>
<source>Non Responding Event</source>
<translation>Gebeurtenis zonder reactie</translation>
</message>
<message>
<location filename="../sleepyhead/SleepLib/schema.cpp" line="135"/>
<source>A type of respiratory event that won't respond to a pressure increase.</source>
<translation>Een ademhalingsgebeurtenis die niet door drukverhoging ophoudt.</translation>
</message>
<message>
<location filename="../sleepyhead/SleepLib/schema.cpp" line="136"/>
<source>Expiratory Puff</source>
<translation>Uitademstoot</translation>
</message>
<message>
<location filename="../sleepyhead/SleepLib/schema.cpp" line="136"/>
<source>Intellipap event where you breathe out your mouth.</source>
<translation>Een Intellipap gebeurtenis waarbij je door de mond uitademt.</translation>
</message>
<message>
<location filename="../sleepyhead/SleepLib/schema.cpp" line="137"/>
<source>User Flag #1</source>
<translation>Gebruikersvlag #1</translation>
</message>
<message>
<location filename="../sleepyhead/SleepLib/schema.cpp" line="137"/>
<location filename="../sleepyhead/SleepLib/schema.cpp" line="138"/>
<location filename="../sleepyhead/SleepLib/schema.cpp" line="139"/>
<source>A user definable event detected by SleepyHead's flow waveform processor.</source>
<translation>Door de gebruiker instelbare gebeurtenis die door SleepyHead wordt herkend.</translation>
</message>
<message>
<location filename="../sleepyhead/SleepLib/schema.cpp" line="138"/>
<source>User Flag #2</source>
<translation>Gebruikersvlag #2</translation>
</message>
<message>
<location filename="../sleepyhead/SleepLib/schema.cpp" line="139"/>
<source>User Flag #3</source>
<translation>Gebruikersvlag #3</translation>
</message>
<message>
<location filename="../sleepyhead/SleepLib/schema.cpp" line="146"/>
<source>Heart rate in beats per minute</source>
<translation>Pols in slagen per minuut</translation>
</message>
<message>
<location filename="../sleepyhead/SleepLib/schema.cpp" line="147"/>
<source>Blood-oxygen saturation percentage</source>
<translation>Bloedzuurstof saturatie in procent</translation>
</message>
<message>
<location filename="../sleepyhead/SleepLib/schema.cpp" line="147"/>
<source>SpO2 %</source>
<translation>SpO2 %</translation>
</message>
<message>
<location filename="../sleepyhead/SleepLib/schema.cpp" line="148"/>
<source>Plethysomogram</source>
<translation>Plethysomogram</translation>
</message>
<message>
<location filename="../sleepyhead/SleepLib/schema.cpp" line="148"/>
<source>hz</source>
<translation>hz</translation>
</message>
<message>
<location filename="../sleepyhead/SleepLib/schema.cpp" line="148"/>
<source>An optical Photo-plethysomogram showing heart rhythm</source>
<translation>Een optische plethysomogram die het hartritme laat zien</translation>
</message>
<message>
<location filename="../sleepyhead/SleepLib/schema.cpp" line="149"/>
<source>Pulse Change</source>
<translation>Wijziging in polsslag</translation>
</message>
<message>
<location filename="../sleepyhead/SleepLib/schema.cpp" line="149"/>
<source>A sudden (user definable) change in heart rate</source>
<translation>Een plotselinge verandering in polsslag (instelbaar)</translation>
</message>
<message>
<location filename="../sleepyhead/SleepLib/schema.cpp" line="150"/>
<source>SpO2 Drop</source>
<translation>SpO2 verlaging</translation>
</message>
<message>
<location filename="../sleepyhead/SleepLib/schema.cpp" line="150"/>
<source>A sudden (user definable) drop in blood oxygen saturation</source>
<translation>Een plotselinge verlaging in zuurstofsaturatie (instelbaar)</translation>
</message>
<message>
<location filename="../sleepyhead/SleepLib/schema.cpp" line="150"/>
<source>SD</source>
<translation>SD</translation>
</message>
<message>
<location filename="../sleepyhead/SleepLib/schema.cpp" line="174"/>
<source>Breathing flow rate waveform</source>
<translation>Ademhalings golfvorm</translation>
</message>
<message>
<location filename="../sleepyhead/SleepLib/schema.cpp" line="174"/>
<location filename="../sleepyhead/SleepLib/schema.cpp" line="177"/>
<location filename="../sleepyhead/SleepLib/schema.cpp" line="179"/>
<location filename="../sleepyhead/SleepLib/schema.cpp" line="182"/>
<location filename="../sleepyhead/SleepLib/schema.cpp" line="189"/>
<location filename="../sleepyhead/SleepLib/schema.cpp" line="191"/>
<location filename="../sleepyhead/SleepLib/schema.cpp" line="192"/>
<source>L/min</source>
<translation>l/min</translation>
</message>
<message>
<location filename="../sleepyhead/SleepLib/schema.cpp" line="175"/>
<location filename="../sleepyhead/SleepLib/schema.cpp" line="176"/>
<source>Mask Pressure</source>
<translation>Maskerdruk</translation>
</message>
<message>
<location filename="../sleepyhead/SleepLib/schema.cpp" line="176"/>
<source>Mask Pressure (High resolution)</source>
<translation>Maskerdruk (hoge resolutie)</translation>
</message>
<message>
<location filename="../sleepyhead/SleepLib/schema.cpp" line="177"/>
<source>Amount of air displaced per breath</source>
<translation>Hoeveelheid lucht verplaatst door ademhaling</translation>
</message>
<message>
<location filename="../sleepyhead/SleepLib/schema.cpp" line="178"/>
<source>Graph displaying snore volume</source>
<translation>Grafiek die de mate van snurken weergeeft</translation>
</message>
<message>
<location filename="../sleepyhead/SleepLib/schema.cpp" line="178"/>
<location filename="../sleepyhead/SleepLib/schema.cpp" line="188"/>
<source>??</source>
<translation>??</translation>
</message>
<message>
<location filename="../sleepyhead/SleepLib/schema.cpp" line="179"/>
<source>Minute Ventilation</source>
<translation>Minuutventilatie</translation>
</message>
<message>
<location filename="../sleepyhead/SleepLib/schema.cpp" line="179"/>
<source>Amount of air displaced per minute</source>
<translation>Hoeveelheid verplaatste lucht per minuut</translation>
</message>
<message>
<location filename="../sleepyhead/SleepLib/schema.cpp" line="180"/>
<source>Respiratory Rate</source>
<translation>Ademhalingstempo</translation>
</message>
<message>
<location filename="../sleepyhead/SleepLib/schema.cpp" line="180"/>
<source>Rate of breaths per minute</source>
<translation>Tempo van de ademhaling per minuut</translation>
</message>
<message>
<location filename="../sleepyhead/SleepLib/schema.cpp" line="180"/>
<source>Bpm</source>
<translation>slagen per minuut</translation>
</message>
<message>
<location filename="../sleepyhead/SleepLib/schema.cpp" line="181"/>
<source>Patient Triggered Breaths</source>
<translation>Pat. Veroorz. Ademh.</translation>
</message>
<message>
<location filename="../sleepyhead/SleepLib/schema.cpp" line="181"/>
<source>Percentage of breaths triggered by patient</source>
<translation>Percentage ademhalingen door de patient</translation>
</message>
<message>
<location filename="../sleepyhead/SleepLib/schema.cpp" line="181"/>
<source>Pat. Trig. Breaths</source>
<translation>Pat. geact. teugen</translation>
</message>
<message>
<location filename="../sleepyhead/SleepLib/schema.cpp" line="182"/>
<source>Leak Rate</source>
<translation>Leksnelheid</translation>
</message>
<message>
<location filename="../sleepyhead/SleepLib/schema.cpp" line="182"/>
<source>Rate of detected mask leakage</source>
<translation>Snelheid van de maskerlekkage</translation>
</message>
<message>
<location filename="../sleepyhead/SleepLib/schema.cpp" line="183"/>
<source>I:E Ratio</source>
<translation>I:E verhouding</translation>
</message>
<message>
<location filename="../sleepyhead/SleepLib/schema.cpp" line="183"/>
<source>Ratio between Inspiratory and Expiratory time</source>
<translation>Verhouding tussen inadem- en uitademtijd</translation>
</message>
<message>
<location filename="../sleepyhead/SleepLib/schema.cpp" line="183"/>
<source>ratio</source>
<translation>verhouding</translation>
</message>
<message>
<location filename="../sleepyhead/SleepLib/schema.cpp" line="184"/>
<source>Expiratory Time</source>
<translation>Uitademtijd</translation>
</message>
<message>
<location filename="../sleepyhead/SleepLib/schema.cpp" line="184"/>
<source>Time taken to breathe out</source>
<translation>Tijdsduur van het uitademen</translation>
</message>
<message>
<location filename="../sleepyhead/SleepLib/schema.cpp" line="184"/>
<location filename="../sleepyhead/SleepLib/schema.cpp" line="185"/>
<source>seconds</source>
<translation>seconden</translation>
</message>
<message>
<location filename="../sleepyhead/SleepLib/schema.cpp" line="185"/>
<source>Inspiratory Time</source>
<translation>Inademtijd</translation>
</message>
<message>
<location filename="../sleepyhead/SleepLib/schema.cpp" line="185"/>
<source>Time taken to breathe in</source>
<translation>Tijdsduur van het inademen</translation>
</message>
<message>
<location filename="../sleepyhead/SleepLib/schema.cpp" line="186"/>
<source>Respiratory Event</source>
<translation>Ademhalingsgebeurtenis</translation>
</message>
<message>
<location filename="../sleepyhead/SleepLib/schema.cpp" line="186"/>
<source>A ResMed data source showing Respiratory Events</source>
<translation>Een ResMed gegevensblok met ademhalingsgebeurtenissen</translation>
</message>
<message>
<location filename="../sleepyhead/SleepLib/schema.cpp" line="186"/>
<source>events</source>
<translation>incidenten</translation>
</message>
<message>
<location filename="../sleepyhead/SleepLib/schema.cpp" line="187"/>
<source>Graph showing severity of flow limitations</source>
<translation>Grafiek die de ernst van de stroombeperking aangeeft</translation>
</message>
<message>
<location filename="../sleepyhead/SleepLib/schema.cpp" line="187"/>
<source>Flow Limit.</source>
<translation>Stroombeperk.</translation>
</message>
<message>
<location filename="../sleepyhead/SleepLib/schema.cpp" line="187"/>
<source>0-1</source>
<translation>0=open, 1=dicht</translation>
</message>
<message>
<location filename="../sleepyhead/SleepLib/schema.cpp" line="188"/>
<source>Target Minute Ventilation</source>
<translation>Doelminuutventilatie</translation>
</message>
<message>
<location filename="../sleepyhead/SleepLib/schema.cpp" line="188"/>
<source>Target Minute Ventilation?</source>
<translation>Doelminuutventilatie?</translation>
</message>
<message>
<location filename="../sleepyhead/SleepLib/schema.cpp" line="189"/>
<source>Maximum Leak</source>
<translation>Maximum lekkage</translation>
</message>
<message>
<location filename="../sleepyhead/SleepLib/schema.cpp" line="189"/>
<source>The maximum rate of mask leakage</source>
<translation>De maximum leksnelheid</translation>
</message>
<message>
<location filename="../sleepyhead/SleepLib/schema.cpp" line="189"/>
<source>Max Leaks</source>
<translation>Max. lek</translation>
</message>
<message>
<location filename="../sleepyhead/SleepLib/schema.cpp" line="190"/>
<source>Apnea Hypopnea Index</source>
<translation>Apneu-hypopneu Index</translation>
</message>
<message>
<location filename="../sleepyhead/SleepLib/schema.cpp" line="190"/>
<source>Graph showing running AHI for the past hour</source>
<translation>Grafiek met de voortschrijdende AHI van het afgelopen uur</translation>
</message>
<message>
<location filename="../sleepyhead/SleepLib/schema.cpp" line="190"/>
<location filename="../sleepyhead/SleepLib/schema.cpp" line="193"/>
<source>events/hour</source>
<translation>gebeurtenissen per uur</translation>
</message>
<message>
<location filename="../sleepyhead/SleepLib/schema.cpp" line="191"/>
<source>Total Leak Rate</source>
<translation>Totale lekkage</translation>
</message>
<message>
<location filename="../sleepyhead/SleepLib/schema.cpp" line="191"/>
<source>Detected mask leakage including natural Mask leakages</source>
<translation>Gedetecteerde maskerlekkage inclusief de bedoelde lek</translation>
</message>
<message>
<location filename="../sleepyhead/SleepLib/schema.cpp" line="192"/>
<source>Median Leak Rate</source>
<translation>Mediaan van de lekkage</translation>
</message>
<message>
<location filename="../sleepyhead/SleepLib/schema.cpp" line="192"/>
<source>Median rate of detected mask leakage</source>
<translation>De mediaan van de leksnelheid</translation>
</message>
<message>
<location filename="../sleepyhead/SleepLib/schema.cpp" line="192"/>
<source>Median Leaks</source>
<translation>Mediaan lek</translation>
</message>
<message>
<location filename="../sleepyhead/SleepLib/schema.cpp" line="193"/>
<source>Respiratory Disturbance Index</source>
<translation>Ademhalings Stoornis Index (RDI)</translation>
</message>
<message>
<location filename="../sleepyhead/SleepLib/schema.cpp" line="193"/>
<source>Graph showing running RDI for the past hour</source>
<translation>Grafiek met de voorstschrijdende RDI van het afgelopen uur</translation>
</message>
</context>
<context>
<name>QextSerialPort</name>
<message>
<location filename="../3rdparty/qextserialport/src/qextserialport.cpp" line="718"/>
<source>No Error has occurred</source>
<translation>Geen fouten</translation>
</message>
<message>
<location filename="../3rdparty/qextserialport/src/qextserialport.cpp" line="720"/>
<source>Invalid file descriptor (port was not opened correctly)</source>
<translation>Onjuiste bestandsbeschrijving (poort was niet correct geopend)</translation>
</message>
<message>
<location filename="../3rdparty/qextserialport/src/qextserialport.cpp" line="722"/>
<source>Unable to allocate memory tables (POSIX)</source>
<translation>Kan geen geheugentabellen toewijzen (POSIX)</translation>
</message>
<message>
<location filename="../3rdparty/qextserialport/src/qextserialport.cpp" line="724"/>
<source>Caught a non-blocked signal (POSIX)</source>
<translation>Ontving een niet-geblokkeerd signaal (POSIX)</translation>
</message>
<message>
<location filename="../3rdparty/qextserialport/src/qextserialport.cpp" line="726"/>
<source>Operation timed out (POSIX)</source>
<translation>Bewerkingstijd verlopen (POSIX)</translation>
</message>
<message>
<location filename="../3rdparty/qextserialport/src/qextserialport.cpp" line="728"/>
<source>The file opened by the port is not a valid device</source>
<translation>Het bestand verwijst naar een ongeldig apparaat</translation>
</message>
<message>
<location filename="../3rdparty/qextserialport/src/qextserialport.cpp" line="730"/>
<source>The port detected a break condition</source>
<translation>De poort werd afgesloten</translation>
</message>
<message>
<location filename="../3rdparty/qextserialport/src/qextserialport.cpp" line="732"/>
<source>The port detected a framing error (usually caused by incorrect baud rate settings)</source>
<translation>De poort gaf een foutmelding (waarschijnlijk de baudrate fout ingesteld)</translation>
</message>
<message>
<location filename="../3rdparty/qextserialport/src/qextserialport.cpp" line="734"/>
<source>There was an I/O error while communicating with the port</source>
<translation>I/O fout bij communicatie met de poort</translation>
</message>
<message>
<location filename="../3rdparty/qextserialport/src/qextserialport.cpp" line="736"/>
<source>Character buffer overrun</source>
<translation>Karakterbuffer overloop</translation>
</message>
<message>
<location filename="../3rdparty/qextserialport/src/qextserialport.cpp" line="738"/>
<source>Receive buffer overflow</source>
<translation>Ontving buffer overloop</translation>
</message>
<message>
<location filename="../3rdparty/qextserialport/src/qextserialport.cpp" line="740"/>
<source>The port detected a parity error in the received data</source>
<translation>De poort detecteerde een pariteitsfout in de gegevens</translation>
</message>
<message>
<location filename="../3rdparty/qextserialport/src/qextserialport.cpp" line="742"/>
<source>Transmit buffer overflow</source>
<translation>Zendbuffer overloop</translation>
</message>
<message>
<location filename="../3rdparty/qextserialport/src/qextserialport.cpp" line="744"/>
<source>General read operation failure</source>
<translation>Algemene leesfout</translation>
</message>
<message>
<location filename="../3rdparty/qextserialport/src/qextserialport.cpp" line="746"/>
<source>General write operation failure</source>
<translation>Algemene schrijffout</translation>
</message>
<message>
<location filename="../3rdparty/qextserialport/src/qextserialport.cpp" line="748"/>
<source>The %1 file doesn't exists</source>
<translation>Het bestand %1 bestaat niet</translation>
</message>
<message>
<location filename="../3rdparty/qextserialport/src/qextserialport.cpp" line="750"/>
<source>Permission denied</source>
<translation>Toegang geweigerd</translation>
</message>
<message>
<location filename="../3rdparty/qextserialport/src/qextserialport.cpp" line="752"/>
<source>Device is already locked</source>
<translation>Het apparaat is al afgesloten</translation>
</message>
<message>
<location filename="../3rdparty/qextserialport/src/qextserialport.cpp" line="754"/>
<source>Unknown error: %1</source>
<translation>Onbekende fout: %1</translation>
</message>
</context>
<context>
<name>QuaGzipFile</name>
<message>
<source>QIODevice::Append is not supported for GZIP</source>
<translation type="vanished">QIODevice::Append is not supported for GZIP</translation>
</message>
<message>
<source>Opening gzip for both reading and writing is not supported</source>
<translation type="vanished">Opening gzip for both reading and writing is not supported</translation>
</message>
<message>
<source>You can open a gzip either for reading or for writing. Which is it?</source>
<translation type="vanished">Je kunt een gzip bestand openen voor lezen of schrijven, wat wil je?</translation>
</message>
<message>
<source>Could not gzopen() file</source>
<translation type="vanished">Kan gzopen() bestand niet openen</translation>
</message>
</context>
<context>
<name>QuaZIODevice</name>
<message>
<source>QIODevice::Append is not supported for QuaZIODevice</source>
<translation type="vanished">QIODevice::Append is not supported for QuaZIODevice</translation>
</message>
<message>
<source>QIODevice::ReadWrite is not supported for QuaZIODevice</source>
<translation type="vanished">QIODevice::ReadWrite is not supported for QuaZIODevice</translation>
</message>
</context>
<context>
<name>QuaZipFilePrivate</name>
<message>
<location filename="../3rdparty/quazip/quazip/quazipfile.cpp" line="217"/>
<source>ZIP/UNZIP API error %1</source>
<translation>Fout bij in/uitpakken van %1</translation>
</message>
</context>
<context>
<name>Report</name>
<message>
<location filename="../sleepyhead/report.ui" line="14"/>
<source>Form</source>
<translation>Formulier</translation>
</message>
<message>
<location filename="../sleepyhead/report.ui" line="27"/>
<source>about:blank</source>
<translation>about:blank</translation>
</message>
</context>
<context>
<name>Summary</name>
<message>
<location filename="../sleepyhead/summary.cpp" line="274"/>
<source>Please Import Some Data</source>
<translation>Graag eerst enige gegevens importeren</translation>
</message>
<message>
<location filename="../sleepyhead/summary.cpp" line="274"/>
<source>SleepyHead is pretty much useless without it.</source>
<translation>SleepyHead is nogal nutteloos zonder gegevens</translation>
</message>
<message>
<location filename="../sleepyhead/summary.cpp" line="274"/>
<source>It might be a good idea to check preferences first,</br>as there are some options that affect import.</source>
<translation>Het is een goed idee om eerst enige instellingen te controleren,
er zijn enkele opties die de import beinvloeden</translation>
</message>
<message>
<location filename="../sleepyhead/summary.cpp" line="274"/>
<source>First import can take a few minutes.</source>
<translation>De eerste keer kan het even duren...</translation>
</message>
<message>
<location filename="../sleepyhead/summary.cpp" line="305"/>
<source>No CPAP Machine Data Imported</source>
<translation>Geen CPAP gegevens geimporteerd</translation>
</message>
<message>
<location filename="../sleepyhead/summary.cpp" line="307"/>
<source>CPAP Statistics as of</source>
<translation>CPAP statistiek van </translation>
</message>
<message>
<location filename="../sleepyhead/summary.cpp" line="313"/>
<source>No CPAP data available.</source>
<translation>Geen CPAP-gegevens beschikbaar.</translation>
</message>
<message>
<location filename="../sleepyhead/summary.cpp" line="315"/>
<source>%1 day of CPAP Data, on %2.</source>
<translation>Dag %1 van CPAP-gegevens, op %2.</translation>
</message>
<message>
<location filename="../sleepyhead/summary.cpp" line="317"/>
<source>%1 days of CPAP Data, between %2 and %3</source>
<translation>%1 dagen met CPAP-gegevens, tussen %2 en %3</translation>
</message>
<message>
<location filename="../sleepyhead/summary.cpp" line="321"/>
<location filename="../sleepyhead/summary.cpp" line="451"/>
<source>Details</source>
<translation>Details</translation>
</message>
<message>
<location filename="../sleepyhead/summary.cpp" line="321"/>
<location filename="../sleepyhead/summary.cpp" line="451"/>
<source>Most Recent</source>
<translation>Laatste ingelezen dag</translation>
</message>
<message>
<location filename="../sleepyhead/summary.cpp" line="321"/>
<location filename="../sleepyhead/summary.cpp" line="451"/>
<source>Last 7 Days</source>
<translation>Afgelopen 7 dagen</translation>
</message>
<message>
<location filename="../sleepyhead/summary.cpp" line="321"/>
<location filename="../sleepyhead/summary.cpp" line="451"/>
<source>Last 30 Days</source>
<translation>Afgelopen 30 dagen</translation>
</message>
<message>
<location filename="../sleepyhead/summary.cpp" line="321"/>
<location filename="../sleepyhead/summary.cpp" line="451"/>
<source>Last 6 months</source>
<translation>Afgelopen 6 maanden</translation>
</message>
<message>
<location filename="../sleepyhead/summary.cpp" line="321"/>
<location filename="../sleepyhead/summary.cpp" line="451"/>
<source>Last Year</source>
<translation>Afgelopen jaar</translation>
</message>
<message>
<location filename="../sleepyhead/summary.cpp" line="332"/>
<source>RERA Index</source>
<translation>RERA-index</translation>
</message>
<message>
<location filename="../sleepyhead/summary.cpp" line="342"/>
<source>Flow Limit Index</source>
<translation>Stroom Beperking Index
(FLI)</translation>
</message>
<message>
<location filename="../sleepyhead/summary.cpp" line="353"/>
<source>Hours per Night</source>
<translation>Uren per nacht</translation>
</message>
<message>
<location filename="../sleepyhead/summary.cpp" line="362"/>
<source>Min EPAP</source>
<translation>Min. EPAP</translation>
</message>
<message>
<location filename="../sleepyhead/summary.cpp" line="376"/>
<source>Max IPAP</source>
<translation>Max. IPAP</translation>
</message>
<message>
<location filename="../sleepyhead/summary.cpp" line="391"/>
<source>Average Pressure</source>
<translation>Gemiddelde druk</translation>
</message>
<message>
<location filename="../sleepyhead/summary.cpp" line="398"/>
<source>%1% Pressure</source>
<translation>%1% Druk</translation>
</message>
<message>
<location filename="../sleepyhead/summary.cpp" line="406"/>
<source>Pressure</source>
<translation>Druk</translation>
</message>
<message>
<location filename="../sleepyhead/summary.cpp" line="422"/>
<source>Average %1</source>
<translation>Gemiddelde %1</translation>
</message>
<message>
<location filename="../sleepyhead/summary.cpp" line="429"/>
<source>%1% %2</source>
<translation>%1% %2</translation>
</message>
<message>
<location filename="../sleepyhead/summary.cpp" line="443"/>
<source>Oximetry Summary</source>
<translation>Oxymetrie overzicht</translation>
</message>
<message>
<location filename="../sleepyhead/summary.cpp" line="445"/>
<source>%1 day of Oximetry Data, on %2.</source>
<translation>%1 dag van oxymetriegegevens, op %2</translation>
</message>
<message>
<location filename="../sleepyhead/summary.cpp" line="447"/>
<source>%1 days of Oximetry Data, between %2 and %3</source>
<translation>%1 dagen van oxymetrie-gegevens, tussen %2 en %3</translation>
</message>
<message>
<location filename="../sleepyhead/summary.cpp" line="461"/>
<source>Average SpO2</source>
<translation>Gemiddelde SpO2</translation>
</message>
<message>
<location filename="../sleepyhead/summary.cpp" line="468"/>
<source>Minimum SpO2</source>
<translation>Minimum SpO2</translation>
</message>
<message>
<location filename="../sleepyhead/summary.cpp" line="475"/>
<source>SpO2 Events / Hour</source>
<translation>SpO2 incidenten per uur</translation>
</message>
<message>
<location filename="../sleepyhead/summary.cpp" line="482"/>
<source>% of time in SpO2 Events</source>
<translation>% Tijd in SpO2 incidenten</translation>
</message>
<message>
<location filename="../sleepyhead/summary.cpp" line="489"/>
<source>Average Pulse Rate</source>
<translation>Gemiddelde polsslag</translation>
</message>
<message>
<location filename="../sleepyhead/summary.cpp" line="496"/>
<source>Minimum Pulse Rate</source>
<translation>Minumum polsslag</translation>
</message>
<message>
<location filename="../sleepyhead/summary.cpp" line="503"/>
<source>Maximum Pulse Rate</source>
<translation>Maximum polsslag</translation>
</message>
<message>
<location filename="../sleepyhead/summary.cpp" line="510"/>
<source>Pulse Change Events / Hour</source>
<translation>Polsslagincidenten per uur</translation>
</message>
<message>
<location filename="../sleepyhead/summary.cpp" line="702"/>
<source>Usage Information</source>
<translation>Gebruiksinformatie</translation>
</message>
<message>
<location filename="../sleepyhead/summary.cpp" line="703"/>
<source>Total Days</source>
<translation>Totaal aantal dagen</translation>
</message>
<message>
<location filename="../sleepyhead/summary.cpp" line="705"/>
<source>Compliant Days</source>
<translation>Therapietrouw-dagen</translation>
</message>
<message>
<location filename="../sleepyhead/summary.cpp" line="712"/>
<source>Days AHI &gt;5.0</source>
<translation>Dagen met AHI &gt;5,0</translation>
</message>
<message>
<location filename="../sleepyhead/summary.cpp" line="716"/>
<source>Best&nbsp;%1</source>
<translation>Beste &nbsp;%1</translation>
</message>
<message>
<location filename="../sleepyhead/summary.cpp" line="725"/>
<source>Worst&nbsp;%1</source>
<translation>Slechtste &nbsp;%1</translation>
</message>
<message>
<location filename="../sleepyhead/summary.cpp" line="771"/>
<source>Best RX Setting</source>
<translation>Beste Rx instelling</translation>
</message>
<message>
<location filename="../sleepyhead/summary.cpp" line="807"/>
<source>Worst RX Setting</source>
<translation>Slechtste Rx instelling</translation>
</message>
<message>
<location filename="../sleepyhead/summary.cpp" line="829"/>
<source>Changes to Prescription Settings</source>
<translation>Wijzigingen in de voorgeschreven instellingen</translation>
</message>
<message>
<source>PS Min</source>
<translation type="vanished">PS min.</translation>
</message>
<message>
<source>PS Max</source>
<translation type="vanished">PS max.</translation>
</message>
<message>
<source>Min Pres.</source>
<translation type="vanished">Min. druk</translation>
</message>
<message>
<source>Max Pres.</source>
<translation type="vanished">Max. druk</translation>
</message>
<message>
<location filename="../sleepyhead/summary.cpp" line="837"/>
<source>Days</source>
<translation>Dagen</translation>
</message>
<message>
<location filename="../sleepyhead/summary.cpp" line="839"/>
<source>FL</source>
<translation>FL</translation>
</message>
<message>
<location filename="../sleepyhead/summary.cpp" line="841"/>
<source>Pr. Rel.</source>
<translation>Drukvermindering</translation>
</message>
<message>
<location filename="../sleepyhead/summary.cpp" line="943"/>
<source>The above has a threshold which excludes day counts less than %1 from the best/worst highlighting</source>
<translation>In het bovenstaande wordt een periode met minder dan %1 dagen niet in de analyse meegenomen</translation>
</message>
<message>
<location filename="../sleepyhead/summary.cpp" line="950"/>
<source>Machine Information</source>
<translation>Apparaat informatie</translation>
</message>
<message>
<location filename="../sleepyhead/summary.cpp" line="956"/>
<source>First Use</source>
<translation>Eerste gebruik</translation>
</message>
<message>
<location filename="../sleepyhead/summary.cpp" line="957"/>
<source>Last Use</source>
<translation>Laatste gebruik</translation>
</message>
</context>
<context>
<name>UpdaterWindow</name>
<message>
<location filename="../sleepyhead/UpdaterWindow.ui" line="14"/>
<source>SleepyHead Updater</source>
<translation>SleepyHead Updater</translation>
</message>
<message>
<location filename="../sleepyhead/UpdaterWindow.ui" line="51"/>
<source>A new version of $APP is available</source>
<translation>Er is een nieuwe versie van $APP</translation>
</message>
<message>
<location filename="../sleepyhead/UpdaterWindow.ui" line="97"/>
<source>Version Information</source>
<translation>Versie-informatie</translation>
</message>
<message>
<location filename="../sleepyhead/UpdaterWindow.ui" line="108"/>
<source>Release Notes</source>
<translation>Versie-opmerkingen</translation>
</message>
<message>
<location filename="../sleepyhead/UpdaterWindow.ui" line="121"/>
<source>about:blank</source>
<translation>about:blank</translation>
</message>
<message>
<location filename="../sleepyhead/UpdaterWindow.ui" line="130"/>
<source>Build Notes</source>
<translation>Build-opmerkingen</translation>
</message>
<message>
<location filename="../sleepyhead/UpdaterWindow.ui" line="174"/>
<source>Maybe &Later</source>
<translation>Misschien &later</translation>
</message>
<message>
<location filename="../sleepyhead/UpdaterWindow.ui" line="194"/>
<source>&Upgrade Now</source>
<translation>Nu &upgraden</translation>
</message>
<message>
<location filename="../sleepyhead/UpdaterWindow.ui" line="220"/>
<source>Please wait while updates are downloaded and installed...</source>
<translation>Wacht even tot de updates zijn gedownload en geïnstalleerd...</translation>
</message>
<message>
<location filename="../sleepyhead/UpdaterWindow.ui" line="234"/>
<source>Updates</source>
<translation>Updates</translation>
</message>
<message>
<location filename="../sleepyhead/UpdaterWindow.ui" line="265"/>
<source>Component</source>
<translation>Onderdeel</translation>
</message>
<message>
<location filename="../sleepyhead/UpdaterWindow.ui" line="270"/>
<source>Version</source>
<translation>Versie</translation>
</message>
<message>
<location filename="../sleepyhead/UpdaterWindow.ui" line="275"/>
<source>Size</source>
<translation>Grootte</translation>
</message>
<message>
<location filename="../sleepyhead/UpdaterWindow.ui" line="280"/>
<source>Progress</source>
<translation>Voortgang</translation>
</message>
<message>
<location filename="../sleepyhead/UpdaterWindow.ui" line="289"/>
<source>Log</source>
<translation>Log</translation>
</message>
<message>
<location filename="../sleepyhead/UpdaterWindow.ui" line="317"/>
<source>Downloading & Installing Updates</source>
<translation>Bestanden worden gedownload en geïnstalleerd</translation>
</message>
<message>
<location filename="../sleepyhead/UpdaterWindow.ui" line="337"/>
<source>&Finished</source>
<translation>&Klaar</translation>
</message>
<message>
<location filename="../sleepyhead/UpdaterWindow.cpp" line="94"/>
<source>Checking for SleepyHead Updates</source>
<translation>Zoeken naar updates</translation>
</message>
<message>
<location filename="../sleepyhead/UpdaterWindow.cpp" line="108"/>
<location filename="../sleepyhead/UpdaterWindow.cpp" line="161"/>
<source>Requesting </source>
<translation>Aanvragen</translation>
</message>
<message>
<location filename="../sleepyhead/UpdaterWindow.cpp" line="168"/>
<source>Saving as </source>
<translation>Opslaan als </translation>
</message>
<message>
<location filename="../sleepyhead/UpdaterWindow.cpp" line="188"/>
<source>XML update structure parsed cleanly</source>
<translation>XML updatestructuur werd juist ontleed</translation>
</message>
<message>
<location filename="../sleepyhead/UpdaterWindow.cpp" line="208"/>
<source>No updates were found for your platform.</source>
<translation>Er zijn geen updates gevonden.</translation>
</message>
<message>
<location filename="../sleepyhead/UpdaterWindow.cpp" line="208"/>
<location filename="../sleepyhead/UpdaterWindow.cpp" line="241"/>
<source>SleepyHead Updates</source>
<translation>SleepyHead Updates</translation>
</message>
<message>
<location filename="../sleepyhead/UpdaterWindow.cpp" line="241"/>
<source>No new updates were found for your platform.</source>
<translation>Er zijn geen nieuwe updates gevonden.</translation>
</message>
<message>
<location filename="../sleepyhead/UpdaterWindow.cpp" line="256"/>
<source>SleepyHead v%1, codename "%2"</source>
<translation>SleepyHead v%1, codename "%2"</translation>
</message>
<message>
<location filename="../sleepyhead/UpdaterWindow.cpp" line="258"/>
<source>platform notes</source>
<translation>Opmerkingen over het platform</translation>
</message>
<message>
<location filename="../sleepyhead/UpdaterWindow.cpp" line="262"/>
<source>A new version of SleepyHead is available!</source>
<translation>Er is een nieuwe versie van SleepyHead beschikbaar!</translation>
</message>
<message>
<location filename="../sleepyhead/UpdaterWindow.cpp" line="263"/>
<source>Shiny new <b>v%1</b> is available. You're running old and busted v%2</source>
<translation>Er is een splinternieuwe <b>v%1</b> beschikbaar. Jij werkt nog met de oude en versleten versie %2</translation>
</message>
<message>
<location filename="../sleepyhead/UpdaterWindow.cpp" line="266"/>
<source>An update for SleepyHead is available.</source>
<translation>Er is een update voor SleepyHead.</translation>
</message>
<message>
<location filename="../sleepyhead/UpdaterWindow.cpp" line="267"/>
<source>Version <b>%1</b> is available. You're currently running v%1</source>
<translation>Versie <b>%1</b> is beschikbaar. Je gebruikt nu versie %1</translation>
</message>
<message>
<location filename="../sleepyhead/UpdaterWindow.cpp" line="276"/>
<source>SleepyHead v%1 build notes</source>
<translation>Opmerkingen over SleepyHead versie %1</translation>
</message>
<message>
<location filename="../sleepyhead/UpdaterWindow.cpp" line="278"/>
<source>Update to QtLibs (v%1)</source>
<translation>Update naar QTlibs (versie %1)</translation>
</message>
<message>
<location filename="../sleepyhead/UpdaterWindow.cpp" line="286"/>
<source>There was an error parsing the XML Update file.</source>
<translation>Er is een fout opgetreden tijdens het ontleden van het bijgewerkte XML-bestand.</translation>
</message>
<message>
<location filename="../sleepyhead/UpdaterWindow.cpp" line="304"/>
<source>%1 bytes received</source>
<translation>%1 bytes ontvangen</translation>
</message>
<message>
<location filename="../sleepyhead/UpdaterWindow.cpp" line="332"/>
<source>Redirected to </source>
<translation>Doorgestuurd naar </translation>
</message>
<message>
<location filename="../sleepyhead/UpdaterWindow.cpp" line="343"/>
<source>File size mismatch for %1</source>
<translation>Bestandsgrootte van %1 klopt niet</translation>
</message>
<message>
<location filename="../sleepyhead/UpdaterWindow.cpp" line="353"/>
<source>File integrity check failed for %1</source>
<translation>Fout in bestandsintegriteit van %1</translation>
</message>
<message>
<location filename="../sleepyhead/UpdaterWindow.cpp" line="381"/>
<source>Extracting </source>
<translation>Uitpakken </translation>
</message>
<message>
<location filename="../sleepyhead/UpdaterWindow.cpp" line="430"/>
<source>You might need to reinstall manually. Sorry :(</source>
<translation>Wellicht opnieuw installeren?! Sorry ;-((</translation>
</message>
<message>
<location filename="../sleepyhead/UpdaterWindow.cpp" line="430"/>
<source>Ugh.. Something went wrong with unzipping.</source>
<translation>Oef! Er ging iets fout bij het uitpakken.</translation>
</message>
<message>
<location filename="../sleepyhead/UpdaterWindow.cpp" line="440"/>
<source>Failed</source>
<translation>Mislukt</translation>
</message>
<message>
<location filename="../sleepyhead/UpdaterWindow.cpp" line="459"/>
<source>Download Complete</source>
<translation>Download klaar</translation>
</message>
<message>
<location filename="../sleepyhead/UpdaterWindow.cpp" line="463"/>
<source>There was an error completing a network request:
(</source>
<translation>Er was een fout bij een netwerkverzoek:
:(</translation>
</message>
<message>
<location filename="../sleepyhead/UpdaterWindow.cpp" line="500"/>
<source>Update Complete!</source>
<translation>Update klaar!</translation>
</message>
<message>
<location filename="../sleepyhead/UpdaterWindow.cpp" line="502"/>
<source>Updates Complete. SleepyHead needs to restart now, click Finished to do so.</source>
<translation>Klaar met updaten. SleepyHead moet opnieuw worden opgestart, klik op Afsluiten.</translation>
</message>
<message>
<location filename="../sleepyhead/UpdaterWindow.cpp" line="505"/>
<source>Update Failed :(</source>
<translation>Update mislukt :(</translation>
</message>
<message>
<location filename="../sleepyhead/UpdaterWindow.cpp" line="507"/>
<source>Download Error. Sorry, try again later.</source>
<translation>Fout met downloaden. Probeer het later nog eens.</translation>
</message>
<message>
<location filename="../sleepyhead/UpdaterWindow.cpp" line="523"/>
<source>Downloading & Installing Updates...</source>
<translation>Updates downloaden en installeren...</translation>
</message>
<message>
<location filename="../sleepyhead/UpdaterWindow.cpp" line="524"/>
<source>Please wait while downloading and installing updates.</source>
<translation>Wacht even terwijl we downloaden en installeren.</translation>
</message>
</context>
</TS><|fim▁end|> | |
<|file_name|>processlock.py<|end_file_name|><|fim▁begin|># Copyright (c) 2012 Hesky Fisher
# See LICENSE.txt for details.
#
# processlock.py - Cross platform global lock to ensure plover only runs once.
"""Global lock to ensure plover only runs once."""
import sys
class LockNotAcquiredException(Exception):
pass
if sys.platform.startswith('win32'):
from ctypes import windll
class PloverLock:
# A GUID from http://createguid.com/
guid = 'plover_{F8C06652-2C51-410B-8D15-C94DF96FC1F9}'
def __init__(self):
pass
def acquire(self):
self.mutex = windll.kernel32.CreateMutexA(None, False, self.guid)
if windll.kernel32.GetLastError() == 0xB7: # ERROR_ALREADY_EXISTS
raise LockNotAcquiredException()
def release(self):
if hasattr(self, 'mutex'):
windll.kernel32.CloseHandle(self.mutex)
del self.mutex
def __del__(self):
self.release()
def __enter__(self):
self.acquire()
def __exit__(self, type, value, traceback):
self.release()
else:
import fcntl
import os
class PloverLock:
def __init__(self):
# Check the environment for items to make the lockfile unique
# fallback if not found
if 'DISPLAY' in os.environ:
display = os.environ['DISPLAY'][-1:]
else:
display = "0"
if hasattr(os, "uname"):
hostname = os.uname()[1]
else:
import socket
hostname = socket.gethostname()
lock_file_name = os.path.expanduser(
'~/.plover-lock-%s-%s' % (hostname, display))
self.fd = open(lock_file_name, 'w')
def acquire(self):
try:
fcntl.flock(self.fd, fcntl.LOCK_EX | fcntl.LOCK_NB)
except IOError as e:
raise LockNotAcquiredException(str(e))
def release(self):
try:
fcntl.flock(self.fd, fcntl.LOCK_UN)
except:
pass<|fim▁hole|>
def __del__(self):
self.release()
try:
self.fd.close()
except:
pass
def __enter__(self):
self.acquire()
def __exit__(self, exc_type, exc_value, traceback):
self.release()<|fim▁end|> | |
<|file_name|>schema.py<|end_file_name|><|fim▁begin|>import graphene
from graphene_django.types import DjangoObjectType
from django.contrib.auth import (get_user_model, authenticate,
login as auth_login, logout as auth_logout,
update_session_auth_hash)
from django.contrib.auth.forms import (UserCreationForm, AuthenticationForm,
PasswordChangeForm)
from cryptographer.models import Cryptographer
from cryptographer.schema import CryptographerType
from helpers.schema import FormError, list_errors
class LoginUser(graphene.Mutation):
class Arguments:
username = graphene.String()
password = graphene.String()
user = graphene.Field(CryptographerType)
success = graphene.Boolean()
errors = graphene.List(FormError)
def mutate(self, info, username, password):
if info.context.user.is_authenticated:
return LoginUser(
user=None,
success=False,
errors=list_errors({ "__all__": ['Cannot login when already logged in']})
)
form = AuthenticationForm(info.context, { "username": username, "password": password })
if form.is_valid():
success = True
user = form.get_user()
auth_login(info.context, user)
return LoginUser(user=user.cryptographer, success=True, errors=[])
else:
return LoginUser(user=None, success=False, errors=list_errors(form.errors))
class SignupUser(graphene.Mutation):
class Arguments:
username = graphene.String()
password1 = graphene.String()<|fim▁hole|>
user = graphene.Field(CryptographerType)
success = graphene.Boolean()
errors = graphene.List(FormError)
def mutate(self, info, username, password1, password2):
if info.context.user.is_authenticated:
return SignupUser(
user=None,
success=False,
errors=list_errors({ "__all__": ['Cannot signup when already logged in']})
)
form = UserCreationForm({
"username": username,
"password1": password1,
"password2": password2
})
if form.is_valid():
form.save()
user = authenticate(username=username, password=password1)
# create a Cryptographer and link it to the user
c = Cryptographer(user=user)
c.save()
auth_login(info.context, user)
return SignupUser(user=c, success=True, errors=[])
else:
return SignupUser(user=None, success=False, errors=list_errors(form.errors))
class LogoutUser(graphene.Mutation):
success = graphene.Boolean()
user = graphene.Field(CryptographerType)
def mutate(self, info):
auth_logout(info.context)
return LogoutUser(success=True, user=None)
class ChangePassword(graphene.Mutation):
class Arguments:
old_password = graphene.String()
new_password1 = graphene.String()
new_password2 = graphene.String()
success = graphene.Boolean()
errors = graphene.List(FormError)
def mutate(self, info, old_password, new_password1, new_password2):
form = PasswordChangeForm(info.context.user, data={
"old_password": old_password,
"new_password1": new_password1,
"new_password2": new_password2
})
if form.is_valid():
form.save()
update_session_auth_hash(info.context, form.user)
return ChangePassword(success=True, errors=[])
else:
return ChangePassword(success=False, errors=list_errors(form.errors))
class Mutation(object):
login_user = LoginUser.Field()
signup_user = SignupUser.Field()
logout_user = LogoutUser.Field()
change_password = ChangePassword.Field()<|fim▁end|> | password2 = graphene.String() |
<|file_name|>gulpfile.js<|end_file_name|><|fim▁begin|>var gulp = require('gulp');
var browserify = require('gulp-browserify');
var uglify = require('gulp-uglify');
var minify = require('gulp-minify');
var rename = require('gulp-rename');
var concat = require('gulp-concat');
var notify = require("gulp-notify");
gulp.task( 'vendors.css', function() {
gulp.src([
'node_modules/todomvc-common/base.css',
'node_modules/todomvc-app-css/index.css'
])
.pipe(concat('vendors.min.css'))
.pipe( minify() )<|fim▁hole|>gulp.task( 'vendors.js', function() {
gulp.src( [
'node_modules/vue/dist/vue.js',
'node_modules/vue-resource/dist/vue-resource.js',
'node_modules/todomvc-common/base.js',
])
.pipe(uglify())
.pipe(concat('vendors.min.js'))
.pipe(gulp.dest('./public/js'))
.pipe(notify("Vendors jaavscript bundle has been successfully compiled!"));
});
gulp.task( 'css', function() {
gulp.src('./resources/assets/css/style.css')
.pipe( minify() )
.pipe(rename('style.bundle.css'))
.pipe(gulp.dest('./public/css'))
.pipe(notify("Css bundle has been successfully compiled!"));
});
gulp.task( 'todos', function() {
gulp.src('./src/Todos/js/App.js')
.pipe(browserify( {
transform: [ 'babelify', 'vueify' ],
}))
.pipe(uglify())
.pipe(rename('todos.bundle.js'))
.pipe(gulp.dest('./public/js/todos'))
.pipe(notify("Todos bundle has been successfully compiled!"));
});
gulp.task( 'watch-todos', function() {
gulp.watch('src/Todos/js/App.js', ['todos']);
});
gulp.task( 'vendors', [ 'vendors.css', 'vendors.js' ] );
gulp.task( 'watch', [ 'watch-todos' ] );
gulp.task( 'default', [ 'watch' ] );<|fim▁end|> | .pipe(gulp.dest('./public/css'))
.pipe(notify("Vendors css bundle has been successfully compiled!"));
});
|
<|file_name|>kendo-ui-tests.ts<|end_file_name|><|fim▁begin|>var is = {
string: (msg: string) => {
return true;
}<|fim▁hole|>}
// TreeView
$(() => {
var treeview = <kendo.ui.TreeView>$("#treeview").data("kendoTreeView");
is.string(treeview.text("#foo"));
treeview.text("#foo", "bar");
});
// Window
$(() => {
var window = <kendo.ui.Window>$("#window").data("kendoWindow");
var dom = $("<em>Foo</em>");
window.content(dom);
});<|fim▁end|> | |
<|file_name|>wl_buffer.rs<|end_file_name|><|fim▁begin|>// Copyright 2014 Jonathan Eyolfson
use libc::{c_int, c_void, uint32_t};
use raw;
use raw::types::listeners;
use raw::types::objects;
pub const WL_BUFFER_DESTROY: uint32_t = 0;
#[inline(always)]
pub unsafe fn wl_buffer_add_listener(
wl_buffer: *mut objects::wl_buffer,
listener: *const listeners::wl_buffer_listener,
data: *mut c_void
) -> c_int {
raw::wl_proxy_add_listener(
wl_buffer as *mut objects::wl_proxy,
listener as *mut extern fn(),
data
)
}
#[inline(always)]
pub unsafe fn wl_buffer_set_user_data(
wl_buffer: *mut objects::wl_buffer,
user_data: *mut c_void
) {
raw::wl_proxy_set_user_data(
wl_buffer as *mut objects::wl_proxy,
user_data
)
}
#[inline(always)]
pub unsafe fn wl_buffer_get_user_data(
wl_buffer: *mut objects::wl_buffer
) -> *mut c_void {
raw::wl_proxy_get_user_data(wl_buffer as *mut objects::wl_proxy)<|fim▁hole|>}
#[inline(always)]
pub unsafe fn wl_buffer_destroy(
wl_buffer: *mut objects::wl_buffer
) {
raw::wl_proxy_marshal(
wl_buffer as *mut objects::wl_proxy,
WL_BUFFER_DESTROY
);
raw::wl_proxy_destroy(wl_buffer as *mut objects::wl_proxy)
}<|fim▁end|> | |
<|file_name|>remove_input_state.py<|end_file_name|><|fim▁begin|>'''
This is a one-off command aimed at fixing a temporary problem encountered where input_state was added to
the same dict object in capa problems, so was accumulating. The fix is simply to remove input_state entry
from state for all problems in the affected date range.
'''
import json
import logging
from optparse import make_option
from django.core.management.base import BaseCommand, CommandError
from django.db import transaction
from courseware.models import StudentModule, StudentModuleHistory
LOG = logging.getLogger(__name__)
class Command(BaseCommand):
'''
The fix here is to remove the "input_state" entry in the StudentModule objects of any problems that
contain them. No problem is yet making use of this, and the code should do the right thing if it's
missing (by recreating an empty dict for its value).
To narrow down the set of problems that might need fixing, the StudentModule
objects to be checked is filtered down to those:
created < '2013-03-29 16:30:00' (the problem must have been answered before the buggy code was reverted,
on Prod and Edge)
modified > '2013-03-28 22:00:00' (the problem must have been visited after the bug was introduced
on Prod and Edge)
state like '%input_state%' (the problem must have "input_state" set).
This filtering is done on the production database replica, so that the larger select queries don't lock
the real production database. The list of id values for Student Modules is written to a file, and the
file is passed into this command. The sql file passed to mysql contains:
select sm.id from courseware_studentmodule sm
where sm.modified > "2013-03-28 22:00:00"
and sm.created < "2013-03-29 16:30:00"
and sm.state like "%input_state%"
and sm.module_type = 'problem';
'''
num_visited = 0
num_changed = 0
num_hist_visited = 0
num_hist_changed = 0
option_list = BaseCommand.option_list + (
make_option('--save',
action='store_true',<|fim▁hole|> )
def fix_studentmodules_in_list(self, save_changes, idlist_path):
'''Read in the list of StudentModule objects that might need fixing, and then fix each one'''
# open file and read id values from it:
for line in open(idlist_path, 'r'):
student_module_id = line.strip()
# skip the header, if present:
if student_module_id == 'id':
continue
try:
module = StudentModule.objects.get(id=student_module_id)
except StudentModule.DoesNotExist:
LOG.error(u"Unable to find student module with id = %s: skipping... ", student_module_id)
continue
self.remove_studentmodule_input_state(module, save_changes)
hist_modules = StudentModuleHistory.objects.filter(student_module_id=student_module_id)
for hist_module in hist_modules:
self.remove_studentmodulehistory_input_state(hist_module, save_changes)
if self.num_visited % 1000 == 0:
LOG.info(" Progress: updated {0} of {1} student modules".format(self.num_changed, self.num_visited))
LOG.info(" Progress: updated {0} of {1} student history modules".format(self.num_hist_changed,
self.num_hist_visited))
@transaction.autocommit
def remove_studentmodule_input_state(self, module, save_changes):
''' Fix the grade assigned to a StudentModule'''
module_state = module.state
if module_state is None:
# not likely, since we filter on it. But in general...
LOG.info("No state found for {type} module {id} for student {student} in course {course_id}"
.format(type=module.module_type, id=module.module_state_key,
student=module.student.username, course_id=module.course_id))
return
state_dict = json.loads(module_state)
self.num_visited += 1
if 'input_state' not in state_dict:
pass
elif save_changes:
# make the change and persist
del state_dict['input_state']
module.state = json.dumps(state_dict)
module.save()
self.num_changed += 1
else:
# don't make the change, but increment the count indicating the change would be made
self.num_changed += 1
@transaction.autocommit
def remove_studentmodulehistory_input_state(self, module, save_changes):
''' Fix the grade assigned to a StudentModule'''
module_state = module.state
if module_state is None:
# not likely, since we filter on it. But in general...
LOG.info("No state found for {type} module {id} for student {student} in course {course_id}"
.format(type=module.module_type, id=module.module_state_key,
student=module.student.username, course_id=module.course_id))
return
state_dict = json.loads(module_state)
self.num_hist_visited += 1
if 'input_state' not in state_dict:
pass
elif save_changes:
# make the change and persist
del state_dict['input_state']
module.state = json.dumps(state_dict)
module.save()
self.num_hist_changed += 1
else:
# don't make the change, but increment the count indicating the change would be made
self.num_hist_changed += 1
def handle(self, *args, **options):
'''Handle management command request'''
if len(args) != 1:
raise CommandError("missing idlist file")
idlist_path = args[0]
save_changes = options['save_changes']
LOG.info("Starting run: reading from idlist file {0}; save_changes = {1}".format(idlist_path, save_changes))
self.fix_studentmodules_in_list(save_changes, idlist_path)
LOG.info("Finished run: updating {0} of {1} student modules".format(self.num_changed, self.num_visited))
LOG.info("Finished run: updating {0} of {1} student history modules".format(self.num_hist_changed,
self.num_hist_visited))<|fim▁end|> | dest='save_changes',
default=False,
help='Persist the changes that were encountered. If not set, no changes are saved.'), |
<|file_name|>vision.py<|end_file_name|><|fim▁begin|>"""
Vision-specific analysis functions.
$Id: featureresponses.py 7714 2008-01-24 16:42:21Z antolikjan $
"""
__version__='$Revision: 7714 $'
from math import fmod,floor,pi,sin,cos,sqrt
import numpy
from numpy.oldnumeric import Float
from numpy import zeros, array, size, empty, object_
#import scipy
try:
import pylab
except ImportError:
print "Warning: Could not import matplotlib; pylab plots will not work."
import param
import topo
from topo.base.cf import CFSheet
from topo.base.sheetview import SheetView
from topo.misc.filepath import normalize_path
from topo.misc.numbergenerator import UniformRandom
from topo.plotting.plotgroup import create_plotgroup, plotgroups
from topo.command.analysis import measure_sine_pref
max_value = 0
global_index = ()
def _complexity_rec(x,y,index,depth,fm):
"""
Recurrent helper function for complexity()
"""
global max_value
global global_index
if depth<size(fm.features):
for i in range(size(fm.features[depth].values)):
_complexity_rec(x,y,index + (i,),depth+1,fm)
else:
if max_value < fm.full_matrix[index][x][y]:
global_index = index
max_value = fm.full_matrix[index][x][y]
def complexity(full_matrix):
global global_index
global max_value
"""This function expects as an input a object of type FullMatrix which contains
responses of all neurons in a sheet to stimuly with different varying parameter values.
One of these parameters (features) has to be phase. In such case it computes the classic
modulation ratio (see Hawken et al. for definition) for each neuron and returns them as a matrix.
"""
rows,cols = full_matrix.matrix_shape
complexity = zeros(full_matrix.matrix_shape)
complex_matrix = zeros(full_matrix.matrix_shape,object_)
fftmeasure = zeros(full_matrix.matrix_shape,Float)
i = 0
for f in full_matrix.features:
if f.name == "phase":
phase_index = i
break
i=i+1
sum = 0.0
res = 0.0
average = 0.0
for x in range(rows):
for y in range(cols):
complex_matrix[x,y] = []#
max_value=-0.01
global_index = ()
_complexity_rec(x,y,(),0,full_matrix)
#compute the sum of the responses over phases given the found index of highest response
iindex = array(global_index)
sum = 0.0
for i in range(size(full_matrix.features[phase_index].values)):
iindex[phase_index] = i
sum = sum + full_matrix.full_matrix[tuple(iindex.tolist())][x][y]
#average
average = sum / float(size(full_matrix.features[phase_index].values))
res = 0.0
#compute the sum of absolute values of the responses minus average
for i in range(size(full_matrix.features[phase_index].values)):
iindex[phase_index] = i
res = res + abs(full_matrix.full_matrix[tuple(iindex.tolist())][x][y] - average)
complex_matrix[x,y] = complex_matrix[x,y] + [full_matrix.full_matrix[tuple(iindex.tolist())][x][y]]<|fim▁hole|> pylab.figure()
pylab.plot(complex_matrix[x,y])
if x==26 and y==26:
pylab.figure()
pylab.plot(complex_matrix[x,y])
#complexity[x,y] = res / (2*sum)
fft = numpy.fft.fft(complex_matrix[x,y]+complex_matrix[x,y]+complex_matrix[x,y]+complex_matrix[x,y],2048)
first_har = 2048/len(complex_matrix[0,0])
if abs(fft[0]) != 0:
fftmeasure[x,y] = 2 *abs(fft[first_har]) /abs(fft[0])
else:
fftmeasure[x,y] = 0
return fftmeasure
def compute_ACDC_orientation_tuning_curves(full_matrix,curve_label,sheet):
""" This function allows and alternative computation of orientation tuning curve where
for each given orientation the response is computed as a maximum of AC or DC component
across the phases instead of the maximum used as a standard in Topographica"""
# this method assumes that only single frequency has been used
i = 0
for f in full_matrix.features:
if f.name == "phase":
phase_index = i
if f.name == "orientation":
orientation_index = i
if f.name == "frequency":
frequency_index = i
i=i+1
print sheet.curve_dict
if not sheet.curve_dict.has_key("orientationACDC"):
sheet.curve_dict["orientationACDC"]={}
sheet.curve_dict["orientationACDC"][curve_label]={}
rows,cols = full_matrix.matrix_shape
for o in xrange(size(full_matrix.features[orientation_index].values)):
s_w = zeros(full_matrix.matrix_shape)
for x in range(rows):
for y in range(cols):
or_response=[]
for p in xrange(size(full_matrix.features[phase_index].values)):
index = [0,0,0]
index[phase_index] = p
index[orientation_index] = o
index[frequency_index] = 0
or_response.append(full_matrix.full_matrix[tuple(index)][x][y])
fft = numpy.fft.fft(or_response+or_response+or_response+or_response,2048)
first_har = 2048/len(or_response)
s_w[x][y] = numpy.maximum(2 *abs(fft[first_har]),abs(fft[0]))
s = SheetView((s_w,sheet.bounds), sheet.name , sheet.precedence, topo.sim.time(),sheet.row_precedence)
sheet.curve_dict["orientationACDC"][curve_label].update({full_matrix.features[orientation_index].values[o]:s})
def phase_preference_scatter_plot(sheet_name,diameter=0.39):
r = UniformRandom(seed=1023)
preference_map = topo.sim[sheet_name].sheet_views['PhasePreference']
offset_magnitude = 0.03
datax = []
datay = []
(v,bb) = preference_map.view()
for z in zeros(66):
x = (r() - 0.5)*2*diameter
y = (r() - 0.5)*2*diameter
rand = r()
xoff = sin(rand*2*pi)*offset_magnitude
yoff = cos(rand*2*pi)*offset_magnitude
xx = max(min(x+xoff,diameter),-diameter)
yy = max(min(y+yoff,diameter),-diameter)
x = max(min(x,diameter),-diameter)
y = max(min(y,diameter),-diameter)
[xc1,yc1] = topo.sim[sheet_name].sheet2matrixidx(xx,yy)
[xc2,yc2] = topo.sim[sheet_name].sheet2matrixidx(x,y)
if((xc1==xc2) & (yc1==yc2)): continue
datax = datax + [v[xc1,yc1]]
datay = datay + [v[xc2,yc2]]
for i in range(0,len(datax)):
datax[i] = datax[i] * 360
datay[i] = datay[i] * 360
if(datay[i] > datax[i] + 180): datay[i]= datay[i]- 360
if((datax[i] > 180) & (datay[i]> 180)): datax[i] = datax[i] - 360; datay[i] = datay[i] - 360
if((datax[i] > 180) & (datay[i] < (datax[i]-180))): datax[i] = datax[i] - 360; #datay[i] = datay[i] - 360
f = pylab.figure()
ax = f.add_subplot(111, aspect='equal')
pylab.plot(datax,datay,'ro')
pylab.plot([0,360],[-180,180])
pylab.plot([-180,180],[0,360])
pylab.plot([-180,-180],[360,360])
ax.axis([-180,360,-180,360])
pylab.xticks([-180,0,180,360], [-180,0,180,360])
pylab.yticks([-180,0,180,360], [-180,0,180,360])
pylab.grid()
pylab.savefig(normalize_path(str(topo.sim.timestr()) + sheet_name + "_scatter.png"))
###############################################################################
# JABALERT: Should we move this plot and command to analysis.py or
# pylabplots.py, where all the rest are?
#
# In any case, it requires generalization; it should not be hardcoded
# to any particular map name, and should just do the right thing for
# most networks for which it makes sense. E.g. it already measures
# the ComplexSelectivity for all measured_sheets, but then
# plot_modulation_ratio only accepts two with specific names.
# plot_modulation_ratio should just plot whatever it is given, and
# then analyze_complexity can simply pass in whatever was measured,
# with the user controlling what is measured using the measure_map
# attribute of each Sheet. That way the complexity of any sheet could
# be measured, which is what we want.
#
# Specific changes needed:
# - Make plot_modulation_ratio accept a list of sheets and
# plot their individual modulation ratios and combined ratio.
# - Remove complex_sheet_name argument, which is no longer needed
# - Make sure it still works fine even if V1Simple doesn't exist;
# as this is just for an optional scatter plot, it's fine to skip
# it.
# - Preferably remove the filename argument by default, so that
# plots will show up in the GUI
def analyze_complexity(full_matrix,simple_sheet_name,complex_sheet_name,filename=None):
"""
Compute modulation ratio for each neuron, to distinguish complex from simple cells.
Uses full_matrix data obtained from measure_or_pref().
If there is a sheet named as specified in simple_sheet_name,
also plots its phase preference as a scatter plot.
"""
import topo
measured_sheets = [s for s in topo.sim.objects(CFSheet).values()
if hasattr(s,'measure_maps') and s.measure_maps]
for sheet in measured_sheets:
# Divide by two to get into 0-1 scale - that means simple/complex boundry is now at 0.5
complx = array(complexity(full_matrix[sheet]))/2.0
# Should this be renamed to ModulationRatio?
sheet.sheet_views['ComplexSelectivity']=SheetView((complx,sheet.bounds), sheet.name , sheet.precedence, topo.sim.time(),sheet.row_precedence)
import topo.command.pylabplots
topo.command.pylabplots.plot_modulation_ratio(full_matrix,simple_sheet_name=simple_sheet_name,complex_sheet_name=complex_sheet_name,filename=filename)
# Avoid error if no simple sheet exists
try:
phase_preference_scatter_plot(simple_sheet_name,diameter=0.24999)
except AttributeError:
print "Skipping phase preference scatter plot; could not analyze region %s." \
% simple_sheet_name
class measure_and_analyze_complexity(measure_sine_pref):
"""Macro for measuring orientation preference and then analyzing its complexity."""
def __call__(self,**params):
fm = super(measure_and_analyze_complexity,self).__call__(**params)
#from topo.command.analysis import measure_or_pref
#fm = measure_or_pref()
analyze_complexity(fm,simple_sheet_name="V1Simple",complex_sheet_name="V1Complex",filename="ModulationRatio")
pg= create_plotgroup(name='Orientation Preference and Complexity',category="Preference Maps",
doc='Measure preference for sine grating orientation.',
pre_plot_hooks=[measure_and_analyze_complexity.instance()])
pg.add_plot('Orientation Preference',[('Hue','OrientationPreference')])
pg.add_plot('Orientation Preference&Selectivity',[('Hue','OrientationPreference'),
('Confidence','OrientationSelectivity')])
pg.add_plot('Orientation Selectivity',[('Strength','OrientationSelectivity')])
pg.add_plot('Modulation Ratio',[('Strength','ComplexSelectivity')])
pg.add_plot('Phase Preference',[('Hue','PhasePreference')])
pg.add_static_image('Color Key','command/or_key_white_vert_small.png')<|fim▁end|> |
#this is taking away the DC component
#complex_matrix[x,y] -= numpy.min(complex_matrix[x,y])
if x==15 and y==15: |
<|file_name|>rules.py<|end_file_name|><|fim▁begin|>class Rule:
'''
规则父类
'''
def action(self,block,handler):
'''
加标记
'''
handler.start(self.type)
handler.feed(block)
handler.end(self.type)
return True
class HeadingRule(Rule):
'''
一号标题规则
'''
type='heading'
def condition(self,block):
'''
判断文本块是否符合规则
'''
return not '\n' in block and len(block)<=70 and not block[-1]==':'
class TitleRule(HeadingRule):
'''
二号标题规则
'''<|fim▁hole|> if not self.first:
return False
self.first=False
return HeadingRule.condition(self,block)
class ListItemRule(Rule):
'''
列表项规则
'''
type='listitem'
def condition(self,block):
return block[0]=='-'
def action(self,block,handler):
handler.start(self.type)
handler.feed(block[1:].strip())
handler.end(self.type)
return True
class ListRule(ListItemRule):
'''
列表规则
'''
type ='list'
inside=False
def condition(self,block):
return True
def action(self,block,handler):
if not self.inside and ListItemRule.condition(self,block):
handler.start(self.type)
elif self.inside and not ListItemRule.condition(self,block):
handler.end(self,type)
self.inside=False
return False
class ParagraphRule(Rule):
'''
段落规则
'''
type='paragraph'
def condition(self,block):
return True<|fim▁end|> | type='title'
first=True
def condintion(self,block): |
<|file_name|>GetClientDocumentsResponse.java<|end_file_name|><|fim▁begin|>package ru.lanbilling.webservice.wsdl;
import java.util.ArrayList;
import java.util.List;
import javax.annotation.Generated;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlType;
/**
* <p>Java class for anonymous complex type.
*
* <p>The following schema fragment specifies the expected content contained within this class.
*
* <pre>
* <complexType>
* <complexContent>
* <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
* <sequence>
* <element name="ret" type="{urn:api3}soapDocument" maxOccurs="unbounded"/>
* </sequence>
* </restriction>
* </complexContent>
* </complexType>
* </pre>
*
*
*/
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "", propOrder = {
"ret"
})
@XmlRootElement(name = "getClientDocumentsResponse")
@Generated(value = "com.sun.tools.xjc.Driver", date = "2015-10-25T05:29:34+06:00", comments = "JAXB RI v2.2.11")
public class GetClientDocumentsResponse {
@XmlElement(required = true)
@Generated(value = "com.sun.tools.xjc.Driver", date = "2015-10-25T05:29:34+06:00", comments = "JAXB RI v2.2.11")
protected List<SoapDocument> ret;
/**
* Gets the value of the ret property.
*
* <p>
* This accessor method returns a reference to the live list,
* not a snapshot. Therefore any modification you make to the
* returned list will be present inside the JAXB object.
* This is why there is not a <CODE>set</CODE> method for the ret property.
*
* <p>
* For example, to add a new item, do as follows:
* <pre>
* getRet().add(newItem);<|fim▁hole|> * </pre>
*
*
* <p>
* Objects of the following type(s) are allowed in the list
* {@link SoapDocument }
*
*
*/
@Generated(value = "com.sun.tools.xjc.Driver", date = "2015-10-25T05:29:34+06:00", comments = "JAXB RI v2.2.11")
public List<SoapDocument> getRet() {
if (ret == null) {
ret = new ArrayList<SoapDocument>();
}
return this.ret;
}
}<|fim▁end|> | |
<|file_name|>views.py<|end_file_name|><|fim▁begin|>import itertools as it
from operator import attrgetter
from flask import Markup, render_template, Blueprint, redirect, url_for, flash, abort, request
from sqlalchemy import desc
from .. import Execution, Stage, Task, TaskStatus
from ..job.JobManager import JobManager
from . import filters
from ..graph.draw import draw_task_graph, draw_stage_graph
def gen_bprint(cosmos_app):
session = cosmos_app.session
def get_execution(id):
return session.query(Execution).filter_by(id=id).one()
bprint = Blueprint('cosmos', __name__, template_folder='templates', static_folder='static',
static_url_path='/cosmos/static')
filters.add_filters(bprint)
@bprint.route('/execution/delete/<int:id>')
def execution_delete(id):
e = get_execution(id)
e.delete(delete_files=True)
flash('Deleted %s' % e)<|fim▁hole|>
@bprint.route('/')
def index():
executions = session.query(Execution).order_by(desc(Execution.created_on)).all()
session.expire_all()
return render_template('cosmos/index.html', executions=executions)
@bprint.route('/')
def home():
return index()
@bprint.route('/execution/<name>/')
# @bprint.route('/execution/<int:id>/')
def execution(name):
execution = session.query(Execution).filter_by(name=name).one()
return render_template('cosmos/execution.html', execution=execution)
@bprint.route('/execution/<execution_name>/<stage_name>/')
def stage(execution_name, stage_name):
ex = session.query(Execution).filter_by(name=execution_name).one()
stage = session.query(Stage).filter_by(execution_id=ex.id, name=stage_name).one()
if stage is None:
return abort(404)
submitted = filter(lambda t: t.status == TaskStatus.submitted, stage.tasks)
jm = JobManager(cosmos_app.get_submit_args)
f = attrgetter('drm')
drm_statuses = {}
for drm, tasks in it.groupby(sorted(submitted, key=f), f):
drm_statuses.update(jm.drms[drm].drm_statuses(list(tasks)))
return render_template('cosmos/stage.html', stage=stage, drm_statuses=drm_statuses)
# x=filter(lambda t: t.status == TaskStatus.submitted, stage.tasks))
@bprint.route('/execution/<int:ex_id>/stage/<stage_name>/delete/')
def stage_delete(ex_id, stage_name):
s = session.query(Stage).filter(Stage.execution_id == ex_id, Stage.name == stage_name).one()
flash('Deleted %s' % s)
ex_url = s.execution.url
s.delete(delete_files=False)
return redirect(ex_url)
# @bprint.route('/task/<int:id>/')
# def task(id):
# task = session.query(Task).get(id)
# if task is None:
# return abort(404)
# return redirect(url_for('cosmos.task_friendly', ex_name=task.execution.name, stage_name=task.stage.name, task_id=task.id))
# @bprint.route('/execution/<ex_name>/<stage_name>/task/')
# def task(ex_name, stage_name):
# # resource_usage = [(category, field, getattr(task, field), profile_help[field]) for category, fields in
# # task.profile_fields for field in fields]
# assert request.method == 'GET'
# tags = request.args
# ex = session.query(Execution).filter_by(name=ex_name).one()
# stage = session.query(Stage).filter_by(execution=ex, name=stage_name).one()
# task = session.query(Task).filter_by(stage=stage, tags=tags).one()
# if task is None:
# return abort(404)
# resource_usage = [(field, getattr(task, field)) for field in task.profile_fields]
# return render_template('cosmos/task.html', task=task, resource_usage=resource_usage)
@bprint.route('/execution/<ex_name>/<stage_name>/task/<task_id>')
def task(ex_name, stage_name, task_id):
# resource_usage = [(category, field, getattr(task, field), profile_help[field]) for category, fields in
# task.profile_fields for field in fields]
task = session.query(Task).get(task_id)
if task is None:
return abort(404)
resource_usage = [(field, getattr(task, field)) for field in task.profile_fields]
return render_template('cosmos/task.html', task=task, resource_usage=resource_usage)
@bprint.route('/execution/<int:id>/taskgraph/<type>/')
def taskgraph(id, type):
from ..graph.draw import pygraphviz_available
ex = get_execution(id)
if pygraphviz_available:
if type == 'task':
svg = Markup(draw_task_graph(ex.task_graph(), url=True))
else:
svg = Markup(draw_stage_graph(ex.stage_graph(), url=True))
else:
svg = 'Pygraphviz not installed, cannot visualize. (Usually: apt-get install graphviz && pip install pygraphviz)'
return render_template('cosmos/taskgraph.html', execution=ex, type=type,
svg=svg)
# @bprint.route('/execution/<int:id>/taskgraph/svg/<type>/')
# def taskgraph_svg(id, type, ):
# e = get_execution(id)
#
# if type == 'task':
# return send_file(io.BytesIO(taskgraph_.tasks_to_image(e.tasks)), mimetype='image/svg+xml')
# else:
# return send_file(io.BytesIO(stages_to_image(e.stages)), mimetype='image/svg+xml')
#
return bprint
profile_help = dict(
# time
system_time='Amount of time that this process has been scheduled in kernel mode',
user_time='Amount of time that this process has been scheduled in user mode. This includes guest time, guest_time (time spent running a virtual CPU, see below), so that applications that are not aware of the guest time field do not lose that time from their calculations',
cpu_time='system_time + user_time',
wall_time='Elapsed real (wall clock) time used by the process.',
percent_cpu='(cpu_time / wall_time) * 100',
# memory
avg_rss_mem='Average resident set size (Kb)',
max_rss_mem='Maximum resident set size (Kb)',
single_proc_max_peak_rss='Maximum single process rss used (Kb)',
avg_virtual_mem='Average virtual memory used (Kb)',
max_virtual_mem='Maximum virtual memory used (Kb)',
single_proc_max_peak_virtual_mem='Maximum single process virtual memory used (Kb)',
major_page_faults='The number of major faults the process has made which have required loading a memory page from disk',
minor_page_faults='The number of minor faults the process has made which have not required loading a memory page from disk',
avg_data_mem='Average size of data segments (Kb)',
max_data_mem='Maximum size of data segments (Kb)',
avg_lib_mem='Average library memory size (Kb)',
max_lib_mem='Maximum library memory size (Kb)',
avg_locked_mem='Average locked memory size (Kb)',
max_locked_mem='Maximum locked memory size (Kb)',
avg_num_threads='Average number of threads',
max_num_threads='Maximum number of threads',
avg_pte_mem='Average page table entries size (Kb)',
max_pte_mem='Maximum page table entries size (Kb)',
#io
nonvoluntary_context_switches='Number of non voluntary context switches',
voluntary_context_switches='Number of voluntary context switches',
block_io_delays='Aggregated block I/O delays',
avg_fdsize='Average number of file descriptor slots allocated',
max_fdsize='Maximum number of file descriptor slots allocated',
#misc
num_polls='Number of times the resource usage statistics were polled from /proc',
names='Names of all descendnt processes (there is always a python process for the profile_working.py script)',
num_processes='Total number of descendant processes that were spawned',
pids='Pids of all the descendant processes',
exit_status='Exit status of the primary process being profiled',
SC_CLK_TCK='sysconf(_SC_CLK_TCK), an operating system variable that is usually equal to 100, or centiseconds',
)<|fim▁end|> | return redirect(url_for('cosmos.index')) |
<|file_name|>views.py<|end_file_name|><|fim▁begin|>from braces.views import LoginRequiredMixin
from django.views.generic import UpdateView
from oauth2_provider.exceptions import OAuthToolkitError
from oauth2_provider.http import HttpResponseUriRedirect
from oauth2_provider.models import get_application_model as get_oauth2_application_model
from oauth2_provider.settings import oauth2_settings
from oauth2_provider.views import AuthorizationView
from oauth2_provider.views.application import ApplicationRegistration
from core.utils import get_default_scopes
from .forms import RegistrationForm
class ApplicationRegistrationView(ApplicationRegistration):
form_class = RegistrationForm
class ApplicationUpdateView(LoginRequiredMixin, UpdateView):
"""
View used to update an application owned by the request.user
"""
form_class = RegistrationForm
context_object_name = 'application'
template_name = "oauth2_provider/application_form.html"
def get_queryset(self):
return get_oauth2_application_model().objects.filter(user=self.request.user)
class CustomAuthorizationView(AuthorizationView):
def form_valid(self, form):<|fim▁hole|> scopes = set(scopes.split(' '))
scopes.update(set(get_default_scopes(application)))
private_scopes = application.private_scopes
if private_scopes:
private_scopes = set(private_scopes.split(' '))
scopes.update(private_scopes)
scopes = ' '.join(list(scopes))
form.cleaned_data['scope'] = scopes
return super(CustomAuthorizationView, self).form_valid(form)
def get(self, request, *args, **kwargs):
"""
Copied blatantly from super method. Had to change few stuff, but didn't find better way
than copying and editing the whole stuff.
Sin Count += 1
"""
try:
scopes, credentials = self.validate_authorization_request(request)
try:
del credentials['request']
# Removing oauthlib.Request from credentials. This is not required in future
except KeyError: # pylint: disable=pointless-except
pass
kwargs['scopes_descriptions'] = [oauth2_settings.SCOPES[scope] for scope in scopes]
kwargs['scopes'] = scopes
# at this point we know an Application instance with such client_id exists in the database
application = get_oauth2_application_model().objects.get(
client_id=credentials['client_id']) # TODO: cache it!
kwargs['application'] = application
kwargs.update(credentials)
self.oauth2_data = kwargs
# following two loc are here only because of https://code.djangoproject.com/ticket/17795
form = self.get_form(self.get_form_class())
kwargs['form'] = form
# Check to see if the user has already granted access and return
# a successful response depending on 'approval_prompt' url parameter
require_approval = request.GET.get('approval_prompt', oauth2_settings.REQUEST_APPROVAL_PROMPT)
# If skip_authorization field is True, skip the authorization screen even
# if this is the first use of the application and there was no previous authorization.
# This is useful for in-house applications-> assume an in-house applications
# are already approved.
if application.skip_authorization:
uri, headers, body, status = self.create_authorization_response(
request=self.request, scopes=" ".join(scopes),
credentials=credentials, allow=True)
return HttpResponseUriRedirect(uri)
elif require_approval == 'auto':
tokens = request.user.accesstoken_set.filter(application=kwargs['application']).all().order_by('-id')
if len(tokens) > 0:
token = tokens[0]
if len(tokens) > 1:
# Enforce one token pair per user policy. Remove all older tokens
request.user.accesstoken_set.exclude(pk=token.id).all().delete()
# check past authorizations regarded the same scopes as the current one
if token.allow_scopes(scopes):
uri, headers, body, status = self.create_authorization_response(
request=self.request, scopes=" ".join(scopes),
credentials=credentials, allow=True)
return HttpResponseUriRedirect(uri)
return self.render_to_response(self.get_context_data(**kwargs))
except OAuthToolkitError as error:
return self.error_response(error)<|fim▁end|> | client_id = form.cleaned_data.get('client_id', '')
application = get_oauth2_application_model().objects.get(client_id=client_id)
scopes = form.cleaned_data.get('scope', '') |
<|file_name|>dart_dependency_catcher.cc<|end_file_name|><|fim▁begin|>// Copyright 2015 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "sky/engine/tonic/dart_dependency_catcher.h"
#include "sky/engine/tonic/dart_library_loader.h"
namespace blink {
<|fim▁hole|>}
DartDependencyCatcher::~DartDependencyCatcher() {
loader_.set_dependency_catcher(nullptr);
}
void DartDependencyCatcher::AddDependency(DartDependency* dependency) {
dependencies_.add(dependency);
}
} // namespace blink<|fim▁end|> | DartDependencyCatcher::DartDependencyCatcher(DartLibraryLoader& loader)
: loader_(loader) {
loader_.set_dependency_catcher(this); |
<|file_name|>buf4_mat_irrep_rd_block.cc<|end_file_name|><|fim▁begin|>/*
* @BEGIN LICENSE
*
* Psi4: an open-source quantum chemistry software package
*
* Copyright (c) 2007-2017 The Psi4 Developers.
*
* The copyrights for code used from other parties are included in
* the corresponding files.
*
* This file is part of Psi4.
*
* Psi4 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, version 3.
*
* Psi4 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 Psi4; if not, write to the Free Software Foundation, Inc.,
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*
* @END LICENSE
*/
/*! \file
\ingroup DPD
\brief Enter brief description of file here
*/
#include "dpd.h"
#include "psi4/libqt/qt.h"
#include "psi4/psi4-dec.h"
#include "psi4/libpsi4util/PsiOutStream.h"
#include <cstdio>
#include <cstdlib>
namespace psi {
int DPD::buf4_mat_irrep_rd_block(dpdbuf4 *Buf, int irrep, int start_pq,
int num_pq)
{
int method, filerow, all_buf_irrep;
int pq, rs; /* dpdbuf row and column indices */
int p, q, r, s; /* orbital indices */
int filepq, filers, filesr; /* Input dpdfile row and column indices */
int rowtot, coltot; /* dpdbuf row and column dimensions */
int b_perm_pq, b_perm_rs, b_peq, b_res;
int f_perm_pq, f_perm_rs, f_peq, f_res;
int pq_permute, permute;
double value;
#ifdef DPD_TIMER
timer_on("buf4_rd_bk");
#endif
all_buf_irrep = Buf->file.my_irrep;
rowtot = Buf->params->rowtot[irrep];
coltot = Buf->params->coltot[irrep^all_buf_irrep];
b_perm_pq = Buf->params->perm_pq; b_perm_rs = Buf->params->perm_rs;
f_perm_pq = Buf->file.params->perm_pq; f_perm_rs = Buf->file.params->perm_rs;
b_peq = Buf->params->peq; b_res = Buf->params->res;
f_peq = Buf->file.params->peq; f_res = Buf->file.params->res;
if((b_perm_pq == f_perm_pq) && (b_perm_rs == f_perm_rs) &&
(b_peq == f_peq) && (b_res == f_res)) {
if(Buf->anti) method = 11;
else method = 12;
}
else if((b_perm_pq != f_perm_pq) && (b_perm_rs == f_perm_rs) &&
(b_res == f_res)) {
if(f_perm_pq && !b_perm_pq) {
if(Buf->anti) {
outfile->Printf( "\n\tUnpack pq and antisymmetrize?\n");
exit(PSI_RETURN_FAILURE);
}
method = 21;
}
else if(!f_perm_pq && b_perm_pq) {
if(Buf->anti) method = 22;
else method = 23;
}
else {
outfile->Printf( "\n\tInvalid second-level method!\n");
exit(PSI_RETURN_FAILURE);
}
}
else if((b_perm_pq == f_perm_pq) && (b_perm_rs != f_perm_rs) &&
(b_peq == f_peq)) {
if(f_perm_rs && !b_perm_rs) {
if(Buf->anti) {
outfile->Printf( "\n\tUnpack rs and antisymmetrize?\n");
exit(PSI_RETURN_FAILURE);
}
method = 31;
}
else if(!f_perm_rs && b_perm_rs) {
if(Buf->anti) method = 32;
else method = 33;
}
else {
outfile->Printf( "\n\tInvalid third-level method!\n");
exit(PSI_RETURN_FAILURE);
}
}
else if((b_perm_pq != f_perm_pq) && (b_perm_rs != f_perm_rs)) {
if(f_perm_pq && !b_perm_pq) {
if(f_perm_rs && !b_perm_rs) {
if(Buf->anti) {
outfile->Printf( "\n\tUnpack pq and rs and antisymmetrize?\n");
exit(PSI_RETURN_FAILURE);
}
else method = 41;
}
else if(!f_perm_rs && b_perm_rs) {
if(Buf->anti) {
outfile->Printf( "\n\tUnpack pq and antisymmetrize?\n");
exit(PSI_RETURN_FAILURE);
}
else method = 42;
}
}
else if(!f_perm_pq && b_perm_pq) {
if(f_perm_rs && !b_perm_rs) {
if(Buf->anti) {
outfile->Printf( "\n\tUnpack rs and antisymmetrize?\n");
exit(PSI_RETURN_FAILURE);
}
else method = 43;
}
else if(!f_perm_rs && b_perm_rs) {
if(Buf->anti) method = 44;
else method = 45;
}
}
else {
outfile->Printf( "\n\tInvalid fourth-level method!\n");
exit(PSI_RETURN_FAILURE);
}
}
else {
outfile->Printf( "\n\tInvalid method in dpd_buf_mat_irrep_rd!\n");
exit(PSI_RETURN_FAILURE);
}
switch(method) {
case 11: /* No change in pq or rs; antisymmetrize */
/* Prepare the input buffer from the input file */
file4_mat_irrep_row_init(&(Buf->file), irrep);
/* Loop over rows in the dpdbuf/dpdfile */
for(pq=0; pq < num_pq; pq++) {
filerow = Buf->file.incore ? pq : 0;
/* Fill the buffer */
file4_mat_irrep_row_rd(&(Buf->file), irrep, pq+start_pq);
/* Loop over the columns in the dpdbuf */
for(rs=0; rs < coltot; rs++) {
r = Buf->params->colorb[irrep^all_buf_irrep][rs][0];
s = Buf->params->colorb[irrep^all_buf_irrep][rs][1];
/* Column indices in the dpdfile */
filers = rs;
filesr = Buf->file.params->colidx[s][r];
value = Buf->file.matrix[irrep][filerow][filers];
value -= Buf->file.matrix[irrep][filerow][filesr];
/* Assign the value */
Buf->matrix[irrep][pq][rs] = value;
}
}
/* Close the input buffer */
file4_mat_irrep_row_close(&(Buf->file), irrep);
break;
case 12: /* no change in pq or rs */
if(Buf->file.incore)
for(pq=0; pq < num_pq; pq++)
for(rs=0; rs < coltot; rs++)
Buf->matrix[irrep][pq][rs] =
Buf->file.matrix[irrep][pq+start_pq][rs];
else {
Buf->file.matrix[irrep] = Buf->matrix[irrep];
file4_mat_irrep_rd_block(&(Buf->file), irrep, start_pq, num_pq);
}
break;
case 21: /* unpack pq; no change in rs */
/* prepare the input buffer from the input file */
file4_mat_irrep_row_init(&(Buf->file), irrep);
/* loop over rows in the dpdbuf */
for(pq=0; pq < num_pq; pq++) {
p = Buf->params->roworb[irrep][pq+start_pq][0];
q = Buf->params->roworb[irrep][pq+start_pq][1];
filepq = Buf->file.params->rowidx[p][q];
filerow = Buf->file.incore ? filepq : 0;
/* set the permutation operator's value */
permute = ((p < q) && (f_perm_pq < 0) ? -1 : 1);
/* fill the buffer */
if(filepq >= 0)
file4_mat_irrep_row_rd(&(Buf->file), irrep, filepq);
else
file4_mat_irrep_row_zero(&(Buf->file), irrep, filepq);
/* loop over the columns in the dpdbuf */
for(rs=0; rs < coltot; rs++) {
filers = rs;
value = Buf->file.matrix[irrep][filerow][filers];
/* assign the value, keeping track of the sign */
Buf->matrix[irrep][pq][rs] = permute*value;
}
}
/* close the input buffer */
file4_mat_irrep_row_close(&(Buf->file), irrep);
break;
case 22: /* pack pq; no change in rs; antisymmetrize */
/* prepare the input buffer from the input file */
file4_mat_irrep_row_init(&(Buf->file), irrep);
/* loop over rows in the dpdbuf */
for(pq=0; pq < num_pq; pq++) {
p = Buf->params->roworb[irrep][pq+start_pq][0];
q = Buf->params->roworb[irrep][pq+start_pq][1];
filepq = Buf->file.params->rowidx[p][q];
filerow = Buf->file.incore ? filepq : 0;
/* fill the buffer */
file4_mat_irrep_row_rd(&(Buf->file), irrep, filepq);
/* loop over the columns in the dpdbuf */
for(rs=0; rs < coltot; rs++) {
r = Buf->params->colorb[irrep^all_buf_irrep][rs][0];
s = Buf->params->colorb[irrep^all_buf_irrep][rs][1];
/* column indices in the dpdfile */
filers = rs;
filesr = Buf->file.params->colidx[s][r];
value = Buf->file.matrix[irrep][filerow][filers];
value -= Buf->file.matrix[irrep][filerow][filesr];
/* assign the value */
Buf->matrix[irrep][pq][rs] = value;
}
}
/* close the input buffer */
file4_mat_irrep_row_close(&(Buf->file), irrep);
break;
case 23: /* pack pq; no change in rs */
/* prepare the input buffer from the input file */
file4_mat_irrep_row_init(&(Buf->file), irrep);
/* loop over rows in the dpdbuf */
for(pq=0; pq < num_pq; pq++) {
p = Buf->params->roworb[irrep][pq+start_pq][0];
q = Buf->params->roworb[irrep][pq+start_pq][1];
filepq = Buf->file.params->rowidx[p][q];
filerow = Buf->file.incore ? filepq : 0;
file4_mat_irrep_row_rd(&(Buf->file), irrep, filepq);
/* loop over the columns in the dpdbuf */
for(rs=0; rs < coltot; rs++) {
filers = rs;
value = Buf->file.matrix[irrep][filerow][filers];
/* assign the value */
Buf->matrix[irrep][pq][rs] = value;
}
}
/* close the input buffer */
file4_mat_irrep_row_close(&(Buf->file), irrep);
break;
case 31: /* no change in pq; unpack rs */
/* prepare the input buffer from the input file */
file4_mat_irrep_row_init(&(Buf->file), irrep);
/* loop over rows in the dpdbuf/dpdfile */
for(pq=0; pq < num_pq; pq++) {
filepq = pq+start_pq;
filerow = Buf->file.incore ? filepq : 0;
/* fill the buffer */
file4_mat_irrep_row_rd(&(Buf->file), irrep, filepq);
/* loop over the columns in the dpdbuf */
for(rs=0; rs < coltot; rs++) {
r = Buf->params->colorb[irrep^all_buf_irrep][rs][0];
s = Buf->params->colorb[irrep^all_buf_irrep][rs][1];
filers = Buf->file.params->colidx[r][s];
/* rs permutation operator */
permute = ((r < s) && (f_perm_rs < 0) ? -1 : 1);
/* is this fast enough? */
value = ((filers < 0) ? 0 :
Buf->file.matrix[irrep][filerow][filers]);
/* assign the value */
Buf->matrix[irrep][pq][rs] = permute*value;
}
}
/* Close the input buffer */
file4_mat_irrep_row_close(&(Buf->file), irrep);
break;
case 32: /* No change in pq; pack rs; antisymmetrize */
/* Prepare the input buffer from the input file */
file4_mat_irrep_row_init(&(Buf->file), irrep);
/* Loop over rows in the dpdbuf/dpdfile */
for(pq=0; pq < num_pq; pq++) {
filepq = pq+start_pq;
filerow = Buf->file.incore ? filepq : 0;
/* Fill the buffer */
file4_mat_irrep_row_rd(&(Buf->file), irrep, filepq);
/* Loop over the columns in the dpdbuf */
for(rs=0; rs < coltot; rs++) {
r = Buf->params->colorb[irrep^all_buf_irrep][rs][0];
s = Buf->params->colorb[irrep^all_buf_irrep][rs][1];
/* Column indices in the dpdfile */
filers = Buf->file.params->colidx[r][s];
filesr = Buf->file.params->colidx[s][r];
value = Buf->file.matrix[irrep][filerow][filers];
value -= Buf->file.matrix[irrep][filerow][filesr];
<|fim▁hole|> Buf->matrix[irrep][pq][rs] = value;
}
}
/* Close the input buffer */
file4_mat_irrep_row_close(&(Buf->file), irrep);
break;
case 33: /* No change in pq; pack rs */
/* Prepare the input buffer from the input file */
file4_mat_irrep_row_init(&(Buf->file), irrep);
/* Loop over rows in the dpdbuf/dpdfile */
for(pq=0; pq < num_pq; pq++) {
filepq = pq+start_pq;
filerow = Buf->file.incore ? filepq : 0;
/* Fill the buffer */
file4_mat_irrep_row_rd(&(Buf->file), irrep, filepq);
/* Loop over the columns in the dpdbuf */
for(rs=0; rs < coltot; rs++) {
r = Buf->params->colorb[irrep^all_buf_irrep][rs][0];
s = Buf->params->colorb[irrep^all_buf_irrep][rs][1];
filers = Buf->file.params->colidx[r][s];
value = Buf->file.matrix[irrep][filerow][filers];
/* Assign the value */
Buf->matrix[irrep][pq][rs] = value;
}
}
/* Close the input buffer */
file4_mat_irrep_row_close(&(Buf->file), irrep);
break;
case 41: /* Unpack pq and rs */
/* Prepare the input buffer from the input file */
file4_mat_irrep_row_init(&(Buf->file), irrep);
/* Loop over rows in the dpdbuf */
for(pq=0; pq < num_pq; pq++) {
p = Buf->params->roworb[irrep][pq+start_pq][0];
q = Buf->params->roworb[irrep][pq+start_pq][1];
filepq = Buf->file.params->rowidx[p][q];
filerow = Buf->file.incore ? filepq : 0;
/* Set the value of the pq permutation operator */
pq_permute = ((p < q) && (f_perm_pq < 0) ? -1 : 1);
/* Fill the buffer */
if(filepq >= 0)
file4_mat_irrep_row_rd(&(Buf->file), irrep, filepq);
else
file4_mat_irrep_row_zero(&(Buf->file), irrep, filepq);
/* Loop over the columns in the dpdbuf */
for(rs=0; rs < coltot; rs++) {
r = Buf->params->colorb[irrep^all_buf_irrep][rs][0];
s = Buf->params->colorb[irrep^all_buf_irrep][rs][1];
filers = Buf->file.params->colidx[r][s];
/* Set the value of the pqrs permutation operator */
permute = ((r < s) && (f_perm_rs < 0) ? -1 : 1)*pq_permute;
value = 0;
/* if(filers >= 0) */
if ((filers >= 0) && (filerow >= 0)) /* Is this alright? (RAK, 11-2005) */
value = Buf->file.matrix[irrep][filerow][filers];
/* Assign the value */
Buf->matrix[irrep][pq][rs] = permute*value;
}
}
/* Close the input buffer */
file4_mat_irrep_row_close(&(Buf->file), irrep);
break;
case 42: /* Pack pq; unpack rs */
outfile->Printf( "\n\tHaven't programmed method 42 yet!\n");
exit(PSI_RETURN_FAILURE);
break;
case 43: /* Unpack pq; pack rs */
outfile->Printf( "\n\tHaven't programmed method 43 yet!\n");
exit(PSI_RETURN_FAILURE);
break;
case 44: /* Pack pq; pack rs; antisymmetrize */
/* Prepare the input buffer from the input file */
file4_mat_irrep_row_init(&(Buf->file), irrep);
/* Loop over rows in the dpdbuf */
for(pq=0; pq < num_pq; pq++) {
p = Buf->params->roworb[irrep][pq+start_pq][0];
q = Buf->params->roworb[irrep][pq+start_pq][1];
filepq = Buf->file.params->rowidx[p][q];
filerow = Buf->file.incore ? filepq : 0;
/* Fill the buffer */
file4_mat_irrep_row_rd(&(Buf->file), irrep, filepq);
/* Loop over the columns in the dpdbuf */
for(rs=0; rs < coltot; rs++) {
r = Buf->params->colorb[irrep^all_buf_irrep][rs][0];
s = Buf->params->colorb[irrep^all_buf_irrep][rs][1];
/* Column indices in the dpdfile */
filers = Buf->file.params->colidx[r][s];
filesr = Buf->file.params->colidx[s][r];
value = Buf->file.matrix[irrep][filerow][filers];
value -= Buf->file.matrix[irrep][filerow][filesr];
/* Assign the value */
Buf->matrix[irrep][pq][rs] = value;
}
}
/* Close the input buffer */
file4_mat_irrep_row_close(&(Buf->file), irrep);
break;
case 45: /* Pack pq and rs */
/* Prepare the input buffer from the input file */
file4_mat_irrep_row_init(&(Buf->file), irrep);
/* Loop over rows in the dpdbuf */
for(pq=0; pq < num_pq; pq++) {
p = Buf->params->roworb[irrep][pq+start_pq][0];
q = Buf->params->roworb[irrep][pq+start_pq][1];
filepq = Buf->file.params->rowidx[p][q];
filerow = Buf->file.incore ? filepq : 0;
file4_mat_irrep_row_rd(&(Buf->file), irrep, filepq);
/* Loop over the columns in the dpdbuf */
for(rs=0; rs < coltot; rs++) {
r = Buf->params->colorb[irrep^all_buf_irrep][rs][0];
s = Buf->params->colorb[irrep^all_buf_irrep][rs][1];
filers = Buf->file.params->colidx[r][s];
if(filers < 0) {
outfile->Printf( "\n\tNegative colidx in method 44?\n");
exit(PSI_RETURN_FAILURE);
}
value = Buf->file.matrix[irrep][filerow][filers];
/* Assign the value */
Buf->matrix[irrep][pq][rs] = value;
}
}
/* Close the input buffer */
file4_mat_irrep_row_close(&(Buf->file), irrep);
break;
default: /* Error trapping */
outfile->Printf( "\n\tInvalid switch case in dpd_buf_mat_irrep_rd!\n");
exit(PSI_RETURN_FAILURE);
break;
}
#ifdef DPD_TIMER
timer_off("buf4_rd_bk");
#endif
return 0;
}
}<|fim▁end|> | /* Assign the value */ |
<|file_name|>authorize-steps.js<|end_file_name|><|fim▁begin|>/**
* Created by moshensky on 6/17/15.
*/
import {inject} from 'aurelia-dependency-injection';
import {Session} from './session';
import {Logger} from './logger';
import {Locale} from './locale';
import {Config} from './config';
import {Redirect} from 'aurelia-router';
class BaseAuthorizeStep {
constructor(session, logger) {
this.session = session;
this.logger = logger;
this.locale = Locale.Repository.default;
this.loginRoute = Config.routerAuthStepOpts.loginRoute;
}
<|fim▁hole|> return next.cancel(new Redirect(this.loginRoute));
}
let canAccess = this.authorize(navigationInstruction);
if (canAccess === false) {
this.logger.error(this.locale.translate('notAuthorized'));
return next.cancel();
}
return next();
}
authorize(navigationInstruction) {
if (navigationInstruction.parentInstruction === null) {
return this.canAccess(navigationInstruction);
} else {
let canAccess = this.canAccess(navigationInstruction);
if (hasRole){
return this.authorize(navigationInstruction.parentInstruction)
} else {
return false;
}
}
}
canAccess() {
}
}
@inject(Session, Logger)
export class RolesAuthorizeStep extends BaseAuthorizeStep {
constructor(session, logger) {
super(session, logger);
}
canAccess(navigationInstruction) {
if (navigationInstruction.config.roles) {
return this.session.userHasAtLeastOneRole(navigationInstruction.config.roles);
}
return true;
}
}
@inject(Session, Logger)
export class AccessRightsAuthorizeStep extends BaseAuthorizeStep {
constructor(session, logger) {
super(session, logger);
}
canAccess(navigationInstruction) {
if (navigationInstruction.config.accessRight) {
return this.session.userHasAccessRight(navigationInstruction.config.accessRight);
}
return true;
}
}<|fim▁end|> | run(navigationInstruction, next) {
if (!this.session.isUserLoggedIn() && navigationInstruction.config.route !== this.loginRoute) {
this.logger.warn(this.locale.translate('pleaseLogin')); |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.