prompt
large_stringlengths 70
991k
| completion
large_stringlengths 0
1.02k
|
---|---|
<|file_name|>ddl_worker_test.go<|end_file_name|><|fim▁begin|>// Copyright 2015 PingCAP, 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,
// See the License for the specific language governing permissions and
// limitations under the License.
package ddl
import (
"time"
. "github.com/pingcap/check"
"github.com/pingcap/tidb/ast"
"github.com/pingcap/tidb/context"
"github.com/pingcap/tidb/kv"
"github.com/pingcap/tidb/meta"
"github.com/pingcap/tidb/model"
"github.com/pingcap/tidb/mysql"
"github.com/pingcap/tidb/terror"
"github.com/pingcap/tidb/util/testleak"
"github.com/pingcap/tidb/util/types"
goctx "golang.org/x/net/context"
)
var _ = Suite(&testDDLSuite{})
type testDDLSuite struct {
originMinBgOwnerTimeout int64
originMinDDLOwnerTimeout int64
}
const testLease = 5 * time.Millisecond
func (s *testDDLSuite) SetUpSuite(c *C) {
s.originMinDDLOwnerTimeout = minDDLOwnerTimeout
s.originMinBgOwnerTimeout = minBgOwnerTimeout
minDDLOwnerTimeout = int64(4 * testLease)
minBgOwnerTimeout = int64(4 * testLease)
}
func (s *testDDLSuite) TearDownSuite(c *C) {
minDDLOwnerTimeout = s.originMinDDLOwnerTimeout
minBgOwnerTimeout = s.originMinBgOwnerTimeout
}
func (s *testDDLSuite) TestCheckOwner(c *C) {
defer testleak.AfterTest(c)()
store := testCreateStore(c, "test_owner")
defer store.Close()
d1 := newDDL(goctx.Background(), nil, store, nil, nil, testLease)
defer d1.Stop()
time.Sleep(testLease)
testCheckOwner(c, d1, true, ddlJobFlag)
testCheckOwner(c, d1, true, bgJobFlag)
d2 := newDDL(goctx.Background(), nil, store, nil, nil, testLease)
defer d2.Stop()
// Change the DDL owner.
d1.Stop()
// Make sure owner is changed.
time.Sleep(6 * testLease)
testCheckOwner(c, d2, true, ddlJobFlag)
testCheckOwner(c, d2, true, bgJobFlag)
// Change the DDL owner.
d2.SetLease(goctx.Background(), 1*time.Second)
err := d2.Stop()
c.Assert(err, IsNil)
d1.start(goctx.Background())
testCheckOwner(c, d1, true, ddlJobFlag)
testCheckOwner(c, d1, true, bgJobFlag)
d2.SetLease(goctx.Background(), 1*time.Second)
d2.SetLease(goctx.Background(), 2*time.Second)
c.Assert(d2.GetLease(), Equals, 2*time.Second)
}
func (s *testDDLSuite) TestSchemaError(c *C) {
defer testleak.AfterTest(c)()
store := testCreateStore(c, "test_schema_error")
defer store.Close()
d := newDDL(goctx.Background(), nil, store, nil, nil, testLease)
defer d.Stop()
ctx := testNewContext(d)
doDDLJobErr(c, 1, 0, model.ActionCreateSchema, []interface{}{1}, ctx, d)
}
func (s *testDDLSuite) TestTableError(c *C) {
defer testleak.AfterTest(c)()
store := testCreateStore(c, "test_table_error")
defer store.Close()
d := newDDL(goctx.Background(), nil, store, nil, nil, testLease)
defer d.Stop()
ctx := testNewContext(d)
// Schema ID is wrong, so dropping table is failed.
doDDLJobErr(c, -1, 1, model.ActionDropTable, nil, ctx, d)
// Table ID is wrong, so dropping table is failed.
dbInfo := testSchemaInfo(c, d, "test")
testCreateSchema(c, testNewContext(d), d, dbInfo)
job := doDDLJobErr(c, dbInfo.ID, -1, model.ActionDropTable, nil, ctx, d)
// Table ID or schema ID is wrong, so getting table is failed.
tblInfo := testTableInfo(c, d, "t", 3)
testCreateTable(c, ctx, d, dbInfo, tblInfo)
err := kv.RunInNewTxn(store, false, func(txn kv.Transaction) error {
job.SchemaID = -1
job.TableID = -1
t := meta.NewMeta(txn)
_, err1 := getTableInfo(t, job, job.SchemaID)
c.Assert(err1, NotNil)
job.SchemaID = dbInfo.ID
_, err1 = getTableInfo(t, job, job.SchemaID)
c.Assert(err1, NotNil)
return nil
})
c.Assert(err, IsNil)
// Args is wrong, so creating table is failed.
doDDLJobErr(c, 1, 1, model.ActionCreateTable, []interface{}{1}, ctx, d)
// Schema ID is wrong, so creating table is failed.
doDDLJobErr(c, -1, tblInfo.ID, model.ActionCreateTable, []interface{}{tblInfo}, ctx, d)
// Table exists, so creating table is failed.
tblInfo.ID = tblInfo.ID + 1
doDDLJobErr(c, dbInfo.ID, tblInfo.ID, model.ActionCreateTable, []interface{}{tblInfo}, ctx, d)
}
func (s *testDDLSuite) TestForeignKeyError(c *C) {
defer testleak.AfterTest(c)()
store := testCreateStore(c, "test_foreign_key_error")
defer store.Close()
d := newDDL(goctx.Background(), nil, store, nil, nil, testLease)
defer d.Stop()
ctx := testNewContext(d)
doDDLJobErr(c, -1, 1, model.ActionAddForeignKey, nil, ctx, d)
doDDLJobErr(c, -1, 1, model.ActionDropForeignKey, nil, ctx, d)
dbInfo := testSchemaInfo(c, d, "test")
tblInfo := testTableInfo(c, d, "t", 3)
testCreateSchema(c, ctx, d, dbInfo)
testCreateTable(c, ctx, d, dbInfo, tblInfo)
doDDLJobErr(c, dbInfo.ID, tblInfo.ID, model.ActionDropForeignKey, []interface{}{model.NewCIStr("c1_foreign_key")}, ctx, d)
}
func (s *testDDLSuite) TestIndexError(c *C) {
defer testleak.AfterTest(c)()
store := testCreateStore(c, "test_index_error")
defer store.Close()
d := newDDL(goctx.Background(), nil, store, nil, nil, testLease)
defer d.Stop()
ctx := testNewContext(d)
<|fim▁hole|> doDDLJobErr(c, -1, 1, model.ActionDropIndex, nil, ctx, d)
dbInfo := testSchemaInfo(c, d, "test")
tblInfo := testTableInfo(c, d, "t", 3)
testCreateSchema(c, ctx, d, dbInfo)
testCreateTable(c, ctx, d, dbInfo, tblInfo)
// for adding index
doDDLJobErr(c, dbInfo.ID, tblInfo.ID, model.ActionAddIndex, []interface{}{1}, ctx, d)
doDDLJobErr(c, dbInfo.ID, tblInfo.ID, model.ActionAddIndex,
[]interface{}{false, model.NewCIStr("t"), 1,
[]*ast.IndexColName{{Column: &ast.ColumnName{Name: model.NewCIStr("c")}, Length: 256}}}, ctx, d)
doDDLJobErr(c, dbInfo.ID, tblInfo.ID, model.ActionAddIndex,
[]interface{}{false, model.NewCIStr("c1_index"), 1,
[]*ast.IndexColName{{Column: &ast.ColumnName{Name: model.NewCIStr("c")}, Length: 256}}}, ctx, d)
testCreateIndex(c, ctx, d, dbInfo, tblInfo, false, "c1_index", "c1")
doDDLJobErr(c, dbInfo.ID, tblInfo.ID, model.ActionAddIndex,
[]interface{}{false, model.NewCIStr("c1_index"), 1,
[]*ast.IndexColName{{Column: &ast.ColumnName{Name: model.NewCIStr("c1")}, Length: 256}}}, ctx, d)
// for dropping index
doDDLJobErr(c, dbInfo.ID, tblInfo.ID, model.ActionDropIndex, []interface{}{1}, ctx, d)
testDropIndex(c, ctx, d, dbInfo, tblInfo, "c1_index")
doDDLJobErr(c, dbInfo.ID, tblInfo.ID, model.ActionDropIndex, []interface{}{model.NewCIStr("c1_index")}, ctx, d)
}
func (s *testDDLSuite) TestColumnError(c *C) {
defer testleak.AfterTest(c)()
store := testCreateStore(c, "test_column_error")
defer store.Close()
d := newDDL(goctx.Background(), nil, store, nil, nil, testLease)
defer d.Stop()
ctx := testNewContext(d)
dbInfo := testSchemaInfo(c, d, "test")
tblInfo := testTableInfo(c, d, "t", 3)
testCreateSchema(c, ctx, d, dbInfo)
testCreateTable(c, ctx, d, dbInfo, tblInfo)
col := &model.ColumnInfo{
Name: model.NewCIStr("c4"),
Offset: len(tblInfo.Columns),
DefaultValue: 0,
}
col.ID = allocateColumnID(tblInfo)
col.FieldType = *types.NewFieldType(mysql.TypeLong)
pos := &ast.ColumnPosition{Tp: ast.ColumnPositionAfter, RelativeColumn: &ast.ColumnName{Name: model.NewCIStr("c5")}}
// for adding column
doDDLJobErr(c, -1, tblInfo.ID, model.ActionAddColumn, []interface{}{col, pos, 0}, ctx, d)
doDDLJobErr(c, dbInfo.ID, -1, model.ActionAddColumn, []interface{}{col, pos, 0}, ctx, d)
doDDLJobErr(c, dbInfo.ID, tblInfo.ID, model.ActionAddColumn, []interface{}{0}, ctx, d)
doDDLJobErr(c, dbInfo.ID, tblInfo.ID, model.ActionAddColumn, []interface{}{col, pos, 0}, ctx, d)
// for dropping column
doDDLJobErr(c, -1, tblInfo.ID, model.ActionDropColumn, []interface{}{col, pos, 0}, ctx, d)
doDDLJobErr(c, dbInfo.ID, -1, model.ActionDropColumn, []interface{}{col, pos, 0}, ctx, d)
doDDLJobErr(c, dbInfo.ID, tblInfo.ID, model.ActionDropColumn, []interface{}{0}, ctx, d)
doDDLJobErr(c, dbInfo.ID, tblInfo.ID, model.ActionDropColumn, []interface{}{model.NewCIStr("c5")}, ctx, d)
}
func testCheckOwner(c *C, d *ddl, isOwner bool, flag JobType) {
err := kv.RunInNewTxn(d.store, true, func(txn kv.Transaction) error {
t := meta.NewMeta(txn)
_, err := d.checkOwner(t, flag)
return err
})
if isOwner {
c.Assert(err, IsNil)
return
}
c.Assert(terror.ErrorEqual(err, errNotOwner), IsTrue)
}
func testCheckJobDone(c *C, d *ddl, job *model.Job, isAdd bool) {
kv.RunInNewTxn(d.store, false, func(txn kv.Transaction) error {
t := meta.NewMeta(txn)
historyJob, err := t.GetHistoryDDLJob(job.ID)
c.Assert(err, IsNil)
c.Assert(historyJob.State, Equals, model.JobDone)
if isAdd {
c.Assert(historyJob.SchemaState, Equals, model.StatePublic)
} else {
c.Assert(historyJob.SchemaState, Equals, model.StateNone)
}
return nil
})
}
func testCheckJobCancelled(c *C, d *ddl, job *model.Job) {
kv.RunInNewTxn(d.store, false, func(txn kv.Transaction) error {
t := meta.NewMeta(txn)
historyJob, err := t.GetHistoryDDLJob(job.ID)
c.Assert(err, IsNil)
c.Assert(historyJob.State, Equals, model.JobCancelled)
return nil
})
}
func doDDLJobErr(c *C, schemaID, tableID int64, tp model.ActionType, args []interface{},
ctx context.Context, d *ddl) *model.Job {
job := &model.Job{
SchemaID: schemaID,
TableID: tableID,
Type: tp,
Args: args,
}
err := d.doDDLJob(ctx, job)
c.Assert(err, NotNil)
testCheckJobCancelled(c, d, job)
return job
}<|fim▁end|>
|
// Schema ID is wrong.
doDDLJobErr(c, -1, 1, model.ActionAddIndex, nil, ctx, d)
|
<|file_name|>pMidiToFrequency.cpp<|end_file_name|><|fim▁begin|>#include "pMidiToFrequency.h"
#include "../pObjectList.hpp"
#include "../../dsp/math.hpp"
using namespace YSE::PATCHER;
#define className pMidiToFrequency
CONSTRUCT() {
midiValue = 0.f;
ADD_IN_0;
REG_FLOAT_IN(SetMidi);
REG_INT_IN(SetMidiInt);
ADD_OUT_FLOAT;
}
FLOAT_IN(SetMidi) {
midiValue = value;<|fim▁hole|>
INT_IN(SetMidiInt) {
midiValue = (float)value;
}
CALC() {
outputs[0].SendFloat(YSE::DSP::MidiToFreq(midiValue), thread);
}<|fim▁end|>
|
}
|
<|file_name|>cg.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 https://mozilla.org/MPL/2.0/. */
use darling::{FromDeriveInput, FromField, FromVariant};
use proc_macro2::{Span, TokenStream};
use quote::TokenStreamExt;
use syn::{self, AngleBracketedGenericArguments, Binding, DeriveInput, Field};
use syn::{GenericArgument, GenericParam, Ident, Path};
use syn::{PathArguments, PathSegment, QSelf, Type, TypeArray};
use syn::{TypeParam, TypeParen, TypePath, TypeSlice, TypeTuple};
use syn::{Variant, WherePredicate};
use synstructure::{self, BindStyle, BindingInfo, VariantAst, VariantInfo};
/// Given an input type which has some where clauses already, like:
///
/// struct InputType<T>
/// where
/// T: Zero,
/// {
/// ...
/// }
///
/// Add the necessary `where` clauses so that the output type of a trait
/// fulfils them.
///
/// For example:
///
/// <T as ToComputedValue>::ComputedValue: Zero,
///
/// This needs to run before adding other bounds to the type parameters.
pub fn propagate_clauses_to_output_type(
where_clause: &mut Option<syn::WhereClause>,
generics: &syn::Generics,
trait_path: Path,
trait_output: Ident,
) {
let where_clause = match *where_clause {
Some(ref mut clause) => clause,
None => return,
};
let mut extra_bounds = vec![];
for pred in &where_clause.predicates {
let ty = match *pred {
syn::WherePredicate::Type(ref ty) => ty,
ref predicate => panic!("Unhanded complex where predicate: {:?}", predicate),
};
let path = match ty.bounded_ty {
syn::Type::Path(ref p) => &p.path,
ref ty => panic!("Unhanded complex where type: {:?}", ty),
};
assert!(
ty.lifetimes.is_none(),
"Unhanded complex lifetime bound: {:?}",
ty,
);
let ident = match path_to_ident(path) {
Some(i) => i,
None => panic!("Unhanded complex where type path: {:?}", path),
};
if generics.type_params().any(|param| param.ident == *ident) {
extra_bounds.push(ty.clone());
}
}
for bound in extra_bounds {
let ty = bound.bounded_ty;
let bounds = bound.bounds;
where_clause
.predicates
.push(parse_quote!(<#ty as #trait_path>::#trait_output: #bounds))
}
}
pub fn add_predicate(where_clause: &mut Option<syn::WhereClause>, pred: WherePredicate) {
where_clause
.get_or_insert(parse_quote!(where))
.predicates
.push(pred);
}
pub fn fmap_match<F>(input: &DeriveInput, bind_style: BindStyle, mut f: F) -> TokenStream
where
F: FnMut(BindingInfo) -> TokenStream,
{
let mut s = synstructure::Structure::new(input);
s.variants_mut().iter_mut().for_each(|v| {
v.bind_with(|_| bind_style);
});
s.each_variant(|variant| {
let (mapped, mapped_fields) = value(variant, "mapped");
let fields_pairs = variant.bindings().iter().zip(mapped_fields);
let mut computations = quote!();
computations.append_all(fields_pairs.map(|(field, mapped_field)| {
let expr = f(field.clone());
quote! { let #mapped_field = #expr; }
}));
computations.append_all(mapped);
Some(computations)
})
}
pub fn fmap_trait_output(input: &DeriveInput, trait_path: &Path, trait_output: Ident) -> Path {
let segment = PathSegment {
ident: input.ident.clone(),
arguments: PathArguments::AngleBracketed(AngleBracketedGenericArguments {
args: input
.generics
.params
.iter()
.map(|arg| match arg {
&GenericParam::Lifetime(ref data) => {
GenericArgument::Lifetime(data.lifetime.clone())
},
&GenericParam::Type(ref data) => {
let ident = &data.ident;
GenericArgument::Type(parse_quote!(<#ident as #trait_path>::#trait_output))
},
ref arg => panic!("arguments {:?} cannot be mapped yet", arg),
})
.collect(),
colon2_token: Default::default(),
gt_token: Default::default(),
lt_token: Default::default(),
}),
};
segment.into()
}
pub fn map_type_params<F>(ty: &Type, params: &[&TypeParam], f: &mut F) -> Type
where
F: FnMut(&Ident) -> Type,
{
match *ty {
Type::Slice(ref inner) => Type::from(TypeSlice {
elem: Box::new(map_type_params(&inner.elem, params, f)),
..inner.clone()
}),
Type::Array(ref inner) => {
//ref ty, ref expr) => {
Type::from(TypeArray {
elem: Box::new(map_type_params(&inner.elem, params, f)),
..inner.clone()
})
},
ref ty @ Type::Never(_) => ty.clone(),
Type::Tuple(ref inner) => Type::from(TypeTuple {
elems: inner
.elems
.iter()
.map(|ty| map_type_params(&ty, params, f))
.collect(),
..inner.clone()
}),
Type::Path(TypePath {
qself: None,
ref path,
}) => {
if let Some(ident) = path_to_ident(path) {
if params.iter().any(|ref param| ¶m.ident == ident) {
return f(ident);
}
}
Type::from(TypePath {
qself: None,
path: map_type_params_in_path(path, params, f),
})
},
Type::Path(TypePath {
ref qself,
ref path,
}) => Type::from(TypePath {
qself: qself.as_ref().map(|qself| QSelf {
ty: Box::new(map_type_params(&qself.ty, params, f)),
position: qself.position,
..qself.clone()
}),
path: map_type_params_in_path(path, params, f),
}),
Type::Paren(ref inner) => Type::from(TypeParen {
elem: Box::new(map_type_params(&inner.elem, params, f)),
..inner.clone()
}),
ref ty => panic!("type {:?} cannot be mapped yet", ty),
}
}
fn map_type_params_in_path<F>(path: &Path, params: &[&TypeParam], f: &mut F) -> Path
where
F: FnMut(&Ident) -> Type,
{
Path {
leading_colon: path.leading_colon,
segments: path
.segments
.iter()
.map(|segment| PathSegment {
ident: segment.ident.clone(),
arguments: match segment.arguments {
PathArguments::AngleBracketed(ref data) => {
PathArguments::AngleBracketed(AngleBracketedGenericArguments {
args: data
.args
.iter()
.map(|arg| match arg {
ty @ &GenericArgument::Lifetime(_) => ty.clone(),
&GenericArgument::Type(ref data) => {
GenericArgument::Type(map_type_params(data, params, f))
},
&GenericArgument::Binding(ref data) => {
GenericArgument::Binding(Binding {
ty: map_type_params(&data.ty, params, f),
..data.clone()
})
},
ref arg => panic!("arguments {:?} cannot be mapped yet", arg),
})
.collect(),
..data.clone()
})
},
ref arg @ PathArguments::None => arg.clone(),
ref parameters => panic!("parameters {:?} cannot be mapped yet", parameters),
},
})
.collect(),
}
}
fn path_to_ident(path: &Path) -> Option<&Ident> {
match *path {
Path {
leading_colon: None,
ref segments,
} if segments.len() == 1 => {
if segments[0].arguments.is_empty() {
Some(&segments[0].ident)
} else {
None
}
},
_ => None,
}
}
pub fn parse_field_attrs<A>(field: &Field) -> A
where
A: FromField,
{
match A::from_field(field) {
Ok(attrs) => attrs,
Err(e) => panic!("failed to parse field attributes: {}", e),
}
}
pub fn parse_input_attrs<A>(input: &DeriveInput) -> A
where
A: FromDeriveInput,
{
match A::from_derive_input(input) {
Ok(attrs) => attrs,
Err(e) => panic!("failed to parse input attributes: {}", e),
}
}
pub fn parse_variant_attrs_from_ast<A>(variant: &VariantAst) -> A
where
A: FromVariant,
{
let v = Variant {
ident: variant.ident.clone(),
attrs: variant.attrs.to_vec(),
fields: variant.fields.clone(),
discriminant: variant.discriminant.clone(),
};
parse_variant_attrs(&v)
}
pub fn parse_variant_attrs<A>(variant: &Variant) -> A
where
A: FromVariant,
{
match A::from_variant(variant) {
Ok(attrs) => attrs,
Err(e) => panic!("failed to parse variant attributes: {}", e),
}
}
pub fn ref_pattern<'a>(
variant: &'a VariantInfo,
prefix: &str,
) -> (TokenStream, Vec<BindingInfo<'a>>) {
let mut v = variant.clone();
v.bind_with(|_| BindStyle::Ref);
v.bindings_mut().iter_mut().for_each(|b| {
b.binding = Ident::new(&format!("{}_{}", b.binding, prefix), Span::call_site())
});
(v.pat(), v.bindings().to_vec())
}
pub fn value<'a>(variant: &'a VariantInfo, prefix: &str) -> (TokenStream, Vec<BindingInfo<'a>>) {
let mut v = variant.clone();
v.bindings_mut().iter_mut().for_each(|b| {
b.binding = Ident::new(&format!("{}_{}", b.binding, prefix), Span::call_site())
});
v.bind_with(|_| BindStyle::Move);
(v.pat(), v.bindings().to_vec())
}
/// Transforms "FooBar" to "foo-bar".
///
/// If the first Camel segment is "Moz", "Webkit", or "Servo", the result string
/// is prepended with "-".
pub fn to_css_identifier(mut camel_case: &str) -> String {
camel_case = camel_case.trim_end_matches('_');
let mut first = true;
let mut result = String::with_capacity(camel_case.len());
while let Some(segment) = split_camel_segment(&mut camel_case) {
if first {
match segment {
"Moz" | "Webkit" | "Servo" => first = false,
_ => {},
}
}
if !first {
result.push_str("-");
}
first = false;
result.push_str(&segment.to_lowercase());
}
result
}
/// Given "FooBar", returns "Foo" and sets `camel_case` to "Bar".
fn split_camel_segment<'input>(camel_case: &mut &'input str) -> Option<&'input str> {
let index = match camel_case.chars().next() {
None => return None,
Some(ch) => ch.len_utf8(),
};
let end_position = camel_case[index..]
.find(char::is_uppercase)
.map_or(camel_case.len(), |pos| index + pos);
let result = &camel_case[..end_position];<|fim▁hole|>}<|fim▁end|>
|
*camel_case = &camel_case[end_position..];
Some(result)
|
<|file_name|>route_bsd.go<|end_file_name|><|fim▁begin|>// Copyright 2011 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// +build darwin dragonfly freebsd netbsd openbsd rumprun
package syscall
import (
"runtime"
"unsafe"
)
var (
freebsdConfArch string // "machine $arch" line in kern.conftxt on freebsd
minRoutingSockaddrLen = rsaAlignOf(0)
)
// Round the length of a raw sockaddr up to align it properly.
func rsaAlignOf(salen int) int {
salign := sizeofPtr
if darwin64Bit {
// Darwin kernels require 32-bit aligned access to
// routing facilities.
salign = 4
} else if netbsd32Bit {
// NetBSD 6 and beyond kernels require 64-bit aligned
// access to routing facilities.
salign = 8
} else if runtime.GOOS == "freebsd" {
// In the case of kern.supported_archs="amd64 i386",
// we need to know the underlying kernel's
// architecture because the alignment for routing
// facilities are set at the build time of the kernel.
if freebsdConfArch == "amd64" {
salign = 8
}
}
if salen == 0 {
return salign
}
return (salen + salign - 1) & ^(salign - 1)
}
// parseSockaddrLink parses b as a datalink socket address.
func parseSockaddrLink(b []byte) (*SockaddrDatalink, error) {
if len(b) < 8 {
return nil, EINVAL
}
sa, _, err := parseLinkLayerAddr(b[4:])
if err != nil {
return nil, err
}
rsa := (*RawSockaddrDatalink)(unsafe.Pointer(&b[0]))
sa.Len = rsa.Len
sa.Family = rsa.Family
sa.Index = rsa.Index
return sa, nil
}
// parseLinkLayerAddr parses b as a datalink socket address in
// conventional BSD kernel form.
func parseLinkLayerAddr(b []byte) (*SockaddrDatalink, int, error) {
// The encoding looks like the following:
// +----------------------------+
// | Type (1 octet) |
// +----------------------------+
// | Name length (1 octet) |
// +----------------------------+
// | Address length (1 octet) |
// +----------------------------+
// | Selector length (1 octet) |
// +----------------------------+
// | Data (variable) |
// +----------------------------+
type linkLayerAddr struct {
Type byte
Nlen byte
Alen byte
Slen byte
}
lla := (*linkLayerAddr)(unsafe.Pointer(&b[0]))
l := 4 + int(lla.Nlen) + int(lla.Alen) + int(lla.Slen)
if len(b) < l {
return nil, 0, EINVAL
}
b = b[4:]
sa := &SockaddrDatalink{Type: lla.Type, Nlen: lla.Nlen, Alen: lla.Alen, Slen: lla.Slen}
for i := 0; len(sa.Data) > i && i < l-4; i++ {
sa.Data[i] = int8(b[i])
}
return sa, rsaAlignOf(l), nil
}
// parseSockaddrInet parses b as an internet socket address.
func parseSockaddrInet(b []byte, family byte) (Sockaddr, error) {
switch family {
case AF_INET:
if len(b) < SizeofSockaddrInet4 {
return nil, EINVAL
}
rsa := (*RawSockaddrAny)(unsafe.Pointer(&b[0]))
return anyToSockaddr(rsa)
case AF_INET6:
if len(b) < SizeofSockaddrInet6 {
return nil, EINVAL
}
rsa := (*RawSockaddrAny)(unsafe.Pointer(&b[0]))
return anyToSockaddr(rsa)
default:
return nil, EINVAL
}
}
const (
offsetofInet4 = int(unsafe.Offsetof(RawSockaddrInet4{}.Addr))
offsetofInet6 = int(unsafe.Offsetof(RawSockaddrInet6{}.Addr))
)
// parseNetworkLayerAddr parses b as an internet socket address in
// conventional BSD kernel form.
func parseNetworkLayerAddr(b []byte, family byte) (Sockaddr, error) {
// The encoding looks similar to the NLRI encoding.
// +----------------------------+
// | Length (1 octet) |
// +----------------------------+
// | Address prefix (variable) |
// +----------------------------+
//
// The differences between the kernel form and the NLRI
// encoding are:
//
// - The length field of the kernel form indicates the prefix
// length in bytes, not in bits
//
// - In the kernel form, zero value of the length field
// doesn't mean 0.0.0.0/0 or ::/0
//
// - The kernel form appends leading bytes to the prefix field
// to make the <length, prefix> tuple to be conformed with
// the routing message boundary
l := int(rsaAlignOf(int(b[0])))
if len(b) < l {
return nil, EINVAL
}
// Don't reorder case expressions.
// The case expressions for IPv6 must come first.
switch {
case b[0] == SizeofSockaddrInet6:
sa := &SockaddrInet6{}
copy(sa.Addr[:], b[offsetofInet6:])
return sa, nil
case family == AF_INET6:
sa := &SockaddrInet6{}
if l-1 < offsetofInet6 {
copy(sa.Addr[:], b[1:l])
} else {
copy(sa.Addr[:], b[l-offsetofInet6:l])
}
return sa, nil
case b[0] == SizeofSockaddrInet4:
sa := &SockaddrInet4{}
copy(sa.Addr[:], b[offsetofInet4:])
return sa, nil
default: // an old fashion, AF_UNSPEC or unknown means AF_INET
sa := &SockaddrInet4{}
if l-1 < offsetofInet4 {
copy(sa.Addr[:], b[1:l])
} else {
copy(sa.Addr[:], b[l-offsetofInet4:l])
}
return sa, nil
}
}
// RouteRIB returns routing information base, as known as RIB,
// which consists of network facility information, states and
// parameters.
//
// Deprecated: Use golang.org/x/net/route instead.
func RouteRIB(facility, param int) ([]byte, error) {
mib := []_C_int{CTL_NET, AF_ROUTE, 0, 0, _C_int(facility), _C_int(param)}
// Find size.
n := uintptr(0)
if err := sysctl(mib, nil, &n, nil, 0); err != nil {
return nil, err
}
if n == 0 {
return nil, nil
}
tab := make([]byte, n)
if err := sysctl(mib, &tab[0], &n, nil, 0); err != nil {
return nil, err
}
return tab[:n], nil
}
// RoutingMessage represents a routing message.
//
// Deprecated: Use golang.org/x/net/route instead.
type RoutingMessage interface {
sockaddr() ([]Sockaddr, error)
}
const anyMessageLen = int(unsafe.Sizeof(anyMessage{}))
type anyMessage struct {
Msglen uint16
Version uint8
Type uint8
}
// RouteMessage represents a routing message containing routing
// entries.
//
// Deprecated: Use golang.org/x/net/route instead.
type RouteMessage struct {
Header RtMsghdr
Data []byte
}
func (m *RouteMessage) sockaddr() ([]Sockaddr, error) {
var sas [RTAX_MAX]Sockaddr
b := m.Data[:]
family := uint8(AF_UNSPEC)
for i := uint(0); i < RTAX_MAX && len(b) >= minRoutingSockaddrLen; i++ {
if m.Header.Addrs&(1<<i) == 0 {
continue
}
rsa := (*RawSockaddr)(unsafe.Pointer(&b[0]))
switch rsa.Family {
case AF_LINK:
sa, err := parseSockaddrLink(b)
if err != nil {
return nil, err
}
sas[i] = sa
b = b[rsaAlignOf(int(rsa.Len)):]
case AF_INET, AF_INET6:
sa, err := parseSockaddrInet(b, rsa.Family)
if err != nil {
return nil, err
}
sas[i] = sa
b = b[rsaAlignOf(int(rsa.Len)):]
family = rsa.Family
default:
sa, err := parseNetworkLayerAddr(b, family)
if err != nil {
return nil, err
}
sas[i] = sa
b = b[rsaAlignOf(int(b[0])):]
}
}
return sas[:], nil
}
// InterfaceMessage represents a routing message containing
// network interface entries.
//
// Deprecated: Use golang.org/x/net/route instead.
type InterfaceMessage struct {
Header IfMsghdr
Data []byte
}
func (m *InterfaceMessage) sockaddr() ([]Sockaddr, error) {
var sas [RTAX_MAX]Sockaddr
if m.Header.Addrs&RTA_IFP == 0 {
return nil, nil
}
sa, err := parseSockaddrLink(m.Data[:])
if err != nil {
return nil, err
}
sas[RTAX_IFP] = sa
return sas[:], nil
}
// InterfaceAddrMessage represents a routing message containing
// network interface address entries.
//
// Deprecated: Use golang.org/x/net/route instead.
type InterfaceAddrMessage struct {
Header IfaMsghdr
Data []byte
}
func (m *InterfaceAddrMessage) sockaddr() ([]Sockaddr, error) {
var sas [RTAX_MAX]Sockaddr
b := m.Data[:]
family := uint8(AF_UNSPEC)
for i := uint(0); i < RTAX_MAX && len(b) >= minRoutingSockaddrLen; i++ {
if m.Header.Addrs&(1<<i) == 0 {
continue
}
rsa := (*RawSockaddr)(unsafe.Pointer(&b[0]))
switch rsa.Family {
case AF_LINK:
sa, err := parseSockaddrLink(b)
if err != nil {
return nil, err
}
sas[i] = sa
b = b[rsaAlignOf(int(rsa.Len)):]
case AF_INET, AF_INET6:
sa, err := parseSockaddrInet(b, rsa.Family)
if err != nil {
return nil, err
}
sas[i] = sa
b = b[rsaAlignOf(int(rsa.Len)):]
family = rsa.Family
default:
sa, err := parseNetworkLayerAddr(b, family)
if err != nil {
return nil, err
}
sas[i] = sa
b = b[rsaAlignOf(int(b[0])):]
}
}
return sas[:], nil
}
// ParseRoutingMessage parses b as routing messages and returns the
// slice containing the RoutingMessage interfaces.
//
// Deprecated: Use golang.org/x/net/route instead.
func ParseRoutingMessage(b []byte) (msgs []RoutingMessage, err error) {
nmsgs, nskips := 0, 0
for len(b) >= anyMessageLen {
nmsgs++
any := (*anyMessage)(unsafe.Pointer(&b[0]))
if any.Version != RTM_VERSION {<|fim▁hole|> if m := any.toRoutingMessage(b); m == nil {
nskips++
} else {
msgs = append(msgs, m)
}
b = b[any.Msglen:]
}
// We failed to parse any of the messages - version mismatch?
if nmsgs != len(msgs)+nskips {
return nil, EINVAL
}
return msgs, nil
}
// ParseRoutingSockaddr parses msg's payload as raw sockaddrs and
// returns the slice containing the Sockaddr interfaces.
//
// Deprecated: Use golang.org/x/net/route instead.
func ParseRoutingSockaddr(msg RoutingMessage) ([]Sockaddr, error) {
sas, err := msg.sockaddr()
if err != nil {
return nil, err
}
return sas, nil
}<|fim▁end|>
|
b = b[any.Msglen:]
continue
}
|
<|file_name|>base.py<|end_file_name|><|fim▁begin|>"""
Project main settings file. These settings are common to the project
if you need to override something do it in local.pt
"""
from sys import path
# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
import os
# PATHS
# Path containing the django project
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
path.append(BASE_DIR)
# Path of the top level directory.
# This directory contains the django project, apps, libs, etc...
PROJECT_ROOT = os.path.dirname(BASE_DIR)
# Add apps and libs to the PROJECT_ROOT
path.append(os.path.join(PROJECT_ROOT, "apps"))
path.append(os.path.join(PROJECT_ROOT, "libs"))
# SITE SETTINGS
# https://docs.djangoproject.com/en/1.10/ref/settings/#site-id
SITE_ID = 1
# https://docs.djangoproject.com/en/1.10/ref/settings/#allowed-hosts
ALLOWED_HOSTS = []
# https://docs.djangoproject.com/en/1.10/ref/settings/#installed-apps
INSTALLED_APPS = [
# Django apps
'django.contrib.admin',
'django.contrib.admindocs',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.sites',
'django.contrib.messages',
'django.contrib.humanize',
'django.contrib.sitemaps',
'django.contrib.syndication',
'django.contrib.staticfiles',
# Third party apps
'compressor',
# Local apps
'base',
]
# https://docs.djangoproject.com/en/1.10/topics/auth/passwords/#using-argon2-with-django
PASSWORD_HASHERS = (
'django.contrib.auth.hashers.Argon2PasswordHasher',
'django.contrib.auth.hashers.BCryptSHA256PasswordHasher',
'django.contrib.auth.hashers.BCryptPasswordHasher',
'django.contrib.auth.hashers.PBKDF2PasswordHasher',
'django.contrib.auth.hashers.PBKDF2SHA1PasswordHasher',
'django.contrib.auth.hashers.SHA1PasswordHasher',
'django.contrib.auth.hashers.MD5PasswordHasher',
'django.contrib.auth.hashers.CryptPasswordHasher',
)
# DEBUG SETTINGS
# https://docs.djangoproject.com/en/1.10/ref/settings/#debug
DEBUG = False
# https://docs.djangoproject.com/en/1.10/ref/settings/#internal-ips
INTERNAL_IPS = ('127.0.0.1')
# LOCALE SETTINGS
# Local time zone for this installation.
# https://docs.djangoproject.com/en/1.10/ref/settings/#time-zone
TIME_ZONE = 'America/Los_Angeles'
# https://docs.djangoproject.com/en/1.10/ref/settings/#language-code
LANGUAGE_CODE = 'en-us'
# https://docs.djangoproject.com/en/1.10/ref/settings/#use-i18n
USE_I18N = True
# https://docs.djangoproject.com/en/1.10/ref/settings/#use-l10n
USE_L10N = True
# https://docs.djangoproject.com/en/1.10/ref/settings/#use-tz
USE_TZ = True
# MEDIA AND STATIC SETTINGS
# Absolute filesystem path to the directory that will hold user-uploaded files.
# https://docs.djangoproject.com/en/1.10/ref/settings/#media-root
MEDIA_ROOT = os.path.join(PROJECT_ROOT, 'public/media')
# URL that handles the media served from MEDIA_ROOT. Use a trailing slash.
# https://docs.djangoproject.com/en/1.10/ref/settings/#media-url<|fim▁hole|>MEDIA_URL = '/media/'
# Absolute path to the directory static files should be collected to.
# Don't put anything in this directory yourself; store your static files
# in apps' "static/" subdirectories and in STATICFILES_DIRS.
# https://docs.djangoproject.com/en/1.10/ref/settings/#static-root
STATIC_ROOT = os.path.join(PROJECT_ROOT, 'public/static')
# URL prefix for static files.
# https://docs.djangoproject.com/en/1.10/ref/settings/#static-url
STATIC_URL = '/static/'
# Additional locations of static files
# https://docs.djangoproject.com/en/1.10/ref/settings/#staticfiles-dirs
STATICFILES_DIRS = (
os.path.join(BASE_DIR, 'static'),
)
# https://docs.djangoproject.com/en/1.10/ref/contrib/staticfiles/#staticfiles-finders
STATICFILES_FINDERS = (
'django.contrib.staticfiles.finders.FileSystemFinder',
'django.contrib.staticfiles.finders.AppDirectoriesFinder',
)
# TEMPLATE SETTINGS
# https://docs.djangoproject.com/en/1.10/ref/settings/#templates
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [os.path.join(BASE_DIR, 'templates')],
'APP_DIRS': True,
'OPTIONS': {
'context_processors': [
'django.contrib.auth.context_processors.auth',
'django.template.context_processors.debug',
'django.template.context_processors.request',
'django.contrib.auth.context_processors.auth',
'django.contrib.messages.context_processors.messages'
],
},
},
]
# URL SETTINGS
# https://docs.djangoproject.com/en/1.10/ref/settings/#root-urlconf.
ROOT_URLCONF = 'shaping_templeat.urls'
# MIDDLEWARE SETTINGS
# See: https://docs.djangoproject.com/en/1.10/ref/settings/#middleware-classes
MIDDLEWARE_CLASSES = [
'django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
]
# LOGGING
# https://docs.djangoproject.com/en/1.10/topics/logging/
LOGGING = {
'version': 1,
'loggers': {
'shaping_templeat': {
'level': "DEBUG"
}
}
}<|fim▁end|>
| |
<|file_name|>urls.py<|end_file_name|><|fim▁begin|>"""URL routes for the sample app."""
from django.conf.urls import include, url
from django.views.generic import TemplateView<|fim▁hole|>
router = DefaultRouter()
router.register(r'users', UserViewSet)
router.register(r'questions', QuestionViewSet)
router.register(r'choices', ChoiceViewSet)
urlpatterns = [
url(r'^$', TemplateView.as_view(
template_name='sample_poll_app/home.html'), name='home'),
url(r'^api-auth/', include(
'rest_framework.urls', namespace='rest_framework')),
url(r'^api/', include(router.urls))
]<|fim▁end|>
|
from rest_framework.routers import DefaultRouter
from .viewsets import ChoiceViewSet, QuestionViewSet, UserViewSet
|
<|file_name|>http_test.go<|end_file_name|><|fim▁begin|>package agent
import (
"bytes"
"encoding/json"
"fmt"
"io"
"io/ioutil"
"net/http"
"net/http/httptest"
"os"
"path/filepath"
"strconv"
"testing"
"time"
"github.com/hashicorp/consul/consul/structs"
"github.com/hashicorp/consul/testutil"
)
func makeHTTPServer(t *testing.T) (string, *HTTPServer) {
conf := nextConfig()
dir, agent := makeAgent(t, conf)
uiDir := filepath.Join(dir, "ui")
if err := os.Mkdir(uiDir, 755); err != nil {
t.Fatalf("err: %v", err)
}
addr, _ := agent.config.ClientListener("", agent.config.Ports.HTTP)
server, err := NewHTTPServer(agent, uiDir, true, agent.logOutput, addr.String())
if err != nil {
t.Fatalf("err: %v", err)
}
return dir, server
}
func encodeReq(obj interface{}) io.ReadCloser {
buf := bytes.NewBuffer(nil)
enc := json.NewEncoder(buf)
enc.Encode(obj)
return ioutil.NopCloser(buf)
}
func TestSetIndex(t *testing.T) {
resp := httptest.NewRecorder()
setIndex(resp, 1000)
header := resp.Header().Get("X-Consul-Index")
if header != "1000" {
t.Fatalf("Bad: %v", header)
}
}
func TestSetKnownLeader(t *testing.T) {
resp := httptest.NewRecorder()
setKnownLeader(resp, true)
header := resp.Header().Get("X-Consul-KnownLeader")
if header != "true" {
t.Fatalf("Bad: %v", header)
}
resp = httptest.NewRecorder()
setKnownLeader(resp, false)
header = resp.Header().Get("X-Consul-KnownLeader")
if header != "false" {
t.Fatalf("Bad: %v", header)
}
}
func TestSetLastContact(t *testing.T) {
resp := httptest.NewRecorder()
setLastContact(resp, 123456*time.Microsecond)
header := resp.Header().Get("X-Consul-LastContact")
if header != "123" {
t.Fatalf("Bad: %v", header)
}
}
func TestSetMeta(t *testing.T) {
meta := structs.QueryMeta{
Index: 1000,
KnownLeader: true,
LastContact: 123456 * time.Microsecond,
}
resp := httptest.NewRecorder()
setMeta(resp, &meta)
header := resp.Header().Get("X-Consul-Index")
if header != "1000" {
t.Fatalf("Bad: %v", header)
}
header = resp.Header().Get("X-Consul-KnownLeader")
if header != "true" {
t.Fatalf("Bad: %v", header)
}
header = resp.Header().Get("X-Consul-LastContact")
if header != "123" {
t.Fatalf("Bad: %v", header)
}
}
func TestContentTypeIsJSON(t *testing.T) {
dir, srv := makeHTTPServer(t)
defer os.RemoveAll(dir)
defer srv.Shutdown()
defer srv.agent.Shutdown()
resp := httptest.NewRecorder()
handler := func(resp http.ResponseWriter, req *http.Request) (interface{}, error) {
// stub out a DirEntry so that it will be encoded as JSON
return &structs.DirEntry{Key: "key"}, nil
}
req, _ := http.NewRequest("GET", "/v1/kv/key", nil)
srv.wrap(handler)(resp, req)
contentType := resp.Header().Get("Content-Type")
if contentType != "application/json" {
t.Fatalf("Content-Type header was not 'application/json'")
}
}
func TestParseWait(t *testing.T) {
resp := httptest.NewRecorder()
var b structs.QueryOptions
req, err := http.NewRequest("GET",
"/v1/catalog/nodes?wait=60s&index=1000", nil)
if err != nil {
t.Fatalf("err: %v", err)
}
if d := parseWait(resp, req, &b); d {
t.Fatalf("unexpected done")
}
if b.MinQueryIndex != 1000 {
t.Fatalf("Bad: %v", b)
}
if b.MaxQueryTime != 60*time.Second {
t.Fatalf("Bad: %v", b)
}
}
func TestParseWait_InvalidTime(t *testing.T) {
resp := httptest.NewRecorder()<|fim▁hole|> var b structs.QueryOptions
req, err := http.NewRequest("GET",
"/v1/catalog/nodes?wait=60foo&index=1000", nil)
if err != nil {
t.Fatalf("err: %v", err)
}
if d := parseWait(resp, req, &b); !d {
t.Fatalf("expected done")
}
if resp.Code != 400 {
t.Fatalf("bad code: %v", resp.Code)
}
}
func TestParseWait_InvalidIndex(t *testing.T) {
resp := httptest.NewRecorder()
var b structs.QueryOptions
req, err := http.NewRequest("GET",
"/v1/catalog/nodes?wait=60s&index=foo", nil)
if err != nil {
t.Fatalf("err: %v", err)
}
if d := parseWait(resp, req, &b); !d {
t.Fatalf("expected done")
}
if resp.Code != 400 {
t.Fatalf("bad code: %v", resp.Code)
}
}
func TestParseConsistency(t *testing.T) {
resp := httptest.NewRecorder()
var b structs.QueryOptions
req, err := http.NewRequest("GET",
"/v1/catalog/nodes?stale", nil)
if err != nil {
t.Fatalf("err: %v", err)
}
if d := parseConsistency(resp, req, &b); d {
t.Fatalf("unexpected done")
}
if !b.AllowStale {
t.Fatalf("Bad: %v", b)
}
if b.RequireConsistent {
t.Fatalf("Bad: %v", b)
}
b = structs.QueryOptions{}
req, err = http.NewRequest("GET",
"/v1/catalog/nodes?consistent", nil)
if err != nil {
t.Fatalf("err: %v", err)
}
if d := parseConsistency(resp, req, &b); d {
t.Fatalf("unexpected done")
}
if b.AllowStale {
t.Fatalf("Bad: %v", b)
}
if !b.RequireConsistent {
t.Fatalf("Bad: %v", b)
}
}
func TestParseConsistency_Invalid(t *testing.T) {
resp := httptest.NewRecorder()
var b structs.QueryOptions
req, err := http.NewRequest("GET",
"/v1/catalog/nodes?stale&consistent", nil)
if err != nil {
t.Fatalf("err: %v", err)
}
if d := parseConsistency(resp, req, &b); !d {
t.Fatalf("expected done")
}
if resp.Code != 400 {
t.Fatalf("bad code: %v", resp.Code)
}
}
// assertIndex tests that X-Consul-Index is set and non-zero
func assertIndex(t *testing.T, resp *httptest.ResponseRecorder) {
header := resp.Header().Get("X-Consul-Index")
if header == "" || header == "0" {
t.Fatalf("Bad: %v", header)
}
}
// checkIndex is like assertIndex but returns an error
func checkIndex(resp *httptest.ResponseRecorder) error {
header := resp.Header().Get("X-Consul-Index")
if header == "" || header == "0" {
return fmt.Errorf("Bad: %v", header)
}
return nil
}
// getIndex parses X-Consul-Index
func getIndex(t *testing.T, resp *httptest.ResponseRecorder) uint64 {
header := resp.Header().Get("X-Consul-Index")
if header == "" {
t.Fatalf("Bad: %v", header)
}
val, err := strconv.Atoi(header)
if err != nil {
t.Fatalf("Bad: %v", header)
}
return uint64(val)
}
func httpTest(t *testing.T, f func(srv *HTTPServer)) {
dir, srv := makeHTTPServer(t)
defer os.RemoveAll(dir)
defer srv.Shutdown()
defer srv.agent.Shutdown()
testutil.WaitForLeader(t, srv.agent.RPC, "dc1")
f(srv)
}<|fim▁end|>
| |
<|file_name|>issue-3021.rs<|end_file_name|><|fim▁begin|>trait SipHash {
fn reset(&self);
}
fn siphash(k0 : u64) {
struct SipState {
v0: u64,
}
impl SipHash for SipState {
fn reset(&self) {
self.v0 = k0 ^ 0x736f6d6570736575; //~ ERROR can't capture dynamic environment
}
}<|fim▁hole|>}
fn main() {}<|fim▁end|>
|
panic!();
|
<|file_name|>disasm_demangler.py<|end_file_name|><|fim▁begin|># Copyright 2016 MongoDB 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<|fim▁hole|>
# 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.
try:
from demangler import demangle
except:
from cppfilt import demangle<|fim▁end|>
|
# http://www.apache.org/licenses/LICENSE-2.0
|
<|file_name|>event.js<|end_file_name|><|fim▁begin|>'use strict';
var mongoose = require('mongoose'),
Schema = mongoose.Schema;
var Event = new Schema({
name: String,
description: String,
sport: String,
place: {
name: String,
coords: {
longitude: { type: Number },
latitude: { type: Number }
},
address: {type: String, default: '', unique: true, trim: true},
landmarks: [{type: String, default: '', trim: true}],
city : {type: String, default: '', trim: true},
},
when: Date,
organizer: {type: Schema.ObjectId, ref: 'User'},
players: {
'yes': [{type: Schema.ObjectId, ref: 'User'}],
'no': [{type: Schema.ObjectId, ref: 'User'}],
'maybe': [{type: Schema.ObjectId, ref: 'User'}],
'none': [{type: Schema.ObjectId, ref: 'User'}]
},
subscribers: [{type: Schema.ObjectId, ref: 'User'}],
score: String,
comments: [{<|fim▁hole|> }],
created_at: {type: Date, default: Date.now},
modified_at: {type: Date, default: Date.now}
});
module.exports = mongoose.model('Event', Event);<|fim▁end|>
|
comment: String,
commented_on: Date,
by: {type: Schema.ObjectId, ref: 'User'}
|
<|file_name|>models.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*-
from django.conf import settings
from django.contrib.auth.models import User
from django.db import models
class QuestionSet(models.Model):
'''
Тест. Состоит из нескольких вопросов
'''
author = models.ForeignKey(User, on_delete=models.CASCADE)
title = models.CharField(max_length=255)
created = models.DateTimeField(auto_now_add=True)
class Meta:
ordering = ('-created', 'author')
def __str__(self):
return 'Автор теста: {}'.format(self.author)
class Question(models.Model):
'''
Является 'атомом' теста
'''
question = models.CharField(max_length=255)
ordering = models.PositiveSmallIntegerField(default=1, unique=True)
question_sets = models.ManyToManyField(QuestionSet)
class Meta:
ordering = ('ordering',)
def __str__(self):
return self.question<|fim▁hole|>
class Option(models.Model):
'''
Вариант ответа на вопрос
'''
question = models.ForeignKey(Question, on_delete=models.CASCADE)
value = models.CharField(max_length=255)
ordering = models.PositiveSmallIntegerField(default=1, unique=True)
is_correct = models.BooleanField()
class Meta:
ordering = ('ordering',)
def __str__(self):
return self.value
class RespondentSubmission(models.Model):
'''
Ответ респондента на вопрос теста
'''
respondent = models.ForeignKey(User, on_delete=models.CASCADE)
option = models.ForeignKey(Option, on_delete=models.CASCADE)
class Meta:
ordering = ('respondent', 'option')
def __str__(self):
return '{} {}'.format(self.respondent, self.option)<|fim▁end|>
| |
<|file_name|>login.component.spec.ts<|end_file_name|><|fim▁begin|>/* tslint:disable:no-unused-variable */
import { async, ComponentFixture, TestBed } from '@angular/core/testing';
import { By } from '@angular/platform-browser';
import { DebugElement } from '@angular/core';<|fim▁hole|>import { LoginComponent } from './login.component';
describe('LoginComponent', () => {
let component: LoginComponent;
let fixture: ComponentFixture<LoginComponent>;
beforeEach(async(() => {
TestBed.configureTestingModule({
declarations: [ LoginComponent ]
})
.compileComponents();
}));
beforeEach(() => {
fixture = TestBed.createComponent(LoginComponent);
component = fixture.componentInstance;
fixture.detectChanges();
});
it('should create', () => {
expect(component).toBeTruthy();
});
});<|fim▁end|>
| |
<|file_name|>main_result.rs<|end_file_name|><|fim▁begin|><|fim▁hole|><|fim▁end|>
|
fn main() -> Result<(), Box<dyn std::error::Error>> {
Ok(())
}
|
<|file_name|>response.py<|end_file_name|><|fim▁begin|>from datetime import datetime
import hashlib
from extractor import Ways
from date import way_date
class Helpers:
'''
'''
@staticmethod
def make_id(website, timestamp):
'''<|fim▁hole|> return m.hexdigest()
class WayDefault:
'''
'''
@classmethod
def set_parser(cls, ParserObj):
'''
'''
cls.parser=ParserObj
def __init__(self, snap_dict):
'''
'''
self._raw=snap_dict
self.timestamp=snap_dict['timestamp']
self._data=self.parser.parse(self._raw['page'])
self._data.update({
'website':snap_dict['website'],
'timestamp':way_date(self.timestamp),
})
self.id=Helpers.make_id(snap_dict['website'],self.timestamp)
self.report=snap_dict['report']
@property
def extracted(self):
'''
'''
return {k:v for k,v in self._data.items() if k != 'page'}
@property
def snapshot(self):
'''
'''
return self._data['page']
@property
def data(self):
'''
'''
return self._data
WayDefault.set_parser(Ways)<|fim▁end|>
|
'''
m=hashlib.md5()
m.update(''.join([website, timestamp]).encode())
|
<|file_name|>jquery.elevatezoom.js<|end_file_name|><|fim▁begin|>vti_encoding:SR|utf8-nl
vti_timelastmodified:TW|14 Aug 2014 13:36:46 -0000
vti_extenderversion:SR|12.0.0.0
vti_author:SR|Office-PC\\Rafael
vti_modifiedby:SR|Office-PC\\Rafael
vti_timecreated:TR|01 Nov 2014 09:10:51 -0000
vti_backlinkinfo:VX|
vti_nexttolasttimemodified:TW|14 Aug 2014 13:36:46 -0000
vti_cacheddtm:TX|03 Nov 2015 21:10:29 -0000
vti_filesize:IR|58273<|fim▁hole|><|fim▁end|>
|
vti_syncofs_mydatalogger.de\:22/%2fvar/www/vhosts/s16851491.onlinehome-server.info/kaufreund.de:TW|14 Aug 2014 13:36:46 -0000
vti_syncwith_mydatalogger.de\:22/%2fvar/www/vhosts/s16851491.onlinehome-server.info/kaufreund.de:TW|03 Nov 2015 21:10:29 -0000
|
<|file_name|>manage.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python3<|fim▁hole|>if __name__ == "__main__":
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "arsoft.web.ddns.settings")
from django.core.management import execute_from_command_line
execute_from_command_line(sys.argv)<|fim▁end|>
|
import os
import sys
|
<|file_name|>aes256.hpp<|end_file_name|><|fim▁begin|>/*
ANCH Framework: ANother C++ Hack is a C++ framework based on C++11 standard
Copyright (C) 2012 Vincent Lachenal
This file is part of ANCH Framework.
ANCH Framework 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 3 of the License, or
(at your option) any later version.
ANCH Framework 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 ANCH Framework. If not, see <http://www.gnu.org/licenses/>.
*/
#pragma once
#include "crypto/cipher/aes.hpp"
#include "crypto/cipher/ecb.hpp"
#include "crypto/cipher/cbc.hpp"
#include "crypto/cipher/pcbc.hpp"
#include "crypto/cipher/cfb.hpp"
#include "crypto/cipher/ofb.hpp"
#include "crypto/cipher/ctr.hpp"
#include "crypto/padding/ansiX923.hpp"
#include "crypto/padding/iso7816_4Padding.hpp"<|fim▁hole|> namespace crypto {
extern template class BlockCipher<16>;
extern template class AES<8,14>;
/*!
* AES-256 defintion
*/
using AES256 = AES<8,14>;
/*!
* Cipher block mode of operation definitions
*/
extern template class BlockCipherModeOfOperation<ECB<AES256,ZeroPadding>,AES256>;
extern template class ECB<AES256,ZeroPadding>;
extern template class BlockCipherModeOfOperation<ECB<AES256,ANSIX923>,AES256>;
extern template class ECB<AES256,ANSIX923>;
extern template class BlockCipherModeOfOperation<ECB<AES256,ISO7816_4Padding>,AES256>;
extern template class ECB<AES256,ISO7816_4Padding>;
extern template class BlockCipherModeOfOperation<ECB<AES256,PKCS5Padding>,AES256>;
extern template class ECB<AES256,PKCS5Padding>;
extern template class BlockCipherModeOfOperation<CBC<AES256,ZeroPadding>,AES256>;
extern template class CBC<AES256,ZeroPadding>;
extern template class BlockCipherModeOfOperation<CBC<AES256,ANSIX923>,AES256>;
extern template class CBC<AES256,ANSIX923>;
extern template class BlockCipherModeOfOperation<CBC<AES256,ISO7816_4Padding>,AES256>;
extern template class CBC<AES256,ISO7816_4Padding>;
extern template class BlockCipherModeOfOperation<CBC<AES256,PKCS5Padding>,AES256>;
extern template class CBC<AES256,PKCS5Padding>;
extern template class BlockCipherModeOfOperation<PCBC<AES256,ZeroPadding>,AES256>;
extern template class PCBC<AES256,ZeroPadding>;
extern template class BlockCipherModeOfOperation<PCBC<AES256,ANSIX923>,AES256>;
extern template class PCBC<AES256,ANSIX923>;
extern template class BlockCipherModeOfOperation<PCBC<AES256,ISO7816_4Padding>,AES256>;
extern template class PCBC<AES256,ISO7816_4Padding>;
extern template class BlockCipherModeOfOperation<PCBC<AES256,PKCS5Padding>,AES256>;
extern template class PCBC<AES256,PKCS5Padding>;
extern template class BlockCipherModeOfOperation<CFB<AES256>,AES256>;
extern template class CFB<AES256>;
extern template class BlockCipherModeOfOperation<OFB<AES256>,AES256>;
extern template class OFB<AES256>;
extern template class BlockCipherModeOfOperation<CTR<AES256>,AES256>;
extern template class CTR<AES256>;
}
}<|fim▁end|>
|
#include "crypto/padding/pkcs5Padding.hpp"
#include "crypto/padding/zeroPadding.hpp"
namespace anch {
|
<|file_name|>test_smbfs.py<|end_file_name|><|fim▁begin|># Copyright 2014 Cloudbase Solutions Srl
#
# 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 contextlib
import copy
import os
import mock
from cinder import exception
from cinder.image import image_utils
from cinder import test
from cinder.volume.drivers import smbfs
class SmbFsTestCase(test.TestCase):<|fim▁hole|> _FAKE_MNT_BASE = '/mnt'
_FAKE_VOLUME_NAME = 'volume-4f711859-4928-4cb7-801a-a50c37ceaccc'
_FAKE_TOTAL_SIZE = '2048'
_FAKE_TOTAL_AVAILABLE = '1024'
_FAKE_TOTAL_ALLOCATED = 1024
_FAKE_VOLUME = {'id': '4f711859-4928-4cb7-801a-a50c37ceaccc',
'size': 1,
'provider_location': _FAKE_SHARE,
'name': _FAKE_VOLUME_NAME,
'status': 'available'}
_FAKE_MNT_POINT = os.path.join(_FAKE_MNT_BASE, 'fake_hash')
_FAKE_VOLUME_PATH = os.path.join(_FAKE_MNT_POINT, _FAKE_VOLUME_NAME)
_FAKE_SNAPSHOT_ID = '5g811859-4928-4cb7-801a-a50c37ceacba'
_FAKE_SNAPSHOT = {'id': _FAKE_SNAPSHOT_ID,
'volume': _FAKE_VOLUME,
'status': 'available',
'volume_size': 1}
_FAKE_SNAPSHOT_PATH = (
_FAKE_VOLUME_PATH + '-snapshot' + _FAKE_SNAPSHOT_ID)
_FAKE_SHARE_OPTS = '-o username=Administrator,password=12345'
_FAKE_OPTIONS_DICT = {'username': 'Administrator',
'password': '12345'}
_FAKE_LISTDIR = [_FAKE_VOLUME_NAME, _FAKE_VOLUME_NAME + '.vhd',
_FAKE_VOLUME_NAME + '.vhdx', 'fake_folder']
_FAKE_SMBFS_CONFIG = mock.MagicMock()
_FAKE_SMBFS_CONFIG.smbfs_oversub_ratio = 2
_FAKE_SMBFS_CONFIG.smbfs_used_ratio = 0.5
_FAKE_SMBFS_CONFIG.smbfs_shares_config = '/fake/config/path'
_FAKE_SMBFS_CONFIG.smbfs_default_volume_format = 'raw'
_FAKE_SMBFS_CONFIG.smbfs_sparsed_volumes = False
def setUp(self):
super(SmbFsTestCase, self).setUp()
smbfs.SmbfsDriver.__init__ = lambda x: None
self._smbfs_driver = smbfs.SmbfsDriver()
self._smbfs_driver._remotefsclient = mock.Mock()
self._smbfs_driver._local_volume_dir = mock.Mock(
return_value=self._FAKE_MNT_POINT)
self._smbfs_driver._execute = mock.Mock()
self._smbfs_driver.base = self._FAKE_MNT_BASE
def test_delete_volume(self):
drv = self._smbfs_driver
fake_vol_info = self._FAKE_VOLUME_PATH + '.info'
drv._ensure_share_mounted = mock.MagicMock()
fake_ensure_mounted = drv._ensure_share_mounted
drv._local_volume_dir = mock.Mock(
return_value=self._FAKE_MNT_POINT)
drv.get_active_image_from_info = mock.Mock(
return_value=self._FAKE_VOLUME_NAME)
drv._delete = mock.Mock()
drv._local_path_volume_info = mock.Mock(
return_value=fake_vol_info)
with mock.patch('os.path.exists', lambda x: True):
drv.delete_volume(self._FAKE_VOLUME)
fake_ensure_mounted.assert_called_once_with(self._FAKE_SHARE)
drv._delete.assert_any_call(
self._FAKE_VOLUME_PATH)
drv._delete.assert_any_call(fake_vol_info)
def _test_setup(self, config, share_config_exists=True):
fake_exists = mock.Mock(return_value=share_config_exists)
fake_ensure_mounted = mock.MagicMock()
self._smbfs_driver._ensure_shares_mounted = fake_ensure_mounted
self._smbfs_driver.configuration = config
with mock.patch('os.path.exists', fake_exists):
if not (config.smbfs_shares_config and share_config_exists and
config.smbfs_oversub_ratio > 0 and
0 <= config.smbfs_used_ratio <= 1):
self.assertRaises(exception.SmbfsException,
self._smbfs_driver.do_setup,
None)
else:
self._smbfs_driver.do_setup(None)
self.assertEqual(self._smbfs_driver.shares, {})
fake_ensure_mounted.assert_called_once()
def test_setup_missing_shares_config_option(self):
fake_config = copy.copy(self._FAKE_SMBFS_CONFIG)
fake_config.smbfs_shares_config = None
self._test_setup(fake_config, None)
def test_setup_missing_shares_config_file(self):
self._test_setup(self._FAKE_SMBFS_CONFIG, False)
def test_setup_invlid_oversub_ratio(self):
fake_config = copy.copy(self._FAKE_SMBFS_CONFIG)
fake_config.smbfs_oversub_ratio = -1
self._test_setup(fake_config)
def test_setup_invalid_used_ratio(self):
fake_config = copy.copy(self._FAKE_SMBFS_CONFIG)
fake_config.smbfs_used_ratio = -1
self._test_setup(fake_config)
def _test_create_volume(self, volume_exists=False, volume_format=None):
fake_method = mock.MagicMock()
self._smbfs_driver.configuration = copy.copy(self._FAKE_SMBFS_CONFIG)
self._smbfs_driver._set_rw_permissions_for_all = mock.MagicMock()
fake_set_permissions = self._smbfs_driver._set_rw_permissions_for_all
self._smbfs_driver.get_volume_format = mock.MagicMock()
windows_image_format = False
fake_vol_path = self._FAKE_VOLUME_PATH
self._smbfs_driver.get_volume_format.return_value = volume_format
if volume_format:
if volume_format in ('vhd', 'vhdx'):
windows_image_format = volume_format
if volume_format == 'vhd':
windows_image_format = 'vpc'
method = '_create_windows_image'
fake_vol_path += '.' + volume_format
else:
method = '_create_%s_file' % volume_format
if volume_format == 'sparsed':
self._smbfs_driver.configuration.smbfs_sparsed_volumes = (
True)
else:
method = '_create_regular_file'
setattr(self._smbfs_driver, method, fake_method)
with mock.patch('os.path.exists', new=lambda x: volume_exists):
if volume_exists:
self.assertRaises(exception.InvalidVolume,
self._smbfs_driver._do_create_volume,
self._FAKE_VOLUME)
return
self._smbfs_driver._do_create_volume(self._FAKE_VOLUME)
if windows_image_format:
fake_method.assert_called_once_with(
fake_vol_path,
self._FAKE_VOLUME['size'],
windows_image_format)
else:
fake_method.assert_called_once_with(
fake_vol_path, self._FAKE_VOLUME['size'])
fake_set_permissions.assert_called_once_with(fake_vol_path)
def test_create_existing_volume(self):
self._test_create_volume(volume_exists=True)
def test_create_vhdx(self):
self._test_create_volume(volume_format='vhdx')
def test_create_qcow2(self):
self._test_create_volume(volume_format='qcow2')
def test_create_sparsed(self):
self._test_create_volume(volume_format='sparsed')
def test_create_regular(self):
self._test_create_volume()
def _test_find_share(self, existing_mounted_shares=True,
eligible_shares=True):
if existing_mounted_shares:
mounted_shares = ('fake_share1', 'fake_share2', 'fake_share3')
else:
mounted_shares = None
self._smbfs_driver._mounted_shares = mounted_shares
self._smbfs_driver._is_share_eligible = mock.Mock(
return_value=eligible_shares)
fake_capacity_info = ((2, 1, 5), (2, 1, 4), (2, 1, 1))
self._smbfs_driver._get_capacity_info = mock.Mock(
side_effect=fake_capacity_info)
if not mounted_shares:
self.assertRaises(exception.SmbfsNoSharesMounted,
self._smbfs_driver._find_share,
self._FAKE_VOLUME['size'])
elif not eligible_shares:
self.assertRaises(exception.SmbfsNoSuitableShareFound,
self._smbfs_driver._find_share,
self._FAKE_VOLUME['size'])
else:
ret_value = self._smbfs_driver._find_share(
self._FAKE_VOLUME['size'])
# The eligible share with the minimum allocated space
# will be selected
self.assertEqual(ret_value, 'fake_share3')
def test_find_share(self):
self._test_find_share()
def test_find_share_missing_mounted_shares(self):
self._test_find_share(existing_mounted_shares=False)
def test_find_share_missing_eligible_shares(self):
self._test_find_share(eligible_shares=False)
def _test_is_share_eligible(self, capacity_info, volume_size):
self._smbfs_driver._get_capacity_info = mock.Mock(
return_value=[float(x << 30) for x in capacity_info])
self._smbfs_driver.configuration = self._FAKE_SMBFS_CONFIG
return self._smbfs_driver._is_share_eligible(self._FAKE_SHARE,
volume_size)
def test_share_volume_above_used_ratio(self):
fake_capacity_info = (4, 1, 1)
fake_volume_size = 2
ret_value = self._test_is_share_eligible(fake_capacity_info,
fake_volume_size)
self.assertEqual(ret_value, False)
def test_eligible_share(self):
fake_capacity_info = (4, 4, 0)
fake_volume_size = 1
ret_value = self._test_is_share_eligible(fake_capacity_info,
fake_volume_size)
self.assertEqual(ret_value, True)
def test_share_volume_above_oversub_ratio(self):
fake_capacity_info = (4, 4, 7)
fake_volume_size = 2
ret_value = self._test_is_share_eligible(fake_capacity_info,
fake_volume_size)
self.assertEqual(ret_value, False)
def test_share_reserved_above_oversub_ratio(self):
fake_capacity_info = (4, 4, 10)
fake_volume_size = 1
ret_value = self._test_is_share_eligible(fake_capacity_info,
fake_volume_size)
self.assertEqual(ret_value, False)
def test_parse_options(self):
(opt_list,
opt_dict) = self._smbfs_driver.parse_options(
self._FAKE_SHARE_OPTS)
expected_ret = ([], self._FAKE_OPTIONS_DICT)
self.assertEqual(expected_ret, (opt_list, opt_dict))
def test_parse_credentials(self):
fake_smb_options = r'-o user=MyDomain\Administrator,noperm'
expected_flags = '-o username=Administrator,noperm'
flags = self._smbfs_driver.parse_credentials(fake_smb_options)
self.assertEqual(expected_flags, flags)
def test_get_volume_path(self):
self._smbfs_driver.get_volume_format = mock.Mock(
return_value='vhd')
self._smbfs_driver._local_volume_dir = mock.Mock(
return_value=self._FAKE_MNT_POINT)
expected = self._FAKE_VOLUME_PATH + '.vhd'
ret_val = self._smbfs_driver.local_path(self._FAKE_VOLUME)
self.assertEqual(expected, ret_val)
def test_initialize_connection(self):
self._smbfs_driver.get_active_image_from_info = mock.Mock(
return_value=self._FAKE_VOLUME_NAME)
self._smbfs_driver._get_mount_point_base = mock.Mock(
return_value=self._FAKE_MNT_BASE)
self._smbfs_driver.shares = {self._FAKE_SHARE: self._FAKE_SHARE_OPTS}
self._smbfs_driver._qemu_img_info = mock.Mock(
return_value=mock.Mock(file_format='raw'))
fake_data = {'export': self._FAKE_SHARE,
'format': 'raw',
'name': self._FAKE_VOLUME_NAME,
'options': self._FAKE_SHARE_OPTS}
expected = {
'driver_volume_type': 'smbfs',
'data': fake_data,
'mount_point_base': self._FAKE_MNT_BASE}
ret_val = self._smbfs_driver.initialize_connection(
self._FAKE_VOLUME, None)
self.assertEqual(expected, ret_val)
def _test_extend_volume(self, extend_failed=False, image_format='raw'):
drv = self._smbfs_driver
drv.local_path = mock.Mock(
return_value=self._FAKE_VOLUME_PATH)
drv._check_extend_volume_support = mock.Mock(
return_value=True)
drv._is_file_size_equal = mock.Mock(
return_value=not extend_failed)
drv._qemu_img_info = mock.Mock(
return_value=mock.Mock(file_format=image_format))
with contextlib.nested(
mock.patch.object(image_utils, 'resize_image'),
mock.patch.object(image_utils, 'convert_image')) as (
fake_resize, fake_convert):
if extend_failed:
self.assertRaises(exception.ExtendVolumeError,
drv._extend_volume,
self._FAKE_VOLUME, mock.sentinel.new_size)
else:
drv._extend_volume(
self._FAKE_VOLUME,
mock.sentinel.new_size)
if image_format in (drv._DISK_FORMAT_VHDX,
drv._DISK_FORMAT_VHD_LEGACY):
fake_tmp_path = self._FAKE_VOLUME_PATH + '.tmp'
fake_convert.assert_any_call(self._FAKE_VOLUME_PATH,
fake_tmp_path, 'raw')
fake_resize.assert_called_once_with(
fake_tmp_path, mock.sentinel.new_size)
fake_convert.assert_any_call(fake_tmp_path,
self._FAKE_VOLUME_PATH,
image_format)
else:
fake_resize.assert_called_once_with(
self._FAKE_VOLUME_PATH, mock.sentinel.new_size)
def test_extend_volume(self):
self._test_extend_volume()
def test_extend_volume_failed(self):
self._test_extend_volume(extend_failed=True)
def test_extend_vhd_volume(self):
self._test_extend_volume(image_format='vpc')
def _test_check_extend_support(self, has_snapshots=False,
is_eligible=True):
self._smbfs_driver.local_path = mock.Mock(
return_value=self._FAKE_VOLUME_PATH)
if has_snapshots:
active_file_path = self._FAKE_SNAPSHOT_PATH
else:
active_file_path = self._FAKE_VOLUME_PATH
self._smbfs_driver.get_active_image_from_info = mock.Mock(
return_value=active_file_path)
self._smbfs_driver._is_share_eligible = mock.Mock(
return_value=is_eligible)
if has_snapshots:
self.assertRaises(exception.InvalidVolume,
self._smbfs_driver._check_extend_volume_support,
self._FAKE_VOLUME, 2)
elif not is_eligible:
self.assertRaises(exception.ExtendVolumeError,
self._smbfs_driver._check_extend_volume_support,
self._FAKE_VOLUME, 2)
else:
self._smbfs_driver._check_extend_volume_support(
self._FAKE_VOLUME, 2)
self._smbfs_driver._is_share_eligible.assert_called_once_with(
self._FAKE_SHARE, 1)
def test_check_extend_support(self):
self._test_check_extend_support()
def test_check_extend_volume_with_snapshots(self):
self._test_check_extend_support(has_snapshots=True)
def test_check_extend_volume_uneligible_share(self):
self._test_check_extend_support(is_eligible=False)
def test_create_volume_from_in_use_snapshot(self):
fake_snapshot = {'status': 'in-use'}
self.assertRaises(
exception.InvalidSnapshot,
self._smbfs_driver.create_volume_from_snapshot,
self._FAKE_VOLUME, fake_snapshot)
def test_copy_volume_from_snapshot(self):
drv = self._smbfs_driver
fake_volume_info = {self._FAKE_SNAPSHOT_ID: 'fake_snapshot_file_name'}
fake_img_info = mock.MagicMock()
fake_img_info.backing_file = self._FAKE_VOLUME_NAME
drv.get_volume_format = mock.Mock(
return_value='raw')
drv._local_path_volume_info = mock.Mock(
return_value=self._FAKE_VOLUME_PATH + '.info')
drv._local_volume_dir = mock.Mock(
return_value=self._FAKE_MNT_POINT)
drv._read_info_file = mock.Mock(
return_value=fake_volume_info)
drv._qemu_img_info = mock.Mock(
return_value=fake_img_info)
drv.local_path = mock.Mock(
return_value=self._FAKE_VOLUME_PATH[:-1])
drv._extend_volume = mock.Mock()
drv._set_rw_permissions_for_all = mock.Mock()
with mock.patch.object(image_utils, 'convert_image') as (
fake_convert_image):
drv._copy_volume_from_snapshot(
self._FAKE_SNAPSHOT, self._FAKE_VOLUME,
self._FAKE_VOLUME['size'])
drv._extend_volume.assert_called_once_with(
self._FAKE_VOLUME, self._FAKE_VOLUME['size'])
fake_convert_image.assert_called_once_with(
self._FAKE_VOLUME_PATH, self._FAKE_VOLUME_PATH[:-1], 'raw')
def test_ensure_mounted(self):
self._smbfs_driver.shares = {self._FAKE_SHARE: self._FAKE_SHARE_OPTS}
self._smbfs_driver._ensure_share_mounted(self._FAKE_SHARE)
self._smbfs_driver._remotefsclient.mount.assert_called_once_with(
self._FAKE_SHARE, self._FAKE_SHARE_OPTS.split())
def _test_copy_image_to_volume(self, unsupported_qemu_version=False,
wrong_size_after_fetch=False):
drv = self._smbfs_driver
vol_size_bytes = self._FAKE_VOLUME['size'] << 30
fake_image_service = mock.MagicMock()
fake_image_service.show.return_value = (
{'id': 'fake_image_id', 'disk_format': 'raw'})
fake_img_info = mock.MagicMock()
if wrong_size_after_fetch:
fake_img_info.virtual_size = 2 * vol_size_bytes
else:
fake_img_info.virtual_size = vol_size_bytes
if unsupported_qemu_version:
qemu_version = [1, 5]
else:
qemu_version = [1, 7]
drv.get_volume_format = mock.Mock(
return_value=drv._DISK_FORMAT_VHDX)
drv.local_path = mock.Mock(
return_value=self._FAKE_VOLUME_PATH)
drv.get_qemu_version = mock.Mock(
return_value=qemu_version)
drv._do_extend_volume = mock.Mock()
drv.configuration = mock.MagicMock()
drv.configuration.volume_dd_blocksize = (
mock.sentinel.block_size)
exc = None
with contextlib.nested(
mock.patch.object(image_utils,
'fetch_to_volume_format'),
mock.patch.object(image_utils,
'qemu_img_info')) as (
fake_fetch,
fake_qemu_img_info):
if wrong_size_after_fetch:
exc = exception.ImageUnacceptable
elif unsupported_qemu_version:
exc = exception.InvalidVolume
fake_qemu_img_info.return_value = fake_img_info
if exc:
self.assertRaises(
exc, drv.copy_image_to_volume,
mock.sentinel.context, self._FAKE_VOLUME,
fake_image_service,
mock.sentinel.image_id)
else:
drv.copy_image_to_volume(
mock.sentinel.context, self._FAKE_VOLUME,
fake_image_service,
mock.sentinel.image_id)
fake_fetch.assert_called_once_with(
mock.sentinel.context, fake_image_service,
mock.sentinel.image_id, self._FAKE_VOLUME_PATH,
drv._DISK_FORMAT_VHDX,
mock.sentinel.block_size)
drv._do_extend_volume.assert_called_once_with(
self._FAKE_VOLUME_PATH, self._FAKE_VOLUME['size'])
def test_copy_image_to_volume(self):
self._test_copy_image_to_volume()
def test_copy_image_to_volume_wrong_size_after_fetch(self):
self._test_copy_image_to_volume(wrong_size_after_fetch=True)
def test_copy_image_to_volume_unsupported_qemu_version(self):
self._test_copy_image_to_volume(unsupported_qemu_version=True)
def test_get_capacity_info(self):
fake_block_size = 4096.0
fake_total_blocks = 1024
fake_avail_blocks = 512
fake_total_allocated = fake_total_blocks * fake_block_size
fake_df = ('%s %s %s' % (fake_block_size, fake_total_blocks,
fake_avail_blocks), None)
fake_du = (str(fake_total_allocated), None)
self._smbfs_driver._get_mount_point_for_share = mock.Mock(
return_value=self._FAKE_MNT_POINT)
self._smbfs_driver._execute = mock.Mock(
side_effect=(fake_df, fake_du))
ret_val = self._smbfs_driver._get_capacity_info(self._FAKE_SHARE)
expected = (fake_block_size * fake_total_blocks,
fake_block_size * fake_avail_blocks,
fake_total_allocated)
self.assertEqual(expected, ret_val)<|fim▁end|>
|
_FAKE_SHARE = '//1.2.3.4/share1'
|
<|file_name|>observation_fields.js<|end_file_name|><|fim▁begin|>$.fn.observationFieldsForm = function(options) {
$(this).each(function() {
var that = this
$('.observation_field_chooser', this).chooser({
collectionUrl: '/observation_fields.json',
resourceUrl: '/observation_fields/{{id}}.json',
afterSelect: function(item) {
$('.observation_field_chooser', that).parents('.ui-chooser:first').next('.button').click()
$('.observation_field_chooser', that).chooser('clear')
}
})
$('.addfieldbutton', this).hide()
$('#createfieldbutton', this).click(ObservationFields.newObservationFieldButtonHandler)
ObservationFields.fieldify({focus: false})
})
}
$.fn.newObservationField = function(markup) {
var currentField = $('.observation_field_chooser', this).chooser('selected')
if (!currentField || typeof(currentField) == 'undefined') {
alert('Please choose a field type')
return
}
if ($('#observation_field_'+currentField.recordId, this).length > 0) {
alert('You already have a field for that type')
return
}
$('.observation_fields', this).append(markup)
ObservationFields.fieldify({observationField: currentField})
}
var ObservationFields = {
newObservationFieldButtonHandler: function() {
var url = $(this).attr('href'),
dialog = $('<div class="dialog"><span class="loading status">Loading...</span></div>')
$(document.body).append(dialog)
$(dialog).dialog({
modal:true,
title: I18n.t('new_observation_field')
})
$(dialog).load(url, "format=js", function() {
$('form', dialog).submit(function() {
$.ajax({
type: "post",
url: $(this).attr('action'),
data: $(this).serialize(),
dataType: 'json'
})
.done(function(data, textStatus, req) {
$(dialog).dialog('close')
$('.observation_field_chooser').chooser('selectItem', data)
})
.fail(function (xhr, ajaxOptions, thrownError){
var json = $.parseJSON(xhr.responseText)
if (json && json.errors && json.errors.length > 0) {
alert(json.errors.join(''))
} else {
alert(I18n.t('doh_something_went_wrong'))
}<|fim▁hole|> })
return false
})
$(this).centerDialog()
})
return false
},
fieldify: function(options) {
options = options || {}
options.focus = typeof(options.focus) == 'undefined' ? true : options.focus
$('.observation_field').not('.fieldified').each(function() {
var lastName = $(this).siblings('.fieldified:last').find('input').attr('name')
if (lastName) {
var matches = lastName.match(/observation_field_values_attributes\]\[(\d*)\]/)
if (matches) {
var index = parseInt(matches[1]) + 1
} else {
var index = 0
}
} else {
var index = 0
}
$(this).addClass('fieldified')
var input = $('.ofv_input input.text', this)
var currentField = options.observationField || $.parseJSON($(input).attr('data-json'))
if (!currentField) return
currentField.recordId = currentField.recordId || currentField.id
$(this).attr('id', 'observation_field_'+currentField.recordId)
$(this).attr('data-observation-field-id', currentField.recordId)
$('.labeldesc label', this).html(currentField.name)
$('.description', this).html(currentField.description)
$('.observation_field_id', this).val(currentField.recordId)
$('input', this).each(function() {
var newName = $(this).attr('name')
.replace(
/observation_field_values_attributes\]\[(\d*)\]/,
'observation_field_values_attributes]['+index+']')
$(this).attr('name', newName)
})
if (currentField.allowed_values && currentField.allowed_values != '') {
var allowed_values = currentField.allowed_values.split('|')
var select = $('<select></select>')
for (var i=0; i < allowed_values.length; i++) {
select.append($('<option>'+allowed_values[i]+'</option>'))
}
select.change(function() { input.val($(this).val()) })
$(input).hide()
$(input).after(select)
select.val(input.val()).change()
if (options.focus) { select.focus() }
} else if (currentField.datatype == 'numeric') {
var newInput = input.clone()
newInput.attr('type', 'number')
newInput.attr('step', 'any')
input.after(newInput)
input.remove()
if (options.focus) { newInput.focus() }
} else if (currentField.datatype == 'date') {
$(input).iNatDatepicker({constrainInput: true})
if (options.focus) { input.focus() }
} else if (currentField.datatype == 'time') {
$(input).timepicker({})
if (options.focus) { input.focus() }
} else if (currentField.datatype == 'taxon') {
var newInput = input.clone()
newInput.attr('name', 'taxon_name')
input.after(newInput)
input.hide()
$(newInput).removeClass('ofv_value_field')
var taxon = input.data( "taxon" );
if( taxon ) {
newInput.val( taxon.leading_name );
}
$(newInput).taxonAutocomplete({
taxon_id_el: input
});
if( options.focus ) {
newInput.focus( );
}
} else if (options.focus) {
input.focus()
}
})
},
showObservationFieldsDialog: function(options) {
options = options || {}
var url = options.url || '/observations/'+window.observation.id+'/fields',
title = options.title || I18n.t('observation_fields'),
originalInput = options.originalInput
var dialog = $('#obsfielddialog')
if (dialog.length == 0) {
dialog = $('<div id="obsfielddialog"></div>').addClass('dialog').html('<div class="loading status">Loading...</div>')
}
$('.qtip.ui-tooltip').qtip('hide');
dialog.load(url, function() {
var diag = this
$(this).observationFieldsForm()
$(this).centerDialog()
$('form:has(input[required])', this).submit(checkFormForRequiredFields)
if (originalInput) {
var form = $('form', this)
$(form).submit(function() {
var ajaxOptions = {
url: $(form).attr('action'),
type: $(form).attr('method'),
data: $(form).serialize(),
dataType: 'json'
}
$.ajax(ajaxOptions).done(function() {
$.rails.fire($(originalInput), 'ajax:success')
$(diag).dialog('close')
}).fail(function() {
alert('Failed to add to project')
})
return false
})
}
})
dialog.dialog({
modal: true,
title: title,
width: 600,
maxHeight: $(window).height() * 0.8
})
}
}
// the following stuff doesn't have too much to do with observation fields, but it's at least tangentially related
$(document).ready(function() {
$(document).on('ajax:success', '#project_menu .addlink, .project_invitation .acceptlink, #projectschooser .addlink', function(e, json, status) {
var observationId = (json && json.observation_id) || $(this).data('observation-id') || window.observation.id
if (json && json.project && json.project.project_observation_fields && json.project.project_observation_fields.length > 0) {
if (json.observation.observation_field_values && json.observation.observation_field_values.length > 0) {
var ofvs = json.observation.observation_field_values,
pofs = json.project.project_observation_fields,
ofv_of_ids = $.map(ofvs, function(ofv) { return ofv.observation_field_id }),
pof_of_ids = $.map(pofs, function(pof) { return pof.observation_field_id }),
intersection = $.map(ofv_of_ids, function(a) { return $.inArray(a, pof_of_ids) < 0 ? null : a })
if (intersection.length >= pof_of_ids.length) { return true }
}
ObservationFields.showObservationFieldsDialog({
url: '/observations/'+observationId+'/fields?project_id='+json.project_id,
title: 'Project observation fields for ' + json.project.title,
originalInput: this
})
}
})
$(document).on('ajax:error', '#project_menu .addlink, .project_invitation .acceptlink, #projectschooser .addlink', function(e, xhr, error, status) {
var json = $.parseJSON(xhr.responseText),
projectId = json.project_observation.project_id || $(this).data('project-id'),
observationId = json.project_observation.observation_id || $(this).data('observation-id') || window.observation.id
if (json.error.match(/observation field/)) {
ObservationFields.showObservationFieldsDialog({
url: '/observations/'+observationId+'/fields?project_id='+projectId,
title: 'Project observation fields',
originalInput: this
})
} else if (json.error.match(/must belong to a member/)) {
showJoinProjectDialog(projectId, {originalInput: this})
} else {
alert(json.error)
}
})
$(document).on('ajax:error', '#project_menu .removelink, .project_invitation .removelink, #projectschooser .removelink', function(e, xhr, error, status) {
alert(xhr.responseText)
})
})<|fim▁end|>
| |
<|file_name|>cli.ts<|end_file_name|><|fim▁begin|>import * as fs from "fs";
import * as path from "path";
import * as commander from "commander";
import { ConsoleLogger } from "@akashic/akashic-cli-commons";
import { promiseExportHTML } from "./exportHTML";
import { promiseExportAtsumaru } from "./exportAtsumaru";
interface CommandParameterObject {
cwd?: string;
source?: string;
force?: boolean;
quiet?: boolean;
output?: string;
exclude?: string[];
strip?: boolean;
hashFilename?: number | boolean;
minify?: boolean;
bundle?: boolean;
magnify?: boolean;
injects?: string[];
atsumaru?: boolean;
}
function cli(param: CommandParameterObject): void {
const logger = new ConsoleLogger({ quiet: param.quiet });
const exportParam = {
cwd: !param.cwd ? process.cwd() : path.resolve(param.cwd),
source: param.source,
force: param.force,
quiet: param.quiet,
output: param.output,
exclude: param.exclude,
logger: logger,
strip: (param.strip != null) ? param.strip : true,
hashLength: !param.hashFilename && !param.atsumaru ? 0 :
(param.hashFilename === true || param.hashFilename === undefined) ? 20 : Number(param.hashFilename),
minify: param.minify,
bundle: param.bundle || param.atsumaru,
magnify: param.magnify || param.atsumaru,
injects: param.injects,
unbundleText: !param.bundle || param.atsumaru,
lint: !param.atsumaru
};
Promise.resolve()
.then(() => {
if (param.output === undefined) {
throw new Error("--output option must be specified.");
}
if (param.atsumaru) {
return promiseExportAtsumaru(exportParam);
} else {
return promiseExportHTML(exportParam);
}
})
.then(() => logger.info("Done!"))
.catch((err: any) => {
logger.error(err);
process.exit(1);
});
}
const ver = JSON.parse(fs.readFileSync(path.resolve(__dirname, "..", "package.json"), "utf8")).version;
commander
.version(ver);
commander
.description("convert your Akashic game runnable standalone.")
.option("-C, --cwd <dir>", "The directory to export from")
.option("-s, --source <dir>", "Source directory to export from cwd/current directory")
.option("-f, --force", "Overwrites existing files")
.option("-q, --quiet", "Suppress output")
.option("-o, --output <fileName>", "Name of output file or directory")
.option("-S, --no-strip", "output fileset without strip")
.option("-H, --hash-filename [length]", "Rename asset files with their hash values")
.option("-M, --minify", "minify JavaScript files")
.option("-b, --bundle", "bundle assets and scripts in index.html (to reduce the number of files)")
.option("-m, --magnify", "fit game area to outer element size")
.option("-i, --inject [fileName]", "specify injected file content into index.html", inject, [])
.option("-a, --atsumaru", "generate files that can be posted to RPG-atsumaru");
export function run(argv: string[]): void {
// Commander の制約により --strip と --no-strip 引数を両立できないため、暫定対応として Commander 前に argv を処理する
const argvCopy = dropDeprecatedArgs(argv);
commander.parse(argvCopy);
cli({<|fim▁hole|> force: commander["force"],
quiet: commander["quiet"],
output: commander["output"],
source: commander["source"],
strip: commander["strip"],
minify: commander["minify"],
bundle: commander["bundle"],
magnify: commander["magnify"],
hashFilename: commander["hashFilename"],
injects: commander["inject"],
atsumaru: commander["atsumaru"]
});
}
function dropDeprecatedArgs(argv: string[]): string[] {
const filteredArgv = argv.filter(v => !/^(-s|--strip)$/.test(v));
if (argv.length !== filteredArgv.length) {
console.log("WARN: --strip option is deprecated. strip is applied by default.");
console.log("WARN: If you do not need to apply it, use --no-strip option.");
}
return filteredArgv;
}
function inject(val: string, injects: string[]): string[] {
injects.push(val);
return injects;
}<|fim▁end|>
|
cwd: commander["cwd"],
|
<|file_name|>grid.js<|end_file_name|><|fim▁begin|>(function() {
'use strict';
/*
* This feature allows you to specify a grid over a portion or the entire chart area.
*
* @name grid
*/
d4.feature('grid', function(name) {
var xAxis = d3.svg.axis();
var yAxis = d3.svg.axis();
return {
accessors: {
formatXAxis: function(xAxis) {
return xAxis.orient('bottom');
},
formatYAxis: function(yAxis) {
return yAxis.orient('left');
}
},
proxies: [{
target: xAxis,
prefix: 'x'
}, {
target: yAxis,
prefix: 'y'
}],
render: function(scope, data, selection) {
xAxis.scale(this.x);
yAxis.scale(this.y);
var formattedXAxis = d4.functor(scope.accessors.formatXAxis).bind(this)(xAxis);
var formattedYAxis = d4.functor(scope.accessors.formatYAxis).bind(this)(yAxis);
var grid = d4.appendOnce(selection, 'g.grid.border.' + name);
var gridBg = d4.appendOnce(grid, 'rect');<|fim▁hole|> gridBg
.attr('transform', 'translate(0,0)')
.attr('x', 0)
.attr('y', 0)
.attr('width', this.width)
.attr('height', this.height);
gridX
.attr('transform', 'translate(0,' + this.height + ')')
.call(formattedXAxis
.tickSize(-this.height, 0, 0)
.tickFormat(''));
gridY
.attr('transform', 'translate(0,0)')
.call(formattedYAxis
.tickSize(-this.width, 0, 0)
.tickFormat(''));
return grid;
}
};
});
}).call(this);<|fim▁end|>
|
var gridX = d4.appendOnce(grid, 'g.x.grid.' + name);
var gridY = d4.appendOnce(grid, 'g.y.grid.' + name);
|
<|file_name|>ProjectItem.js<|end_file_name|><|fim▁begin|>import React, {
Component
} from 'react';
class ProjectItem extends Component {
render() {
return ( <<|fim▁hole|> <
strong > {
this.props.project.title
} < /strong> - {this.props.project.category} < /
li >
);
}
}
export default ProjectItem;<|fim▁end|>
|
li className = "Project" >
|
<|file_name|>upload_latest.rs<|end_file_name|><|fim▁begin|>use crate::{api_client::{self,
Client},
common::ui::{Status,
UIWriter,
UI},
error::{Error,
Result},
PRODUCT,
VERSION};
use habitat_core::{crypto::keys::{Key,
KeyCache,
PublicOriginSigningKey,
SecretOriginSigningKey},
origin::Origin};
use reqwest::StatusCode;
pub async fn start(ui: &mut UI,
bldr_url: &str,
token: &str,
origin: &Origin,
with_secret: bool,
key_cache: &KeyCache)
-> Result<()> {
let api_client = Client::new(bldr_url, PRODUCT, VERSION, None)?;
ui.begin(format!("Uploading latest public origin key {}", &origin))?;
// Figure out the latest public key
let public_key: PublicOriginSigningKey = key_cache.latest_public_origin_signing_key(origin)?;
// The path to the key in the cache
let public_keyfile = key_cache.path_in_cache(&public_key);
ui.status(Status::Uploading, public_keyfile.display())?;
// TODO (CM): Really, we just need to pass the key itself; it's
// got all the information
match api_client.put_origin_key(public_key.named_revision().name(),
public_key.named_revision().revision(),
&public_keyfile,
token,
ui.progress())
.await
{
Ok(()) => ui.status(Status::Uploaded, public_key.named_revision())?,
Err(api_client::Error::APIError(StatusCode::CONFLICT, _)) => {
ui.status(Status::Using,
format!("public key revision {} which already exists in the depot",
public_key.named_revision()))?;
}
Err(err) => return Err(Error::from(err)),
}
ui.end(format!("Upload of public origin key {} complete.",
public_key.named_revision()))?;
if with_secret {
// get matching secret key
let secret_key: SecretOriginSigningKey =
key_cache.secret_signing_key(public_key.named_revision())?;
let secret_keyfile = key_cache.path_in_cache(&secret_key);
ui.status(Status::Uploading, secret_keyfile.display())?;
match api_client.put_origin_secret_key(secret_key.named_revision().name(),
secret_key.named_revision().revision(),
&secret_keyfile,
token,
ui.progress())
.await
{
Ok(()) => {
ui.status(Status::Uploaded, secret_key.named_revision())?;
ui.end(format!("Upload of secret origin key {} complete.",
secret_key.named_revision()))?;
}
Err(e) => {<|fim▁hole|> }
}
}
Ok(())
}<|fim▁end|>
|
return Err(Error::APIClient(e));
|
<|file_name|>daemon.go<|end_file_name|><|fim▁begin|>package daemon
import (
"fmt"
"io"
"io/ioutil"
"os"
"path"
"regexp"
"runtime"
"strings"
"sync"
"time"
"github.com/docker/libcontainer/label"
"github.com/docker/docker/archive"
"github.com/docker/docker/daemon/execdriver"
"github.com/docker/docker/daemon/execdriver/execdrivers"
"github.com/docker/docker/daemon/execdriver/lxc"
"github.com/docker/docker/daemon/graphdriver"
_ "github.com/docker/docker/daemon/graphdriver/vfs"
_ "github.com/docker/docker/daemon/networkdriver/bridge"
"github.com/docker/docker/daemon/networkdriver/portallocator"
"github.com/docker/docker/dockerversion"
"github.com/docker/docker/engine"
"github.com/docker/docker/graph"
"github.com/docker/docker/image"
"github.com/docker/docker/pkg/broadcastwriter"
"github.com/docker/docker/pkg/graphdb"
"github.com/docker/docker/pkg/log"
"github.com/docker/docker/pkg/namesgenerator"
"github.com/docker/docker/pkg/networkfs/resolvconf"
"github.com/docker/docker/pkg/parsers"
"github.com/docker/docker/pkg/parsers/kernel"
"github.com/docker/docker/pkg/sysinfo"
"github.com/docker/docker/pkg/truncindex"
"github.com/docker/docker/runconfig"
"github.com/docker/docker/utils"
)
var (
DefaultDns = []string{"8.8.8.8", "8.8.4.4"}
validContainerNameChars = `[a-zA-Z0-9_.-]`
validContainerNamePattern = regexp.MustCompile(`^/?` + validContainerNameChars + `+$`)
)
type contStore struct {
s map[string]*Container
sync.Mutex
}
func (c *contStore) Add(id string, cont *Container) {
c.Lock()
c.s[id] = cont
c.Unlock()
}
func (c *contStore) Get(id string) *Container {
c.Lock()
res := c.s[id]
c.Unlock()
return res
}
func (c *contStore) Delete(id string) {
c.Lock()
delete(c.s, id)
c.Unlock()
}
func (c *contStore) List() []*Container {
containers := new(History)
c.Lock()
for _, cont := range c.s {
containers.Add(cont)
}
c.Unlock()
containers.Sort()
return *containers
}
type Daemon struct {
repository string
sysInitPath string
containers *contStore
graph *graph.Graph
repositories *graph.TagStore
idIndex *truncindex.TruncIndex
sysInfo *sysinfo.SysInfo
volumes *graph.Graph
eng *engine.Engine
config *Config
containerGraph *graphdb.Database
driver graphdriver.Driver
execDriver execdriver.Driver
}
// Install installs daemon capabilities to eng.
func (daemon *Daemon) Install(eng *engine.Engine) error {
// FIXME: rename "delete" to "rm" for consistency with the CLI command
// FIXME: rename ContainerDestroy to ContainerRm for consistency with the CLI command
// FIXME: remove ImageDelete's dependency on Daemon, then move to graph/
for name, method := range map[string]engine.Handler{
"attach": daemon.ContainerAttach,
"build": daemon.CmdBuild,
"commit": daemon.ContainerCommit,
"container_changes": daemon.ContainerChanges,
"container_copy": daemon.ContainerCopy,
"container_inspect": daemon.ContainerInspect,
"containers": daemon.Containers,
"create": daemon.ContainerCreate,
"delete": daemon.ContainerDestroy,
"export": daemon.ContainerExport,
"info": daemon.CmdInfo,
"kill": daemon.ContainerKill,
"logs": daemon.ContainerLogs,
"pause": daemon.ContainerPause,
"resize": daemon.ContainerResize,
"restart": daemon.ContainerRestart,
"start": daemon.ContainerStart,
"stop": daemon.ContainerStop,
"top": daemon.ContainerTop,
"unpause": daemon.ContainerUnpause,
"wait": daemon.ContainerWait,
"image_delete": daemon.ImageDelete, // FIXME: see above
} {
if err := eng.Register(name, method); err != nil {
return err
}
}
if err := daemon.Repositories().Install(eng); err != nil {
return err
}
// FIXME: this hack is necessary for legacy integration tests to access
// the daemon object.
eng.Hack_SetGlobalVar("httpapi.daemon", daemon)
return nil
}
// Get looks for a container by the specified ID or name, and returns it.
// If the container is not found, or if an error occurs, nil is returned.
func (daemon *Daemon) Get(name string) *Container {
if id, err := daemon.idIndex.Get(name); err == nil {
return daemon.containers.Get(id)
}
if c, _ := daemon.GetByName(name); c != nil {
return c
}
return nil
}
// Exists returns a true if a container of the specified ID or name exists,
// false otherwise.
func (daemon *Daemon) Exists(id string) bool {
return daemon.Get(id) != nil
}
func (daemon *Daemon) containerRoot(id string) string {
return path.Join(daemon.repository, id)
}
// Load reads the contents of a container from disk
// This is typically done at startup.
func (daemon *Daemon) load(id string) (*Container, error) {
container := &Container{root: daemon.containerRoot(id), State: NewState()}
if err := container.FromDisk(); err != nil {
return nil, err
}
if container.ID != id {
return container, fmt.Errorf("Container %s is stored at %s", container.ID, id)
}
container.readHostConfig()
return container, nil
}
// Register makes a container object usable by the daemon as <container.ID>
// This is a wrapper for register
func (daemon *Daemon) Register(container *Container) error {
return daemon.register(container, true)
}
// register makes a container object usable by the daemon as <container.ID>
func (daemon *Daemon) register(container *Container, updateSuffixarray bool) error {
if container.daemon != nil || daemon.Exists(container.ID) {
return fmt.Errorf("Container is already loaded")
}
if err := validateID(container.ID); err != nil {
return err
}
if err := daemon.ensureName(container); err != nil {
return err
}
container.daemon = daemon
// Attach to stdout and stderr
container.stderr = broadcastwriter.New()
container.stdout = broadcastwriter.New()
// Attach to stdin
if container.Config.OpenStdin {
container.stdin, container.stdinPipe = io.Pipe()
} else {
container.stdinPipe = utils.NopWriteCloser(ioutil.Discard) // Silently drop stdin
}
// done
daemon.containers.Add(container.ID, container)
// don't update the Suffixarray if we're starting up
// we'll waste time if we update it for every container
daemon.idIndex.Add(container.ID)
// FIXME: if the container is supposed to be running but is not, auto restart it?
// if so, then we need to restart monitor and init a new lock
// If the container is supposed to be running, make sure of it
if container.State.IsRunning() {
log.Debugf("killing old running container %s", container.ID)
existingPid := container.State.Pid
container.State.SetStopped(0)
// We only have to handle this for lxc because the other drivers will ensure that
// no processes are left when docker dies
if container.ExecDriver == "" || strings.Contains(container.ExecDriver, "lxc") {
lxc.KillLxc(container.ID, 9)
} else {
// use the current driver and ensure that the container is dead x.x
cmd := &execdriver.Command{
ID: container.ID,
}
var err error
cmd.Process, err = os.FindProcess(existingPid)
if err != nil {
log.Debugf("cannot find existing process for %d", existingPid)
}
daemon.execDriver.Terminate(cmd)
}
if err := container.Unmount(); err != nil {
log.Debugf("unmount error %s", err)
}
if err := container.ToDisk(); err != nil {
log.Debugf("saving stopped state to disk %s", err)
}
info := daemon.execDriver.Info(container.ID)
if !info.IsRunning() {
log.Debugf("Container %s was supposed to be running but is not.", container.ID)
log.Debugf("Marking as stopped")
container.State.SetStopped(-127)
if err := container.ToDisk(); err != nil {
return err
}
}
}
return nil
}
func (daemon *Daemon) ensureName(container *Container) error {
if container.Name == "" {
name, err := daemon.generateNewName(container.ID)
if err != nil {
return err
}
container.Name = name
if err := container.ToDisk(); err != nil {
log.Debugf("Error saving container name %s", err)
}
}
return nil
}
func (daemon *Daemon) LogToDisk(src *broadcastwriter.BroadcastWriter, dst, stream string) error {
log, err := os.OpenFile(dst, os.O_RDWR|os.O_APPEND|os.O_CREATE, 0600)
if err != nil {
return err
}
src.AddWriter(log, stream)
return nil
}
func (daemon *Daemon) restore() error {
var (
debug = (os.Getenv("DEBUG") != "" || os.Getenv("TEST") != "")
containers = make(map[string]*Container)
currentDriver = daemon.driver.String()
)
if !debug {
log.Infof("Loading containers: ")
}
dir, err := ioutil.ReadDir(daemon.repository)
if err != nil {
return err
}
for _, v := range dir {
id := v.Name()
container, err := daemon.load(id)
if !debug {
fmt.Print(".")
}
if err != nil {
log.Errorf("Failed to load container %v: %v", id, err)
continue
}
// Ignore the container if it does not support the current driver being used by the graph
if (container.Driver == "" && currentDriver == "aufs") || container.Driver == currentDriver {
log.Debugf("Loaded container %v", container.ID)
containers[container.ID] = container
} else {
log.Debugf("Cannot load container %s because it was created with another graph driver.", container.ID)
}
}
registeredContainers := []*Container{}
if entities := daemon.containerGraph.List("/", -1); entities != nil {
for _, p := range entities.Paths() {
if !debug {
fmt.Print(".")
}
e := entities[p]
if container, ok := containers[e.ID()]; ok {
if err := daemon.register(container, false); err != nil {
log.Debugf("Failed to register container %s: %s", container.ID, err)
}
registeredContainers = append(registeredContainers, container)
// delete from the map so that a new name is not automatically generated
delete(containers, e.ID())
}
}
}
// Any containers that are left over do not exist in the graph
for _, container := range containers {
// Try to set the default name for a container if it exists prior to links
container.Name, err = daemon.generateNewName(container.ID)
if err != nil {
log.Debugf("Setting default id - %s", err)
}
if err := daemon.register(container, false); err != nil {
log.Debugf("Failed to register container %s: %s", container.ID, err)
}
registeredContainers = append(registeredContainers, container)
}
// check the restart policy on the containers and restart any container with
// the restart policy of "always"
if daemon.config.AutoRestart {
log.Debugf("Restarting containers...")
for _, container := range registeredContainers {
if container.hostConfig.RestartPolicy.Name == "always" ||
(container.hostConfig.RestartPolicy.Name == "on-failure" && container.State.ExitCode != 0) {
log.Debugf("Starting container %s", container.ID)
if err := container.Start(); err != nil {
log.Debugf("Failed to start container %s: %s", container.ID, err)
}
}
}
}
if !debug {
log.Infof(": done.")
}
return nil
}
func (daemon *Daemon) checkDeprecatedExpose(config *runconfig.Config) bool {
if config != nil {
if config.PortSpecs != nil {
for _, p := range config.PortSpecs {
if strings.Contains(p, ":") {
return true
}
}
}
}
return false
}
func (daemon *Daemon) mergeAndVerifyConfig(config *runconfig.Config, img *image.Image) ([]string, error) {
warnings := []string{}
if daemon.checkDeprecatedExpose(img.Config) || daemon.checkDeprecatedExpose(config) {
warnings = append(warnings, "The mapping to public ports on your host via Dockerfile EXPOSE (host:port:port) has been deprecated. Use -p to publish the ports.")
}
if img.Config != nil {
if err := runconfig.Merge(config, img.Config); err != nil {
return nil, err
}
}
if len(config.Entrypoint) == 0 && len(config.Cmd) == 0 {
return nil, fmt.Errorf("No command specified")
}
return warnings, nil
}
func (daemon *Daemon) generateIdAndName(name string) (string, string, error) {
var (
err error
id = utils.GenerateRandomID()
)
if name == "" {
if name, err = daemon.generateNewName(id); err != nil {
return "", "", err
}
return id, name, nil
}
if name, err = daemon.reserveName(id, name); err != nil {
return "", "", err
}
return id, name, nil
}
func (daemon *Daemon) reserveName(id, name string) (string, error) {
if !validContainerNamePattern.MatchString(name) {
return "", fmt.Errorf("Invalid container name (%s), only %s are allowed", name, validContainerNameChars)
}
if name[0] != '/' {
name = "/" + name
}
if _, err := daemon.containerGraph.Set(name, id); err != nil {
if !graphdb.IsNonUniqueNameError(err) {
return "", err
}
conflictingContainer, err := daemon.GetByName(name)
if err != nil {
if strings.Contains(err.Error(), "Could not find entity") {
return "", err
}
// Remove name and continue starting the container
if err := daemon.containerGraph.Delete(name); err != nil {
return "", err
}
} else {
nameAsKnownByUser := strings.TrimPrefix(name, "/")
return "", fmt.Errorf(
"Conflict, The name %s is already assigned to %s. You have to delete (or rename) that container to be able to assign %s to a container again.", nameAsKnownByUser,
utils.TruncateID(conflictingContainer.ID), nameAsKnownByUser)
}
}
return name, nil
}
func (daemon *Daemon) generateNewName(id string) (string, error) {
var name string
for i := 0; i < 6; i++ {
name = namesgenerator.GetRandomName(i)
if name[0] != '/' {
name = "/" + name
}
if _, err := daemon.containerGraph.Set(name, id); err != nil {
if !graphdb.IsNonUniqueNameError(err) {
return "", err
}
continue
}
return name, nil
}
name = "/" + utils.TruncateID(id)
if _, err := daemon.containerGraph.Set(name, id); err != nil {
return "", err
}
return name, nil
}
func (daemon *Daemon) generateHostname(id string, config *runconfig.Config) {
// Generate default hostname
// FIXME: the lxc template no longer needs to set a default hostname
if config.Hostname == "" {
config.Hostname = id[:12]
}
}
func (daemon *Daemon) getEntrypointAndArgs(config *runconfig.Config) (string, []string) {
var (
entrypoint string
args []string
)
if len(config.Entrypoint) != 0 {
entrypoint = config.Entrypoint[0]
args = append(config.Entrypoint[1:], config.Cmd...)
} else {
entrypoint = config.Cmd[0]
args = config.Cmd[1:]
}
return entrypoint, args
}
func (daemon *Daemon) newContainer(name string, config *runconfig.Config, img *image.Image) (*Container, error) {
var (
id string
err error
)
id, name, err = daemon.generateIdAndName(name)
if err != nil {
return nil, err
}
daemon.generateHostname(id, config)
entrypoint, args := daemon.getEntrypointAndArgs(config)
container := &Container{
// FIXME: we should generate the ID here instead of receiving it as an argument
ID: id,
Created: time.Now().UTC(),
Path: entrypoint,
Args: args, //FIXME: de-duplicate from config
Config: config,
hostConfig: &runconfig.HostConfig{},
Image: img.ID, // Always use the resolved image id
NetworkSettings: &NetworkSettings{},
Name: name,
Driver: daemon.driver.String(),
ExecDriver: daemon.execDriver.Name(),
State: NewState(),
}
container.root = daemon.containerRoot(container.ID)
if container.ProcessLabel, container.MountLabel, err = label.GenLabels(""); err != nil {
return nil, err
}
return container, nil
}
func (daemon *Daemon) createRootfs(container *Container, img *image.Image) error {
// Step 1: create the container directory.
// This doubles as a barrier to avoid race conditions.
if err := os.Mkdir(container.root, 0700); err != nil {
return err
}
initID := fmt.Sprintf("%s-init", container.ID)
if err := daemon.driver.Create(initID, img.ID); err != nil {
return err
}
initPath, err := daemon.driver.Get(initID, "")
if err != nil {
return err
}
defer daemon.driver.Put(initID)
if err := graph.SetupInitLayer(initPath); err != nil {
return err
}
if err := daemon.driver.Create(container.ID, initID); err != nil {
return err
}
return nil
}
func GetFullContainerName(name string) (string, error) {
if name == "" {
return "", fmt.Errorf("Container name cannot be empty")
}
if name[0] != '/' {
name = "/" + name
}
return name, nil
}
func (daemon *Daemon) GetByName(name string) (*Container, error) {
fullName, err := GetFullContainerName(name)
if err != nil {
return nil, err
}
entity := daemon.containerGraph.Get(fullName)
if entity == nil {
return nil, fmt.Errorf("Could not find entity for %s", name)
}
e := daemon.containers.Get(entity.ID())
if e == nil {
return nil, fmt.Errorf("Could not find container for entity id %s", entity.ID())
}
return e, nil
}
func (daemon *Daemon) Children(name string) (map[string]*Container, error) {
name, err := GetFullContainerName(name)
if err != nil {
return nil, err
}
children := make(map[string]*Container)
err = daemon.containerGraph.Walk(name, func(p string, e *graphdb.Entity) error {
c := daemon.Get(e.ID())
if c == nil {
return fmt.Errorf("Could not get container for name %s and id %s", e.ID(), p)
}
children[p] = c
return nil
}, 0)
if err != nil {
return nil, err
}
return children, nil
}
func (daemon *Daemon) RegisterLink(parent, child *Container, alias string) error {
fullName := path.Join(parent.Name, alias)
if !daemon.containerGraph.Exists(fullName) {
_, err := daemon.containerGraph.Set(fullName, child.ID)
return err
}
return nil
}
func (daemon *Daemon) RegisterLinks(container *Container, hostConfig *runconfig.HostConfig) error {
if hostConfig != nil && hostConfig.Links != nil {
for _, l := range hostConfig.Links {
parts, err := parsers.PartParser("name:alias", l)
if err != nil {
return err
}
child, err := daemon.GetByName(parts["name"])
if err != nil {
return err
}
if child == nil {
return fmt.Errorf("Could not get container for %s", parts["name"])
}
if err := daemon.RegisterLink(container, child, parts["alias"]); err != nil {
return err
}
}
// After we load all the links into the daemon
// set them to nil on the hostconfig
hostConfig.Links = nil
if err := container.WriteHostConfig(); err != nil {
return err
}
}
return nil
}
// FIXME: harmonize with NewGraph()
func NewDaemon(config *Config, eng *engine.Engine) (*Daemon, error) {
daemon, err := NewDaemonFromDirectory(config, eng)
if err != nil {
return nil, err
}
return daemon, nil
}
func NewDaemonFromDirectory(config *Config, eng *engine.Engine) (*Daemon, error) {
// Apply configuration defaults
if config.Mtu == 0 {
// FIXME: GetDefaultNetwork Mtu doesn't need to be public anymore
config.Mtu = GetDefaultNetworkMtu()
}
// Check for mutually incompatible config options
if config.BridgeIface != "" && config.BridgeIP != "" {
return nil, fmt.Errorf("You specified -b & --bip, mutually exclusive options. Please specify only one.")
}
if !config.EnableIptables && !config.InterContainerCommunication {
return nil, fmt.Errorf("You specified --iptables=false with --icc=false. ICC uses iptables to function. Please set --icc or --iptables to true.")
}
// FIXME: DisableNetworkBidge doesn't need to be public anymore
config.DisableNetwork = config.BridgeIface == DisableNetworkBridge
// Claim the pidfile first, to avoid any and all unexpected race conditions.
// Some of the init doesn't need a pidfile lock - but let's not try to be smart.
if config.Pidfile != "" {
if err := utils.CreatePidFile(config.Pidfile); err != nil {
return nil, err
}
eng.OnShutdown(func() {
// Always release the pidfile last, just in case
utils.RemovePidFile(config.Pidfile)
})
}
// Check that the system is supported and we have sufficient privileges
// FIXME: return errors instead of calling Fatal
if runtime.GOOS != "linux" {
log.Fatalf("The Docker daemon is only supported on linux")
}
if os.Geteuid() != 0 {
log.Fatalf("The Docker daemon needs to be run as root")
}
if err := checkKernelAndArch(); err != nil {
log.Fatalf(err.Error())
}
// set up the TempDir to use a canonical path
tmp, err := utils.TempDir(config.Root)
if err != nil {
log.Fatalf("Unable to get the TempDir under %s: %s", config.Root, err)
}
realTmp, err := utils.ReadSymlinkedDirectory(tmp)
if err != nil {
log.Fatalf("Unable to get the full path to the TempDir (%s): %s", tmp, err)
}
os.Setenv("TMPDIR", realTmp)
if !config.EnableSelinuxSupport {
selinuxSetDisabled()
}
// get the canonical path to the Docker root directory
var realRoot string
if _, err := os.Stat(config.Root); err != nil && os.IsNotExist(err) {
realRoot = config.Root
} else {
realRoot, err = utils.ReadSymlinkedDirectory(config.Root)
if err != nil {
log.Fatalf("Unable to get the full path to root (%s): %s", config.Root, err)
}
}
config.Root = realRoot
// Create the root directory if it doesn't exists
if err := os.MkdirAll(config.Root, 0700); err != nil && !os.IsExist(err) {
return nil, err
}
// Set the default driver
graphdriver.DefaultDriver = config.GraphDriver
// Load storage driver
driver, err := graphdriver.New(config.Root, config.GraphOptions)
if err != nil {
return nil, err
}
log.Debugf("Using graph driver %s", driver)
// As Docker on btrfs and SELinux are incompatible at present, error on both being enabled
if config.EnableSelinuxSupport && driver.String() == "btrfs" {
return nil, fmt.Errorf("SELinux is not supported with the BTRFS graph driver!")
}
daemonRepo := path.Join(config.Root, "containers")
if err := os.MkdirAll(daemonRepo, 0700); err != nil && !os.IsExist(err) {
return nil, err
}
// Migrate the container if it is aufs and aufs is enabled
if err = migrateIfAufs(driver, config.Root); err != nil {
return nil, err
}
log.Debugf("Creating images graph")
g, err := graph.NewGraph(path.Join(config.Root, "graph"), driver)
if err != nil {
return nil, err
}
// We don't want to use a complex driver like aufs or devmapper
// for volumes, just a plain filesystem
volumesDriver, err := graphdriver.GetDriver("vfs", config.Root, config.GraphOptions)
if err != nil {
return nil, err
}
log.Debugf("Creating volumes graph")
volumes, err := graph.NewGraph(path.Join(config.Root, "volumes"), volumesDriver)
if err != nil {
return nil, err
}
log.Debugf("Creating repository list")
repositories, err := graph.NewTagStore(path.Join(config.Root, "repositories-"+driver.String()), g)
if err != nil {
return nil, fmt.Errorf("Couldn't create Tag store: %s", err)
}
if !config.DisableNetwork {
job := eng.Job("init_networkdriver")
job.SetenvBool("EnableIptables", config.EnableIptables)
job.SetenvBool("InterContainerCommunication", config.InterContainerCommunication)
job.SetenvBool("EnableIpForward", config.EnableIpForward)
job.Setenv("BridgeIface", config.BridgeIface)
job.Setenv("BridgeIP", config.BridgeIP)
job.Setenv("DefaultBindingIP", config.DefaultIp.String())
if err := job.Run(); err != nil {
return nil, err
}
}
graphdbPath := path.Join(config.Root, "linkgraph.db")
graph, err := graphdb.NewSqliteConn(graphdbPath)
if err != nil {
return nil, err
}
localCopy := path.Join(config.Root, "init", fmt.Sprintf("dockerinit-%s", dockerversion.VERSION))
sysInitPath := utils.DockerInitPath(localCopy)
if sysInitPath == "" {
return nil, fmt.Errorf("Could not locate dockerinit: This usually means docker was built incorrectly. See http://docs.docker.com/contributing/devenvironment for official build instructions.")
}
if sysInitPath != localCopy {
// When we find a suitable dockerinit binary (even if it's our local binary), we copy it into config.Root at localCopy for future use (so that the original can go away without that being a problem, for example during a package upgrade).
if err := os.Mkdir(path.Dir(localCopy), 0700); err != nil && !os.IsExist(err) {
return nil, err
}
if _, err := utils.CopyFile(sysInitPath, localCopy); err != nil {
return nil, err
}
if err := os.Chmod(localCopy, 0700); err != nil {
return nil, err
}
sysInitPath = localCopy
}
sysInfo := sysinfo.New(false)
ed, err := execdrivers.NewDriver(config.ExecDriver, config.Root, sysInitPath, sysInfo)
if err != nil {
return nil, err
}
daemon := &Daemon{
repository: daemonRepo,
containers: &contStore{s: make(map[string]*Container)},
graph: g,
repositories: repositories,
idIndex: truncindex.NewTruncIndex([]string{}),
sysInfo: sysInfo,
volumes: volumes,
config: config,
containerGraph: graph,
driver: driver,
sysInitPath: sysInitPath,
execDriver: ed,
eng: eng,
}
if err := daemon.checkLocaldns(); err != nil {
return nil, err
}
if err := daemon.restore(); err != nil {
return nil, err
}
// Setup shutdown handlers
// FIXME: can these shutdown handlers be registered closer to their source?
eng.OnShutdown(func() {
// FIXME: if these cleanup steps can be called concurrently, register
// them as separate handlers to speed up total shutdown time
// FIXME: use engine logging instead of log.Errorf
if err := daemon.shutdown(); err != nil {
log.Errorf("daemon.shutdown(): %s", err)
}
if err := portallocator.ReleaseAll(); err != nil {
log.Errorf("portallocator.ReleaseAll(): %s", err)
}
if err := daemon.driver.Cleanup(); err != nil {
log.Errorf("daemon.driver.Cleanup(): %s", err.Error())
}
if err := daemon.containerGraph.Close(); err != nil {
log.Errorf("daemon.containerGraph.Close(): %s", err.Error())
}
})
return daemon, nil
}
func (daemon *Daemon) shutdown() error {
group := sync.WaitGroup{}
log.Debugf("starting clean shutdown of all containers...")
for _, container := range daemon.List() {
c := container
if c.State.IsRunning() {
log.Debugf("stopping %s", c.ID)
group.Add(1)
go func() {
defer group.Done()
if err := c.KillSig(15); err != nil {
log.Debugf("kill 15 error for %s - %s", c.ID, err)
}
c.State.WaitStop(-1 * time.Second)
log.Debugf("container stopped %s", c.ID)
}()
}
}
group.Wait()
return nil
}
func (daemon *Daemon) Mount(container *Container) error {
dir, err := daemon.driver.Get(container.ID, container.GetMountLabel())
if err != nil {
return fmt.Errorf("Error getting container %s from driver %s: %s", container.ID, daemon.driver, err)
}
if container.basefs == "" {
container.basefs = dir
} else if container.basefs != dir {
return fmt.Errorf("Error: driver %s is returning inconsistent paths for container %s ('%s' then '%s')",
daemon.driver, container.ID, container.basefs, dir)
}
return nil
}
func (daemon *Daemon) Unmount(container *Container) error {
daemon.driver.Put(container.ID)
return nil
}
func (daemon *Daemon) Changes(container *Container) ([]archive.Change, error) {
if differ, ok := daemon.driver.(graphdriver.Differ); ok {
return differ.Changes(container.ID)
}
cDir, err := daemon.driver.Get(container.ID, "")
if err != nil {
return nil, fmt.Errorf("Error getting container rootfs %s from driver %s: %s", container.ID, container.daemon.driver, err)
}
defer daemon.driver.Put(container.ID)
initDir, err := daemon.driver.Get(container.ID+"-init", "")
if err != nil {
return nil, fmt.Errorf("Error getting container init rootfs %s from driver %s: %s", container.ID, container.daemon.driver, err)
}
defer daemon.driver.Put(container.ID + "-init")
return archive.ChangesDirs(cDir, initDir)
}
func (daemon *Daemon) Diff(container *Container) (archive.Archive, error) {
if differ, ok := daemon.driver.(graphdriver.Differ); ok {
return differ.Diff(container.ID)
}
changes, err := daemon.Changes(container)
if err != nil {
return nil, err
}
cDir, err := daemon.driver.Get(container.ID, "")
if err != nil {<|fim▁hole|> archive, err := archive.ExportChanges(cDir, changes)
if err != nil {
return nil, err
}
return utils.NewReadCloserWrapper(archive, func() error {
err := archive.Close()
daemon.driver.Put(container.ID)
return err
}), nil
}
func (daemon *Daemon) Run(c *Container, pipes *execdriver.Pipes, startCallback execdriver.StartCallback) (int, error) {
return daemon.execDriver.Run(c.command, pipes, startCallback)
}
func (daemon *Daemon) Pause(c *Container) error {
if err := daemon.execDriver.Pause(c.command); err != nil {
return err
}
c.State.SetPaused()
return nil
}
func (daemon *Daemon) Unpause(c *Container) error {
if err := daemon.execDriver.Unpause(c.command); err != nil {
return err
}
c.State.SetUnpaused()
return nil
}
func (daemon *Daemon) Kill(c *Container, sig int) error {
return daemon.execDriver.Kill(c.command, sig)
}
// Nuke kills all containers then removes all content
// from the content root, including images, volumes and
// container filesystems.
// Again: this will remove your entire docker daemon!
// FIXME: this is deprecated, and only used in legacy
// tests. Please remove.
func (daemon *Daemon) Nuke() error {
var wg sync.WaitGroup
for _, container := range daemon.List() {
wg.Add(1)
go func(c *Container) {
c.Kill()
wg.Done()
}(container)
}
wg.Wait()
return os.RemoveAll(daemon.config.Root)
}
// FIXME: this is a convenience function for integration tests
// which need direct access to daemon.graph.
// Once the tests switch to using engine and jobs, this method
// can go away.
func (daemon *Daemon) Graph() *graph.Graph {
return daemon.graph
}
func (daemon *Daemon) Repositories() *graph.TagStore {
return daemon.repositories
}
func (daemon *Daemon) Config() *Config {
return daemon.config
}
func (daemon *Daemon) SystemConfig() *sysinfo.SysInfo {
return daemon.sysInfo
}
func (daemon *Daemon) SystemInitPath() string {
return daemon.sysInitPath
}
func (daemon *Daemon) GraphDriver() graphdriver.Driver {
return daemon.driver
}
func (daemon *Daemon) ExecutionDriver() execdriver.Driver {
return daemon.execDriver
}
func (daemon *Daemon) Volumes() *graph.Graph {
return daemon.volumes
}
func (daemon *Daemon) ContainerGraph() *graphdb.Database {
return daemon.containerGraph
}
func (daemon *Daemon) checkLocaldns() error {
resolvConf, err := resolvconf.Get()
if err != nil {
return err
}
if len(daemon.config.Dns) == 0 && utils.CheckLocalDns(resolvConf) {
log.Infof("Local (127.0.0.1) DNS resolver found in resolv.conf and containers can't use it. Using default external servers : %v", DefaultDns)
daemon.config.Dns = DefaultDns
}
return nil
}
func (daemon *Daemon) ImageGetCached(imgID string, config *runconfig.Config) (*image.Image, error) {
// Retrieve all images
images, err := daemon.Graph().Map()
if err != nil {
return nil, err
}
// Store the tree in a map of map (map[parentId][childId])
imageMap := make(map[string]map[string]struct{})
for _, img := range images {
if _, exists := imageMap[img.Parent]; !exists {
imageMap[img.Parent] = make(map[string]struct{})
}
imageMap[img.Parent][img.ID] = struct{}{}
}
// Loop on the children of the given image and check the config
var match *image.Image
for elem := range imageMap[imgID] {
img, err := daemon.Graph().Get(elem)
if err != nil {
return nil, err
}
if runconfig.Compare(&img.ContainerConfig, config) {
if match == nil || match.Created.Before(img.Created) {
match = img
}
}
}
return match, nil
}
func checkKernelAndArch() error {
// Check for unsupported architectures
if runtime.GOARCH != "amd64" {
return fmt.Errorf("The Docker runtime currently only supports amd64 (not %s). This will change in the future. Aborting.", runtime.GOARCH)
}
// Check for unsupported kernel versions
// FIXME: it would be cleaner to not test for specific versions, but rather
// test for specific functionalities.
// Unfortunately we can't test for the feature "does not cause a kernel panic"
// without actually causing a kernel panic, so we need this workaround until
// the circumstances of pre-3.8 crashes are clearer.
// For details see http://github.com/docker/docker/issues/407
if k, err := kernel.GetKernelVersion(); err != nil {
log.Infof("WARNING: %s", err)
} else {
if kernel.CompareKernelVersion(k, &kernel.KernelVersionInfo{Kernel: 3, Major: 8, Minor: 0}) < 0 {
if os.Getenv("DOCKER_NOWARN_KERNEL_VERSION") == "" {
log.Infof("WARNING: You are running linux kernel version %s, which might be unstable running docker. Please upgrade your kernel to 3.8.0.", k.String())
}
}
}
return nil
}<|fim▁end|>
|
return nil, fmt.Errorf("Error getting container rootfs %s from driver %s: %s", container.ID, container.daemon.driver, err)
}
|
<|file_name|>add.rs<|end_file_name|><|fim▁begin|>use std::string::{String};
use std::sync::{Arc};
use std::ops::{Mul, Add};
use math::{Vec2};
use node::{Node, Graph};
use tensor::{Tensor};
fn operation<T>(vec: Vec<Tensor<T>>) -> Tensor<T> where T: Copy + Mul<Output=T> + Add<Output=T> {
let Vec2(x1, y1) = vec[0].dim();
let Vec2(x2, _) = vec[1].dim();
if x1 != 1 && x2 == 1 {
let transform = vec[1].buffer();
Tensor::from_vec(Vec2(x1, y1), vec[0].buffer().iter().enumerate().map(|(i, &x)| x + transform[i % y1]).collect())
} else {
&vec[0] + &vec[1]
}
}
fn operation_prime<T>(gradient: &Tensor<T>, vec: Vec<&Tensor<T>>) -> Vec<Tensor<T>> where T: Copy + Mul<Output=T> + Add<Output=T> {
let Vec2(x1, y1) = vec[0].dim();
let Vec2(x2, _) = vec[1].dim();
if x1 != 1 && x2 == 1 {
let mut vector_grad = Vec::with_capacity(y1);
for i in 0..y1 {
let mut k = gradient.get(Vec2(0, i));
for j in 1..x1 {
k = k + gradient.get(Vec2(j, i));
}
vector_grad.push(k);
}
vec![gradient.clone(), Tensor::from_vec(Vec2(1, y1), vector_grad)]<|fim▁hole|> vec![gradient.clone(), gradient.clone()]
}
}
fn calc_dim(dims: Vec<Vec2>) -> Vec2 {
let Vec2(x1, y1) = dims[0];
let Vec2(x2, y2) = dims[1];
assert!(x1 == 0 && x2 == 1 || x1 == x2);
assert_eq!(y1, y2);
dims[0]
}
pub fn add<T>(node_id: String, a: Arc<Graph<T>>, b: Arc<Graph<T>>) -> Node<T> where T: Copy + Mul<Output=T> + Add<Output=T> {
Node::new(node_id, operation, operation_prime, vec![a, b], calc_dim)
}<|fim▁end|>
|
} else {
|
<|file_name|>match-tag-nullary.rs<|end_file_name|><|fim▁begin|>// Copyright 2012 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.
// error-pattern: mismatched types
enum a { A, }<|fim▁hole|><|fim▁end|>
|
enum b { B, }
fn main() { let x: a = a::A; match x { b::B => { } } }
|
<|file_name|>skirmishpreparationplayeroptions.hpp<|end_file_name|><|fim▁begin|>#ifndef QRW_SKIRMISHPREPARATIONPLAYEROPTIONS_HPP
#define QRW_SKIRMISHPREPARATIONPLAYEROPTIONS_HPP
#include <string>
#include "gui/ng/window.hpp"
namespace namelessgui
{
class LineInput;
}
namespace qrw
{<|fim▁hole|> SkirmishPreparationPlayerOptions();
SkirmishPreparationPlayerOptions(const SkirmishPreparationPlayerOptions&) = delete;
SkirmishPreparationPlayerOptions& operator=(const SkirmishPreparationPlayerOptions&) = delete;
const std::string& getPlayerName();
void setPlayerName(const std::string& name);
private:
namelessgui::LineInput* playerNameInput_;
};
} // namespace qrw
#endif //QRW_SKIRMISHPREPARATIONPLAYEROPTIONS_HPP<|fim▁end|>
|
class SkirmishPreparationPlayerOptions : public namelessgui::Window
{
public:
|
<|file_name|>element.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::types::*;
use dom::bindings::codegen::*;
use dom::bindings::utils::{BindingObject, WrapperCache, CacheableWrapper, Traceable};
use dom::node::ScriptView;
use js::jsapi::{JSContext, JSObject, JSTracer};
macro_rules! generate_cacheable_wrapper(
($name: path, $wrap: path) => (
impl CacheableWrapper for $name {
fn get_wrappercache(&mut self) -> &mut WrapperCache {
self.parent.get_wrappercache()
}
fn wrap_object_shared(@mut self, cx: *JSContext, scope: *JSObject) -> *JSObject {
let mut unused = false;
$wrap(cx, scope, self, &mut unused)
}
}
)
)
macro_rules! generate_binding_object(
($name: path) => (
impl BindingObject for $name {
fn GetParentObject(&self, cx: *JSContext) -> Option<@mut CacheableWrapper> {
self.parent.GetParentObject(cx)
}
}
)
)
macro_rules! generate_traceable(
($name: path) => (
impl Traceable for $name {
fn trace(&self, trc: *mut JSTracer) {
self.parent.trace(trc);
}
}
)
)
generate_cacheable_wrapper!(Comment, CommentBinding::Wrap)
generate_binding_object!(Comment)
generate_traceable!(Comment)
generate_cacheable_wrapper!(DocumentType<ScriptView>, DocumentTypeBinding::Wrap)
generate_binding_object!(DocumentType<ScriptView>)
generate_traceable!(DocumentType<ScriptView>)
generate_cacheable_wrapper!(Text, TextBinding::Wrap)
generate_binding_object!(Text)
generate_traceable!(Text)
generate_cacheable_wrapper!(HTMLHeadElement, HTMLHeadElementBinding::Wrap)
generate_binding_object!(HTMLHeadElement)
generate_traceable!(HTMLHeadElement)
generate_cacheable_wrapper!(HTMLAnchorElement, HTMLAnchorElementBinding::Wrap)
generate_binding_object!(HTMLAnchorElement)
generate_traceable!(HTMLAnchorElement)
generate_cacheable_wrapper!(HTMLAppletElement, HTMLAppletElementBinding::Wrap)
generate_binding_object!(HTMLAppletElement)
generate_traceable!(HTMLAppletElement)
generate_cacheable_wrapper!(HTMLAreaElement, HTMLAreaElementBinding::Wrap)
generate_binding_object!(HTMLAreaElement)
generate_traceable!(HTMLAreaElement)
generate_cacheable_wrapper!(HTMLAudioElement, HTMLAudioElementBinding::Wrap)
generate_binding_object!(HTMLAudioElement)
generate_traceable!(HTMLAudioElement)
generate_cacheable_wrapper!(HTMLBaseElement, HTMLBaseElementBinding::Wrap)
generate_binding_object!(HTMLBaseElement)
generate_traceable!(HTMLBaseElement)
generate_cacheable_wrapper!(HTMLBodyElement, HTMLBodyElementBinding::Wrap)
generate_binding_object!(HTMLBodyElement)
generate_traceable!(HTMLBodyElement)
generate_cacheable_wrapper!(HTMLButtonElement, HTMLButtonElementBinding::Wrap)
generate_binding_object!(HTMLButtonElement)
generate_traceable!(HTMLButtonElement)
generate_cacheable_wrapper!(HTMLCanvasElement, HTMLCanvasElementBinding::Wrap)
generate_binding_object!(HTMLCanvasElement)
generate_traceable!(HTMLCanvasElement)
generate_cacheable_wrapper!(HTMLDataListElement, HTMLDataListElementBinding::Wrap)
generate_binding_object!(HTMLDataListElement)
generate_traceable!(HTMLDataListElement)
generate_cacheable_wrapper!(HTMLDListElement, HTMLDListElementBinding::Wrap)
generate_binding_object!(HTMLDListElement)
generate_traceable!(HTMLDListElement)
generate_cacheable_wrapper!(HTMLFormElement, HTMLFormElementBinding::Wrap)
generate_binding_object!(HTMLFormElement)
generate_traceable!(HTMLFormElement)
generate_cacheable_wrapper!(HTMLFrameElement, HTMLFrameElementBinding::Wrap)
generate_binding_object!(HTMLFrameElement)
generate_traceable!(HTMLFrameElement)
generate_cacheable_wrapper!(HTMLFrameSetElement, HTMLFrameSetElementBinding::Wrap)
generate_binding_object!(HTMLFrameSetElement)
generate_traceable!(HTMLFrameSetElement)
generate_cacheable_wrapper!(HTMLBRElement, HTMLBRElementBinding::Wrap)
generate_binding_object!(HTMLBRElement)
generate_traceable!(HTMLBRElement)
generate_cacheable_wrapper!(HTMLHRElement, HTMLHRElementBinding::Wrap)
generate_binding_object!(HTMLHRElement)
generate_traceable!(HTMLHRElement)
generate_cacheable_wrapper!(HTMLHtmlElement, HTMLHtmlElementBinding::Wrap)
generate_binding_object!(HTMLHtmlElement)
generate_traceable!(HTMLHtmlElement)
generate_cacheable_wrapper!(HTMLDataElement, HTMLDataElementBinding::Wrap)
generate_binding_object!(HTMLDataElement)
generate_traceable!(HTMLDataElement)
generate_cacheable_wrapper!(HTMLDirectoryElement, HTMLDirectoryElementBinding::Wrap)
generate_binding_object!(HTMLDirectoryElement)
generate_traceable!(HTMLDirectoryElement)
generate_cacheable_wrapper!(HTMLDivElement, HTMLDivElementBinding::Wrap)
generate_binding_object!(HTMLDivElement)
generate_traceable!(HTMLDivElement)
generate_cacheable_wrapper!(HTMLEmbedElement, HTMLEmbedElementBinding::Wrap)
generate_binding_object!(HTMLEmbedElement)
generate_traceable!(HTMLEmbedElement)
generate_cacheable_wrapper!(HTMLFieldSetElement, HTMLFieldSetElementBinding::Wrap)
generate_binding_object!(HTMLFieldSetElement)
generate_traceable!(HTMLFieldSetElement)
generate_cacheable_wrapper!(HTMLFontElement, HTMLFontElementBinding::Wrap)
generate_binding_object!(HTMLFontElement)
generate_traceable!(HTMLFontElement)
generate_cacheable_wrapper!(HTMLHeadingElement, HTMLHeadingElementBinding::Wrap)
generate_binding_object!(HTMLHeadingElement)
generate_traceable!(HTMLHeadingElement)
generate_cacheable_wrapper!(HTMLIFrameElement, HTMLIFrameElementBinding::Wrap)
generate_binding_object!(HTMLIFrameElement)
generate_traceable!(HTMLIFrameElement)
generate_cacheable_wrapper!(HTMLImageElement, HTMLImageElementBinding::Wrap)
generate_binding_object!(HTMLImageElement)
generate_traceable!(HTMLImageElement)
generate_cacheable_wrapper!(HTMLInputElement, HTMLInputElementBinding::Wrap)
generate_binding_object!(HTMLInputElement)
generate_traceable!(HTMLInputElement)
generate_cacheable_wrapper!(HTMLLabelElement, HTMLLabelElementBinding::Wrap)
generate_binding_object!(HTMLLabelElement)
generate_traceable!(HTMLLabelElement)
generate_cacheable_wrapper!(HTMLLegendElement, HTMLLegendElementBinding::Wrap)
generate_binding_object!(HTMLLegendElement)
generate_traceable!(HTMLLegendElement)
generate_cacheable_wrapper!(HTMLLIElement, HTMLLIElementBinding::Wrap)
generate_binding_object!(HTMLLIElement)
generate_traceable!(HTMLLIElement)
generate_cacheable_wrapper!(HTMLLinkElement, HTMLLinkElementBinding::Wrap)
generate_binding_object!(HTMLLinkElement)
generate_traceable!(HTMLLinkElement)
generate_cacheable_wrapper!(HTMLMapElement, HTMLMapElementBinding::Wrap)
generate_binding_object!(HTMLMapElement)
generate_traceable!(HTMLMapElement)
generate_cacheable_wrapper!(HTMLMediaElement, HTMLMediaElementBinding::Wrap)
generate_binding_object!(HTMLMediaElement)
generate_traceable!(HTMLMediaElement)
generate_cacheable_wrapper!(HTMLMetaElement, HTMLMetaElementBinding::Wrap)
generate_binding_object!(HTMLMetaElement)
generate_traceable!(HTMLMetaElement)
generate_cacheable_wrapper!(HTMLMeterElement, HTMLMeterElementBinding::Wrap)
generate_binding_object!(HTMLMeterElement)
generate_traceable!(HTMLMeterElement)
generate_cacheable_wrapper!(HTMLModElement, HTMLModElementBinding::Wrap)
generate_binding_object!(HTMLModElement)
generate_traceable!(HTMLModElement)
generate_cacheable_wrapper!(HTMLObjectElement, HTMLObjectElementBinding::Wrap)
generate_binding_object!(HTMLObjectElement)<|fim▁hole|>generate_binding_object!(HTMLOListElement)
generate_traceable!(HTMLOListElement)
generate_cacheable_wrapper!(HTMLOptGroupElement, HTMLOptGroupElementBinding::Wrap)
generate_binding_object!(HTMLOptGroupElement)
generate_traceable!(HTMLOptGroupElement)
generate_cacheable_wrapper!(HTMLOptionElement, HTMLOptionElementBinding::Wrap)
generate_binding_object!(HTMLOptionElement)
generate_traceable!(HTMLOptionElement)
generate_cacheable_wrapper!(HTMLOutputElement, HTMLOutputElementBinding::Wrap)
generate_binding_object!(HTMLOutputElement)
generate_traceable!(HTMLOutputElement)
generate_cacheable_wrapper!(HTMLParagraphElement, HTMLParagraphElementBinding::Wrap)
generate_binding_object!(HTMLParagraphElement)
generate_traceable!(HTMLParagraphElement)
generate_cacheable_wrapper!(HTMLParamElement, HTMLParamElementBinding::Wrap)
generate_binding_object!(HTMLParamElement)
generate_traceable!(HTMLParamElement)
generate_cacheable_wrapper!(HTMLPreElement, HTMLPreElementBinding::Wrap)
generate_binding_object!(HTMLPreElement)
generate_traceable!(HTMLPreElement)
generate_cacheable_wrapper!(HTMLProgressElement, HTMLProgressElementBinding::Wrap)
generate_binding_object!(HTMLProgressElement)
generate_traceable!(HTMLProgressElement)
generate_cacheable_wrapper!(HTMLQuoteElement, HTMLQuoteElementBinding::Wrap)
generate_binding_object!(HTMLQuoteElement)
generate_traceable!(HTMLQuoteElement)
generate_cacheable_wrapper!(HTMLScriptElement, HTMLScriptElementBinding::Wrap)
generate_binding_object!(HTMLScriptElement)
generate_traceable!(HTMLScriptElement)
generate_cacheable_wrapper!(HTMLSelectElement, HTMLSelectElementBinding::Wrap)
generate_binding_object!(HTMLSelectElement)
generate_traceable!(HTMLSelectElement)
generate_cacheable_wrapper!(HTMLSourceElement, HTMLSourceElementBinding::Wrap)
generate_binding_object!(HTMLSourceElement)
generate_traceable!(HTMLSourceElement)
generate_cacheable_wrapper!(HTMLSpanElement, HTMLSpanElementBinding::Wrap)
generate_binding_object!(HTMLSpanElement)
generate_traceable!(HTMLSpanElement)
generate_cacheable_wrapper!(HTMLStyleElement, HTMLStyleElementBinding::Wrap)
generate_binding_object!(HTMLStyleElement)
generate_traceable!(HTMLStyleElement)
generate_cacheable_wrapper!(HTMLTableElement, HTMLTableElementBinding::Wrap)
generate_binding_object!(HTMLTableElement)
generate_traceable!(HTMLTableElement)
generate_cacheable_wrapper!(HTMLTableCaptionElement, HTMLTableCaptionElementBinding::Wrap)
generate_binding_object!(HTMLTableCaptionElement)
generate_traceable!(HTMLTableCaptionElement)
generate_cacheable_wrapper!(HTMLTableCellElement, HTMLTableCellElementBinding::Wrap)
generate_binding_object!(HTMLTableCellElement)
generate_traceable!(HTMLTableCellElement)
generate_cacheable_wrapper!(HTMLTableColElement, HTMLTableColElementBinding::Wrap)
generate_binding_object!(HTMLTableColElement)
generate_traceable!(HTMLTableColElement)
generate_cacheable_wrapper!(HTMLTableRowElement, HTMLTableRowElementBinding::Wrap)
generate_binding_object!(HTMLTableRowElement)
generate_traceable!(HTMLTableRowElement)
generate_cacheable_wrapper!(HTMLTableSectionElement, HTMLTableSectionElementBinding::Wrap)
generate_binding_object!(HTMLTableSectionElement)
generate_traceable!(HTMLTableSectionElement)
generate_cacheable_wrapper!(HTMLTemplateElement, HTMLTemplateElementBinding::Wrap)
generate_binding_object!(HTMLTemplateElement)
generate_traceable!(HTMLTemplateElement)
generate_cacheable_wrapper!(HTMLTextAreaElement, HTMLTextAreaElementBinding::Wrap)
generate_binding_object!(HTMLTextAreaElement)
generate_traceable!(HTMLTextAreaElement)
generate_cacheable_wrapper!(HTMLTitleElement, HTMLTitleElementBinding::Wrap)
generate_binding_object!(HTMLTitleElement)
generate_traceable!(HTMLTitleElement)
generate_cacheable_wrapper!(HTMLTimeElement, HTMLTimeElementBinding::Wrap)
generate_binding_object!(HTMLTimeElement)
generate_traceable!(HTMLTimeElement)
generate_cacheable_wrapper!(HTMLTrackElement, HTMLTrackElementBinding::Wrap)
generate_binding_object!(HTMLTrackElement)
generate_traceable!(HTMLTrackElement)
generate_cacheable_wrapper!(HTMLUListElement, HTMLUListElementBinding::Wrap)
generate_binding_object!(HTMLUListElement)
generate_traceable!(HTMLUListElement)
generate_cacheable_wrapper!(HTMLUnknownElement, HTMLUnknownElementBinding::Wrap)
generate_binding_object!(HTMLUnknownElement)
generate_traceable!(HTMLUnknownElement)
generate_cacheable_wrapper!(HTMLVideoElement, HTMLVideoElementBinding::Wrap)
generate_binding_object!(HTMLVideoElement)
generate_traceable!(HTMLVideoElement)
generate_traceable!(HTMLElement)
generate_traceable!(Element)
generate_traceable!(CharacterData)<|fim▁end|>
|
generate_traceable!(HTMLObjectElement)
generate_cacheable_wrapper!(HTMLOListElement, HTMLOListElementBinding::Wrap)
|
<|file_name|>lib.rs<|end_file_name|><|fim▁begin|>// TODO: work with sfackler and rust-openssl to get this here
<|fim▁hole|><|fim▁end|>
|
pub mod probe;
|
<|file_name|>config.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*-
#
# codimension - graphics python two-way code editor and analyzer
# Copyright (C) 2010-2017 Sergey Satskiy <[email protected]>
#
# 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<|fim▁hole|># 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/>.
#
"""A few constants which do not depend on other project files"""
# Default encoding for the cases when:
# - the encoding could not be detected
# - replaces ascii to be on the safe side
DEFAULT_ENCODING = 'utf-8'
# File encoding used for various settings and project files
SETTINGS_ENCODING = 'utf-8'
# Directory to store Codimension settings and projects
CONFIG_DIR = '.codimension3'<|fim▁end|>
|
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
<|file_name|>utility_positional.py<|end_file_name|><|fim▁begin|>import numpy as np
import cv2
import math
# Calculates rotation matrix to euler angles
# The result is the same as MATLAB except the order
# of the euler angles ( x and z are swapped ).
def rot_vec_to_euler(r):
# Rotate around x axis by 180 degrees to have [0, 0, 0] when facing forward
R = np.dot(np.array([[1, 0, 0],
[0, -1, 0],
[0, 0, -1]]),
np.array(cv2.Rodrigues(r)[0]))
sy = math.sqrt(R[0, 0] * R[0, 0] + R[1, 0] * R[1, 0])
singular = sy < 1e-6
if not singular:
x = math.atan2(R[2, 1], R[2, 2])
y = math.atan2(-R[2, 0], sy)
z = math.atan2(R[1, 0], R[0, 0])
else:
x = math.atan2(-R[1, 2], R[1, 1])
y = math.atan2(-R[2, 0], sy)
z = 0
return np.array([x, y, z])
# Calculates Rotation Matrix given euler angles.
def euler_to_rot_vec(theta):
r_x = np.array([[1, 0, 0],
[0, math.cos(theta[0]), -math.sin(theta[0])],
[0, math.sin(theta[0]), math.cos(theta[0])]
])
r_y = np.array([[math.cos(theta[1]), 0, math.sin(theta[1])],
[0, 1, 0],
[-math.sin(theta[1]), 0, math.cos(theta[1])]
])
r_z = np.array([[math.cos(theta[2]), -math.sin(theta[2]), 0],
[math.sin(theta[2]), math.cos(theta[2]), 0],
[0, 0, 1]
])
return np.array(cv2.Rodrigues(np.dot(np.array([[1, 0, 0],
[0, -1, 0],
[0, 0, -1]]),
np.dot(r_z, np.dot(r_y, r_x))))[0])
class poseExtractor:
def __init__(self):
self.image_points = np.array([30, 29, 28, 27, 33, 32, 34, 31, 35,
36, 45, 39, 42,
21, 22, 20, 23, 19, 24, 18, 25
], dtype=np.intp)
self.model_points = np.array([
(0.0, 0.0, 0.0), # Nose tip
(0.0, 0.40412, -0.35702), # Nose 1
(0.0, 0.87034, -0.65485), # Nose 2
(0, 1.33462, -0.92843), # Nose 3
(0, -0.63441, -0.65887), # Under Nose #0
(0, 0, 0), # Under Nose #1, L
(0.25466, -0.59679, -0.80215), # Under Nose #1, R
(0, 0, 0), # Under Nose #2, L
(0.49277, -0.56169, -0.96709), # Under Nose #2, R
(0, 0, 0), # Left eye outer corner
(1.60745, 1.21855, -1.9585), # Right eye outer corner
(0, 0, 0), # Left eye inner corner
(0.53823, 1.15389, -1.37273), # Right eye inner corner
(0, 0, 0), # Eyebrow #0, L
(0.34309, 1.67208, -0.96486), # Eyebrow #0, R
(0, 0, 0), # Eyebrow #1, L
(0.65806, 1.85405, -1.04975), # Eyebrow #1, R
(0, 0, 0), # Eyebrow #2, L
(0.96421, 1.95277, -1.23015), # Eyebrow #2, R
(0, 0, 0), # Eyebrow #3, L
(1.32075, 1.95305, -1.48482) # Eyebrow #3, R<|fim▁hole|> self.model_points[i, 1:3] = self.model_points[i + 1, 1:3]
self.camera_matrix = None # Hack so camera matrix can be used for printing later
self.dist_coeffs = np.zeros((4, 1)) # Assuming no lens distortion
self.rvec = None
self.tvec = None
def get_head_rotation(self, landmarks, img_size):
# Camera internals
focal_length = img_size[1]
center = (img_size[1] / 2, img_size[0] / 2)
self.camera_matrix = np.array(
[[focal_length, 0, center[0]],
[0, focal_length, center[1]],
[0, 0, 1]], dtype="double"
)
if self.rvec is None:
(success, self.rvec, self.tvec) = cv2.solvePnP(
self.model_points, landmarks[self.image_points[:, np.newaxis], :],
self.camera_matrix, self.dist_coeffs, flags=cv2.SOLVEPNP_EPNP)
else:
(success, self.rvec, self.tvec) = cv2.solvePnP(
self.model_points, landmarks[self.image_points[:, np.newaxis], :],
self.camera_matrix, self.dist_coeffs, flags=cv2.SOLVEPNP_EPNP,
rvec=self.rvec, tvec=self.tvec, useExtrinsicGuess=True)
return success
def get_positional_features(self, landmarks, img_size):
rotation_success = self.get_head_rotation(landmarks, img_size)
if not rotation_success:
return None
return self.tvec, rot_vec_to_euler(self.rvec)
def get_position_by_average(landmarks, img_size):
position = np.mean(landmarks, axis=0)
size = 2 * np.mean(np.linalg.norm((landmarks - position), axis=1, ord=2))
return np.append(position / img_size[0], size / img_size[0])<|fim▁end|>
|
])
for i in range(5, self.model_points.shape[0], 2):
self.model_points[i, 0] = -self.model_points[i + 1, 0]
|
<|file_name|>wire.rs<|end_file_name|><|fim▁begin|>// Copyright lowRISC contributors.
// Licensed under the Apache License, Version 2.0, see LICENSE for details.
// SPDX-License-Identifier: Apache-2.0
// This file was forked from https://github.com/lowRISC/manticore.
//! Wire format traits.
//!
//! This module provides [`FromWire`] and [`ToWire`], a pair of traits similar
//! to the core traits in the [`serde`] library. Rather than representing a
//! generically serializeable type, they represent types that can be converted
//! to and from Cerberus's wire format, which has a unique, ad-hoc data model.
//!
//! [`FromWire`]: trait.FromWire.html
//! [`ToWire`]: trait.ToWire.html
//! [`serde`]: https://serde.rs
use crate::io;
use crate::io::BeInt;
use crate::io::Read;
use crate::io::Write;
/// A type which can be deserialized from the Cerberus wire format.
///
/// The lifetime `'wire` indicates that the type can be deserialized from a
/// buffer of lifetime `'wire`.
pub trait FromWire<'wire>: Sized {
/// Deserializes a `Self` w of `r`.
fn from_wire<R: Read<'wire>>(r: R) -> Result<Self, FromWireError>;
}
/// An deserialization error.
#[derive(Clone, Copy, Debug)]
pub enum FromWireError {
/// Indicates that something went wrong in an `io` operation.
///
/// [`io`]: ../../io/index.html
Io(io::Error),
/// Indicates that some field within the request was outside of its
/// valid range.
OutOfRange,
}
impl From<io::Error> for FromWireError {
fn from(e: io::Error) -> Self {
Self::Io(e)
}
}
/// A type which can be serialized into the Cerberus wire format.
pub trait ToWire: Sized {
/// Serializes `self` into `w`.
fn to_wire<W: Write>(&self, w: W) -> Result<(), ToWireError>;
}
/// A serializerion error.
#[derive(Clone, Copy, Debug)]
pub enum ToWireError {
/// Indicates that something went wrong in an [`io`] operation.
///
/// [`io`]: ../../io/index.html
Io(io::Error),
/// Indicates that the data to be serialized was invalid.
InvalidData,
}
impl From<io::Error> for ToWireError {
fn from(e: io::Error) -> Self {
Self::Io(e)
}
}
/// Represents a C-like enum that can be converted to and from a wire
/// representation as well as to and from a string representation.
///
/// An implementation of this trait can be thought of as an unsigned
/// integer with a limited range: every enum variant can be converted
/// to the wire format and back, though not every value of the wire
/// representation can be converted into an enum variant.
///
/// In particular the following identity must hold for all types T:
/// ```
/// # use spiutils::protocol::wire::WireEnum;
/// # fn test<T: WireEnum + Copy + PartialEq + std::fmt::Debug>(x: T) {
/// assert_eq!(T::from_wire_value(T::to_wire_value(x)), Some(x));
/// # }
/// ```
///
/// Also, the following identity must hold for all types T:
/// ```
/// # use manticore::protocol::wire::WireEnum;
/// # fn test<T: WireEnum + Copy + PartialEq + std::fmt::Debug>(x: T) {
/// assert_eq!(T::from_name(T::name(x)), Some(x));<|fim▁hole|>/// # }
/// ```
pub trait WireEnum: Sized + Copy {
/// The unrelying "wire type". This is almost always some kind of
/// unsigned integer.
type Wire: BeInt;
/// Converts `self` into its underlying wire representation.
fn to_wire_value(self) -> Self::Wire;
/// Attempts to parse a value of `Self` from the underlying wire
/// representation.
fn from_wire_value(wire: Self::Wire) -> Option<Self>;
/// Converts `self` into a string representation.
fn name(self) -> &'static str;
/// Attempts to convert a value of `Self` from a string representation.
fn from_name(str: &str) -> Option<Self>;
}
impl<'wire, E> FromWire<'wire> for E
where
E: WireEnum,
{
fn from_wire<R: Read<'wire>>(mut r: R) -> Result<Self, FromWireError> {
let wire = <Self as WireEnum>::Wire::read_from(&mut r)?;
Self::from_wire_value(wire).ok_or(FromWireError::OutOfRange)
}
}
impl<E> ToWire for E
where
E: WireEnum,
{
fn to_wire<W: Write>(&self, mut w: W) -> Result<(), ToWireError> {
self.to_wire_value().write_to(&mut w)?;
Ok(())
}
}
/// A deserialization-from-string error.
#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash, Default)]
pub struct WireEnumFromStrError;
/// A conveinence macro for generating `WireEnum`-implementing enums.
///
///
/// Syntax is as follows:
/// ```text
/// wire_enum! {
/// /// This is my enum.
/// pub enum MyEnum : u8 {
/// /// Variant `A`.
/// A = 0x00,
/// /// Variant `B`.
/// B = 0x01,
/// }
/// }
/// ```
/// This macro will generate an implementation of `WireEnum<Wire=u8>` for
/// the above enum.
macro_rules! wire_enum {
($(#[$meta:meta])* $vis:vis enum $name:ident : $wire:ident {
$($(#[$meta_variant:meta])* $variant:ident = $value:literal,)*
}) => {
$(#[$meta])*
#[repr($wire)]
#[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Debug)]
$vis enum $name {
$(
$(#[$meta_variant])*
$variant = $value,
)*
}
impl $crate::protocol::wire::WireEnum for $name {
type Wire = $wire;
fn to_wire_value(self) -> Self::Wire {
self as $wire
}
fn from_wire_value(wire: Self::Wire) -> Option<Self> {
match wire {
$(
$value => Some(Self::$variant),
)*
_ => None,
}
}
fn name(self) -> &'static str {
match self {
$(
Self::$variant => stringify!($variant),
)*
}
}
fn from_name(name: &str) -> Option<Self> {
match name {
$(
stringify!($variant) => Some(Self::$variant),
)*
_ => None,
}
}
}
impl core::fmt::Display for $name {
fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result {
use $crate::protocol::wire::WireEnum;
write!(f, "{}", self.name())
}
}
impl core::str::FromStr for $name {
type Err = $crate::protocol::wire::WireEnumFromStrError;
fn from_str(s: &str) -> Result<Self, $crate::protocol::wire::WireEnumFromStrError> {
use $crate::protocol::wire::WireEnum;
match $name::from_name(s) {
Some(val) => Ok(val),
None => Err($crate::protocol::wire::WireEnumFromStrError),
}
}
}
}
}
#[cfg(test)]
mod test {
wire_enum! {
/// An enum for testing.
#[cfg_attr(feature = "arbitrary-derive", derive(Arbitrary))]
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
pub enum DemoEnum: u8 {
/// Unknown value
Unknown = 0x00,
/// First enum value
First = 0x01,
/// Second enum value
Second = 0x02,
}
}
#[test]
fn from_name() {
use crate::protocol::wire::*;
let value = DemoEnum::from_name("Second").expect("from_name failed");
assert_eq!(value, DemoEnum::Second);
let value = DemoEnum::from_name("First").expect("from_name failed");
assert_eq!(value, DemoEnum::First);
assert_eq!(None, DemoEnum::from_name("does not exist"));
}
#[test]
fn name() {
use crate::protocol::wire::*;
assert_eq!(DemoEnum::First.name(), "First");
assert_eq!(DemoEnum::Second.name(), "Second");
}
}<|fim▁end|>
| |
<|file_name|>coverage2text.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python
import sys
from coverage import coverage
from coverage.results import Numbers
from coverage.summary import SummaryReporter
from twisted.python import usage
# this is an adaptation of the code behind "coverage report", modified to
# display+sortby "lines uncovered", which (IMHO) is more important of a
# metric than lines covered or percentage covered. Concentrating on the files
# with the most uncovered lines encourages getting the tree and test suite
# into a state that provides full line-coverage on all files.
# much of this code was adapted from coverage/summary.py in the 'coverage'
# distribution, and is used under their BSD license.
<|fim▁hole|> ]
class MyReporter(SummaryReporter):
def report(self, outfile=None, sortby="uncovered"):
self.find_code_units(None, ["/System", "/Library", "/usr/lib",
"buildbot/test", "simplejson"])
# Prepare the formatting strings
max_name = max([len(cu.name) for cu in self.code_units] + [5])
fmt_name = "%%- %ds " % max_name
fmt_err = "%s %s: %s\n"
header1 = (fmt_name % "") + " Statements "
header2 = (fmt_name % "Name") + " Uncovered Covered"
fmt_coverage = fmt_name + "%9d %7d "
if self.branches:
header1 += " Branches "
header2 += " Found Excutd"
fmt_coverage += " %6d %6d"
header1 += " Percent"
header2 += " Covered"
fmt_coverage += " %7d%%"
if self.show_missing:
header1 += " "
header2 += " Missing"
fmt_coverage += " %s"
rule = "-" * len(header1) + "\n"
header1 += "\n"
header2 += "\n"
fmt_coverage += "\n"
if not outfile:
outfile = sys.stdout
# Write the header
outfile.write(header1)
outfile.write(header2)
outfile.write(rule)
total = Numbers()
total_uncovered = 0
lines = []
for cu in self.code_units:
try:
analysis = self.coverage._analyze(cu)
nums = analysis.numbers
uncovered = nums.n_statements - nums.n_executed
total_uncovered += uncovered
args = (cu.name, uncovered, nums.n_executed)
if self.branches:
args += (nums.n_branches, nums.n_executed_branches)
args += (nums.pc_covered,)
if self.show_missing:
args += (analysis.missing_formatted(),)
if sortby == "covered":
sortkey = nums.pc_covered
elif sortby == "uncovered":
sortkey = uncovered
else:
sortkey = cu.name
lines.append((sortkey, fmt_coverage % args))
total += nums
except KeyboardInterrupt: # pragma: no cover
raise
except:
if not self.ignore_errors:
typ, msg = sys.exc_info()[:2]
outfile.write(fmt_err % (cu.name, typ.__name__, msg))
lines.sort()
if sortby in ("uncovered", "covered"):
lines.reverse()
for sortkey, line in lines:
outfile.write(line)
if total.n_files > 1:
outfile.write(rule)
args = ("TOTAL", total_uncovered, total.n_executed)
if self.branches:
args += (total.n_branches, total.n_executed_branches)
args += (total.pc_covered,)
if self.show_missing:
args += ("",)
outfile.write(fmt_coverage % args)
def report(o):
c = coverage()
c.load()
r = MyReporter(c, show_missing=False, ignore_errors=False)
r.report(sortby=o['sortby'])
if __name__ == '__main__':
o = Options()
o.parseOptions()
report(o)<|fim▁end|>
|
class Options(usage.Options):
optParameters = [
("sortby", "s", "uncovered", "how to sort: uncovered, covered, name"),
|
<|file_name|>csp_font-src_cross-origin_allowed-manual.py<|end_file_name|><|fim▁begin|>def main(request, response):
import simplejson as json
f = file('config.json')
source = f.read()
s = json.JSONDecoder().decode(source)
url1 = "http://" + s['host'] + ":" + str(s['ports']['http'][1])
_CSP = "font-src " + url1
response.headers.set("Content-Security-Policy", _CSP)
response.headers.set("X-Content-Security-Policy", _CSP)
response.headers.set("X-WebKit-CSP", _CSP)
return """<!DOCTYPE html>
<!--
Copyright (c) 2013 Intel Corporation.
Redistribution and use in source and binary forms, with or without modification,
are permitted provided that the following conditions are met:
* Redistributions of works must retain the original copyright notice, this list
of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the original copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
* Neither the name of Intel Corporation nor the names of its contributors
may be used to endorse or promote products derived from this work without
specific prior written permission.
THIS SOFTWARE IS PROVIDED BY INTEL CORPORATION "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL INTEL CORPORATION BE LIABLE FOR ANY DIRECT,
INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,
EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
Authors:
Hao, Yunfei <[email protected]>
-->
<html>
<head>
<title>CSP Test: csp_font-src_cross-origin_allowed</title>
<link rel="author" title="Intel" href="http://www.intel.com"/>
<link rel="help" href="http://www.w3.org/TR/2012/CR-CSP-20121115/#font-src"/>
<meta name="flags" content=""/>
<meta charset="utf-8"/>
<style>
@font-face {
font-family: Canvas;
src: url('""" + url1 + """/tests/csp/support/w3c/CanvasTest.ttf');
}
#test {<|fim▁hole|> </head>
<body>
<p>Test passes if the two lines are different in font</p>
<div id="test">1234 ABCD</div>
<div>1234 ABCD</div>
</body>
</html> """<|fim▁end|>
|
font-family: Canvas;
}
</style>
|
<|file_name|>config.py<|end_file_name|><|fim▁begin|>""" config.py """
import os
from flask import Flask
from peewee import MySQLDatabase, SqliteDatabase
#-------------------------------------------------------------------------------
# Environment
#-------------------------------------------------------------------------------
DB = 'idreamoftoast'
ENV = os.environ.get('TOAST_PRODUCTION', None)<|fim▁hole|>
#-------------------------------------------------------------------------------
# Config Methods
#-------------------------------------------------------------------------------
def get_app():
app = None
# If env is set, we are in production!
if ENV:
app = Flask(__name__)
import logging
file_handler = logging.FileHandler(LOG_PATH + 'flask.log')
file_handler.setLevel(logging.WARNING)
file_handler.setFormatter(logging.Formatter(
'%(asctime)s %(levelname)s: %(message)s '
'[in %(pathname)s:%(lineno)d]'
))
app.logger.addHandler(file_handler)
else:
# Development settings here!
app = Flask(__name__, static_folder='public', static_url_path='')
@app.route("/")
def root():
return app.send_static_file('index.html')
return app
def get_database():
db = None
# If env is set, we are in production!
if ENV:
# Production settings here!
if not (HOST or USER or PASSWD):
import sys
print('Environment variables NOT set!')
sys.exit()
db = MySQLDatabase(DB, host=HOST, user=USER, passwd=PASSWD)
else:
# Development settings here!
db = SqliteDatabase('toast.db')#, threadlocals=True)
return db<|fim▁end|>
|
HOST = os.environ.get('TOAST_HOST', None)
USER = os.environ.get('TOAST_USER', None)
PASSWD = os.environ.get('TOAST_PASSWD', None)
LOG_PATH = os.environ.get('TOAST_LOG_PATH', './')
|
<|file_name|>dynamo-store-doc.js<|end_file_name|><|fim▁begin|>module.exports = function (seneca, util) {<|fim▁hole|> //var Joi = util.Joi
}<|fim▁end|>
| |
<|file_name|>test_sympify.py<|end_file_name|><|fim▁begin|>from __future__ import with_statement
from sympy import Symbol, exp, Integer, Float, sin, cos, log, Poly, Lambda, \
Function, I, S, sqrt, srepr, Rational, Tuple, Matrix, Interval
from sympy.abc import x, y
from sympy.core.sympify import sympify, _sympify, SympifyError, kernS
from sympy.core.decorators import _sympifyit
from sympy.utilities.pytest import XFAIL, raises
from sympy.utilities.decorator import conserve_mpmath_dps
from sympy.geometry import Point, Line
from sympy.functions.combinatorial.factorials import factorial, factorial2
from sympy.abc import _clash, _clash1, _clash2
from sympy.core.compatibility import HAS_GMPY
from sympy import mpmath
def test_439():
v = sympify("exp(x)")
assert v == exp(x)
assert type(v) == type(exp(x))
assert str(type(v)) == str(type(exp(x)))
def test_sympify1():
assert sympify("x") == Symbol("x")
assert sympify(" x") == Symbol("x")
assert sympify(" x ") == Symbol("x")
# 1778
n1 = Rational(1, 2)
assert sympify('--.5') == n1
assert sympify('-1/2') == -n1
assert sympify('-+--.5') == -n1
assert sympify('-.[3]') == Rational(-1, 3)
assert sympify('.[3]') == Rational(1, 3)
assert sympify('+.[3]') == Rational(1, 3)
assert sympify('+0.[3]*10**-2') == Rational(1, 300)
assert sympify('.[052631578947368421]') == Rational(1, 19)
assert sympify('.0[526315789473684210]') == Rational(1, 19)
assert sympify('.034[56]') == Rational(1711, 49500)
# options to make reals into rationals
assert sympify('1.22[345]', rational=True) == \
1 + Rational(22, 100) + Rational(345, 99900)
assert sympify('2/2.6', rational=True) == Rational(10, 13)
assert sympify('2.6/2', rational=True) == Rational(13, 10)
assert sympify('2.6e2/17', rational=True) == Rational(260, 17)
assert sympify('2.6e+2/17', rational=True) == Rational(260, 17)
assert sympify('2.6e-2/17', rational=True) == Rational(26, 17000)
assert sympify('2.1+3/4', rational=True) == \
Rational(21, 10) + Rational(3, 4)
assert sympify('2.234456', rational=True) == Rational(279307, 125000)
assert sympify('2.234456e23', rational=True) == 223445600000000000000000
assert sympify('2.234456e-23', rational=True) == \
Rational(279307, 12500000000000000000000000000)
assert sympify('-2.234456e-23', rational=True) == \
Rational(-279307, 12500000000000000000000000000)
assert sympify('12345678901/17', rational=True) == \
Rational(12345678901, 17)
assert sympify('1/.3 + x', rational=True) == Rational(10, 3) + x
# make sure longs in fractions work
assert sympify('222222222222/11111111111') == \
Rational(222222222222, 11111111111)
# ... even if they come from repetend notation
assert sympify('1/.2[123456789012]') == Rational(333333333333, 70781892967)
# ... or from high precision reals
assert sympify('.1234567890123456', rational=True) == \
Rational(19290123283179, 156250000000000)
def test_sympify_Fraction():
try:
import fractions
except ImportError:
pass
else:
value = sympify(fractions.Fraction(101, 127))
assert value == Rational(101, 127) and type(value) is Rational
def test_sympify_gmpy():
if HAS_GMPY:
if HAS_GMPY == 2:
import gmpy2 as gmpy
elif HAS_GMPY == 1:
import gmpy
value = sympify(gmpy.mpz(1000001))
assert value == Integer(1000001) and type(value) is Integer
value = sympify(gmpy.mpq(101, 127))
assert value == Rational(101, 127) and type(value) is Rational
@conserve_mpmath_dps
def test_sympify_mpmath():
value = sympify(mpmath.mpf(1.0))
assert value == Float(1.0) and type(value) is Float
mpmath.mp.dps = 12
assert sympify(
mpmath.pi).epsilon_eq(Float("3.14159265359"), Float("1e-12")) is True
assert sympify(
mpmath.pi).epsilon_eq(Float("3.14159265359"), Float("1e-13")) is False
mpmath.mp.dps = 6
assert sympify(
mpmath.pi).epsilon_eq(Float("3.14159"), Float("1e-5")) is True
assert sympify(
mpmath.pi).epsilon_eq(Float("3.14159"), Float("1e-6")) is False
assert sympify(mpmath.mpc(1.0 + 2.0j)) == Float(1.0) + Float(2.0)*I
def test_sympify2():
class A:
def _sympy_(self):
return Symbol("x")**3
a = A()
assert _sympify(a) == x**3
assert sympify(a) == x**3
assert a == x**3
def test_sympify3():
assert sympify("x**3") == x**3
assert sympify("x^3") == x**3
assert sympify("1/2") == Integer(1)/2
raises(SympifyError, lambda: _sympify('x**3'))
raises(SympifyError, lambda: _sympify('1/2'))
def test_sympify_keywords():
raises(SympifyError, lambda: sympify('if'))
raises(SympifyError, lambda: sympify('for'))
raises(SympifyError, lambda: sympify('while'))
raises(SympifyError, lambda: sympify('lambda'))
def test_sympify_float():
assert sympify("1e-64") != 0
assert sympify("1e-20000") != 0
def test_sympify_bool():
"""Test that sympify accepts boolean values
and that output leaves them unchanged"""
assert sympify(True) is True
assert sympify(False) is False
def test_sympyify_iterables():
ans = [Rational(3, 10), Rational(1, 5)]
assert sympify(['.3', '.2'], rational=True) == ans
assert sympify(set(['.3', '.2']), rational=True) == set(ans)
assert sympify(tuple(['.3', '.2']), rational=True) == Tuple(*ans)
assert sympify(dict(x=0, y=1)) == {x: 0, y: 1}
assert sympify(['1', '2', ['3', '4']]) == [S(1), S(2), [S(3), S(4)]]
def test_sympify4():
class A:
def _sympy_(self):
return Symbol("x")
a = A()
assert _sympify(a)**3 == x**3
assert sympify(a)**3 == x**3
assert a == x
def test_sympify_text():
assert sympify('some') == Symbol('some')
assert sympify('core') == Symbol('core')
assert sympify('True') is True
assert sympify('False') is False
assert sympify('Poly') == Poly
assert sympify('sin') == sin
def test_sympify_function():
assert sympify('factor(x**2-1, x)') == -(1 - x)*(x + 1)
assert sympify('sin(pi/2)*cos(pi)') == -Integer(1)
def test_sympify_poly():
p = Poly(x**2 + x + 1, x)
assert _sympify(p) is p
assert sympify(p) is p
def test_sympify_factorial():
assert sympify('x!') == factorial(x)
assert sympify('(x+1)!') == factorial(x + 1)
assert sympify('(1 + y*(x + 1))!') == factorial(1 + y*(x + 1))
assert sympify('(1 + y*(x + 1)!)^2') == (1 + y*factorial(x + 1))**2
assert sympify('y*x!') == y*factorial(x)
assert sympify('x!!') == factorial2(x)
assert sympify('(x+1)!!') == factorial2(x + 1)
assert sympify('(1 + y*(x + 1))!!') == factorial2(1 + y*(x + 1))
assert sympify('(1 + y*(x + 1)!!)^2') == (1 + y*factorial2(x + 1))**2
assert sympify('y*x!!') == y*factorial2(x)
assert sympify('factorial2(x)!') == factorial(factorial2(x))
raises(SympifyError, lambda: sympify("+!!"))
raises(SympifyError, lambda: sympify(")!!"))
raises(SympifyError, lambda: sympify("!"))
raises(SympifyError, lambda: sympify("(!)"))
raises(SympifyError, lambda: sympify("x!!!"))
def test_sage():
# how to effectivelly test for the _sage_() method without having SAGE
# installed?
assert hasattr(x, "_sage_")
assert hasattr(Integer(3), "_sage_")
assert hasattr(sin(x), "_sage_")
assert hasattr(cos(x), "_sage_")
assert hasattr(x**2, "_sage_")
assert hasattr(x + y, "_sage_")
assert hasattr(exp(x), "_sage_")
assert hasattr(log(x), "_sage_")
def test_bug496():
assert sympify("a_") == Symbol("a_")
assert sympify("_a") == Symbol("_a")
@XFAIL
def test_lambda():
x = Symbol('x')
assert sympify('lambda: 1') == Lambda((), 1)
assert sympify('lambda x: 2*x') == Lambda(x, 2*x)
assert sympify('lambda x, y: 2*x+y') == Lambda([x, y], 2*x + y)
def test_lambda_raises():
with raises(SympifyError):
_sympify('lambda: 1')
def test_sympify_raises():
raises(SympifyError, lambda: sympify("fx)"))
def test__sympify():
x = Symbol('x')
f = Function('f')
# positive _sympify
assert _sympify(x) is x
assert _sympify(f) is f
assert _sympify(1) == Integer(1)
assert _sympify(0.5) == Float("0.5")
assert _sympify(1 + 1j) == 1.0 + I*1.0
class A:
def _sympy_(self):
return Integer(5)
a = A()
assert _sympify(a) == Integer(5)
# negative _sympify
raises(SympifyError, lambda: _sympify('1'))
raises(SympifyError, lambda: _sympify([1, 2, 3]))
def test_sympifyit():
x = Symbol('x')
y = Symbol('y')
@_sympifyit('b', NotImplemented)
def add(a, b):
return a + b
assert add(x, 1) == x + 1
assert add(x, 0.5) == x + Float('0.5')
assert add(x, y) == x + y
assert add(x, '1') == NotImplemented
@_sympifyit('b')
def add_raises(a, b):
return a + b
assert add_raises(x, 1) == x + 1
assert add_raises(x, 0.5) == x + Float('0.5')
assert add_raises(x, y) == x + y
raises(SympifyError, lambda: add_raises(x, '1'))
def test_int_float():
class F1_1(object):
def __float__(self):
return 1.1
class F1_1b(object):
"""
This class is still a float, even though it also implements __int__().
"""
def __float__(self):
return 1.1
def __int__(self):
return 1
class F1_1c(object):
"""
This class is still a float, because it implements _sympy_()
"""
def __float__(self):
return 1.1
def __int__(self):
return 1
def _sympy_(self):
return Float(1.1)
class I5(object):
def __int__(self):
return 5
class I5b(object):
"""
This class implements both __int__() and __float__(), so it will be
treated as Float in SymPy. One could change this behavior, by using
float(a) == int(a), but deciding that integer-valued floats represent
exact numbers is arbitrary and often not correct, so we do not do it.
If, in the future, we decide to do it anyway, the tests for I5b need to
be changed.
"""
def __float__(self):
return 5.0
def __int__(self):
return 5
class I5c(object):
"""
This class implements both __int__() and __float__(), but also
a _sympy_() method, so it will be Integer.
"""
def __float__(self):
return 5.0
def __int__(self):
return 5
def _sympy_(self):
return Integer(5)
i5 = I5()
i5b = I5b()
i5c = I5c()
f1_1 = F1_1()
f1_1b = F1_1b()<|fim▁hole|> assert isinstance(sympify(i5), Integer)
assert sympify(i5b) == 5
assert isinstance(sympify(i5b), Float)
assert sympify(i5c) == 5
assert isinstance(sympify(i5c), Integer)
assert abs(sympify(f1_1) - 1.1) < 1e-5
assert abs(sympify(f1_1b) - 1.1) < 1e-5
assert abs(sympify(f1_1c) - 1.1) < 1e-5
assert _sympify(i5) == 5
assert isinstance(_sympify(i5), Integer)
assert _sympify(i5b) == 5
assert isinstance(_sympify(i5b), Float)
assert _sympify(i5c) == 5
assert isinstance(_sympify(i5c), Integer)
assert abs(_sympify(f1_1) - 1.1) < 1e-5
assert abs(_sympify(f1_1b) - 1.1) < 1e-5
assert abs(_sympify(f1_1c) - 1.1) < 1e-5
def test_issue1034():
a = sympify('Integer(4)')
assert a == Integer(4)
assert a.is_Integer
def test_issue883():
a = [3, 2.0]
assert sympify(a) == [Integer(3), Float(2.0)]
assert sympify(tuple(a)) == Tuple(Integer(3), Float(2.0))
assert sympify(set(a)) == set([Integer(3), Float(2.0)])
def test_S_sympify():
assert S(1)/2 == sympify(1)/2
assert (-2)**(S(1)/2) == sqrt(2)*I
def test_issue1689():
assert srepr(S(1.0 + 0J)) == srepr(S(1.0)) == srepr(Float(1.0))
def test_issue1699_None():
assert S(None) is None
def test_issue3218():
assert sympify("x+\ny") == x + y
def test_issue1889_builtins():
C = Symbol('C')
vars = {}
vars['C'] = C
exp1 = sympify('C')
assert exp1 == C # Make sure it did not get mixed up with sympy.C
exp2 = sympify('C', vars)
assert exp2 == C # Make sure it did not get mixed up with sympy.C
def test_geometry():
p = sympify(Point(0, 1))
assert p == Point(0, 1) and type(p) == Point
L = sympify(Line(p, (1, 0)))
assert L == Line((0, 1), (1, 0)) and type(L) == Line
def test_kernS():
s = '-1 - 2*(-(-x + 1/x)/(x*(x - 1/x)**2) - 1/(x*(x - 1/x)))'
# when 1497 is fixed, this no longer should pass: the expression
# should be unchanged
assert -1 - 2*(-(-x + 1/x)/(x*(x - 1/x)**2) - 1/(x*(x - 1/x))) == -1
# sympification should not allow the constant to enter a Mul
# or else the structure can change dramatically
ss = kernS(s)
assert ss != -1 and ss.simplify() == -1
s = '-1 - 2*(-(-x + 1/x)/(x*(x - 1/x)**2) - 1/(x*(x - 1/x)))'.replace(
'x', '_kern')
ss = kernS(s)
assert ss != -1 and ss.simplify() == -1
# issue 3588
assert kernS('Interval(-1,-2 - 4*(-3))') == Interval(-1, 10)
assert kernS('_kern') == Symbol('_kern')
assert kernS('E**-(x)') == exp(-x)
e = 2*(x + y)*y
assert kernS(['2*(x + y)*y', ('2*(x + y)*y',)]) == [e, (e,)]
assert kernS('-(2*sin(x)**2 + 2*sin(x)*cos(x))*y/2') == \
-y*(2*sin(x)**2 + 2*sin(x)*cos(x))/2
def test_issue_3441_3453():
assert S('[[1/3,2], (2/5,)]') == [[Rational(1, 3), 2], (Rational(2, 5),)]
assert S('[[2/6,2], (2/4,)]') == [[Rational(1, 3), 2], (Rational(1, 2),)]
assert S('[[[2*(1)]]]') == [[[2]]]
assert S('Matrix([2*(1)])') == Matrix([2])
def test_issue_2497():
assert str(S("Q & C", locals=_clash1)) == 'And(C, Q)'
assert str(S('pi(x)', locals=_clash2)) == 'pi(x)'
assert str(S('pi(C, Q)', locals=_clash)) == 'pi(C, Q)'
locals = {}
exec "from sympy.abc import Q, C" in locals
assert str(S('C&Q', locals)) == 'And(C, Q)'<|fim▁end|>
|
f1_1c = F1_1c()
assert sympify(i5) == 5
|
<|file_name|>setup.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python
# -*- coding: utf-8 -*-
import codecs
import os
import re
import sys
from setuptools import setup
root_dir = os.path.abspath(os.path.dirname(__file__))
def get_version(package_name):
version_re = re.compile(r"^__version__ = [\"']([\w_.-]+)[\"']$")
package_components = package_name.split('.')
init_path = os.path.join(root_dir, *(package_components + ['__init__.py']))
with codecs.open(init_path, 'r', 'utf-8') as f:
for line in f:
match = version_re.match(line[:-1])
if match:
return match.groups()[0]
return '0.1.0'
if sys.version_info[0:2] < (2, 7): # pragma: no cover
test_loader = 'unittest2:TestLoader'
else:
test_loader = 'unittest:TestLoader'
PACKAGE = 'factory'
setup(
name='factory_boy',
version=get_version(PACKAGE),
description="A versatile test fixtures replacement based on thoughtbot's factory_bot for Ruby.",
long_description=codecs.open(os.path.join(root_dir, 'README.rst'), 'r', 'utf-8').read(),
author='Mark Sandstrom',
author_email='[email protected]',
maintainer='Raphaël Barrois',
maintainer_email='[email protected]',
url='https://github.com/FactoryBoy/factory_boy',
keywords=['factory_boy', 'factory', 'fixtures'],
packages=['factory'],
zip_safe=False,
license='MIT',
python_requires=">=2.7, !=3.0.*, !=3.1.*, !=3.2.*, !=3.3.*",
install_requires=[
'Faker>=0.7.0',
],
setup_requires=[
'setuptools>=0.8',
],
tests_require=[
#'mock',
],<|fim▁hole|> "Intended Audience :: Developers",
"Framework :: Django",
"License :: OSI Approved :: MIT License",
"Operating System :: OS Independent",
"Programming Language :: Python",
"Programming Language :: Python :: 2",
"Programming Language :: Python :: 2.7",
"Programming Language :: Python :: 3",
"Programming Language :: Python :: 3.4",
"Programming Language :: Python :: 3.5",
"Programming Language :: Python :: 3.6",
"Programming Language :: Python :: Implementation :: PyPy",
"Topic :: Software Development :: Testing",
"Topic :: Software Development :: Libraries :: Python Modules",
],
test_suite='tests',
test_loader=test_loader,
)<|fim▁end|>
|
classifiers=[
"Development Status :: 5 - Production/Stable",
|
<|file_name|>SpecParser.py<|end_file_name|><|fim▁begin|>from JumpScale import j
# from SpecModelactorsGenerator import SpecModelactorsGenerator
class Specbase(j.tools.code.classGetBase()):
def __init__(self, linenr):
self.name = ""
self.description = ""
self.tags = ""
self.comment = ""
self.linenr = linenr
def addDefaults(self):
pass
def getDefaultValue(self, type, value):
if value.strip() == "" or value.strip() == "None":
return None
elif j.data.types.string.check(value):
value = value.strip("\"")
if type == 'int' and value:
return int(value)
elif type == 'bool' and value:
return j.data.types.bool.fromString(value)
return value
class SpecEnum(Specbase):
def __init__(self, name, specpath, linenr):
Specbase.__init__(self, linenr)
self.name = name
self.specpath = specpath
self.appname = ""
self.enums = []
self.actorname = ""
def _parse(self, parser, content):
for line in content.split("\n"):
if line.strip() != "":
self.enums.append(line.strip())
class Specactor(Specbase):
def __init__(self, name, descr, tags, specpath, linenr):
Specbase.__init__(self, linenr)
self.name = name
self.description = descr
self.tags = tags
self.specpath = specpath
self.appname = ""
self.methods = []
self.type = ""
def _addItem(self, obj):
self.methods.append(obj)
def addDefaults(self):
pass
class SpecactorMethod(Specbase):
def __init__(self, linenr):
Specbase.__init__(self, linenr)
self.vars = []
self.result = None
def _parseFirstLine(self, parser, line):
self.comment, self.tags, line = parser.getTagsComment(line)
self.name = line.strip()
def _parse(self, parser, content):
content = parser.deIndent(content, self.linenr)
linenr = self.linenr
for line in content.split("\n"):
linenr += 1
line0 = line
if line.strip() == "" or line.strip()[0] == "#":
continue
if line.find(":") != -1:
comments, tags, line = parser.getTagsComment(line)
errormsg = "Syntax error, right syntax var:$name $type,$defaultvalue,$description @tags #remarks"
try:
varname, line = line.split(":", 1)
except:
return parser.raiseError(errormsg, line0, linenr)
if varname == "var":
if line.find(" ") == -1:
return parser.raiseError(errormsg, line0, linenr)
else:
varname, line = line.split(" ", 1)
try:
ttype, default, descr = line.split(",", 2)
except:
return parser.raiseError(errormsg, line0, linenr)
default = self.getDefaultValue(ttype, default)
spec = SpecactorMethodVar(
varname, descr, tags, linenr, default, ttype)
spec.comment = comments
self.vars.append(spec)
elif varname == "result":
errormsg = "Syntax error, right syntax result:$type @tags #remarks"
if line.find(" ") == -1 and (line.find("@") != -1 or line.find("$") != -1):
return parser.raiseError(errormsg, line0, linenr)
if line.find(" ") == -1:
ttype = line
else:
ttype, line = line.split(" ", 1)
self.result = Specbase(linenr)
self.result.type = ttype
self.result.comment = comments
else:
return parser.raiseError("Only var & result support on line, syntaxerror.", line0, linenr)
class SpecactorMethodVar(Specbase):
def __init__(self, name, descr, tags, linenr, default, ttype):
Specbase.__init__(self, linenr)
self.name = name
self.description = descr
self.tags = tags
self.defaultvalue = default
self.ttype = ttype
class SpecModel(Specbase):
def __init__(self, name, descr, tags, specpath, linenr):
Specbase.__init__(self, linenr)
self.name = name
self.description = descr
self.tags = tags
self.specpath = specpath
self.properties = []
self.type = ""
self.actorname = ""
self.rootobject = False
def _addItem(self, obj):
self.properties.append(obj)
def exists(self, propname):
for prop in self.properties:
if str(prop.name) == propname:
return True
return False
def addDefaults(self):
if self.type == "rootmodel":
if not self.exists("id"):
s = SpecModelProperty(0)
s.type = 'int'
s.name = 'id'
s.description = 'Auto generated id @optional'
self._addItem(s)
class SpecModelProperty(Specbase):
def __init__(self, linenr):
Specbase.__init__(self, linenr)
self.default = None
self.type = None
def _parseFirstLine(self, parser, line):
errormsg = "Syntax error, right syntax prop:$name $type,$defaultvalue,$description @tags #remarks"
line0 = "prop:%s" % line
if line.find(" ") == -1:
return parser.raiseError(errormsg, line0, self.linenr)
else:
self.name, line = line.split(" ", 1)
try:
self.type, self.default, self.description = line.split(",", 2)
self.default = self.getDefaultValue(self.type, self.default)
except:
return parser.raiseError(errormsg, line0, self.linenr)
def _parse(self, parser, content):
pass
class SpecBlock:
"""
generic block of specs identified with starting with [...]
can be multiple types
"""
def __init__(self, parser, line, linenr, appname, actorname):
self.appname = appname
self.actorname = actorname
self.descr = ""
self.content = ""
self.name = ""
self.comment, self.tags, line = parser.getTagsComment(
line) # get @ out of the block
# if line.find("@") != -1:
# line=line.split("@")[0]
# if line.find("#") != -1:
# line=line.split("#")[0]
line = line.replace("[", "")
if line.find("]") == -1:
return parser.raiseError("each [ on block should finish with ]", line, linenr)
line = line.replace("]", "").strip()
splitted = line.split(":")
splitted = [item.strip().lower() for item in splitted]
self.type = splitted[0]
if len(splitted) == 1:
self.name = ""
elif len(splitted) == 2:
self.name = splitted[1]
else:
return parser.raiseError(
"each [...] on block need to be in format [$type:$name] or [$type], did not find :", line, linenr)
self.parser = parser
self.startline = linenr
self.items = []
def parse(self):
self.content = self.parser.deIndent(self.content, self.startline)
if self.type == "actor":
ttypeId = "method"
spec = None
if len(list(j.core.specparser.specs.keys())) > 0 and self.type == "actor":
key = "%s_%s" % (self.appname, self.actorname)
if key in j.core.specparser.actornames:
spec = j.core.specparser.getactorSpec(
self.appname, self.actorname, False)
if spec is None:
spec = Specactor(self.name, self.descr, self.tags,
self.parser.path, self.startline)
spec.actorname = self.actorname
spec.appname = self.appname
if spec.appname not in j.core.specparser.app_actornames:
j.core.specparser.app_actornames[self.appname] = []
if spec.actorname not in j.core.specparser.app_actornames[self.appname]:
j.core.specparser.app_actornames[
self.appname].append(spec.actorname)
currentitemClass = SpecactorMethod
elif self.type == "enumeration":
ttypeId = "enumeration"
spec = SpecEnum(self.name, self.parser.path, self.startline)
spec.actorname = self.actorname
currentitemClass = None
elif self.type == "model" or self.type == "rootmodel":
ttypeId = "prop"
spec = SpecModel(self.name, self.descr, self.tags,
self.parser.path, self.startline)
spec.actorname = self.actorname
spec.appname = self.appname
spec.name = self.name
if self.type == "rootmodel":
spec.rootobject = True
# print "found model %s %s"%(self.name,self.parser.path)
# print self.content
# print "###########"
currentitemClass = SpecModelProperty
else:
return self.parser.raiseError(
"Invalid type '%s' could not find right type of spec doc, only supported model,actor,enum :" % self.type, self.content, self.startline)
# find the items in the block
linenr = self.startline
state = "start"
currentitemContent = ""
currentitem = None
if self.type == "enumeration":
currentitemContent = self.content
self.content = ""
currentitem = spec
for line in self.content.split("\n"):
linenr += 1
line = line.rstrip()
# print "line:%s state:%s" % (line,state)
if line.strip() == "":
if currentitem is not None and currentitemContent == "":
currentitem.linenr = linenr + 1
continue
if state == "description" and line.strip().find("\"\"\"") == 0:
# end of description
state = "blockfound"
currentitem.linenr = linenr + 1
continue
if state == "description":
currentitem.description += "%s\n" % line.strip()
if (state == "start" or state == "blockfound") and line.strip().find("\"\"\"") == 0:
# found description
state = "description"
continue
if state == "blockfound" and line.strip().find("@") == 0:
# found labels tags on right level
tmp1, currentitem.tags, tmp2 = self.parser.getTagsComment(line)
currentitem.linenr = linenr + 1
continue
if state == "blockfound" and line[0] == " ":
# we are in block & no block descr
currentitemContent += "%s\n" % line
if (state == "start" or state == "blockfound") and line[0] != " " and line.find(":") != -1:
typeOnLine = line.split(":", 1)[0].strip()
if ttypeId == typeOnLine:
state = "blockfound"
if currentitemContent != "":
currentitem._parse(self.parser, currentitemContent)
currentitemContent = ""
currentitem = currentitemClass(linenr)
comment, tags, line = self.parser.getTagsComment(line)
currentitem._parseFirstLine(
self.parser, line.split(":", 1)[1].strip())
if comment != "":
currentitem.comment = comment
if tags != "":
currentitem.tags = tags
spec._addItem(currentitem)
currentitemContent = ""
else:
self.parser.raiseError("Found item %s, only %s supported." % (
typeOnLine, ttypeId), line, linenr)
# are at end of file make sure last item is processed
if currentitemContent != "":
currentitem._parse(self.parser, currentitemContent)
# spec.appname=self.appname
# spec.actorname=self.actorname
spec.type = self.type
spec.addDefaults()
j.core.specparser.addSpec(spec)
def __str__(self):
s = "name:%s\n" % self.name
s += "type:%s\n" % self.type
s += "descr:%s\n" % self.descr
s += "tags:%s\n" % self.tags
s += "content:\n%s\n" % self.content
return s
__repr__ = __str__
class SpecDirParser:
def __init__(self, path, appname, actorname):
self.appname = appname
self.actorname = actorname
self.path = path
files = j.sal.fs.listFilesInDir(self.path, True, "*.spec")
def sortFilesFollowingLength(files):
r = {}
result = []
for item in ["actor", "enum", "model"]:
for p in files:
pp = j.sal.fs.getBaseName(p)
if pp.find(item) == 0:
result.append(p)
files.pop(files.index(p))
for p in files:
if len(p) not in r:
r[len(p)] = []
r[len(p)].append(p)
lkeysSorted = sorted(r.keys())
for lkey in lkeysSorted:
result = result + r[lkey]
return result
files = sortFilesFollowingLength(files)
self.specblocks = {}
for path in files:
if j.sal.fs.getBaseName(path).find("example__") == 0:
continue
parser = j.core.specparser._getSpecFileParser(
path, self.appname, self.actorname)
for key in list(parser.specblocks.keys()):
block = parser.specblocks[key]
self.specblocks[block.type + "_" + block.name] = block
def getSpecBlock(self, type, name):
key = type + "_" + name
if key in self.specblocks:
return self.specblocks[key]
else:
return False
def __str__(self):
s = "path:%s\n" % self.path
for key in list(self.specblocks.keys()):
block = self.specblocks[key]
s += "%s\n\n" % block
return s
__repr__ = __str__
class SpecFileParser:
def __init__(self, path, appname, actorname):
"""
find blocks in file
"""
self.path = path
self.appname = appname<|fim▁hole|> self.actorname = actorname
if self.appname != self.appname.lower().strip():
emsg = "appname %s for specs should be lowercase & no spaces" % self.appname
raise j.exceptions.RuntimeError(
emsg + " {category:spec.nameerror}")
self.contentin = j.sal.fs.fileGetContents(path)
self.contentout = ""
self.specblocks = {} # key is name
state = "start"
# a block starts with [...] and ends with next [] or end of file
state = "start"
linenr = 0
currentblock = None
# content=self.contentin+"\n***END***\n"
for line in self.contentin.split("\n"):
linenr += 1
line = line.rstrip()
# remove empty lines
line = line.replace("\t", " ")
if line.strip() == "" or line.strip()[0] == "#":
if currentblock is not None and currentblock.content == "":
currentblock.startline = linenr + 1
continue
# remove comments from line
# if line.find("#")>0:
# line=line.split("#",1)[0]
if state == "blockfound" and line[0] == "[":
# block ended
state = "start"
if state == "blockdescription" and line.strip().find("\"\"\"") == 0:
# end of description
state = "blockfound"
self.contentout += "%s\n" % line
currentblock.startline = linenr + 2
continue
if state == "blockdescription":
currentblock.descr += "%s\n" % line.strip()
if state == "blockfound" and line.strip().find("\"\"\"") == 0 and currentblock.descr == "":
# found description
state = "blockdescription"
self.contentout += "%s\n" % line
continue
# if state=="blockfound" and self._checkIdentation(line,linenr,1,1) and line.strip().find("@") != -1:
# found labels tags on right level
# if currentblock is not None:
# comments,currentblock.tags,tmp=self.getTagsComment(line)
# currentblock.startline=linenr
# else:
#self.raiseError("Cannot find label & tags when there is no specblock opened [...]",line,linenr)
#self.contentout+="%s\n" % line
# continue
if state == "blockfound":
# we are in block & no block descr
currentblock.content += "%s\n" % line
if state == "start" and line[0] == "[":
state = "blockfound"
# line2=line
# if line2.find("#")>0:
#from JumpScale.core.Shell import ipshellDebug,ipshell
# print "DEBUG NOW jjj"
# ipshell()
# line2=line.split("#",1)[0]
currentblock = SpecBlock(
self, line, linenr + 1, appname=self.appname, actorname=self.actorname)
self.specblocks[currentblock.name] = currentblock
self.contentout += "%s\n" % line
for key in list(self.specblocks.keys()):
block = self.specblocks[key]
block.parse()
# print block.name
def getTagsComment(self, line):
"""
return comment,tags,line
"""
if line.find("#") != -1:
comment = line.split("#", 1)[1]
line = line.split("#", 1)[0]
else:
comment = ""
tags = None
if line.find("@") != -1:
tags = line.split("@", 1)[1]
line = line.split("@", 1)[0]
if comment.find("@") != -1:
tags = comment.split("@", 1)[1]
comment = comment.split("@")[0]
if comment is not None:
comment = comment.strip()
if tags is not None:
tags = tags.strip()
return comment, tags, line
def deIndent(self, content, startline):
# remove garbage & fix identation
content2 = ""
linenr = startline
for line in content.split("\n"):
linenr += 1
if line.strip() == "":
continue
else:
if line.find(" ") != 0:
return self.raiseError("identation error.", line, linenr)
content2 += "%s\n" % line[4:]
return content2
def _checkIdentation(self, line, linenr, minLevel=1, maxLevel=1):
"""
"""
line = line.replace("\t", " ")
ok = True
if(len(line) < maxLevel * 4):
self.raiseError(
"line is too small, there should be max identation of %s" % maxLevel, line, linenr)
for i in range(0, minLevel):
if line[i * 4:(i + 1) * 4] != " ":
ok = False
if line[maxLevel * 4 + 1] == " ":
ok = False
return ok
def raiseError(self, msg, line="", linenr=0):
j.errorconditionhandler.raiseInputError("Cannot parse file %s\nError on line:%s\n%s\n%s\n" % (
self.path, linenr, line, msg), "specparser.input")
class Role(j.tools.code.classGetBase()):
def __init__(self, name, actors=[]):
self.actors = actors
self.name = name
class SpecParserFactory:
def __init__(self):
self.__jslocation__ = "j.core.specparser"
self.specs = {}
self.childspecs = {}
self.appnames = []
self.actornames = []
self.app_actornames = {}
self.modelnames = {} # key = appname_actorname
self.roles = {} # key is appname_rolename
#self.codepath=j.sal.fs.joinPaths( j.dirs.varDir,"actorscode")
def getEnumerationSpec(self, app, actorname, name, die=True):
key = "enumeration_%s_%s_%s" % (app, actorname, name)
if key in self.specs:
return self.specs[key]
else:
if die:
emsg = "Cannot find enumeration with name %s for app %s" % (
name, app)
raise j.exceptions.RuntimeError(
emsg + " {category:specs.enumeration.notfound}")
else:
return False
def getactorSpec(self, app, name, raiseError=True):
key = "actor_%s_%s_%s" % (app, name, "")
if key in self.specs:
return self.specs[key]
else:
if raiseError:
raise j.exceptions.RuntimeError("Cannot find actor with name %s for app %s" % (
name, app) + " {category:specs.actor.notfound}")
else:
return None
def getModelSpec(self, app, actorname, name, die=True):
key = "model_%s_%s_%s" % (app, actorname, name)
key = key.lower()
if key in self.specs:
return self.specs[key]
else:
if die:
emsg = "Cannot find model with name %s for app %s" % (
name, app)
raise j.exceptions.RuntimeError(
emsg + " {category:specs.model.notfound}")
else:
return False
def getChildModelSpec(self, app, actorname, name, die=True):
key = "childmodel_%s_%s_%s" % (app, actorname, name)
key = key.lower()
if key in self.childspecs:
return self.childspecs[key]
else:
if die:
emsg = "Cannot find model with name %s for app %s" % (
name, app)
raise j.exceptions.RuntimeError(
emsg + " {category:specs.model.notfound}")
else:
return False
def getModelNames(self, appname, actorname):
key = "%s_%s" % (appname, actorname)
if key in j.core.specparser.modelnames:
return self.modelnames[key]
else:
return []
def addSpec(self, spec):
if spec.name == spec.actorname:
specname = ""
else:
specname = spec.name
if spec.type == "rootmodel":
if spec.type == "rootmodel":
spec.type = "model"
key = "%s_%s" % (spec.appname, spec.actorname)
if key not in self.modelnames:
self.modelnames[key] = []
if spec.name not in self.modelnames[key]:
self.modelnames[key].append(spec.name)
elif spec.type == "model":
k = "%s_%s_%s_%s" % ("childmodel", spec.appname,
spec.actorname, specname)
self.childspecs[k] = spec
if spec.type == "actor" and specname != "":
print(
"DEBUG NOW addSpec in specparser, cannot have actor with specname != empty")
key = "%s_%s_%s_%s" % (spec.type, spec.appname,
spec.actorname, specname)
if spec.type != spec.type.lower().strip():
emsg = "type %s of spec %s should be lowercase & no spaces" % (
spec.type, key)
# TODO: P2 the errorcondition handler does not deal with this format to escalate categories
raise j.exceptions.RuntimeError(emsg + " {category:specs.input}")
if spec.name != spec.name.lower().strip():
emsg = "name %s of spec %s should be lowercase & no spaces" % (
spec.name, key)
raise j.exceptions.RuntimeError(emsg + " {category:specs.input}")
if spec.appname not in self.appnames:
self.appnames.append(spec.appname)
if spec.actorname == "":
emsg = "actorname cannot be empty for spec:%s" % (spec.name)
raise j.exceptions.RuntimeError(emsg + "\n{category:specs.input}")
if "%s_%s" % (spec.appname, spec.actorname) not in self.actornames:
self.actornames.append("%s_%s" % (spec.appname, spec.actorname))
self.specs[key] = spec
def findSpec(self, query="", appname="", actorname="", specname="", type="", findFromSpec=None, findOnlyOne=True):
"""
do not specify query with one of the other filter criteria
@param query is in dot notation e.g. $appname.$actorname.$modelname ... the items in front are optional
"""
# print "findspec: '%s/%s/%s'"%(appname,actorname,specname)
# print "query:'%s'"%query
spec = findFromSpec
if query != "":
type = ""
if query[0] == "E":
type = "enumeration"
if query[0] == "M":
type = "model"
if query.find("(") != -1 and query.find(")") != -1:
query = query.split("(", 1)[1]
query = query.split(")")[0]
splitted = query.split(".")
# see if we can find an appname
appname = ""
if len(splitted) > 1:
possibleappname = splitted[0]
if possibleappname in j.core.specparser.appnames:
appname = possibleappname
splitted = splitted[1:] # remove the already matched item
# see if we can find an actor
actorname = ""
if len(splitted) > 1:
possibleactor = splitted[0]
if possibleactor in j.core.specparser.actornames:
actorname = possibleactor
splitted = splitted[1:] # remove the already matched item
query = ".".join(splitted)
if query.strip() != "." and query.strip() != "":
specname = query
if actorname == "" and spec is not None:
# no specificiation of actor or app so needs to be local to
# this spec
actorname = spec.actorname
if appname == "" and spec is not None:
# no specificiation of actor or app so needs to be local to
# this spec
appname = spec.appname
result = []
if actorname == specname:
specname = ""
else:
specname = specname
if actorname != "" and appname != "" and specname != "" and type != "":
key = "%s_%s_%s_%s" % (type, appname, actorname, specname)
if key in j.core.specparser.specs:
result = [j.core.specparser.specs[key]]
else:
# not enough specified need to walk over all
for key in list(j.core.specparser.specs.keys()):
spec = j.core.specparser.specs[key]
found = True
if actorname != "" and spec.actorname != actorname:
found = False
if appname != "" and spec.appname != appname:
found = False
if specname != "" and spec.name != specname:
found = False
if type != "" and spec.type != type:
found = False
if found:
result.append(spec)
# print 'actorname:%s'%actorname
if len(result) == 0:
if spec is not None:
emsg = "Could not find spec with query:%s appname:%s actorname:%s name:%s (spec info: '%s'_'%s'_'%s')" % \
(query, appname, actorname, specname,
spec.name, spec.specpath, spec.linenr)
else:
emsg = "Could not find spec with query:'%s' appname:'%s' actorname:'%s' name:'%s' " % \
(query, appname, actorname, specname)
raise j.exceptions.RuntimeError(
emsg + " {category:specs.finderror}")
if findOnlyOne:
if len(result) != 1:
if spec is not None:
emsg = "Found more than 1 spec for search query:%s appname:%s actorname:%s name:%s (spec info: %s_%s_%s)" % \
(query, appname, actorname, specname,
spec.name, spec.specpath, spec.linenr)
else:
emsg = "Found more than 1 spec for search query:%s appname:%s actorname:%s name:%s " % \
(query, appname, actorname, specname)
raise j.exceptions.RuntimeError(
emsg + " {category:specs.finderror}")
else:
result = result[0]
return result
def _getSpecFileParser(self, path, appname, actorname):
return SpecFileParser(path, appname, actorname)
def init(self):
self.__init__()
def removeSpecsForactor(self, appname, actorname):
appname = appname.lower()
actorname = actorname.lower()
if appname in self.appnames:
i = self.appnames.index(appname)
self.appnames.pop(i)
key = "%s_%s" % (appname, actorname)
if key in self.actornames:
# found actor remove the specs
for key2 in list(self.specs.keys()):
type, app, item, remaining = key2.split("_", 3)
if app == appname and item.find(actorname) == 0:
print(("remove specs %s from memory" % key))
self.specs.pop(key2)
i = self.actornames.index(key)
self.actornames.pop(i)
def resetMemNonSystem(self):
self.appnames = ["system"]
for key2 in list(self.specs.keys()):
type, app, item, remaining = key2.split("_", 3)
if app != "system":
self.specs.pop(key2)
for key in self.actornames:
appname, actorname = key.split("_", 1)
if appname != "system":
i = self.actornames.index(key)
self.actornames.pop(i)
def parseSpecs(self, specpath, appname, actorname):
"""
@param specpath if empty will look for path specs in current dir
"""
if not j.sal.fs.exists(specpath):
raise j.exceptions.RuntimeError(
"Cannot find specs on path %s" % specpath)
SpecDirParser(specpath, appname, actorname=actorname)
# generate specs for model actors
# smg=SpecModelactorsGenerator(appname,actorname,specpath)
# smg.generate()
# parse again to include the just generated specs
# SpecDirParser(specpath,appname,actorname=actorname)
def getSpecFromTypeStr(self, appname, actorname, typestr):
"""
@param typestr e.g list(machine.status)
@return $returntype,$spec $returntype=list,dict,object,enum (list & dict can be of primitive types or objects (NOT enums))
"""
if typestr in ["int", "str", "float", "bool"]:
return None, None
elif typestr.find("list") == 0 or typestr.find("dict") == 0:
if typestr.find("list") == 0:
returntype = "list"
else:
returntype = "dict"
typestr = typestr.split("(")[1]
typestr = typestr.split(")")[0]
# print "typestr:%s" % typestr
else:
returntype = "object"
if typestr in ["int", "str", "float", "bool", "list", "dict"]:
spec = typestr
else:
result = self.getEnumerationSpec(
appname, actorname, typestr, die=False)
if result is False:
result = self.getModelSpec(
appname, actorname, typestr, die=False)
if result is False:
if returntype not in ["list", "dict"]:
returntype = "enum"
if result is False:
raise j.exceptions.RuntimeError(
"Cannot find spec for app:%s, actor:%s, with typestr:%s" % (appname, actorname, typestr))
else:
spec = result
return returntype, spec
#raise j.exceptions.RuntimeError("Could not find type:%s in getSpecFromTypeStr" % type)<|fim▁end|>
| |
<|file_name|>mod.rs<|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
// KIND, either express or implied. See the License for the<|fim▁hole|><|fim▁end|>
|
// specific language governing permissions and limitations
// under the License.
pub mod maintenance_facility;
|
<|file_name|>ref_lrn.hpp<|end_file_name|><|fim▁begin|>/*******************************************************************************
* Copyright 2019 Intel Corporation
*
* 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.
*******************************************************************************/
#ifndef OCL_REF_LRN_HPP
#define OCL_REF_LRN_HPP
#include "common/c_types_map.hpp"
#include "common/nstl.hpp"
#include "common/type_helpers.hpp"
#include "ocl/cl_engine.hpp"
#include "ocl/jit_primitive_conf.hpp"
#include "ocl/ocl_lrn_pd.hpp"
#include "ocl/ocl_stream.hpp"
#include "ocl/ocl_utils.hpp"
extern const char *ref_lrn_kernel;
namespace mkldnn {
namespace impl {
namespace ocl {
template <impl::data_type_t data_type>
struct ref_lrn_fwd_t : public primitive_t {
struct pd_t : public ocl_lrn_fwd_pd_t {
pd_t(engine_t *engine, const lrn_desc_t *adesc,
const primitive_attr_t *attr, const lrn_fwd_pd_t *hint_fwd_pd)
: ocl_lrn_fwd_pd_t(engine, adesc, attr, hint_fwd_pd) {}
virtual ~pd_t() {}
DECLARE_COMMON_PD_T("ref:any", ref_lrn_fwd_t);
status_t init() {
assert(engine()->kind() == engine_kind::gpu);
auto *cl_engine = utils::downcast<cl_engine_t *>(engine());
bool ok = true
&& utils::one_of(desc()->prop_kind,
prop_kind::forward_inference,
prop_kind::forward_training)
&& utils::one_of(desc()->alg_kind,
alg_kind::lrn_across_channels,
alg_kind::lrn_within_channel)<|fim▁hole|> && IMPLICATION(data_type == data_type::f16,
cl_engine->mayiuse(cl_device_ext_t::khr_fp16));
if (!ok)
return status::unimplemented;
if (desc_.prop_kind == prop_kind::forward_training) {
ws_md_ = *src_md();
}
gws[0] = H() * W();
gws[1] = C();
gws[2] = MB();
ocl_utils::get_optimal_lws(gws, lws, 3);
return status::success;
}
size_t gws[3];
size_t lws[3];
};
ref_lrn_fwd_t(const pd_t *apd) : primitive_t(apd) {}
~ref_lrn_fwd_t() = default;
virtual status_t init() override {
using namespace alg_kind;
auto jit = ocl_jit_t(ref_lrn_kernel);
status_t status = status::success;
const auto *desc = pd()->desc();
jit.set_data_type(desc->data_desc.data_type);
jit.define_int("LRN_FWD", 1);
if (desc->prop_kind == prop_kind::forward_training)
jit.define_int("IS_TRAINING", 1);
switch (desc->alg_kind) {
case lrn_across_channels:
jit.define_int("ACROSS_CHANNEL", 1);
break;
case lrn_within_channel:
jit.define_int("WITHIN_CHANNEL", 1);
break;
default: status = status::unimplemented;
}
if (status != status::success)
return status;
const memory_desc_wrapper src_d(pd()->src_md());
const memory_desc_wrapper dst_d(pd()->dst_md());
const int ndims = src_d.ndims();
jit.define_int("NDIMS", ndims);
jit.define_int("MB", pd()->MB());
jit.define_int("IC", pd()->C());
jit.define_int("IH", pd()->H());
jit.define_int("IW", pd()->W());
const uint32_t round_norm_size = (desc->local_size / 2) * 2 + 1;
uint32_t num_elements = round_norm_size * round_norm_size;
if (desc->alg_kind == lrn_across_channels) {
num_elements = round_norm_size;
}
const float num_element_div = 1.f / (float)num_elements;
const auto padding = (desc->local_size - 1) / 2;
jit.define_float("NUM_ELEMENTS_DIV", num_element_div);
jit.define_int("PADDING", padding);
jit.define_int("LOCAL_SIZE", desc->local_size);
jit.define_float("LRN_ALPHA", desc->lrn_alpha);
jit.define_float("LRN_BETA", desc->lrn_beta);
jit.define_float("LRN_K", desc->lrn_k);
jit.define_int("GWS_MB", 2);
jit.define_int("GWS_IC", 1);
jit.define_int("GWS_HW", 0);
jit_offsets jit_off;
set_offsets(src_d, jit_off.src_off);
set_offsets(dst_d, jit_off.dst_off);
def_offsets(jit_off.src_off, jit, "SRC", ndims);
def_offsets(jit_off.dst_off, jit, "DST", ndims);
status = jit.build(engine());
if (status != status::success)
return status;
kernel_ = jit.get_kernel("ref_lrn_fwd");
if (!kernel_)
return status::runtime_error;
return status::success;
}
virtual status_t execute(const exec_ctx_t &ctx) const override {
return execute_forward(ctx);
}
private:
status_t execute_forward(const exec_ctx_t &ctx) const;
const pd_t *pd() const { return (const pd_t *)primitive_t::pd(); }
ocl_kernel_t kernel_;
};
template <impl::data_type_t data_type>
struct ref_lrn_bwd_t : public primitive_t {
struct pd_t : public ocl_lrn_bwd_pd_t {
pd_t(engine_t *engine, const lrn_desc_t *adesc,
const primitive_attr_t *attr, const lrn_fwd_pd_t *hint_fwd_pd)
: ocl_lrn_bwd_pd_t(engine, adesc, attr, hint_fwd_pd) {}
virtual ~pd_t() {}
DECLARE_COMMON_PD_T("ref:any", ref_lrn_bwd_t);
status_t init() {
assert(engine()->kind() == engine_kind::gpu);
auto *cl_engine = utils::downcast<cl_engine_t *>(engine());
bool ok = true
&& utils::one_of(desc()->prop_kind,
prop_kind::backward_data)
&& utils::one_of(desc()->alg_kind,
alg_kind::lrn_across_channels,
alg_kind::lrn_within_channel)
&& utils::everyone_is(
data_type, desc()->data_desc.data_type)
&& mkldnn::impl::operator==(desc()->data_desc,
desc()->diff_data_desc)
&& attr()->has_default_values()
&& IMPLICATION(data_type == data_type::f16,
cl_engine->mayiuse(cl_device_ext_t::khr_fp16));
if (!ok)
return status::unimplemented;
ws_md_ = *src_md();
if (!compare_ws(hint_fwd_pd_))
return status::unimplemented;
gws[0] = H() * W();
gws[1] = C();
gws[2] = MB();
ocl_utils::get_optimal_lws(gws, lws, 3);
return status::success;
}
size_t gws[3];
size_t lws[3];
};
ref_lrn_bwd_t(const pd_t *apd) : primitive_t(apd) {}
~ref_lrn_bwd_t() = default;
virtual status_t init() override {
using namespace alg_kind;
auto jit = ocl_jit_t(ref_lrn_kernel);
status_t status = status::success;
const auto *desc = pd()->desc();
jit.set_data_type(desc->data_desc.data_type);
jit.define_int("LRN_BWD", 1);
switch (desc->alg_kind) {
case lrn_across_channels:
jit.define_int("ACROSS_CHANNEL", 1);
break;
case lrn_within_channel:
jit.define_int("WITHIN_CHANNEL", 1);
break;
default: status = status::unimplemented;
}
if (status != status::success)
return status;
const memory_desc_wrapper src_d(pd()->src_md());
const memory_desc_wrapper diff_dst_d(pd()->diff_dst_md());
const int ndims = src_d.ndims();
jit.define_int("NDIMS", ndims);
jit.define_int("MB", pd()->MB());
jit.define_int("IC", pd()->C());
jit.define_int("IH", pd()->H());
jit.define_int("IW", pd()->W());
const uint32_t round_norm_size = (desc->local_size / 2) * 2 + 1;
uint32_t num_elements = round_norm_size * round_norm_size;
if (desc->alg_kind == lrn_across_channels) {
num_elements = round_norm_size;
}
const float num_element_div = 1.f / (float)num_elements;
const auto padding = (desc->local_size - 1) / 2;
jit.define_float("NUM_ELEMENTS_DIV", num_element_div);
jit.define_int("PADDING", padding);
jit.define_int("LOCAL_SIZE", desc->local_size);
jit.define_float("LRN_ALPHA", desc->lrn_alpha);
jit.define_float("LRN_BETA", desc->lrn_beta);
jit.define_float("LRN_K", desc->lrn_k);
jit.define_int("GWS_MB", 2);
jit.define_int("GWS_IC", 1);
jit.define_int("GWS_HW", 0);
jit_offsets jit_off;
set_offsets(src_d, jit_off.src_off);
set_offsets(diff_dst_d, jit_off.dst_off);
def_offsets(jit_off.src_off, jit, "SRC", ndims);
def_offsets(jit_off.dst_off, jit, "DST", ndims);
status = jit.build(engine());
if (status != status::success)
return status;
kernel_ = jit.get_kernel("ref_lrn_bwd");
if (!kernel_)
return status::runtime_error;
return status::success;
}
virtual status_t execute(const exec_ctx_t &ctx) const override {
return execute_backward(ctx);
}
private:
status_t execute_backward(const exec_ctx_t &ctx) const;
const pd_t *pd() const { return (const pd_t *)primitive_t::pd(); }
ocl_kernel_t kernel_;
};
} // namespace ocl
} // namespace impl
} // namespace mkldnn
#endif<|fim▁end|>
|
&& utils::everyone_is(
data_type, desc()->data_desc.data_type)
&& attr()->has_default_values()
|
<|file_name|>rarbg-get.py<|end_file_name|><|fim▁begin|>#!env /usr/bin/python3<|fim▁hole|>
import sys
import urllib.parse
import urllib.request
def main():
search = sys.argv[1]
url = 'http://rarbg.to/torrents.php?order=seeders&by=DESC&search='
url = url + search
print(url)
req = urllib.request.Request(url, headers={'User-Agent' : "Magic Browser"})
resp = urllib.request.urlopen(req)
respData = resp.read()
if __name__ == '__main__':
main()<|fim▁end|>
| |
<|file_name|>trace.java<|end_file_name|><|fim▁begin|>public class trace {
public void mnonnullelements(int[] a) {
int i = 0;
//@ assert i == 0 && \nonnullelements(a);
<|fim▁hole|>
public void mnotmodified(int i) {
//@ assert \not_modified(i);
i = 4;
//@ assert i == 4 && \not_modified(i);
return ;
}
}<|fim▁end|>
|
return ;
}
|
<|file_name|>imagescale-c.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python3
# Copyright © 2012-13 Qtrac Ltd. All rights reserved.
# This program or module 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. It is provided for
# educational purposes and 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.
import argparse
import collections
import math
import multiprocessing
import os
import sys
import Image
import Qtrac
Result = collections.namedtuple("Result", "todo copied scaled name")
def main():
size, smooth, source, target, concurrency = handle_commandline()
Qtrac.report("starting...")
canceled = False
try:
scale(size, smooth, source, target, concurrency)
except KeyboardInterrupt:
Qtrac.report("canceling...")
canceled = True
summarize(concurrency, canceled)
def handle_commandline():
parser = argparse.ArgumentParser()
parser.add_argument("-c", "--concurrency", type=int,
default=multiprocessing.cpu_count(),
help="specify the concurrency (for debugging and "
"timing) [default: %(default)d]")
parser.add_argument("-s", "--size", default=400, type=int,
help="make a scaled image that fits the given dimension "
"[default: %(default)d]")
parser.add_argument("-S", "--smooth", action="store_true",
help="use smooth scaling (slow but good for text)")
parser.add_argument("source",
help="the directory containing the original .xpm images")
parser.add_argument("target",
help="the directory for the scaled .xpm images")
args = parser.parse_args()
source = os.path.abspath(args.source)
target = os.path.abspath(args.target)
if source == target:
args.error("source and target must be different")
if not os.path.exists(args.target):
os.makedirs(target)
return args.size, args.smooth, source, target, args.concurrency
def scale(size, smooth, source, target, concurrency):
pipeline = create_pipeline(size, smooth, concurrency)
for i, (sourceImage, targetImage) in enumerate(
get_jobs(source, target)):
pipeline.send((sourceImage, targetImage, i % concurrency))
def create_pipeline(size, smooth, concurrency):
pipeline = None
sink = results()
for who in range(concurrency):
pipeline = scaler(pipeline, sink, size, smooth, who)
return pipeline
def get_jobs(source, target):
for name in os.listdir(source):
yield os.path.join(source, name), os.path.join(target, name)
<|fim▁hole|>@Qtrac.coroutine
def scaler(receiver, sink, size, smooth, me):
while True:
sourceImage, targetImage, who = (yield)
if who == me:
try:
result = scale_one(size, smooth, sourceImage, targetImage)
sink.send(result)
except Image.Error as err:
Qtrac.report(str(err), True)
elif receiver is not None:
receiver.send((sourceImage, targetImage, who))
@Qtrac.coroutine
def results():
while True:
result = (yield)
results.todo += result.todo
results.copied += result.copied
results.scaled += result.scaled
Qtrac.report("{} {}".format("copied" if result.copied else "scaled",
os.path.basename(result.name)))
results.todo = results.copied = results.scaled = 0
def scale_one(size, smooth, sourceImage, targetImage):
oldImage = Image.from_file(sourceImage)
if oldImage.width <= size and oldImage.height <= size:
oldImage.save(targetImage)
return Result(1, 1, 0, targetImage)
else:
if smooth:
scale = min(size / oldImage.width, size / oldImage.height)
newImage = oldImage.scale(scale)
else:
stride = int(math.ceil(max(oldImage.width / size,
oldImage.height / size)))
newImage = oldImage.subsample(stride)
newImage.save(targetImage)
return Result(1, 0, 1, targetImage)
def summarize(concurrency, canceled):
message = "copied {} scaled {} ".format(results.copied, results.scaled)
difference = results.todo - (results.copied + results.scaled)
if difference:
message += "skipped {} ".format(difference)
message += "using {} coroutines".format(concurrency)
if canceled:
message += " [canceled]"
Qtrac.report(message)
print()
if __name__ == "__main__":
main()<|fim▁end|>
| |
<|file_name|>parser.rs<|end_file_name|><|fim▁begin|>use crate::prelude::*;
use num_bigint::{BigInt, ToBigInt};
use num_traits::{One, Zero};
use byteorder::{BigEndian, ReadBytesExt};
use encoding::all::ISO_8859_1;
use encoding::{DecoderTrap, Encoding};
pub type ParserNext = fn(&mut BertParser) -> Option<Result<BertTerm>>;
#[derive(Debug)]
pub struct BertParser {
contents: Vec<u8>,
pos: usize,
}
impl BertParser {
pub fn new(contents: Vec<u8>) -> BertParser {
BertParser {
contents: contents,
pos: 0,
}
}
// "Iterators"
pub fn bert1_next(&mut self) -> Option<Result<BertTerm>> {
if self.eof() {
return None;
}
let result = self.magic_number().and_then(|_| self.bert_term());
return Some(result);
}
pub fn bert2_next(&mut self) -> Option<Result<BertTerm>> {
if self.eof() {
return None;
}
let result = self
.parse_varint()
.and_then(|_| self.magic_number())
.and_then(|_| self.bert_term());
return Some(result);
}
pub fn disk_log_next(&mut self) -> Option<Result<BertTerm>> {
if self.eof() {
return None;
}
let result = self
.disk_log_magic()
.and_then(|_| self.disk_log_opened_status())
.and_then(|_| self.disk_log_term());
return Some(result);
}
// Parsers
pub fn magic_number(&mut self) -> Result<()> {
let initial_pos = self.pos;
let magic = self.eat_u8()?;
if magic != BERT_MAGIC_NUMBER {
return Err(BertError::InvalidMagicNumber {
offset: initial_pos,
actual: magic,
});
}
return Ok(());
}
pub fn disk_log_magic(&mut self) -> Result<()> {
let initial_pos = self.pos;
let magic = self.eat_u32_be()?;
if magic != DISK_LOG_MAGIC {
return Err(BertError::InvalidDiskLogMagic {
offset: initial_pos,
actual: magic,
});
}
return Ok(());
}
pub fn disk_log_opened_status(&mut self) -> Result<()> {
let initial_pos = self.pos;
let status = self.eat_u32_be()?;
if status != DISK_LOG_OPENED && status != DISK_LOG_CLOSED {
return Err(BertError::InvalidDiskLogOpenedStatus {
offset: initial_pos,
actual: status,
});
}
return Ok(());
}
pub fn disk_log_term(&mut self) -> Result<BertTerm> {
// XXX(vfoley): should we check that the correct length was read?
let _len_offset = self.pos;
let _len = self.eat_u32_be()?;
let magic_pos = self.pos;
let magic = self.eat_u32_be()?;
if magic != DISK_LOG_TERM_MAGIC {
return Err(BertError::InvalidDiskLogTermMagic {
offset: magic_pos,
actual: magic,
});
}
let magic_pos = self.pos;
let magic = self.eat_u8()?;
if magic != BERT_MAGIC_NUMBER {
return Err(BertError::InvalidMagicNumber {
offset: magic_pos,<|fim▁hole|> }
return self.bert_term();
}
pub fn bert_term(&mut self) -> Result<BertTerm> {
let initial_pos = self.pos;
match self.eat_u8()? {
SMALL_INTEGER_EXT => self.small_integer(),
INTEGER_EXT => self.integer(),
FLOAT_EXT => self.old_float(),
NEW_FLOAT_EXT => self.new_float(),
ATOM_EXT => {
let len = self.eat_u16_be()? as usize;
self.atom(len)
}
SMALL_ATOM_EXT => {
let len = self.eat_u8()? as usize;
self.atom(len)
}
ATOM_UTF8_EXT => {
let len = self.eat_u16_be()? as usize;
self.atom_utf8(len)
}
SMALL_ATOM_UTF8_EXT => {
let len = self.eat_u8()? as usize;
self.atom_utf8(len)
}
SMALL_TUPLE_EXT => {
let len = self.eat_u8()? as usize;
self.tuple(len)
}
LARGE_TUPLE_EXT => {
let len = self.eat_u32_be()? as usize;
self.tuple(len)
}
NIL_EXT => Ok(BertTerm::Nil),
LIST_EXT => self.list(),
STRING_EXT => self.string(),
BINARY_EXT => self.binary(),
SMALL_BIG_EXT => {
let len = self.eat_u8()?;
self.bigint(len as usize)
}
LARGE_BIG_EXT => {
let len = self.eat_u32_be()?;
self.bigint(len as usize)
}
MAP_EXT => self.map(),
tag => Err(BertError::InvalidTag(initial_pos, tag)),
}
}
pub fn small_integer(&mut self) -> Result<BertTerm> {
let b = self.eat_u8()?;
Ok(BertTerm::Int(b as i32))
}
pub fn integer(&mut self) -> Result<BertTerm> {
let n = self.eat_i32_be()?;
Ok(BertTerm::Int(n))
}
pub fn old_float(&mut self) -> Result<BertTerm> {
let initial_pos = self.pos;
let mut s = String::new();
while !self.eof() && self.peek()? != 0 {
s.push(self.eat_char()?);
}
while !self.eof() && self.peek()? == 0 {
let _ = self.eat_u8()?;
}
s.parse::<f64>()
.map_err(|_| BertError::InvalidFloat(initial_pos))
.map(|f| BertTerm::Float(f))
}
pub fn new_float(&mut self) -> Result<BertTerm> {
let raw_bytes = self.eat_u64_be()?;
let f: f64 = f64::from_bits(raw_bytes);
Ok(BertTerm::Float(f))
}
pub fn atom(&mut self, len: usize) -> Result<BertTerm> {
let initial_pos = self.pos;
let bytes: Vec<u8> = self.eat_slice(len)?.to_owned();
let is_ascii = bytes.iter().all(|byte| *byte < 128);
// Optimization: ASCII atoms represent the overwhelming
// majority of use cases of atoms. When we read the bytes
// of the atom, we record whether they are all ASCII
// (i.e., small than 128); if it's the case, we don't
// need to bother with latin-1 decoding. We use an unsafe
// method because ASCII strings are guaranteed to be valid
// UTF-8 strings.
if is_ascii {
let s = unsafe { String::from_utf8_unchecked(bytes) };
Ok(BertTerm::Atom(s))
} else {
ISO_8859_1
.decode(&bytes, DecoderTrap::Strict)
.map(|s| BertTerm::Atom(s))
.map_err(|_| BertError::InvalidLatin1Atom(initial_pos))
}
}
pub fn atom_utf8(&mut self, len: usize) -> Result<BertTerm> {
let initial_pos = self.pos;
let buf: Vec<u8> = self.eat_slice(len)?.to_owned();
String::from_utf8(buf)
.map(|s| BertTerm::Atom(s))
.map_err(|_| BertError::InvalidUTF8Atom(initial_pos))
}
pub fn tuple(&mut self, len: usize) -> Result<BertTerm> {
let mut terms = Vec::with_capacity(len);
for _ in 0..len {
terms.push(self.bert_term()?);
}
Ok(BertTerm::Tuple(terms))
}
pub fn string(&mut self) -> Result<BertTerm> {
let len = self.eat_u16_be()? as usize;
let bytes: Vec<u8> = self.eat_slice(len)?.to_owned();
Ok(BertTerm::String(bytes))
}
pub fn binary(&mut self) -> Result<BertTerm> {
let len = self.eat_u32_be()? as usize;
let bytes: Vec<u8> = self.eat_slice(len)?.to_owned();
Ok(BertTerm::Binary(bytes))
}
pub fn list(&mut self) -> Result<BertTerm> {
let len = self.eat_u32_be()?;
let mut terms = Vec::with_capacity(len as usize + 1);
for _ in 0..len {
terms.push(self.bert_term()?);
}
let tail = self.bert_term()?;
match tail {
BertTerm::Nil => (),
last_term => {
terms.push(last_term);
}
};
Ok(BertTerm::List(terms))
}
pub fn bigint(&mut self, len: usize) -> Result<BertTerm> {
let sign = self.eat_u8()?;
let mut sum: BigInt = Zero::zero();
let mut pos: BigInt = One::one();
for _ in 0..len {
let d = self.eat_u8()?;
let t = &pos * &(d.to_bigint().unwrap());
sum = sum + &t;
pos = pos * (256).to_bigint().unwrap();
}
if sign == 1 {
sum = -sum;
}
Ok(BertTerm::BigInt(sum))
}
// TODO(vfoley): ensure no duplicate keys
pub fn map(&mut self) -> Result<BertTerm> {
let len = self.eat_u32_be()? as usize;
let mut keys = Vec::with_capacity(len);
let mut vals = Vec::with_capacity(len);
for _ in 0..len {
keys.push(self.bert_term()?);
vals.push(self.bert_term()?);
}
Ok(BertTerm::Map(keys, vals))
}
// Low-level parsing methods
pub fn eof(&self) -> bool {
self.pos >= self.contents.len()
}
pub fn peek(&self) -> Result<u8> {
if self.eof() {
return Err(BertError::NotEnoughData {
offset: self.pos,
needed: 1,
available: 0,
});
} else {
return Ok(self.contents[self.pos]);
}
}
pub fn can_read(&self, n: usize) -> bool {
(self.pos + n) <= self.contents.len()
}
pub fn eat_slice(&mut self, len: usize) -> Result<&[u8]> {
if !self.can_read(len) {
return Err(BertError::NotEnoughData {
offset: self.pos,
needed: len,
available: self.contents.len() - self.pos,
});
}
let slice = &self.contents[self.pos..self.pos + len];
self.pos += len;
return Ok(slice);
}
pub fn eat_u8(&mut self) -> Result<u8> {
let b = self.peek()?;
self.pos += 1;
return Ok(b);
}
pub fn eat_char(&mut self) -> Result<char> {
let b = self.eat_u8()?;
return Ok(b as char);
}
pub fn eat_u16_be(&mut self) -> Result<u16> {
let mut bytes = self.eat_slice(2)?;
let n = bytes.read_u16::<BigEndian>()?;
return Ok(n);
}
pub fn eat_i32_be(&mut self) -> Result<i32> {
let mut bytes = self.eat_slice(4)?;
let n = bytes.read_i32::<BigEndian>()?;
return Ok(n);
}
pub fn eat_u32_be(&mut self) -> Result<u32> {
let mut bytes = self.eat_slice(4)?;
let n = bytes.read_u32::<BigEndian>()?;
return Ok(n);
}
pub fn eat_u64_be(&mut self) -> Result<u64> {
let mut bytes = self.eat_slice(8)?;
let n = bytes.read_u64::<BigEndian>()?;
return Ok(n);
}
// https://developers.google.com/protocol-buffers/docs/encoding#varints
pub fn parse_varint(&mut self) -> Result<u64> {
const MAX_LEN: u64 = 8;
let start_pos = self.pos;
let mut i: u64 = 0;
let mut val: u64 = 0;
while !self.eof() && i < MAX_LEN {
let b = self.eat_u8()?;
val = val | ((b as u64 & 0x7f) << (7 * i));
if b & 0x80 == 0 {
break;
}
i += 1;
}
if i >= MAX_LEN {
return Err(BertError::VarintTooLarge(start_pos));
}
return Ok(val);
}
}
#[test]
fn test_varint() {
assert_eq!(1, {
match BertParser::new(vec![1]).parse_varint() {
Ok(x) => x,
Err(_) => u64::max_value(),
}
});
assert_eq!(300, {
match BertParser::new(vec![0b1010_1100, 0b0000_0010]).parse_varint() {
Ok(x) => x,
Err(_) => u64::max_value(),
}
});
assert!(
BertParser::new(vec![0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x7f])
.parse_varint()
.is_ok()
);
assert!(
BertParser::new(vec![0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x80])
.parse_varint()
.is_err()
);
}<|fim▁end|>
|
actual: magic,
});
|
<|file_name|>__init__.py<|end_file_name|><|fim▁begin|># Copyright 2015 Google Inc. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
# in compliance with the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software distributed under the License<|fim▁hole|>
from __future__ import absolute_import
from . import _bigquery
__all__ = ['_bigquery']<|fim▁end|>
|
# 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.
|
<|file_name|>ImageTextView.java<|end_file_name|><|fim▁begin|>package com.dodola.animview;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.os.AsyncTask;
import android.text.Html;
import android.util.AttributeSet;
import android.widget.TextView;
import com.nostra13.universalimageloader.cache.disc.naming.Md5FileNameGenerator;
import com.nostra13.universalimageloader.cache.memory.impl.WeakMemoryCache;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.ImageLoaderConfiguration;
import com.nostra13.universalimageloader.core.assist.QueueProcessingType;
/**
* Created by Yaoll
* Time on 2015/10/23.
* Description text里插入图片实现
*/
public class ImageTextView extends TextView {
public ImageTextView(Context context) {
super(context);
}
public ImageTextView(Context context, AttributeSet attrs) {
super(context, attrs);
}
public ImageTextView(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
}
public void setImageText(CharSequence text, String... imageUrls) {
StringBuffer stringBuffer = new StringBuffer();
if(imageUrls != null) {
for(String imageUrl : imageUrls) {
stringBuffer.append("<img src='");
stringBuffer.append(imageUrl);
stringBuffer.append("'/>");
}
}
stringBuffer.append(text);
new ImageAsyncTask().execute(stringBuffer.toString());
}
private class ImageAsyncTask extends AsyncTask<String, Void, CharSequence> {
@Override
protected void onPreExecute() {
super.onPreExecute();
}
<|fim▁hole|> public Drawable getDrawable(String source) {
Bitmap bitmap = getImageLoader().loadImageSync(source);
Drawable drawable = new BitmapDrawable(getResources(), bitmap);
int width = drawable.getMinimumWidth();
int height = drawable.getMinimumHeight();
int outHeight = (int) (getPaint().descent() - getPaint().ascent());
int outWidth = (width * outHeight) / height;
drawable.setBounds(0, 0, outWidth, outHeight);
drawable.setLevel(1);
return drawable;
}
};
CharSequence charSequence = Html.fromHtml(params[0].toString(), imageGetter, null);
return charSequence;
}
@Override
protected void onPostExecute(CharSequence charSequence) {
super.onPostExecute(charSequence);
ImageTextView.super.setText(charSequence);
}
}
private ImageLoader mImageLoader;
private ImageLoader getImageLoader() {
if(mImageLoader == null) {
ImageLoaderConfiguration config = new ImageLoaderConfiguration.Builder(getContext())//
.threadPriority(Thread.NORM_PRIORITY - 2)
.memoryCache(new WeakMemoryCache())//
.diskCacheFileNameGenerator(new Md5FileNameGenerator())//
.tasksProcessingOrder(QueueProcessingType.LIFO)//
.build();
mImageLoader = ImageLoader.getInstance();
mImageLoader.init(config);
}
return mImageLoader;
}
}<|fim▁end|>
|
@Override
protected CharSequence doInBackground(String... params) {
Html.ImageGetter imageGetter = new Html.ImageGetter() {
@Override
|
<|file_name|>dsm.js<|end_file_name|><|fim▁begin|>module.exports = {
// Scale for HTML Canvas (1=2kx2k, 2=1kx1k, 4=500x500, ...)
scaleFactor: 4,
<|fim▁hole|><|fim▁end|>
|
};
|
<|file_name|>login_details.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*-
###
# (C) Copyright (2012-2017) Hewlett Packard Enterprise Development LP
#<|fim▁hole|># 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 pprint import pprint
from hpOneView.oneview_client import OneViewClient
from config_loader import try_load_from_file
config = {
"ip": "<oneview_ip>",
"credentials": {
"userName": "<username>",
"password": "<password>"
}
}
# Try load config from a file (if there is a config file)
config = try_load_from_file(config)
oneview_client = OneViewClient(config)
print("\n Querying system for login details\n")
login_detail = oneview_client.login_details.get_login_details()
print("\n Login details are: \n")
pprint(login_detail)<|fim▁end|>
|
# Permission is hereby granted, free of charge, to any person obtaining a copy
|
<|file_name|>pat-lt-bracket-2.rs<|end_file_name|><|fim▁begin|>// Copyright 2015 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at<|fim▁hole|>// 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.
fn a(B<) {}
//~^ error: expected one of `:` or `@`, found `<`<|fim▁end|>
| |
<|file_name|>const-autoderef.rs<|end_file_name|><|fim▁begin|>// run-pass
const A: [u8; 1] = ['h' as u8];
const B: u8 = (&A)[0];
const C: &'static &'static &'static &'static [u8; 1] = & & & &A;
const D: u8 = (&C)[0];
pub fn main() {<|fim▁hole|>}<|fim▁end|>
|
assert_eq!(B, A[0]);
assert_eq!(D, A[0]);
|
<|file_name|>test_blackjack.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python
"""
Test code for blackjack game. Tests can be run with py.test or nosetests
"""
from __future__ import print_function
from unittest import TestCase
from card_games import blackjack
from card_games.blackjack import BlackJack
print(blackjack.__file__)
class TestRule(TestCase):
def setUp(self):
pass
def tearDown(self):
pass
def test_init(self):
mygame = BlackJack()<|fim▁hole|>
def test_player_bust(self):
mygame = BlackJack()
for cnt in range(10): # Draw 10 cards - Sure to loose
mygame.draw_card_player()
self.assertEqual(len(mygame.player_hand), 12) # Twelve cards in Player's hand
self.assertEqual(mygame.game_result(), 'bust') # Definitely a bust<|fim▁end|>
|
self.assertEqual(len(mygame.player_hand), 2) # Initial hand for Player
self.assertEqual(len(mygame.dealer_hand), 2) # Initial hand for Dealer
|
<|file_name|>dsytrd2_gpu.cpp<|end_file_name|><|fim▁begin|>/*
-- MAGMA (version 2.1.0) --
Univ. of Tennessee, Knoxville
Univ. of California, Berkeley
Univ. of Colorado, Denver
@date August 2016
@author Raffaele Solca
@author Stan Tomov
@author Mark Gates
@generated from src/zhetrd2_gpu.cpp, normal z -> d, Tue Aug 30 09:38:14 2016
*/
#include "magma_internal.h"
/***************************************************************************//**
Purpose
-------
DSYTRD2_GPU reduces a real symmetric matrix A to real symmetric
tridiagonal form T by an orthogonal similarity transformation:
Q**H * A * Q = T.
This version passes a workspace that is used in an optimized
GPU matrix-vector product.
Arguments
---------
@param[in]
uplo magma_uplo_t
- = MagmaUpper: Upper triangle of A is stored;
- = MagmaLower: Lower triangle of A is stored.
@param[in]
n INTEGER
The order of the matrix A. N >= 0.
@param[in,out]
dA DOUBLE PRECISION array on the GPU, dimension (LDDA,N)
On entry, the symmetric matrix A. If UPLO = MagmaUpper, the leading
N-by-N upper triangular part of A contains the upper
triangular part of the matrix A, and the strictly lower
triangular part of A is not referenced. If UPLO = MagmaLower, the
leading N-by-N lower triangular part of A contains the lower
triangular part of the matrix A, and the strictly upper
triangular part of A is not referenced.
On exit, if UPLO = MagmaUpper, the diagonal and first superdiagonal
of A are overwritten by the corresponding elements of the
tridiagonal matrix T, and the elements above the first
superdiagonal, with the array TAU, represent the orthogonal
matrix Q as a product of elementary reflectors; if UPLO
= MagmaLower, the diagonal and first subdiagonal of A are over-
written by the corresponding elements of the tridiagonal
matrix T, and the elements below the first subdiagonal, with
the array TAU, represent the orthogonal matrix Q as a product
of elementary reflectors. See Further Details.
@param[in]
ldda INTEGER
The leading dimension of the array A. LDDA >= max(1,N).
@param[out]
d DOUBLE PRECISION array, dimension (N)
The diagonal elements of the tridiagonal matrix T:
D(i) = A(i,i).
@param[out]
e DOUBLE PRECISION array, dimension (N-1)
The off-diagonal elements of the tridiagonal matrix T:
E(i) = A(i,i+1) if UPLO = MagmaUpper, E(i) = A(i+1,i) if UPLO = MagmaLower.
@param[out]
tau DOUBLE PRECISION array, dimension (N-1)
The scalar factors of the elementary reflectors (see Further
Details).
@param[out]
A (workspace) DOUBLE PRECISION array, dimension (LDA,N)
On exit the diagonal, the upper part (if uplo=MagmaUpper)
or the lower part (if uplo=MagmaLower) are copies of DA
@param[in]
lda INTEGER
The leading dimension of the array A. LDA >= max(1,N).
@param[out]
work (workspace) DOUBLE PRECISION array, dimension (MAX(1,LWORK))
On exit, if INFO = 0, WORK[0] returns the optimal LWORK.
@param[in]
lwork INTEGER
The dimension of the array WORK. LWORK >= N*NB, where NB is the
optimal blocksize given by magma_get_dsytrd_nb().
\n
If LWORK = -1, then a workspace query is assumed; the routine
only calculates the optimal size of the WORK array, returns
this value as the first entry of the WORK array, and no error
message related to LWORK is issued by XERBLA.
@param[out]
dwork (workspace) DOUBLE PRECISION array on the GPU, dim (MAX(1,LDWORK))
@param[in]
ldwork INTEGER
The dimension of the array DWORK.
LDWORK >= ldda*ceil(n/64) + 2*ldda*nb, where nb = magma_get_dsytrd_nb(n),
and 64 is for the blocksize of magmablas_dsymv.
@param[out]
info INTEGER
- = 0: successful exit
- < 0: if INFO = -i, the i-th argument had an illegal value
Further Details
---------------
If UPLO = MagmaUpper, the matrix Q is represented as a product of elementary
reflectors
Q = H(n-1) . . . H(2) H(1).
Each H(i) has the form
H(i) = I - tau * v * v'
where tau is a real scalar, and v is a real vector with
v(i+1:n) = 0 and v(i) = 1; v(1:i-1) is stored on exit in
A(1:i-1,i+1), and tau in TAU(i).
If UPLO = MagmaLower, the matrix Q is represented as a product of elementary
reflectors
Q = H(1) H(2) . . . H(n-1).
Each H(i) has the form
H(i) = I - tau * v * v'
where tau is a real scalar, and v is a real vector with
v(1:i) = 0 and v(i+1) = 1; v(i+2:n) is stored on exit in A(i+2:n,i),
and tau in TAU(i).
The contents of A on exit are illustrated by the following examples
with n = 5:
if UPLO = MagmaUpper: if UPLO = MagmaLower:
( d e v2 v3 v4 ) ( d )
( d e v3 v4 ) ( e d )
( d e v4 ) ( v1 e d )
( d e ) ( v1 v2 e d )
( d ) ( v1 v2 v3 e d )
where d and e denote diagonal and off-diagonal elements of T, and vi
denotes an element of the vector defining H(i).
@ingroup magma_hetrd
*******************************************************************************/
extern "C" magma_int_t
magma_dsytrd2_gpu(
magma_uplo_t uplo, magma_int_t n,
magmaDouble_ptr dA, magma_int_t ldda,
double *d, double *e, double *tau,
double *A, magma_int_t lda,
double *work, magma_int_t lwork,
magmaDouble_ptr dwork, magma_int_t ldwork,
magma_int_t *info)
{
#define A(i_, j_) ( A + (i_) + (j_)*lda )
#define dA(i_, j_) (dA + (i_) + (j_)*ldda)
/* Constants */
const double c_zero = MAGMA_D_ZERO;
const double c_neg_one = MAGMA_D_NEG_ONE;
const double c_one = MAGMA_D_ONE;
const double d_one = MAGMA_D_ONE;
/* Local variables */
const char* uplo_ = lapack_uplo_const( uplo );
magma_int_t nb = magma_get_dsytrd_nb( n );
magma_int_t kk, nx;
magma_int_t i, j, i_n;
magma_int_t iinfo;
magma_int_t ldw, lddw, lwkopt;
magma_int_t lquery;
*info = 0;
bool upper = (uplo == MagmaUpper);
lquery = (lwork == -1);
if (! upper && uplo != MagmaLower) {
*info = -1;
} else if (n < 0) {
*info = -2;
} else if (ldda < max(1,n)) {
*info = -4;
} else if (lda < max(1,n)) {
*info = -9;
} else if (lwork < nb*n && ! lquery) {
*info = -11;
} else if (ldwork < ldda*magma_ceildiv(n,64) + 2*ldda*nb) {
*info = -13;
}
/* Determine the block size. */
ldw = n;
lddw = ldda; // hopefully ldda is rounded up to multiple of 32; ldwork is in terms of ldda, so lddw can't be > ldda.
lwkopt = n * nb;
if (*info == 0) {
work[0] = magma_dmake_lwork( lwkopt );
}
if (*info != 0) {
magma_xerbla( __func__, -(*info) );
return *info;
}
else if (lquery)
return *info;
/* Quick return if possible */
if (n == 0) {
work[0] = c_one;
return *info;
}
// nx <= n is required
// use LAPACK for n < 3000, otherwise switch at 512
if (n < 3000)
nx = n;
else
nx = 512;
double *work2;
if (MAGMA_SUCCESS != magma_dmalloc_cpu( &work2, n )) {
*info = MAGMA_ERR_HOST_ALLOC;
return *info;
}
magma_queue_t queue = NULL;
magma_device_t cdev;
magma_getdevice( &cdev );
magma_queue_create( cdev, &queue );
// clear out dwork in case it has NANs (used as y in dsymv)
// rest of dwork (used as work in magmablas_dsymv) doesn't need to be cleared
magmablas_dlaset( MagmaFull, n, nb, c_zero, c_zero, dwork, lddw, queue );
if (upper) {
/* Reduce the upper triangle of A.
Columns 1:kk are handled by the unblocked method. */
kk = n - magma_roundup( n - nx, nb );
for (i = n - nb; i >= kk; i -= nb) {
/* Reduce columns i:i+nb-1 to tridiagonal form and form the
matrix W which is needed to update the unreduced part of
the matrix */
/* Get the current panel */
magma_dgetmatrix( i+nb, nb, dA(0, i), ldda, A(0, i), lda, queue );
magma_dlatrd2( uplo, i+nb, nb, A(0, 0), lda, e, tau,
work, ldw, work2, n, dA(0, 0), ldda, dwork, lddw,
dwork + 2*lddw*nb, ldwork - 2*lddw*nb, queue );
/* Update the unreduced submatrix A(0:i-2,0:i-2), using an
update of the form: A := A - V*W' - W*V' */
magma_dsetmatrix( i + nb, nb, work, ldw, dwork, lddw, queue );
magma_dsyr2k( uplo, MagmaNoTrans, i, nb, c_neg_one,
dA(0, i), ldda, dwork, lddw,
d_one, dA(0, 0), ldda, queue );
<|fim▁hole|> elements into D */
for (j = i; j < i+nb; ++j) {
*A(j-1,j) = MAGMA_D_MAKE( e[j - 1], 0 );
d[j] = MAGMA_D_REAL( *A(j, j) );
}
}
magma_dgetmatrix( kk, kk, dA(0, 0), ldda, A(0, 0), lda, queue );
/* Use CPU code to reduce the last or only block */
lapackf77_dsytrd( uplo_, &kk, A(0, 0), &lda, d, e, tau, work, &lwork, &iinfo );
magma_dsetmatrix( kk, kk, A(0, 0), lda, dA(0, 0), ldda, queue );
}
else {
/* Reduce the lower triangle of A */
for (i = 0; i < n-nx; i += nb) {
/* Reduce columns i:i+nb-1 to tridiagonal form and form the
matrix W which is needed to update the unreduced part of
the matrix */
/* Get the current panel */
magma_dgetmatrix( n-i, nb, dA(i, i), ldda, A(i, i), lda, queue );
magma_dlatrd2( uplo, n-i, nb, A(i, i), lda, &e[i], &tau[i],
work, ldw, work2, n, dA(i, i), ldda, dwork, lddw,
dwork + 2*lddw*nb, ldwork - 2*lddw*nb, queue );
/* Update the unreduced submatrix A(i+ib:n,i+ib:n), using
an update of the form: A := A - V*W' - W*V' */
magma_dsetmatrix( n-i, nb, work, ldw, dwork, lddw, queue );
// cublas 6.5 crashes here if lddw % 32 != 0, e.g., N=250.
magma_dsyr2k( MagmaLower, MagmaNoTrans, n-i-nb, nb, c_neg_one,
dA(i+nb, i), ldda, &dwork[nb], lddw,
d_one, dA(i+nb, i+nb), ldda, queue );
/* Copy subdiagonal elements back into A, and diagonal
elements into D */
for (j = i; j < i+nb; ++j) {
*A(j+1,j) = MAGMA_D_MAKE( e[j], 0 );
d[j] = MAGMA_D_REAL( *A(j, j) );
}
}
/* Use CPU code to reduce the last or only block */
magma_dgetmatrix( n-i, n-i, dA(i, i), ldda, A(i, i), lda, queue );
i_n = n-i;
lapackf77_dsytrd( uplo_, &i_n, A(i, i), &lda, &d[i], &e[i],
&tau[i], work, &lwork, &iinfo );
magma_dsetmatrix( n-i, n-i, A(i, i), lda, dA(i, i), ldda, queue );
}
magma_free_cpu( work2 );
magma_queue_destroy( queue );
work[0] = magma_dmake_lwork( lwkopt );
return *info;
} /* magma_dsytrd2_gpu */<|fim▁end|>
|
/* Copy superdiagonal elements back into A, and diagonal
|
<|file_name|>houzz.js<|end_file_name|><|fim▁begin|>'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
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 _reactIconBase = require('react-icon-base');
var _reactIconBase2 = _interopRequireDefault(_reactIconBase);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
var FaHouzz = function FaHouzz(props) {
return _react2.default.createElement(
_reactIconBase2.default,
_extends({ viewBox: '0 0 40 40' }, props),
_react2.default.createElement(<|fim▁hole|> null,
_react2.default.createElement('path', { d: 'm19.9 26.6l11.5-6.6v13.2l-11.5 6.6v-13.2z m-11.4-6.6v13.2l11.4-6.6z m11.4-19.8v13.2l-11.4 6.6v-13.2z m0 13.2l11.5-6.6v13.2z' })
)
);
};
exports.default = FaHouzz;
module.exports = exports['default'];<|fim▁end|>
|
'g',
|
<|file_name|>particleProperties_py.cc<|end_file_name|><|fim▁begin|>#include "particleProperties_py.h"
#include "stlContainers_py.h"
namespace bp = boost::python;
namespace {
struct particlePropertiesWrapper : public rpwa::particleProperties,
bp::wrapper<rpwa::particleProperties>
{
particlePropertiesWrapper()
: rpwa::particleProperties(),
bp::wrapper<rpwa::particleProperties>() { }
particlePropertiesWrapper(const particleProperties& partProp)
: rpwa::particleProperties(partProp),
bp::wrapper<rpwa::particleProperties>() { }
particlePropertiesWrapper(const std::string& partName,
const int isospin,
const int G,
const int J,
const int P,
const int C)
: rpwa::particleProperties(partName, isospin, G, J, P, C),
bp::wrapper<rpwa::particleProperties>() { }
std::string qnSummary() const {
if(bp::override qnSummary = this->get_override("qnSummary")) {
return qnSummary();
}
return rpwa::particleProperties::qnSummary();
}
std::string default_qnSummary() const {
return rpwa::particleProperties::qnSummary();
}
};
bool particleProperties_equal(const rpwa::particleProperties& self, const bp::object& rhsObj) {
bp::extract<rpwa::particleProperties> get_partProp(rhsObj);
if(get_partProp.check()) {
return (self == get_partProp());
}
std::pair<rpwa::particleProperties, std::string> rhsPair;
if(not rpwa::py::convertBPObjectToPair<rpwa::particleProperties, std::string>(rhsObj, rhsPair))
{
PyErr_SetString(PyExc_TypeError, "Got invalid input when executing rpwa::particleProperties::operator==()");<|fim▁hole|> }
return (self == rhsPair);
}
bool particleProperties_nequal(const rpwa::particleProperties& self, const bp::object& rhsObj) {
return not (self == rhsObj);
}
bool particleProperties_hasDecay(const rpwa::particleProperties& self, bp::object& pyDaughters) {
std::multiset<std::string> daughters;
if(not rpwa::py::convertBPObjectToMultiSet<std::string>(pyDaughters, daughters)) {
PyErr_SetString(PyExc_TypeError, "Got invalid input for daughters when executing rpwa::particleProperties::hasDecay()");
bp::throw_error_already_set();
}
return self.hasDecay(daughters);
}
void particleProperties_addDecayMode(rpwa::particleProperties& self, bp::object& pyDaughters) {
std::multiset<std::string> daughters;
if(not rpwa::py::convertBPObjectToMultiSet<std::string>(pyDaughters, daughters)) {
PyErr_SetString(PyExc_TypeError, "Got invalid input for daughters when executing rpwa::particleProperties::addDecayMode()");
bp::throw_error_already_set();
}
self.addDecayMode(daughters);
}
bool particleProperties_read(rpwa::particleProperties& self, bp::object& pyLine) {
std::string strLine = bp::extract<std::string>(pyLine);
std::istringstream sstrLine(strLine, std::istringstream::in);
return self.read(sstrLine);
}
bp::tuple particleProperties_chargeFromName(const std::string& name) {
int charge;
std::string newName = rpwa::particleProperties::chargeFromName(name, charge);
return bp::make_tuple(newName, charge);
}
}
void rpwa::py::exportParticleProperties()
{
bp::class_< particlePropertiesWrapper >( "particleProperties" )
.def(bp::init<const rpwa::particleProperties&>())
.def(bp::init<std::string, int, int, int, int, int>())
.def("__eq__", &particleProperties_equal)
.def("__neq__", &particleProperties_nequal)
.def(bp::self_ns::str(bp::self))
.add_property("name", &rpwa::particleProperties::name, &rpwa::particleProperties::setName)
.add_property("bareName", &rpwa::particleProperties::bareName)
.add_property("antiPartName", &rpwa::particleProperties::antiPartName, &rpwa::particleProperties::setAntiPartName)
.add_property("antiPartBareName", &rpwa::particleProperties::antiPartBareName)
.add_property("charge", &rpwa::particleProperties::charge, &rpwa::particleProperties::setCharge)
.add_property("mass", &rpwa::particleProperties::mass, &rpwa::particleProperties::setMass)
.add_property("mass2", &rpwa::particleProperties::mass2)
.add_property("width", &rpwa::particleProperties::width, &rpwa::particleProperties::setWidth)
.add_property("baryonNmb", &rpwa::particleProperties::baryonNmb, &rpwa::particleProperties::setBaryonNmb)
.add_property("isospin", &rpwa::particleProperties::isospin, &rpwa::particleProperties::setIsospin)
.add_property("isospinProj", &rpwa::particleProperties::isospinProj, &rpwa::particleProperties::setIsospinProj)
.add_property("strangeness", &rpwa::particleProperties::strangeness, &rpwa::particleProperties::setStrangeness)
.add_property("charm", &rpwa::particleProperties::charm, &rpwa::particleProperties::setCharm)
.add_property("beauty", &rpwa::particleProperties::beauty, &rpwa::particleProperties::setBeauty)
.add_property("G", &rpwa::particleProperties::G, &rpwa::particleProperties::setG)
.add_property("J", &rpwa::particleProperties::J, &rpwa::particleProperties::setJ)
.add_property("P", &rpwa::particleProperties::P, &rpwa::particleProperties::setP)
.add_property("C", &rpwa::particleProperties::C, &rpwa::particleProperties::setC)
.add_property("isXParticle", &rpwa::particleProperties::isXParticle)
.add_property("isMeson", &rpwa::particleProperties::isMeson)
.add_property("isBaryon", &rpwa::particleProperties::isBaryon)
.add_property("isLepton", &rpwa::particleProperties::isLepton)
.add_property("isPhoton", &rpwa::particleProperties::isPhoton)
.add_property("isItsOwnAntiPart", &rpwa::particleProperties::isItsOwnAntiPart)
.add_property("isSpinExotic", &rpwa::particleProperties::isSpinExotic)
.def(
"fillFromDataTable"
, &rpwa::particleProperties::fillFromDataTable
, (bp::arg("name"), bp::arg("warnIfNotExistent")=(bool const)(true))
)
.add_property("nmbDecays", &rpwa::particleProperties::nmbDecays)
.def("hasDecay", &particleProperties_hasDecay)
.def("addDecayMode", &particleProperties_addDecayMode)
.add_property("isStable", &rpwa::particleProperties::isStable)
.def("setSCB", &rpwa::particleProperties::setSCB)
.def("setIGJPC", &rpwa::particleProperties::setIGJPC)
.add_property("antiPartProperties", &rpwa::particleProperties::antiPartProperties)
.def("qnSummary", &particlePropertiesWrapper::qnSummary, &particlePropertiesWrapper::default_qnSummary)
.def("qnSummary", &rpwa::particleProperties::qnSummary)
.add_property("bareNameLaTeX", &rpwa::particleProperties::bareNameLaTeX)
.def("read", &particleProperties_read)
.def("nameWithCharge", &rpwa::particleProperties::nameWithCharge)
.staticmethod("nameWithCharge")
.def("chargeFromName", &particleProperties_chargeFromName)
.staticmethod("chargeFromName")
.def("stripChargeFromName", &rpwa::particleProperties::stripChargeFromName)
.staticmethod("stripChargeFromName")
.add_static_property("debugParticleProperties", &rpwa::particleProperties::debug, &rpwa::particleProperties::setDebug);
}<|fim▁end|>
|
bp::throw_error_already_set();
|
<|file_name|>GroupHeader41.go<|end_file_name|><|fim▁begin|>package iso20022
// Set of characteristics shared by all individual transactions included in the message.
type GroupHeader41 struct {
// Point to point reference, as assigned by the instructing party, and sent to the next party in the chain to unambiguously identify the message.
// Usage: The instructing party has to make sure that MessageIdentification is unique per instructed party for a pre-agreed period.
MessageIdentification *Max35Text `xml:"MsgId"`
// Date and time at which the message was created.
CreationDateTime *ISODateTime `xml:"CreDtTm"`
// User identification or any user key to be used to check whether the initiating party is allowed to initiate transactions from the account specified in the message.
//
// Usage: The content is not of a technical nature, but reflects the organisational structure at the initiating side.
// The authorisation element can typically be used in relay scenarios, payment initiations, payment returns or payment reversals that are initiated on behalf of a party different from the initiating party.
Authorisation []*Authorisation1Choice `xml:"Authstn,omitempty"`
// Identifies whether a single entry per individual transaction or a batch entry for the sum of the amounts of all transactions within the group of a message is requested.
// Usage: Batch booking is used to request and not order a possible batch booking.
BatchBooking *BatchBookingIndicator `xml:"BtchBookg,omitempty"`
// Number of individual transactions contained in the message.
NumberOfTransactions *Max15NumericText `xml:"NbOfTxs"`
// Total of all individual amounts included in the message, irrespective of currencies.
ControlSum *DecimalNumber `xml:"CtrlSum,omitempty"`
// Indicates whether the reversal applies to the whole group of transactions or to individual transactions within the original group.
GroupReversal *TrueFalseIndicator `xml:"GrpRvsl,omitempty"`
// Total amount of money moved between the instructing agent and the instructed agent in the reversal message.
TotalReversedInterbankSettlementAmount *ActiveCurrencyAndAmount `xml:"TtlRvsdIntrBkSttlmAmt,omitempty"`
// Date on which the amount of money ceases to be available to the agent that owes it and when the amount of money becomes available to the agent to which it is due.
InterbankSettlementDate *ISODate `xml:"IntrBkSttlmDt,omitempty"`
// Specifies the details on how the settlement of the transaction(s) between the instructing agent and the instructed agent is completed.
SettlementInformation *SettlementInformation13 `xml:"SttlmInf"`
// Agent that instructs the next party in the chain to carry out the (set of) instruction(s).
//
// Usage: The instructing agent is the party sending the reversal message and not the party that sent the original instruction that is being reversed.
InstructingAgent *BranchAndFinancialInstitutionIdentification4 `xml:"InstgAgt,omitempty"`
// Agent that is instructed by the previous party in the chain to carry out the (set of) instruction(s).
//
// Usage: The instructed agent is the party receiving the reversal message and not the party that received the original instruction that is being reversed.
InstructedAgent *BranchAndFinancialInstitutionIdentification4 `xml:"InstdAgt,omitempty"`
}
func (g *GroupHeader41) SetMessageIdentification(value string) {
g.MessageIdentification = (*Max35Text)(&value)
}
func (g *GroupHeader41) SetCreationDateTime(value string) {
g.CreationDateTime = (*ISODateTime)(&value)
}
func (g *GroupHeader41) AddAuthorisation() *Authorisation1Choice {
newValue := new(Authorisation1Choice)
g.Authorisation = append(g.Authorisation, newValue)
return newValue
}
func (g *GroupHeader41) SetBatchBooking(value string) {
g.BatchBooking = (*BatchBookingIndicator)(&value)
}
func (g *GroupHeader41) SetNumberOfTransactions(value string) {
g.NumberOfTransactions = (*Max15NumericText)(&value)
}
func (g *GroupHeader41) SetControlSum(value string) {
g.ControlSum = (*DecimalNumber)(&value)
}
func (g *GroupHeader41) SetGroupReversal(value string) {
g.GroupReversal = (*TrueFalseIndicator)(&value)
}<|fim▁hole|>
func (g *GroupHeader41) SetTotalReversedInterbankSettlementAmount(value, currency string) {
g.TotalReversedInterbankSettlementAmount = NewActiveCurrencyAndAmount(value, currency)
}
func (g *GroupHeader41) SetInterbankSettlementDate(value string) {
g.InterbankSettlementDate = (*ISODate)(&value)
}
func (g *GroupHeader41) AddSettlementInformation() *SettlementInformation13 {
g.SettlementInformation = new(SettlementInformation13)
return g.SettlementInformation
}
func (g *GroupHeader41) AddInstructingAgent() *BranchAndFinancialInstitutionIdentification4 {
g.InstructingAgent = new(BranchAndFinancialInstitutionIdentification4)
return g.InstructingAgent
}
func (g *GroupHeader41) AddInstructedAgent() *BranchAndFinancialInstitutionIdentification4 {
g.InstructedAgent = new(BranchAndFinancialInstitutionIdentification4)
return g.InstructedAgent
}<|fim▁end|>
| |
<|file_name|>sturm_equation.cpp<|end_file_name|><|fim▁begin|>// implementation for sturm_equation.h
#include <cmath>
#include <algorithm>
#include <list>
#include <utils/array1d.h>
#include <algebra/vector.h>
#include <algebra/sparse_matrix.h>
#include <numerics/eigenvalues.h>
#include <numerics/gauss_data.h>
namespace WaveletTL
{
template <class WBASIS>
SturmEquation<WBASIS>::SturmEquation(const SimpleSturmBVP& bvp,
const bool precompute_f)
: bvp_(bvp), basis_(bvp.bc_left(), bvp.bc_right()), normA(0.0), normAinv(0.0)
{
#ifdef ENERGY
// compute_diagonal();
#endif
if (precompute_f) precompute_rhs();
//const int jmax = 12;
//basis_.set_jmax(jmax);
}
template <class WBASIS>
SturmEquation<WBASIS>::SturmEquation(const SimpleSturmBVP& bvp,
const WBASIS& basis,
const bool precompute_f)
: bvp_(bvp), basis_(basis), normA(0.0), normAinv(0.0)
{
#ifdef ENERGY
compute_diagonal();
#endif
if (precompute_f) precompute_rhs();
//const int jmax = 12;
//basis_.set_jmax(jmax);
}
template <class WBASIS>
void
SturmEquation<WBASIS>::precompute_rhs() const
{
typedef typename WaveletBasis::Index Index;
cout << "precompute rhs.." << endl;
// precompute the right-hand side on a fine level
InfiniteVector<double,Index> fhelp;
InfiniteVector<double,int> fhelp_int;
#ifdef FRAME
// cout << basis_.degrees_of_freedom() << endl;
for (int i=0; i<basis_.degrees_of_freedom();i++) {
// cout << "hallo" << endl;
// cout << *(basis_.get_quarklet(i)) << endl;
const double coeff = f(*(basis_.get_quarklet(i)))/D(*(basis_.get_quarklet(i)));
fhelp.set_coefficient(*(basis_.get_quarklet(i)), coeff);
fhelp_int.set_coefficient(i, coeff);
// cout << *(basis_.get_quarklet(i)) << endl;
}
// cout << "bin hier1" << endl;
#else
for (int i=0; i<basis_.degrees_of_freedom();i++) {
// cout << "bin hier: " << i << endl;
// cout << D(*(basis_.get_wavelet(i))) << endl;
// cout << *(basis_.get_wavelet(i)) << endl;
const double coeff = f(*(basis_.get_wavelet(i)))/D(*(basis_.get_wavelet(i)));
// cout << f(*(basis_.get_wavelet(i))) << endl;
// cout << coeff << endl;
fhelp.set_coefficient(*(basis_.get_wavelet(i)), coeff);
fhelp_int.set_coefficient(i, coeff);
// cout << *(basis_.get_wavelet(i)) << endl;
}
// const int j0 = basis().j0();
// for (Index lambda(basis_.first_generator(j0));;++lambda)
// {
// const double coeff = f(lambda)/D(lambda);
// if (fabs(coeff)>1e-15)
// fhelp.set_coefficient(lambda, coeff);
// fhelp_int.set_coefficient(i, coeff);
// if (lambda == basis_.last_wavelet(jmax))
// break;
//
//
// }
#endif
fnorm_sqr = l2_norm_sqr(fhelp);
// sort the coefficients into fcoeffs
fcoeffs.resize(fhelp.size());
fcoeffs_int.resize(fhelp_int.size());
unsigned int id(0), id2(0);
for (typename InfiniteVector<double,Index>::const_iterator it(fhelp.begin()), itend(fhelp.end());
it != itend; ++it, ++id)
fcoeffs[id] = std::pair<Index,double>(it.index(), *it);
sort(fcoeffs.begin(), fcoeffs.end(), typename InfiniteVector<double,Index>::decreasing_order());
for (typename InfiniteVector<double,int>::const_iterator it(fhelp_int.begin()), itend(fhelp_int.end());
it != itend; ++it, ++id2)
fcoeffs_int[id2] = std::pair<int,double>(it.index(), *it);
sort(fcoeffs_int.begin(), fcoeffs_int.end(), typename InfiniteVector<double,int>::decreasing_order());
rhs_precomputed = true;
cout << "end precompute rhs.." << endl;
// cout << fhelp << endl;
// cout << fcoeffs << endl;
}
template <class WBASIS>
inline
double
SturmEquation<WBASIS>::D(const typename WBASIS::Index& lambda) const
{
#ifdef FRAME
#ifdef DYADIC
return mypow((1<<lambda.j())*mypow(1+lambda.p(),6),operator_order())*mypow(1+lambda.p(),2); //2^j*(p+1)^6, falls operator_order()=1 (\delta=4)
// return 1<<(lambda.j()*(int) operator_order());
#endif
#ifdef TRIVIAL
return 1;
#endif
#ifdef ENERGY
return stiff_diagonal[lambda.number()]*(lambda.p()+1);
#endif
#endif
#ifdef BASIS
#ifdef DYADIC
return 1<<(lambda.j()*(int) operator_order());
// return pow(ldexp(1.0, lambda.j()),operator_order());
#else
#ifdef TRIVIAL
return 1;
#else
#ifdef ENERGY
// return sqrt(a(lambda, lambda));
return stiff_diagonal[lambda.number()];
#else
return sqrt(a(lambda, lambda));
#endif
#endif
#endif
#else
return 1;
#endif
// return 1;
// return lambda.e() == 0 ? 1.0 : ldexp(1.0, lambda.j()); // do not scale the generators
// return lambda.e() == 0 ? 1.0 : sqrt(a(lambda, lambda)); // do not scale the generators
}
template <class WBASIS>
inline
double
SturmEquation<WBASIS>::a(const typename WBASIS::Index& lambda,
const typename WBASIS::Index& nu) const
{
return a(lambda, nu, 2*WBASIS::primal_polynomial_degree());
}
template <class WBASIS>
double
SturmEquation<WBASIS>::a(const typename WBASIS::Index& lambda,
const typename WBASIS::Index& nu,
const unsigned int p) const
{
// a(u,v) = \int_0^1 [p(t)u'(t)v'(t)+q(t)u(t)v(t)] dt
double r = 0;
// Remark: There are of course many possibilities to evaluate
// a(u,v) numerically.
// In this implementation, we rely on the fact that the primal functions in
// WBASIS are splines with respect to a dyadic subgrid.
// We can then apply an appropriate composite quadrature rule.
// In the scope of WBASIS, the routines intersect_supports() and evaluate()
// must exist, which is the case for DSBasis<d,dT>.
// First we compute the support intersection of \psi_\lambda and \psi_\nu:
typedef typename WBASIS::Support Support;
Support supp;
if (intersect_supports(basis_, lambda, nu, supp))
{
// Set up Gauss points and weights for a composite quadrature formula:
// (TODO: maybe use an instance of MathTL::QuadratureRule instead of computing
// the Gauss points and weights)
#ifdef FRAME
const unsigned int N_Gauss = std::min((unsigned int)10,(p+1)/2+ (lambda.p()+nu.p()+1)/2);
// const unsigned int N_Gauss = 10;
// const unsigned int N_Gauss = (p+1)/2;
#else
const unsigned int N_Gauss = (p+1)/2;
#endif
const double h = ldexp(1.0, -supp.j);
Array1D<double> gauss_points (N_Gauss*(supp.k2-supp.k1)), func1values, func2values, der1values, der2values;
for (int patch = supp.k1, id = 0; patch < supp.k2; patch++) // refers to 2^{-j}[patch,patch+1]
for (unsigned int n = 0; n < N_Gauss; n++, id++)
gauss_points[id] = h*(2*patch+1+GaussPoints[N_Gauss-1][n])/2.;
// - compute point values of the integrands
evaluate(basis_, lambda, gauss_points, func1values, der1values);
evaluate(basis_, nu, gauss_points, func2values, der2values);
// if((lambda.number()==19 && nu.number()==19) || (lambda.number()==26 && nu.number()==26)){
// cout << lambda << endl;
// cout << gauss_points << endl;
// cout << func1values << endl;
// cout << func2values << endl;
// }
// - add all integral shares
for (int patch = supp.k1, id = 0; patch < supp.k2; patch++)
for (unsigned int n = 0; n < N_Gauss; n++, id++) {
const double t = gauss_points[id];
const double gauss_weight = GaussWeights[N_Gauss-1][n] * h;
const double pt = bvp_.p(t);
if (pt != 0)
r += pt * der1values[id] * der2values[id] * gauss_weight;
const double qt = bvp_.q(t);
if (qt != 0)
r += qt * func1values[id] * func2values[id] * gauss_weight;
}
}
return r;
}
template <class WBASIS>
double
SturmEquation<WBASIS>::norm_A() const
{
if (normA == 0.0) {
typedef typename WaveletBasis::Index Index;
std::set<Index> Lambda;
const int j0 = basis().j0();
const int jmax = j0+3;
#ifdef FRAME
const int pmax = std::min(basis().get_pmax_(),2);
//const int pmax = 0;
int p = 0;
for (Index lambda = basis().first_generator(j0,0);;) {
Lambda.insert(lambda);
if (lambda == basis().last_wavelet(jmax,pmax)) break;
//if (i==7) break;
if (lambda == basis().last_wavelet(jmax,p)){
++p;
lambda = basis().first_generator(j0,p);
}
else
++lambda;
}
#else
for (Index lambda = first_generator(&basis(), j0);; ++lambda) {
Lambda.insert(lambda);
if (lambda == last_wavelet(&basis(), jmax)) break;
}
#endif
SparseMatrix<double> A_Lambda;
setup_stiffness_matrix(*this, Lambda, A_Lambda);
#if 1
double help;
unsigned int iterations;
LanczosIteration(A_Lambda, 1e-6, help, normA, 200, iterations);
normAinv = 1./help;
#else
Vector<double> xk(Lambda.size(), false);
xk = 1;
unsigned int iterations;
normA = PowerIteration(A_Lambda, xk, 1e-6, 100, iterations);
#endif
}
return normA;
}
template <class WBASIS>
double
SturmEquation<WBASIS>::norm_Ainv() const
{
if (normAinv == 0.0) {
typedef typename WaveletBasis::Index Index;
std::set<Index> Lambda;
const int j0 = basis().j0();
const int jmax = j0+3;
#ifdef FRAME
const int pmax = std::min(basis().get_pmax_(),2);
//const int pmax = 0;
int p = 0;
for (Index lambda = basis().first_generator(j0,0);;) {
Lambda.insert(lambda);
if (lambda == basis().last_wavelet(jmax,pmax)) break;
//if (i==7) break;
if (lambda == basis().last_wavelet(jmax,p)){
++p;
lambda = basis().first_generator(j0,p);
}
else<|fim▁hole|> for (Index lambda = first_generator(&basis(), j0);; ++lambda) {
Lambda.insert(lambda);
if (lambda == last_wavelet(&basis(), jmax)) break;
}
#endif
SparseMatrix<double> A_Lambda;
setup_stiffness_matrix(*this, Lambda, A_Lambda);
#if 1
double help;
unsigned int iterations;
LanczosIteration(A_Lambda, 1e-6, help, normA, 200, iterations);
normAinv = 1./help;
#else
Vector<double> xk(Lambda.size(), false);
xk = 1;
unsigned int iterations;
normAinv = InversePowerIteration(A_Lambda, xk, 1e-6, 200, iterations);
#endif
}
return normAinv;
}
template <class WBASIS>
double
SturmEquation<WBASIS>::f(const typename WBASIS::Index& lambda) const
{
// f(v) = \int_0^1 g(t)v(t) dt
// cout << "bin in f" << endl;
double r = 0;
const int j = lambda.j()+lambda.e();
int k1, k2;
support(basis_, lambda, k1, k2);
// Set up Gauss points and weights for a composite quadrature formula:
const unsigned int N_Gauss = 7; //perhaps we need +lambda.p()/2 @PHK
const double h = ldexp(1.0, -j);
Array1D<double> gauss_points (N_Gauss*(k2-k1)), vvalues;
for (int patch = k1; patch < k2; patch++) // refers to 2^{-j}[patch,patch+1]
for (unsigned int n = 0; n < N_Gauss; n++)
gauss_points[(patch-k1)*N_Gauss+n] = h*(2*patch+1+GaussPoints[N_Gauss-1][n])/2;
// - compute point values of the integrand
evaluate(basis_, 0, lambda, gauss_points, vvalues);
// cout << "bin immer noch in f" << endl;
// - add all integral shares
for (int patch = k1, id = 0; patch < k2; patch++)
for (unsigned int n = 0; n < N_Gauss; n++, id++) {
const double t = gauss_points[id];
const double gauss_weight = GaussWeights[N_Gauss-1][n] * h;
const double gt = bvp_.g(t);
if (gt != 0)
r += gt
* vvalues[id]
* gauss_weight;
}
#ifdef DELTADIS
// double tmp = 1;
// Point<1> p1;
// p1[0] = 0.5;
// Point<1> p2;
// chart->map_point_inv(p1,p2);
// tmp = evaluate(basis_, 0,
// typename WBASIS::Index(lambda.j(),
// lambda.e()[0],
// lambda.k()[0],
// basis_),
// p2[0]);
// tmp /= chart->Gram_factor(p2);
//
//
// return 4.0*tmp + r;
#ifdef NONZERONEUMANN
return r + 4*basis_.evaluate(0, lambda, 0.5)+3*M_PI*(basis_.evaluate(0, lambda, 1)+basis_.evaluate(0, lambda, 0));
#else
return r+ 4*basis_.evaluate(0, lambda, 0.5);
#endif
#else
return r;
#endif
}
template <class WBASIS>
inline
void
SturmEquation<WBASIS>::RHS(const double eta,
InfiniteVector<double, typename WBASIS::Index>& coeffs) const
{
if (!rhs_precomputed) precompute_rhs();
coeffs.clear();
double coarsenorm(0);
double bound(fnorm_sqr - eta*eta);
typedef typename WBASIS::Index Index;
typename Array1D<std::pair<Index, double> >::const_iterator it(fcoeffs.begin());
do {
coarsenorm += it->second * it->second;
coeffs.set_coefficient(it->first, it->second);
++it;
} while (it != fcoeffs.end() && coarsenorm < bound);
}
template <class WBASIS>
inline
void
SturmEquation<WBASIS>::RHS(const double eta,
InfiniteVector<double,int>& coeffs) const
{
if (!rhs_precomputed) precompute_rhs();
coeffs.clear();
double coarsenorm(0);
double bound(fnorm_sqr - eta*eta);
typename Array1D<std::pair<int, double> >::const_iterator it(fcoeffs_int.begin());
do {
coarsenorm += it->second * it->second;
coeffs.set_coefficient(it->first, it->second);
++it;
} while (it != fcoeffs_int.end() && coarsenorm < bound);
}
template <class WBASIS>
void
SturmEquation<WBASIS>::compute_diagonal()
{
cout << "SturmEquation(): precompute diagonal of stiffness matrix..." << endl;
SparseMatrix<double> diag(1,basis_.degrees_of_freedom());
char filename[50];
char matrixname[50];
#ifdef ONE_D
int d = WBASIS::primal_polynomial_degree();
int dT = WBASIS::primal_vanishing_moments();
#else
#ifdef TWO_D
int d = WBASIS::primal_polynomial_degree();
int dT = WBASIS::primal_vanishing_moments();
#endif
#endif
// prepare filenames for 1D and 2D case
#ifdef ONE_D
sprintf(filename, "%s%d%s%d", "stiff_diagonal_poisson_interval_lap07_d", d, "_dT", dT);
sprintf(matrixname, "%s%d%s%d", "stiff_diagonal_poisson_1D_lap07_d", d, "_dT", dT);
#endif
#ifdef TWO_D
sprintf(filename, "%s%d%s%d", "stiff_diagonal_poisson_lshaped_lap1_d", d, "_dT", dT);
sprintf(matrixname, "%s%d%s%d", "stiff_diagonal_poisson_2D_lap1_d", d, "_dT", dT);
#endif
#ifndef PRECOMP_DIAG
std::list<Vector<double>::size_type> indices;
std::list<double> entries;
#endif
#ifdef PRECOMP_DIAG
cout << "reading in diagonal of unpreconditioned stiffness matrix from file "
<< filename << "..." << endl;
diag.matlab_input(filename);
cout << "...ready" << endl;
#endif
stiff_diagonal.resize(basis_.degrees_of_freedom());
for (int i = 0; i < basis_.degrees_of_freedom(); i++) {
#ifdef PRECOMP_DIAG
stiff_diagonal[i] = diag.get_entry(0,i);
#endif
#ifndef PRECOMP_DIAG
#ifdef FRAME
stiff_diagonal[i] = sqrt(a(*(basis_.get_quarklet(i)),*(basis_.get_quarklet(i))));
#endif
#ifdef BASIS
stiff_diagonal[i] = sqrt(a(*(basis_.get_wavelet(i)),*(basis_.get_wavelet(i))));
#endif
indices.push_back(i);
entries.push_back(stiff_diagonal[i]);
#endif
//cout << stiff_diagonal[i] << " " << *(basis_->get_wavelet(i)) << endl;
}
#ifndef PRECOMP_DIAG
diag.set_row(0,indices, entries);
diag.matlab_output(filename, matrixname, 1);
#endif
cout << "... done, diagonal of stiffness matrix computed" << endl;
}
}<|fim▁end|>
|
++lambda;
}
#else
|
<|file_name|>app.libraries.js<|end_file_name|><|fim▁begin|>import angular from 'angular';
import uiRouter from 'angular-ui-router';
import uiBoostrap from 'angular-ui-bootstrap';
import angularJwt from 'angular-jwt';
let librariesModules = angular.module('app.libraries', [
uiRouter,
uiBoostrap,<|fim▁hole|>]);
export default librariesModules;<|fim▁end|>
|
angularJwt
|
<|file_name|>dispatcher.py<|end_file_name|><|fim▁begin|>"""Offers a simple XML-RPC dispatcher for django_xmlrpc
Author::
Graham Binns
Credit must go to Brendan W. McAdams <[email protected]>, who
posted the original SimpleXMLRPCDispatcher to the Django wiki:
http://code.djangoproject.com/wiki/XML-RPC
New BSD License
===============
Copyright (c) 2007, Graham Binns http://launchpad.net/~codedragon
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.<|fim▁hole|>
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
"""
# This file is needed to run XMLRPC
from inspect import getargspec
from SimpleXMLRPCServer import SimpleXMLRPCDispatcher
from django.conf import settings
# If we need to debug, now we know
DEBUG = hasattr(settings, 'XMLRPC_DEBUG') and settings.XMLRPC_DEBUG
class DjangoXMLRPCDispatcher(SimpleXMLRPCDispatcher):
"""A simple XML-RPC dispatcher for Django.
Subclassess SimpleXMLRPCServer.SimpleXMLRPCDispatcher for the purpose of
overriding certain built-in methods (it's nicer than monkey-patching them,
that's for sure).
"""
def system_methodSignature(self, method):
"""Returns the signature details for a specified method
method
The name of the XML-RPC method to get the details for
"""
# See if we can find the method in our funcs dict
# TODO: Handle this better: We really should return something more
# formal than an AttributeError
func = self.funcs[method]
try:
sig = func._xmlrpc_signature
except:
sig = {
'returns': 'string',
'args': ['string' for arg in getargspec(func)[0]],
}
return [sig['returns']] + sig['args']<|fim▁end|>
|
* Neither the name of the <ORGANIZATION> nor the names of its contributors
may be used to endorse or promote products derived from this software
without specific prior written permission.
|
<|file_name|>home.component.ts<|end_file_name|><|fim▁begin|>import { Component } from '@angular/core';
import { Router } from '@angular/router';
import { AuthService } from '../auth/auth.service';
@Component({
selector: 'app-home',
templateUrl: './home.component.html',
styleUrls: ['./home.component.css']
})
<|fim▁hole|>export class HomeComponent {
constructor(public router: Router, public auth: AuthService) {
}
}<|fim▁end|>
| |
<|file_name|>enum_map.cpp<|end_file_name|><|fim▁begin|>#if BUILD_UNIT_TESTS
#include "augs/misc/enum/enum_map.h"
#include <Catch/single_include/catch2/catch.hpp>
TEST_CASE("EnumMap") {
enum class tenum {
_0,
_1,
_2,
_3,
_4,
COUNT
};
augs::enum_map<tenum, int> mm;
mm[tenum::_0] = 0;
mm[tenum::_1] = 1;
mm[tenum::_2] = 2;
int cnt = 0;
for (const auto&& m : mm) {
REQUIRE(m.first == tenum(m.second));
REQUIRE(m.second == cnt++);<|fim▁hole|>
REQUIRE(3 == cnt);
for (const auto&& m : reverse(mm)) {
REQUIRE(m.first == tenum(m.second));
REQUIRE(m.second == --cnt);
}
REQUIRE(0 == cnt);
{
augs::enum_map<tenum, int> emp;
for (const auto&& abc : emp) {
REQUIRE(false);
(void)abc;
}
for (const auto&& abc : reverse(emp)) {
REQUIRE(false);
(void)abc;
}
REQUIRE(emp.size() == 0);
emp[tenum::_0] = 48;
REQUIRE(emp.size() == 1);
for (const auto&& m : reverse(emp)) {
REQUIRE(48 == m.second);
}
emp.clear();
REQUIRE(emp.size() == 0);
emp[tenum::_1] = 84;
REQUIRE(emp.size() == 1);
for (const auto&& m : reverse(emp)) {
REQUIRE(84 == m.second);
}
emp[tenum::_0] = 0;
emp[tenum::_1] = 1;
emp[tenum::_2] = 2;
REQUIRE(emp.size() == 3);
for (const auto&& m : emp) {
REQUIRE(m.first == tenum(m.second));
REQUIRE(m.second == cnt++);
}
REQUIRE(3 == cnt);
for (const auto&& m : reverse(emp)) {
REQUIRE(m.first == tenum(m.second));
REQUIRE(m.second == --cnt);
}
emp.clear();
REQUIRE(emp.size() == 0);
emp[tenum::_4] = 4;
emp[tenum::_3] = 3;
emp[tenum::_1] = 1;
emp[tenum::_0] = 0;
auto it = emp.rbegin();
REQUIRE((*it).second == 4);
REQUIRE((*++it).second == 3);
REQUIRE((*++it).second == 1);
REQUIRE((*++it).second == 0);
REQUIRE(++it == emp.rend());
}
}
#endif<|fim▁end|>
|
}
|
<|file_name|>tree.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*-
#
# tree.py
#
# (c) D.C.-G. 2014
#
# Tree widget for albow
#
from albow.widget import Widget
from albow.menu import Menu
from albow.fields import IntField, FloatField, TextFieldWrapped
from albow.controls import CheckBox, AttrRef, Label, Button
from albow.dialogs import ask, alert, input_text_buttons
from albow.translate import _
from extended_widgets import ChoiceButton
from theme import ThemeProperty
from layout import Column, Row
from dialogs import Dialog
from palette_view import PaletteView
from scrollpanel import ScrollRow
from utils import blit_in_rect
from pygame import image, Surface, Rect, SRCALPHA, draw, event
import copy
#-----------------------------------------------------------------------------
item_types_map = {dict: ("Compound", None, {}),
int: ("Integer", IntField, 0),
float: ("Floating point", FloatField, 0.0),
unicode: ("Text", TextFieldWrapped, ""),
bool: ("Boolean", CheckBox, True),
}
def setup_map_types_item(mp=None):
if not mp:
mp = item_types_map
map_types_item = {}
for k, v in mp.items():
if v[0] in map_types_item.keys():
_v = map_types_item.pop(v[0])
map_types_item[u"%s (%s)"%(_(v[0]), _v[0].__name__)] = _v
map_types_item[u"%s (%s)"%(_(v[0]), k.__name__)] = (k, v[1], v[2])
else:
map_types_item[v[0]] = (k, v[1], v[2])
return map_types_item
map_types_item = setup_map_types_item()
#-----------------------------------------------------------------------------
# Tree item builder methods
def create_base_item(self, i_type, i_name, i_value):
return i_name, type(i_type)(i_value)
create_dict = create_int = create_float = create_unicode = create_bool = create_base_item
#-----------------------------------------------------------------------------
class SetupNewItemPanel(Dialog):
def __init__(self, type_string, types=map_types_item, ok_action=None):
self.type_string = type_string
self.ok_action = ok_action
title = Label("Choose default data")
self.t, widget, self.v = types[type_string]
self.n = u""
w_name = TextFieldWrapped(ref=AttrRef(self, 'n'))
self.w_value = self.get_widget(widget)
col = Column([Column([title,]), Label(_("Item Type: %s")%type_string, doNotTranslate=True), Row([Label("Name"), w_name], margin=0), Row([Label("Value"), self.w_value], margin=0), Row([Button("OK", action=ok_action or self.dismiss_ok), Button("Cancel", action=self.dismiss)], margin=0)], margin=0, spacing=2)
Dialog.__init__(self, client=col)
def dismiss_ok(self):
self.dismiss((self.t, self.n, getattr(self.w_value, 'value', map_types_item.get(self.type_string, [None,] * 3)[2])))
def get_widget(self, widget):
if hasattr(widget, 'value'):
value = widget(value=self.v)
elif hasattr(widget, 'text'):
value = widget(text=self.v)
elif widget is None:
value = Label("This item type is a container. Add chlidren later.")
else:
msg = "*** Error in SelectItemTypePanel.__init__():\n Widget <%s> has no 'text' or 'value' member."%widget
print msg
value = Label(msg)
return value
#-----------------------------------------------------------------------------
class SelectItemTypePanel(Dialog):
def __init__(self, title, responses, default=None, ok_action=None):
self.response = responses[0]
self.ok_action = ok_action
title = Label(title)
self.w_type = ChoiceButton(responses)
col = Column([title, self.w_type, Row([Button("OK", action=ok_action or self.dismiss_ok), Button("Cancel", action=ok_action or self.dismiss)], margin=0)], margin=0, spacing=2)
Dialog.__init__(self, client=col)
def dismiss_ok(self):
self.dismiss(self.w_type.selectedChoice)
#-----------------------------------------------------------------------------
def select_item_type(ok_action, types=map_types_item):
if len(types) > 1:
choices = types.keys()
choices.sort()
result = SelectItemTypePanel("Choose item type", responses=choices, default=None).present()
else:
result = types.keys()[0]
if type(result) in (str, unicode):
return SetupNewItemPanel(result, types, ok_action).present()
return None
#-----------------------------------------------------------------------------
class TreeRow(ScrollRow):
def click_item(self, n, e):
self.parent.click_item(n, e.local)
def mouse_down(self, e):
if e.button == 3:
_e = event.Event(e.type, {'alt': e.alt, 'meta': e.meta, 'ctrl': e.ctrl,
'shift': e.shift, 'button': 1, 'cmd': e.cmd,
'local': e.local, 'pos': e.pos,
'num_clicks': e.num_clicks})
ScrollRow.mouse_down(self, _e)
self.parent.show_menu(e.local)
else:
ScrollRow.mouse_down(self, e)
#-----------------------------------------------------------------------------
class Tree(Column):
"""..."""
rows = []
row_margin = 2
column_margin = 2
bullet_size = ThemeProperty('bullet_size')
bullet_color_active = ThemeProperty('bullet_color_active')
bullet_color_inactive = ThemeProperty('bullet_color_inactive')
def __init__(self, *args, **kwargs):
self.menu = [("Add", "add_item"),
("Delete", "delete_item"),
("New child", "add_child"),
("Rename", "rename_item"),
("", ""),
("Cut", "cut_item"),
("Copy", "copy_item"),
("Paste", "paste_item"),
("Paste as child", "paste_child"),
]
if not hasattr(self, 'map_types_item'):
global map_types_item
self.map_types_item = setup_map_types_item()
self.selected_item_index = None
self.selected_item = None
self.clicked_item = None
self.copyBuffer = kwargs.pop('copyBuffer', None)
self._parent = kwargs.pop('_parent', None)
self.styles = kwargs.pop('styles', {})
self.compound_types = [dict,] + kwargs.pop('compound_types', [])
self.item_types = self.compound_types + kwargs.pop('item_types', [a[0] for a in self.map_types_item.values()] or [int, float, unicode, bool])
for t in self.item_types:
if 'create_%s'%t.__name__ in globals().keys():
setattr(self, 'create_%s'%t.__name__, globals()['create_%s'%t.__name__])
self.show_fields = kwargs.pop('show_fields', False)
self.deployed = []
self.data = data = kwargs.pop("data", {})
self.draw_zebra = draw_zebra = kwargs.pop('draw_zebra', True)
# self.inner_width = kwargs.pop('inner_width', 'auto')
self.inner_width = kwargs.pop('inner_width', 500)
self.__num_rows = len(data.keys())
self.build_layout()
# row_height = self.font.size(' ')[1]
row_height = self.font.get_linesize()
self.treeRow = treeRow = TreeRow((self.inner_width, row_height), 10, draw_zebra=draw_zebra)
Column.__init__(self, [treeRow,], **kwargs)
def dispatch_key(self, name, evt):
if not hasattr(evt, 'key'):
return
if name == "key_down":
keyname = self.root.getKey(evt)
if keyname == "Up" and self.selected_item_index > 0:
if self.selected_item_index == None:
self.selected_item_index = -1
self.selected_item_index = max(self.selected_item_index - 1, 0)
elif keyname == "Down" and self.selected_item_index < len(self.rows) - 1:
if self.selected_item_index == None:
self.selected_item_index = -1
self.selected_item_index += 1
elif keyname == 'Page down':
if self.selected_item_index == None:
self.selected_item_index = -1
self.selected_item_index = min(len(self.rows) - 1, self.selected_item_index + self.treeRow.num_rows())
elif keyname == 'Page up':
if self.selected_item_index == None:
self.selected_item_index = -1
self.selected_item_index = max(0, self.selected_item_index - self.treeRow.num_rows())
if self.treeRow.cell_to_item_no(0, 0) != None and (self.treeRow.cell_to_item_no(0, 0) + self.treeRow.num_rows() -1 > self.selected_item_index or self.treeRow.cell_to_item_no(0, 0) + self.treeRow.num_rows() -1 < self.selected_item_index):
self.treeRow.scroll_to_item(self.selected_item_index)
if keyname == 'Return' and self.selected_item_index != None:
self.select_item(self.selected_item_index)
if self.selected_item[7] in self.compound_types:
self.deploy(self.selected_item[6])
def cut_item(self):
self.copyBuffer = ([] + self.selected_item, 1)
self.delete_item()
def copy_item(self):
self.copyBuffer = ([] + self.selected_item, 0)
def paste_item(self):
parent = self.get_item_parent(self.selected_item)
name = self.copyBuffer[0][3]
old_name = u"%s"%self.copyBuffer[0][3]
if self.copyBuffer[1] == 0:
name = input_text_buttons("Choose a name", 300, self.copyBuffer[0][3])
else:
old_name = ""
if name and type(name) in (str, unicode) and name != old_name:
new_item = copy.deepcopy(self.copyBuffer[0][9])
if hasattr(new_item, 'name'):
new_item.name = name
self.add_item_to(parent, (name, new_item))
def paste_child(self):
name = self.copyBuffer[0][3]
old_name = u"%s"%self.copyBuffer[0][3]
names = []
children = self.get_item_children(self.selected_item)
if children:
names = [a[3] for a in children]
if name in names:
name = input_text_buttons("Choose a name", 300, self.copyBuffer[0][3])
else:
old_name = ""
if name and type(name) in (str, unicode) and name != old_name:
new_item = copy.deepcopy(self.copyBuffer[0][9])
if hasattr(new_item, 'name'):
new_item.name = name
self.add_item_to(self.selected_item, (name, new_item))
@staticmethod
def add_item_to_dict(parent, name, item):
parent[name] = item
def add_item_to(self, parent, (name, item)):
if parent is None:
tp = 'dict'
parent = self.data
else:
tp = parent[7].__name__
parent = parent[9]
if not name:
i = 0
name = 'Item %03d'%i
while name in self.data.keys():
i += 1
name = 'Item %03d'%i
meth = getattr(self, 'add_item_to_%s'%tp, None)
if meth:
meth(parent, name, item)
self.build_layout()
else:
alert(_("No function implemented to add items to %s type.")%type(parent).__name__, doNotTranslate=True)
def add_item(self, types_item=None):
r = select_item_type(None, types_item or self.map_types_item)
if type(r) in (list, tuple):
t, n, v = r
meth = getattr(self, 'create_%s'%t.__name__, None)
if meth:
new_item = meth(self, t, n, v)
self.add_item_to(self.get_item_parent(self.selected_item), new_item)
def add_child(self, types_item=None):
r = select_item_type(None, types_item or self.map_types_item)
if type(r) in (list, tuple):
t, n, v = r
meth = getattr(self, 'create_%s'%t.__name__, None)
if meth:
new_item = meth(self, t, n, v)
self.add_item_to(self.selected_item, new_item)
def delete_item(self):
parent = self.get_item_parent(self.selected_item) or self.data
del parent[self.selected_item]
self.selected_item_index = None
self.selected_item = None
self.build_layout()
def rename_item(self):
result = input_text_buttons("Choose a name", 300, self.selected_item[3])
if type(result) in (str, unicode):
self.selected_item[3] = result
self.build_layout()
def get_item_parent(self, item):
if item:
pid = item[4]
for itm in self.rows:
if pid == itm[6]:
return itm
def get_item_children(self, item):
children = []
if item:
if item[6] in self.deployed:
cIds = item[5]
idx = self.rows.index(item)
for child in self.rows[idx:]:
if child[8] == item[8] + 1 and child[4] == item[6]:
children.append(child)
else:
k = item[3]
v = item[9]
lvl = item[8]
id = item[6]
aId = len(self.rows) + 1
meth = getattr(self, 'parse_%s'%v.__class__.__name__, None)
if meth is not None:
_v = meth(k, v)
else:
_v = v
ks = _v.keys()
ks.sort()
ks.reverse()
for a in ks:
b = _v[a]
itm = [lvl + 1, a, b, id, [], aId]
itm = [None, None, None, a, id, [], aId, type(b), lvl + 1, b]
children.insert(0, itm)
aId += 1
return children
def show_menu(self, pos):
if self.menu:
m = Menu("Menu", self.menu, handler=self)
i = m.present(self, pos)
if i > -1:
meth = getattr(self, self.menu[i][1], None)
if meth:
meth()
def cut_item_enabled(self):
return self.selected_item is not None
def copy_item_enabled(self):
return self.cut_item_enabled()
def paste_item_enabled(self):
return self.copyBuffer is not None
def paste_child_enabled(self):
if not self.selected_item:
return False
return self.paste_item_enabled() and self.selected_item[7] in self.compound_types
def add_item_enabled(self):
return True
def add_child_enabled(self):
if not self.selected_item:
return False
return self.selected_item[7] in self.compound_types
def delete_item_enabled(self):
return self.selected_item is not None
def rename_item_enabled(self):
return self.selected_item is not None
def build_layout(self):
data = self.data
parent = 0
children = []
keys = data.keys()
keys.sort()
items = [[0, a, data[a], parent, children, keys.index(a) + 1] for a in keys]
rows = []
w = 50
aId = len(items) + 1
while items:
lvl, k, v, p, c, id = items.pop(0)
_c = False
fields = []
c = [] + c
if type(v) in self.compound_types:
meth = getattr(self, 'parse_%s'%v.__class__.__name__, None)
if meth is not None:
_v = meth(k, v)
else:
_v = v
ks = _v.keys()
ks.sort()
ks.reverse()
for a in ks:
b = _v[a]
if id in self.deployed:
itm = [lvl + 1, a, b, id, [], aId]
items.insert(0, itm)
c.append(aId)
_c = True
aId += 1
else:
if type(v) in (list, tuple):
fields = v
elif type(v) not in self.compound_types or hasattr(self._parent, 'build_%s'%k.lower()):
fields = [v,]
head = Surface((self.bullet_size * (lvl + 1) + self.font.size(k)[0], self.bullet_size), SRCALPHA)
if _c:
meth = getattr(self, 'draw_%s_bullet'%{False: 'closed', True: 'opened'}[id in self.deployed])
else:
meth = getattr(self, 'draw_%s_bullet'%v.__class__.__name__, None)
if not meth:
meth = self.draw_deadend_bullet
bg, fg, shape, text = self.styles.get(type(v),
({True: self.bullet_color_active, False: self.bullet_color_inactive}[_c],
self.fg_color, 'square', ''),
)
try:
meth(head, bg, fg, shape, text, k, lvl)
except:
pass
rows.append([head, fields, [w] * len(fields), k, p, c, id, type(v), lvl, v])
self.rows = rows
return rows
def deploy(self, id):
p = None
if self.selected_item:
s_idx = 0 + self.selected_item_index
num_rows = len(self.rows)
if id in self.deployed:
self.deployed.remove(id)
if self.selected_item:
if self.selected_item[4] == id:
p = self.get_item_parent(self.selected_item)
p_idx = self.rows.index(p)
else:
self.deployed.append(id)
self.build_layout()
if p:
self.select_item(p_idx)
elif self.selected_item and s_idx > id:
self.select_item(s_idx + (len(self.rows) - num_rows))
def click_item(self, n, pos):
"""..."""
self.clicked_item = row = self.rows[n]
r = self.get_bullet_rect(row[0], row[8])
x = pos[0]
if self.margin + r.left - self.treeRow.hscroll <= x <= self.margin + self.treeRow.margin + r.right - self.treeRow.hscroll:
id = row[6]
self.deploy(id)
else:
self.select_item(n)
def select_item(self, n):
self.selected_item_index = n
self.selected_item = self.rows[n]
def get_bullet_rect(self, surf, lvl):
r = Rect(0, 0, self.bullet_size, self.bullet_size)
r.left = self.bullet_size * lvl
r.inflate_ip(-4, -4)
return r
def draw_item_text(self, surf, r, text):
buf = self.font.render(unicode(text), True, self.fg_color)
blit_in_rect(surf, buf, Rect(r.right, r.top, surf.get_width() - r.right, r.height), 'c')
def draw_deadend_bullet(self, surf, bg, fg, shape, text, item_text, lvl):
r = self.get_bullet_rect(surf, lvl)
draw.polygon(surf, bg, [r.midtop, r.midright, r.midbottom, r.midleft])
self.draw_item_text(surf, r, item_text)
def draw_closed_bullet(self, surf, bg, fg, shape, text, item_text, lvl):
r = self.get_bullet_rect(surf, lvl)
draw.polygon(surf, bg, [r.topleft, r.midright, r.bottomleft])
self.draw_item_text(surf, r, item_text)
def draw_opened_bullet(self, surf, bg, fg, shape, text, item_text, lvl):
r = self.get_bullet_rect(surf, lvl)
draw.polygon(surf, bg, [r.topleft, r.midbottom, r.topright])
self.draw_item_text(surf, r, item_text)
def draw_tree_cell(self, surf, i, data, cell_rect, column):
"""..."""
if type(data) in (str, unicode):
self.draw_text_cell(surf, i, data, cell_rect, 'l', self.font)
else:
self.draw_image_cell(surf, i, data, cell_rect, column)
@staticmethod
def draw_image_cell(surf, i, data, cell_rect, column):
"""..."""
blit_in_rect(surf, data, cell_rect, 'l')
def draw_text_cell(self, surf, i, data, cell_rect, align, font):
buf = font.render(unicode(data), True, self.fg_color)
blit_in_rect(surf, buf, cell_rect, align)
def num_rows(self):
return len(self.rows)
def row_data(self, row):
return self.rows[row]
def column_info(self, row_data):
m = self.column_margin
d = 2 * m
x = 0
for i in range(0,2):
if i < 1:<|fim▁hole|> x += width
if self.show_fields:
for i in range(len(row_data[2])):
width = 50 * (i + 1)
data = row_data[2][i]
if type(data) != (str, unicode):
data = repr(data)
yield i, x + m, width - d, None, data
x += width<|fim▁end|>
|
width = self.width
data = row_data[i]
yield i, x + m, width - d, None, data
|
<|file_name|>offset.js<|end_file_name|><|fim▁begin|>define([
"./core",
"./core/access",
"./var/document",
"./var/documentElement",
"./css/var/rnumnonpx",
"./css/curCSS",
"./css/addGetHookIf",
"./css/support",
"./core/init",
"./css",
"./selector" // contains
], function( jQuery, access, document, documentElement, rnumnonpx, curCSS, addGetHookIf, support ) {
/**
* Gets a window from an element
*/
function getWindow( elem ) {
return jQuery.isWindow( elem ) ? elem : elem.nodeType === 9 && elem.defaultView;
}
jQuery.offset = {
setOffset: function( elem, options, i ) {
var curPosition, curLeft, curCSSTop, curTop, curOffset, curCSSLeft, calculatePosition,
position = jQuery.css( elem, "position" ),
curElem = jQuery( elem ),
props = {};
// Set position first, in-case top/left are set even on static elem
if ( position === "static" ) {
elem.style.position = "relative";
}
curOffset = curElem.offset();
curCSSTop = jQuery.css( elem, "top" );
curCSSLeft = jQuery.css( elem, "left" );
calculatePosition = ( position === "absolute" || position === "fixed" ) &&
( curCSSTop + curCSSLeft ).indexOf("auto") > -1;
// Need to be able to calculate position if either
// top or left is auto and position is either absolute or fixed
if ( calculatePosition ) {
curPosition = curElem.position();
curTop = curPosition.top;
curLeft = curPosition.left;
} else {
curTop = parseFloat( curCSSTop ) || 0;
curLeft = parseFloat( curCSSLeft ) || 0;
}
if ( jQuery.isFunction( options ) ) {
// Use jQuery.extend here to allow modification of coordinates argument (gh-1848)
options = options.call( elem, i, jQuery.extend( {}, curOffset ) );
}
if ( options.top != null ) {
props.top = ( options.top - curOffset.top ) + curTop;
}
if ( options.left != null ) {
props.left = ( options.left - curOffset.left ) + curLeft;
}
if ( "using" in options ) {
options.using.call( elem, props );
} else {
curElem.css( props );
}
}
};
jQuery.fn.extend({
offset: function( options ) {
// Preserve chaining for setter
if ( arguments.length ) {
return options === undefined ?
this :
this.each(function( i ) {
jQuery.offset.setOffset( this, options, i );
});
}
var docElem, win, rect, doc,
elem = this[ 0 ];
if ( !elem ) {
return;
}
rect = elem.getBoundingClientRect();
// Make sure element is not hidden (display: none) or disconnected
if ( rect.width || rect.height || elem.getClientRects().length ) {
doc = elem.ownerDocument;
win = getWindow( doc );
docElem = doc.documentElement;
return {
top: rect.top + win.pageYOffset - docElem.clientTop,
left: rect.left + win.pageXOffset - docElem.clientLeft
};
}
},
position: function() {
if ( !this[ 0 ] ) {
return;
}
var offsetParent, offset,
elem = this[ 0 ],
parentOffset = { top: 0, left: 0 };
// Fixed elements are offset from window (parentOffset = {top:0, left: 0},
// because it is its only offset parent
if ( jQuery.css( elem, "position" ) === "fixed" ) {
// Assume getBoundingClientRect is there when computed position is fixed
offset = elem.getBoundingClientRect();
} else {
// Get *real* offsetParent
offsetParent = this.offsetParent();
// Get correct offsets
offset = this.offset();
if ( !jQuery.nodeName( offsetParent[ 0 ], "html" ) ) {
parentOffset = offsetParent.offset();
}
// Add offsetParent borders
// Subtract offsetParent scroll positions
parentOffset.top += jQuery.css( offsetParent[ 0 ], "borderTopWidth", true ) -
offsetParent.scrollTop();
parentOffset.left += jQuery.css( offsetParent[ 0 ], "borderLeftWidth", true ) -
offsetParent.scrollLeft();
}
// Subtract parent offsets and element margins
return {
top: offset.top - parentOffset.top - jQuery.css( elem, "marginTop", true ),
left: offset.left - parentOffset.left - jQuery.css( elem, "marginLeft", true )
};
},
// This method will return documentElement in the following cases:<|fim▁hole|> // 1) For the element inside the iframe without offsetParent, this method will return
// documentElement of the parent window
// 2) For the hidden or detached element
// 3) For body or html element, i.e. in case of the html node - it will return itself
//
// but those exceptions were never presented as a real life use-cases
// and might be considered as more preferable results.
//
// This logic, however, is not guaranteed and can change at any point in the future
offsetParent: function() {
return this.map(function() {
var offsetParent = this.offsetParent;
while ( offsetParent && jQuery.css( offsetParent, "position" ) === "static" ) {
offsetParent = offsetParent.offsetParent;
}
return offsetParent || documentElement;
});
}
});
// Create scrollLeft and scrollTop methods
jQuery.each( { scrollLeft: "pageXOffset", scrollTop: "pageYOffset" }, function( method, prop ) {
var top = "pageYOffset" === prop;
jQuery.fn[ method ] = function( val ) {
return access( this, function( elem, method, val ) {
var win = getWindow( elem );
if ( val === undefined ) {
return win ? win[ prop ] : elem[ method ];
}
if ( win ) {
win.scrollTo(
!top ? val : win.pageXOffset,
top ? val : win.pageYOffset
);
} else {
elem[ method ] = val;
}
}, method, val, arguments.length, null );
};
});
// Support: Safari<7+, Chrome<37+
// Add the top/left cssHooks using jQuery.fn.position
// Webkit bug: https://bugs.webkit.org/show_bug.cgi?id=29084
// Blink bug: https://code.google.com/p/chromium/issues/detail?id=229280
// getComputedStyle returns percent when specified for top/left/bottom/right;
// rather than make the css module depend on the offset module, just check for it here
jQuery.each( [ "top", "left" ], function( i, prop ) {
jQuery.cssHooks[ prop ] = addGetHookIf( support.pixelPosition,
function( elem, computed ) {
if ( computed ) {
computed = curCSS( elem, prop );
// If curCSS returns percentage, fallback to offset
return rnumnonpx.test( computed ) ?
jQuery( elem ).position()[ prop ] + "px" :
computed;
}
}
);
});
return jQuery;
});<|fim▁end|>
| |
<|file_name|>Mesure_test.cpp<|end_file_name|><|fim▁begin|>//
//#include "Mesure.h"
//
<|fim▁hole|>//{
//
//}
//
//void loop()
//{
// m = new Mesure(13,20,4,4);
// m->addNote(Note_E,4,NOIR);
// m->addNote(Note_E,4,NOIR);
// m->addNote(Note_E,4,NOIR);
// m->addNote(Note_C,4,NOIR);
// m->play();
//
// m = new Mesure(13,20,4,4);
// m->addNote(Note_E,4,NOIR);
// m->addNote(Note_G,4,NOIR);
// m->addNote(Note_G,3,NOIR);
// m->addNote(Note_C,4,NOIR);
// m->play();
//
// m = new Mesure(13,20,4,4);
// m->addNote(Note_G,3,NOIR);
// m->addNote(Note_E,3,NOIR);
// m->addNote(Note_G,3,NOIR);
// m->addNote(Note_A,3,NOIR);
// m->play();
//
// m = new Mesure(13,20,4,4);
// m->addNote(Note_Gd,3,NOIR);
// m->addNote(Note_Gd,3,NOIR);
// m->addNote(Note_E,4,NOIR);
// m->addNote(Note_G,4,NOIR);
// m->play();
//
// m = new Mesure(13,20,4,4);
// m->addNote(Note_A,4,NOIR);
// m->addNote(Note_F,4,NOIR);
// m->addNote(Note_G,4,NOIR);
// m->addNote(Note_E,4,NOIR);
// m->play();
//
// m = new Mesure(13,20,4,4);
// m->addNote(Note_C,4,NOIR);
// m->addNote(Note_D,4,NOIR);
// m->addNote(Note_B,3,NOIR);
// m->addNote(Note_C,4,NOIR);
// m->play();
//
// m = new Mesure(13,20,4,4);
// m->addNote(Note_G,3,NOIR);
// m->addNote(Note_E,3,NOIR);
// m->addNote(Note_G,3,NOIR);
// m->addNote(Note_A,3,NOIR);
// m->play();
//
// m = new Mesure(13,20,4,4);
// m->addNote(Note_Gd,3,NOIR);
// m->addNote(Note_Gd,3,NOIR);
// m->addNote(Note_E,4,NOIR);
// m->addNote(Note_G,4,NOIR);
// m->play();
//
// delay(5000);
//}<|fim▁end|>
|
//Mesure *m;
//
//void setup()
|
<|file_name|>ProofPreferencesPanelPluginLoader.java<|end_file_name|><|fim▁begin|>package org.liveontologies.protege.justification.proof.preferences;
/*-
* #%L
* Protege Proof Justification
* $Id:$
* $HeadURL:$
* %%
* Copyright (C) 2016 - 2017 Live Ontologies Project
* %%
* 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.
* #L%
*/
import org.eclipse.core.runtime.IExtension;
import org.protege.editor.core.editorkit.EditorKit;
import org.protege.editor.core.plugin.AbstractPluginLoader;
public class ProofPreferencesPanelPluginLoader extends AbstractPluginLoader<ProofPreferencesPanelPlugin> {
private final EditorKit kit;
private static final String ID = "JustificationProofPreferences";
private static final String KEY = "org.liveontologies.protege.justification.proof";
public ProofPreferencesPanelPluginLoader(EditorKit kit) {
<|fim▁hole|> super(KEY, ID);
this.kit = kit;
}
@Override
protected ProofPreferencesPanelPlugin createInstance(IExtension extension) {
return new ProofPreferencesPanelPlugin(kit, extension);
}
}<|fim▁end|>
| |
<|file_name|>djb2.rs<|end_file_name|><|fim▁begin|>use redox::hash::Hasher;
pub struct Djb2 {
state: u64,
}
impl Djb2 {
/// Create new DJB2 hasher
pub fn new() -> Self {
Djb2 {
state: 5381,
}
}
}
impl Hasher for Djb2 {
fn finish(&self) -> u64 {
self.state
}
fn write(&mut self, bytes: &[u8]) {
for &b in bytes {
self.state = ((self.state << 5) + self.state) + b as u64;
}
}<|fim▁hole|><|fim▁end|>
|
}
|
<|file_name|>ageondate.py<|end_file_name|><|fim▁begin|>#
# Gramps - a GTK+/GNOME based genealogy program
#
# Copyright (C) 2000-2007 Donald N. Allingham
# Copyright (C) 2007-2008 Brian G. Matherly
# Copyright (C) 2009 Douglas S. Blank
#
# 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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
#
#
# $Id$
#
#
"""
Display references for any object
"""
from gramps.gen.simple import SimpleAccess, SimpleDoc
from gramps.gui.plug.quick import QuickTable
from gramps.gen.utils.alive import probably_alive
from gramps.gen.ggettext import gettext as _
from gramps.gen.datehandler import displayer
from gramps.gen.config import config
def run(database, document, date):
"""
Display people probably alive and their ages on a particular date.
"""
# setup the simple access functions
sdb = SimpleAccess(database)
sdoc = SimpleDoc(document)
stab = QuickTable(sdb)
if not date.get_valid():
sdoc.paragraph("Date is not a valid date.")
return
# display the title
if date.get_day_valid():
sdoc.title(_("People probably alive and their ages the %s") %
displayer.display(date))
else:
sdoc.title(_("People probably alive and their ages on %s") %
displayer.display(date))
stab.columns(_("Person"), _("Age")) # Actual Date makes column unicode
matches = 0
for person in sdb.all_people():
alive, birth, death, explain, relative = \
probably_alive(person, database, date, return_range=True)
# Doesn't show people probably alive but no way of figuring an age:
if alive and birth:
diff_span = (date - birth)
stab.row(person, str(diff_span))
stab.row_sort_val(1, int(diff_span))
matches += 1<|fim▁hole|> sdoc.paragraph("")
def get_event_date_from_ref(database, ref):
date = None
if ref:
handle = ref.get_reference_handle()
if handle:
event = database.get_event_from_handle(handle)
if event:
date = event.get_date_object()
return date<|fim▁end|>
|
document.has_data = matches > 0
sdoc.paragraph(_("\n%d matches.\n") % matches)
stab.write(sdoc)
|
<|file_name|>dumpStream.hh<|end_file_name|><|fim▁begin|>//::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
//
// This file is part of Libmoleculizer
//
// Copyright (C) 2001-2009 The Molecular Sciences Institute.
//
//::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
//
// Moleculizer 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 3 of the License, or
// (at your option) any later version.
//
// Moleculizer 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 Moleculizer; if not, write to the Free Software Foundation
// Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307, USA
//
// END HEADER<|fim▁hole|>//
// Original Author:
// Larry Lok, Research Fellow, Molecular Sciences Institute, 2001
//
// Modifing Authors:
//
//
#ifndef FND_DUMPSTREAM_H
#define FND_DUMPSTREAM_H
#include <fstream>
#include <vector>
#include "utl/xcpt.hh"
#include "utl/autoVector.hh"
#include "fnd/dumpable.hh"
#include "fnd/dmpColumn.hh"
namespace fnd
{
class dumpStream :
public utl::autoVector<basicDmpColumn>
{
// Now that the output stream and everything else is passed to
// the dumpables through a dumpArg, these are here mainly to
// memory-manage the stream, to emphasize that this class is what
// corresponds to a .dmp file, and to facilitate the construction
// of dumpArg's through getOstream(), in particular.
std::string fileName;
std::ostream* pOs;
std::ofstream* pFileStream;
public:
// Use a genuine file path, "-" for std::cout, "+" for std::cerr.
dumpStream( const std::string& rFileName )
throw( utl::xcpt );
~dumpStream( void )
{
// This is null if the output stream not actually a file.
delete pFileStream;
}
std::ostream&
getOstream( void ) const
{
return *pOs;
}
// Returns the file name given at construction time, including
// the special cases.
const std::string&
getFileName( void ) const
{
return fileName;
}
// Initializes output stream and writes column headers.
void
init( void )
throw( utl::xcpt );
// Writes a line in the output file.
void
doDump( void );
};
}
#endif // FND_DUMPSTREAM_H<|fim▁end|>
| |
<|file_name|>lexer.js<|end_file_name|><|fim▁begin|>/*!
* Jade - Lexer
* Copyright(c) 2010 TJ Holowaychuk <[email protected]>
* MIT Licensed
*/
/**
* Initialize `Lexer` with the given `str`.
*
* Options:
*
* - `colons` allow colons for attr delimiters
*
* @param {String} str
* @param {Object} options
* @api private
*/
var Lexer = module.exports = function Lexer(str, options) {
options = options || {};
this.input = str.replace(/\r\n|\r/g, '\n');
this.colons = options.colons;
this.deferredTokens = [];
this.lastIndents = 0;
this.lineno = 1;
this.stash = [];
this.indentStack = [];
this.indentRe = null;
this.pipeless = false;
};
/**
* Lexer prototype.
*/
Lexer.prototype = {
/**
* Construct a token with the given `type` and `val`.
*
* @param {String} type
* @param {String} val
* @return {Object}
* @api private
*/
tok: function(type, val){
return {
type: type
, line: this.lineno
, val: val
}
},
/**
* Consume the given `len` of input.
*
* @param {Number} len
* @api private
*/
consume: function(len){
this.input = this.input.substr(len);
},
/**
* Scan for `type` with the given `regexp`.
*
* @param {String} type
* @param {RegExp} regexp
* @return {Object}
* @api private
*/
scan: function(regexp, type){
var captures;
if (captures = regexp.exec(this.input)) {
this.consume(captures[0].length);
return this.tok(type, captures[1]);
}
},
/**
* Defer the given `tok`.
*
* @param {Object} tok
* @api private
*/
defer: function(tok){
this.deferredTokens.push(tok);
},
/**
* Lookahead `n` tokens.
*
* @param {Number} n
* @return {Object}
* @api private
*/
lookahead: function(n){
var fetch = n - this.stash.length;
while (fetch-- > 0) this.stash.push(this.next());
return this.stash[--n];
},
/**
* Return the indexOf `start` / `end` delimiters.
*
* @param {String} start
* @param {String} end
* @return {Number}<|fim▁hole|> */
indexOfDelimiters: function(start, end){
var str = this.input
, nstart = 0
, nend = 0
, pos = 0;
for (var i = 0, len = str.length; i < len; ++i) {
if (start == str.charAt(i)) {
++nstart;
} else if (end == str.charAt(i)) {
if (++nend == nstart) {
pos = i;
break;
}
}
}
return pos;
},
/**
* Stashed token.
*/
stashed: function() {
return this.stash.length
&& this.stash.shift();
},
/**
* Deferred token.
*/
deferred: function() {
return this.deferredTokens.length
&& this.deferredTokens.shift();
},
/**
* end-of-source.
*/
eos: function() {
if (this.input.length) return;
if (this.indentStack.length) {
this.indentStack.shift();
return this.tok('outdent');
} else {
return this.tok('eos');
}
},
/**
* Comment.
*/
comment: function() {
var captures;
if (captures = /^ *\/\/(-)?([^\n]*)/.exec(this.input)) {
this.consume(captures[0].length);
var tok = this.tok('comment', captures[2]);
tok.buffer = '-' != captures[1];
return tok;
}
},
/**
* Tag.
*/
tag: function() {
var captures;
if (captures = /^(\w[-:\w]*)/.exec(this.input)) {
this.consume(captures[0].length);
var tok, name = captures[1];
if (':' == name[name.length - 1]) {
name = name.slice(0, -1);
tok = this.tok('tag', name);
this.defer(this.tok(':'));
while (' ' == this.input[0]) this.input = this.input.substr(1);
} else {
tok = this.tok('tag', name);
}
return tok;
}
},
/**
* Filter.
*/
filter: function() {
return this.scan(/^:(\w+)/, 'filter');
},
/**
* Doctype.
*/
doctype: function() {
return this.scan(/^(?:!!!|doctype) *([^\n]+)?/, 'doctype');
},
/**
* Id.
*/
id: function() {
return this.scan(/^#([\w-]+)/, 'id');
},
/**
* Class.
*/
className: function() {
return this.scan(/^\.([\w-]+)/, 'class');
},
/**
* Text.
*/
text: function() {
return this.scan(/^(?:\| ?)?([^\n]+)/, 'text');
},
/**
* Extends.
*/
"extends": function() {
return this.scan(/^extends +([^\n]+)/, 'extends');
},
/**
* Block prepend.
*/
prepend: function() {
var captures;
if (captures = /^prepend +([^\n]+)/.exec(this.input)) {
this.consume(captures[0].length);
var mode = 'prepend'
, name = captures[1]
, tok = this.tok('block', name);
tok.mode = mode;
return tok;
}
},
/**
* Block append.
*/
append: function() {
var captures;
if (captures = /^append +([^\n]+)/.exec(this.input)) {
this.consume(captures[0].length);
var mode = 'append'
, name = captures[1]
, tok = this.tok('block', name);
tok.mode = mode;
return tok;
}
},
/**
* Block.
*/
block: function() {
var captures;
if (captures = /^block +(?:(prepend|append) +)?([^\n]+)/.exec(this.input)) {
this.consume(captures[0].length);
var mode = captures[1] || 'replace'
, name = captures[2]
, tok = this.tok('block', name);
tok.mode = mode;
return tok;
}
},
/**
* Yield.
*/
yield: function() {
return this.scan(/^yield */, 'yield');
},
/**
* Include.
*/
include: function() {
return this.scan(/^include +([^\n]+)/, 'include');
},
/**
* Case.
*/
"case": function() {
return this.scan(/^case +([^\n]+)/, 'case');
},
/**
* When.
*/
when: function() {
return this.scan(/^when +([^:\n]+)/, 'when');
},
/**
* Default.
*/
"default": function() {
return this.scan(/^default */, 'default');
},
/**
* Assignment.
*/
assignment: function() {
var captures;
if (captures = /^(\w+) += *([^;\n]+)( *;? *)/.exec(this.input)) {
this.consume(captures[0].length);
var name = captures[1]
, val = captures[2];
return this.tok('code', 'var ' + name + ' = (' + val + ');');
}
},
/**
* Mixin.
*/
mixin: function(){
var captures;
if (captures = /^mixin +([-\w]+)(?: *\((.*)\))?/.exec(this.input)) {
this.consume(captures[0].length);
var tok = this.tok('mixin', captures[1]);
tok.args = captures[2];
return tok;
}
},
/**
* Conditional.
*/
conditional: function() {
var captures;
if (captures = /^(if|unless|else if|else)\b([^\n]*)/.exec(this.input)) {
this.consume(captures[0].length);
var type = captures[1]
, js = captures[2];
switch (type) {
case 'if': js = 'if (' + js + ')'; break;
case 'unless': js = 'if (!(' + js + '))'; break;
case 'else if': js = 'else if (' + js + ')'; break;
case 'else': js = 'else'; break;
}
return this.tok('code', js);
}
},
/**
* While.
*/
"while": function() {
var captures;
if (captures = /^while +([^\n]+)/.exec(this.input)) {
this.consume(captures[0].length);
return this.tok('code', 'while (' + captures[1] + ')');
}
},
/**
* Each.
*/
each: function() {
var captures;
if (captures = /^(?:- *)?(?:each|for) +(\w+)(?: *, *(\w+))? * in *([^\n]+)/.exec(this.input)) {
this.consume(captures[0].length);
var tok = this.tok('each', captures[1]);
tok.key = captures[2] || '$index';
tok.code = captures[3];
return tok;
}
},
/**
* Code.
*/
code: function() {
var captures;
if (captures = /^(!?=|-)([^\n]+)/.exec(this.input)) {
this.consume(captures[0].length);
var flags = captures[1];
captures[1] = captures[2];
var tok = this.tok('code', captures[1]);
tok.escape = flags[0] === '=';
tok.buffer = flags[0] === '=' || flags[1] === '=';
return tok;
}
},
/**
* Attributes.
*/
attrs: function() {
if ('(' == this.input.charAt(0)) {
var index = this.indexOfDelimiters('(', ')')
, str = this.input.substr(1, index-1)
, tok = this.tok('attrs')
, len = str.length
, colons = this.colons
, states = ['key']
, key = ''
, val = ''
, quote
, c;
function state(){
return states[states.length - 1];
}
function interpolate(attr) {
return attr.replace(/#\{([^}]+)\}/g, function(_, expr){
return quote + " + (" + expr + ") + " + quote;
});
}
this.consume(index + 1);
tok.attrs = {};
function parse(c) {
var real = c;
// TODO: remove when people fix ":"
if (colons && ':' == c) c = '=';
switch (c) {
case ',':
case '\n':
switch (state()) {
case 'expr':
case 'array':
case 'string':
case 'object':
val += c;
break;
default:
states.push('key');
val = val.trim();
key = key.trim();
if ('' == key) return;
tok.attrs[key.replace(/^['"]|['"]$/g, '')] = '' == val
? true
: interpolate(val);
key = val = '';
}
break;
case '=':
switch (state()) {
case 'key char':
key += real;
break;
case 'val':
case 'expr':
case 'array':
case 'string':
case 'object':
val += real;
break;
default:
states.push('val');
}
break;
case '(':
if ('val' == state()
|| 'expr' == state()) states.push('expr');
val += c;
break;
case ')':
if ('expr' == state()
|| 'val' == state()) states.pop();
val += c;
break;
case '{':
if ('val' == state()) states.push('object');
val += c;
break;
case '}':
if ('object' == state()) states.pop();
val += c;
break;
case '[':
if ('val' == state()) states.push('array');
val += c;
break;
case ']':
if ('array' == state()) states.pop();
val += c;
break;
case '"':
case "'":
switch (state()) {
case 'key':
states.push('key char');
break;
case 'key char':
states.pop();
break;
case 'string':
if (c == quote) states.pop();
val += c;
break;
default:
states.push('string');
val += c;
quote = c;
}
break;
case '':
break;
default:
switch (state()) {
case 'key':
case 'key char':
key += c;
break;
default:
val += c;
}
}
}
for (var i = 0; i < len; ++i) {
parse(str.charAt(i));
}
parse(',');
return tok;
}
},
/**
* Indent | Outdent | Newline.
*/
indent: function() {
var captures, re;
// established regexp
if (this.indentRe) {
captures = this.indentRe.exec(this.input);
// determine regexp
} else {
// tabs
re = /^\n(\t*) */;
captures = re.exec(this.input);
// spaces
if (captures && !captures[1].length) {
re = /^\n( *)/;
captures = re.exec(this.input);
}
// established
if (captures && captures[1].length) this.indentRe = re;
}
if (captures) {
var tok
, indents = captures[1].length;
++this.lineno;
this.consume(indents + 1);
if (' ' == this.input[0] || '\t' == this.input[0]) {
throw new Error('Invalid indentation, you can use tabs or spaces but not both');
}
// blank line
if ('\n' == this.input[0]) return this.tok('newline');
// outdent
if (this.indentStack.length && indents < this.indentStack[0]) {
while (this.indentStack.length && this.indentStack[0] > indents) {
this.stash.push(this.tok('outdent'));
this.indentStack.shift();
}
tok = this.stash.pop();
// indent
} else if (indents && indents != this.indentStack[0]) {
this.indentStack.unshift(indents);
tok = this.tok('indent', indents);
// newline
} else {
tok = this.tok('newline');
}
return tok;
}
},
/**
* Pipe-less text consumed only when
* pipeless is true;
*/
pipelessText: function() {
if (this.pipeless) {
if ('\n' == this.input[0]) return;
var i = this.input.indexOf('\n');
if (-1 == i) i = this.input.length;
var str = this.input.substr(0, i);
this.consume(str.length);
return this.tok('text', str);
}
},
/**
* ':'
*/
colon: function() {
return this.scan(/^: */, ':');
},
/**
* Return the next token object, or those
* previously stashed by lookahead.
*
* @return {Object}
* @api private
*/
advance: function(){
return this.stashed()
|| this.next();
},
/**
* Return the next token object.
*
* @return {Object}
* @api private
*/
next: function() {
return this.deferred()
|| this.eos()
|| this.pipelessText()
|| this.yield()
|| this.doctype()
|| this["case"]()
|| this.when()
|| this["default"]()
|| this["extends"]()
|| this.append()
|| this.prepend()
|| this.block()
|| this.include()
|| this.mixin()
|| this.conditional()
|| this.each()
|| this["while"]()
|| this.assignment()
|| this.tag()
|| this.filter()
|| this.code()
|| this.id()
|| this.className()
|| this.attrs()
|| this.indent()
|| this.comment()
|| this.colon()
|| this.text();
}
};<|fim▁end|>
|
* @api private
|
<|file_name|>PropertiesDTO.java<|end_file_name|><|fim▁begin|>/*
* Copyright (c) 2013-2014, Arjuna Technologies Limited, Newcastle-upon-Tyne, England. All rights reserved.
*/
package com.arjuna.databroker.control.comms;
import java.io.Serializable;
import java.util.Map;
public class PropertiesDTO implements Serializable
{
private static final long serialVersionUID = -4823706453142980142L;
public PropertiesDTO()
{
}
public PropertiesDTO(Map<String, String> properties)
{
_properties = properties;
}
public Map<String, String> getProperties()
{
return _properties;
}
public void setProperties(Map<String, String> properties)
{
_properties = properties;
}
<|fim▁hole|> private Map<String, String> _properties;
}<|fim▁end|>
| |
<|file_name|>control_flow_grad.py<|end_file_name|><|fim▁begin|># Copyright 2015 The TensorFlow Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ==============================================================================
"""Gradients for operators defined in control_flow_ops.py."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from six.moves import xrange # pylint: disable=redefined-builtin
from tensorflow.python.framework import ops
from tensorflow.python.framework import sparse_tensor
from tensorflow.python.ops import control_flow_ops
from tensorflow.python.ops import math_ops
# go/tf-wildcard-import
# pylint: disable=wildcard-import,undefined-variable
from tensorflow.python.ops.control_flow_ops import *
from tensorflow.python.ops.gen_control_flow_ops import *
# pylint: enable=wildcard-import
def _SwitchGrad(op, *grad):
"""Gradients for a Switch op is calculated using a Merge op.
If the switch is a loop switch, it will be visited twice. We create
the merge on the first visit, and update the other input of the merge
on the second visit. A next_iteration is also added on second visit.
"""
graph = ops.get_default_graph()
# pylint: disable=protected-access
op_ctxt = op._get_control_flow_context()
grad_ctxt = graph._get_control_flow_context()
# pylint: enable=protected-access
if isinstance(op_ctxt, WhileContext):
merge_grad = grad_ctxt.grad_state.switch_map.get(op)
if merge_grad is not None:
# This is the second time this Switch is visited. It comes from
# the non-exit branch of the Switch, so update the second input
# to the Merge.
# TODO(yuanbyu): Perform shape inference with this new input.
if grad[1] is not None:
# pylint: disable=protected-access
control_flow_ops._AddNextAndBackEdge(merge_grad, grad[1])
# pylint: enable=protected-access
return None, None
elif grad[0] is not None:
# This is the first time this Switch is visited. It comes from
# the Exit branch, which is grad[0]. grad[1] is empty at this point.
# Use grad[0] for both inputs to merge for now, but update the second
# input of merge when we see this Switch the second time.
merge_grad = merge([grad[0], grad[0]], name="b_switch")[0]
grad_ctxt.grad_state.switch_map[op] = merge_grad
return merge_grad, None
else:
# This is the first time this Switch is visited. It comes from the
# Identity branch. Such a Switch has `None` gradient for the Exit branch,
# meaning the output is not differentiable.
return None, None
elif isinstance(op_ctxt, CondContext):
zero_grad = grad[1 - op_ctxt.branch]
# At this point, we have created zero_grad guarded by the right switch.
# Unfortunately, we may still get None here for not trainable data types.
if zero_grad is None:
return None, None
return merge(grad, name="cond_grad")[0], None
else:
false_grad = switch(grad[0], op.inputs[1])[0]
true_grad = switch(grad[1], op.inputs[1])[1]
return merge([false_grad, true_grad])[0], None
ops.RegisterGradient("Switch")(_SwitchGrad)
ops.RegisterGradient("RefSwitch")(_SwitchGrad)
@ops.RegisterGradient("Merge")
def _MergeGrad(op, grad, _):
"""Gradients for a Merge op are calculated using a Switch op."""
input_op = op.inputs[0].op
graph = ops.get_default_graph()
# pylint: disable=protected-access
op_ctxt = control_flow_ops._GetOutputContext(input_op)
grad_ctxt = graph._get_control_flow_context()
# pylint: enable=protected-access
if isinstance(op_ctxt, WhileContext):
# pylint: disable=protected-access
return control_flow_ops._SwitchRefOrTensor(grad, grad_ctxt.pivot)
# pylint: enable=protected-access
elif isinstance(op_ctxt, CondContext):
pred = op_ctxt.pred
if grad_ctxt and grad_ctxt.grad_state:
# This Merge node is part of a cond within a loop.
# The backprop needs to have the value of this predicate for every
# iteration. So we must have its values accumulated in the forward, and
# use the accumulated values as the predicate for this backprop switch.
grad_state = grad_ctxt.grad_state
real_pred = grad_state.history_map.get(pred.name)
if real_pred is None:
# Remember the value of pred for every iteration.
grad_ctxt = grad_state.grad_context
grad_ctxt.Exit()
history_pred = grad_state.AddForwardAccumulator(pred)
grad_ctxt.Enter()
# Add the stack pop op. If pred.op is in a (outer) CondContext,
# the stack pop will be guarded with a switch.
real_pred = grad_state.AddBackpropAccumulatedValue(history_pred, pred)
grad_state.history_map[pred.name] = real_pred
pred = real_pred
# pylint: disable=protected-access
return control_flow_ops._SwitchRefOrTensor(grad, pred, name="cond_grad")
# pylint: enable=protected-access
else:
num_inputs = len(op.inputs)
cond = [math_ops.equal(op.outputs[1], i) for i in xrange(num_inputs)]
# pylint: disable=protected-access
return [control_flow_ops._SwitchRefOrTensor(grad, cond[i])[1]
for i in xrange(num_inputs)]
# pylint: enable=protected-access
@ops.RegisterGradient("RefMerge")
def _RefMergeGrad(op, grad, _):
return _MergeGrad(op, grad, _)
@ops.RegisterGradient("Exit")
def _ExitGrad(op, grad):
"""Gradients for an exit op are calculated using an Enter op."""
graph = ops.get_default_graph()
# pylint: disable=protected-access
grad_ctxt = graph._get_control_flow_context()
# pylint: enable=protected-access
if not grad_ctxt.back_prop:
# The flag `back_prop` is set by users to suppress gradient
# computation for this loop. If the attribute `back_prop` is false,
# no gradient computation.
return None
# pylint: disable=protected-access
if op._get_control_flow_context().grad_state:
raise TypeError("Second-order gradient for while loops not supported.")
# pylint: enable=protected-access
if isinstance(grad, ops.Tensor):
grad_ctxt.AddName(grad.name)
else:<|fim▁hole|> grad_ctxt.AddName(grad.indices.name)
dense_shape = grad.dense_shape
if dense_shape is not None:
grad_ctxt.AddName(dense_shape.name)
grad_ctxt.Enter()
# pylint: disable=protected-access
result = control_flow_ops._Enter(
grad, grad_ctxt.name, is_constant=False,
parallel_iterations=grad_ctxt.parallel_iterations,
name="b_exit")
# pylint: enable=protected-access
grad_ctxt.loop_enters.append(result)
grad_ctxt.Exit()
return result
ops.RegisterGradient("RefExit")(_ExitGrad)
@ops.RegisterGradient("NextIteration")
def _NextIterationGrad(_, grad):
"""A forward next_iteration is translated into a backprop identity.
Note that the backprop next_iteration is added in switch grad.
"""
return grad
@ops.RegisterGradient("RefNextIteration")
def _RefNextIterationGrad(_, grad):
return _NextIterationGrad(_, grad)
@ops.RegisterGradient("Enter")
def _EnterGrad(op, grad):
"""Gradients for an Enter are calculated using an Exit op.
For loop variables, grad is the gradient so just add an exit.
For loop invariants, we need to add an accumulator loop.
"""
graph = ops.get_default_graph()
# pylint: disable=protected-access
grad_ctxt = graph._get_control_flow_context()
# pylint: enable=protected-access
if not grad_ctxt.back_prop:
# Skip gradient computation, if the attribute `back_prop` is false.
return grad
if grad_ctxt.grad_state is None:
# Pass the gradient through if we are not in a gradient while context.
return grad
if op.get_attr("is_constant"):
# Add a gradient accumulator for each loop invariant.
if isinstance(grad, ops.Tensor):
result = grad_ctxt.AddBackpropAccumulator(op, grad)
elif isinstance(grad, ops.IndexedSlices):
result = grad_ctxt.AddBackpropIndexedSlicesAccumulator(op, grad)
else:
# TODO(yuanbyu, lukasr): Add support for SparseTensor.
raise TypeError("Type %s not supported" % type(grad))
else:
result = exit(grad)
grad_ctxt.loop_exits.append(result)
grad_ctxt.ExitResult([result])
return result
@ops.RegisterGradient("RefEnter")
def _RefEnterGrad(op, grad):
return _EnterGrad(op, grad)
@ops.RegisterGradient("LoopCond")
def _LoopCondGrad(_):
"""Stop backprop for the predicate of a while loop."""
return None<|fim▁end|>
|
if not isinstance(grad, (ops.IndexedSlices, sparse_tensor.SparseTensor)):
raise TypeError("Type %s not supported" % type(grad))
grad_ctxt.AddName(grad.values.name)
|
<|file_name|>testutil.py<|end_file_name|><|fim▁begin|>import unittest
import tempfile
import os
from os.path import join
import zipfile
from git import *
from shutil import rmtree
from gitbranchhealth.branchhealth import BranchHealthConfig
class GitRepoTest(unittest.TestCase):
def setUp(self):
self.__mOriginTempDir = tempfile.mkdtemp(prefix='gitBranchHealthTest')
self.assertTrue(os.path.exists(self.__mOriginTempDir))
# Create our origin first
testRepoZipPath = join(self.__findTestDir(), 'testrepo.zip')
zipFh = open(testRepoZipPath, 'rb')
testRepoZip = zipfile.ZipFile(zipFh)
for name in testRepoZip.namelist():
testRepoZip.extract(name, self.__mOriginTempDir)
zipFh.close()
self.__mOriginGitRepoPath = os.path.join(self.__mOriginTempDir, 'testrepo')
originRepo = Repo(self.__mOriginGitRepoPath)
self.__mTempDir = tempfile.mkdtemp(prefix='gitBranchHealthTest')
os.mkdir(os.path.join(self.__mTempDir, 'testrepo'))
self.assertTrue(os.path.exists(self.__mTempDir))
# Now create the local repo
self.__mGitRepoPath = os.path.join(self.__mTempDir, 'testrepo')
originRepo.clone(self.__mGitRepoPath)
self.assertTrue(os.path.exists(self.__mGitRepoPath))
self.__mConfig = BranchHealthConfig(self.__mGitRepoPath)
self.__trackAllRemoteBranches()
def tearDown(self):
pass
# rmtree(self.__mTempDir)
# rmtree(self.__mOriginTempDir)
def getConfig(self):
return self.__mConfig
def getTempDir(self):
return self.__mTempDir
## Private API ###
def __trackAllRemoteBranches(self):
repo = Repo(self.__mGitRepoPath)
for remote in repo.remotes:
for branch in remote.refs:
localBranchName = branch.name.split('/')[-1]
if localBranchName != 'master' and localBranchName != 'HEAD':
repo.git.checkout(branch.name, b=localBranchName)
<|fim▁hole|> for (root, dirs, files) in os.walk('.'):
if 'testrepo.zip' in files:
return root<|fim▁end|>
|
repo.heads.master.checkout()
def __findTestDir(self):
# Find the file called 'testrepo.zip', starting at the current dir
|
<|file_name|>test_cookie.py<|end_file_name|><|fim▁begin|># Simple test suite for Cookie.py
from test.test_support import verify, verbose, run_doctest
import Cookie
import warnings
warnings.filterwarnings("ignore",<|fim▁hole|># Currently this only tests SimpleCookie
cases = [
('chips=ahoy; vienna=finger', {'chips':'ahoy', 'vienna':'finger'}),
('keebler="E=mc2; L=\\"Loves\\"; fudge=\\012;";',
{'keebler' : 'E=mc2; L="Loves"; fudge=\012;'}),
# Check illegal cookies that have an '=' char in an unquoted value
('keebler=E=mc2;', {'keebler' : 'E=mc2'})
]
for data, dict in cases:
C = Cookie.SimpleCookie() ; C.load(data)
print repr(C)
print str(C)
items = dict.items()
items.sort()
for k, v in items:
print ' ', k, repr( C[k].value ), repr(v)
verify(C[k].value == v)
print C[k]
C = Cookie.SimpleCookie()
C.load('Customer="WILE_E_COYOTE"; Version=1; Path=/acme')
verify(C['Customer'].value == 'WILE_E_COYOTE')
verify(C['Customer']['version'] == '1')
verify(C['Customer']['path'] == '/acme')
print C.output(['path'])
print C.js_output()
print C.js_output(['path'])
# Try cookie with quoted meta-data
C = Cookie.SimpleCookie()
C.load('Customer="WILE_E_COYOTE"; Version="1"; Path="/acme"')
verify(C['Customer'].value == 'WILE_E_COYOTE')
verify(C['Customer']['version'] == '1')
verify(C['Customer']['path'] == '/acme')
print "If anything blows up after this line, it's from Cookie's doctest."
run_doctest(Cookie)<|fim▁end|>
|
".* class is insecure.*",
DeprecationWarning)
|
<|file_name|>BrokerConfig.java<|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 KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.rocketmq.common;
import org.apache.rocketmq.common.annotation.ImportantField;
import org.apache.rocketmq.common.constant.PermName;
import org.apache.rocketmq.remoting.common.RemotingUtil;
import java.net.InetAddress;
import java.net.UnknownHostException;
public class BrokerConfig {
private String rocketmqHome = System.getProperty(MixAll.ROCKETMQ_HOME_PROPERTY, System.getenv(MixAll.ROCKETMQ_HOME_ENV));
@ImportantField
private String namesrvAddr = System.getProperty(MixAll.NAMESRV_ADDR_PROPERTY, System.getenv(MixAll.NAMESRV_ADDR_ENV));
@ImportantField
private String brokerIP1 = RemotingUtil.getLocalAddress();
private String brokerIP2 = RemotingUtil.getLocalAddress();
@ImportantField
private String brokerName = localHostName();
@ImportantField
private String brokerClusterName = "DefaultCluster";
@ImportantField
private long brokerId = MixAll.MASTER_ID;
/**
* Broker 权限(读写等)
*/
private int brokerPermission = PermName.PERM_READ | PermName.PERM_WRITE;
private int defaultTopicQueueNums = 8;
@ImportantField
private boolean autoCreateTopicEnable = true;
private boolean clusterTopicEnable = true;
private boolean brokerTopicEnable = true;
@ImportantField
private boolean autoCreateSubscriptionGroup = true;
private String messageStorePlugIn = "";
private int sendMessageThreadPoolNums = 1; //16 + Runtime.getRuntime().availableProcessors() * 4;
private int pullMessageThreadPoolNums = 16 + Runtime.getRuntime().availableProcessors() * 2;
private int adminBrokerThreadPoolNums = 16;
private int clientManageThreadPoolNums = 32;
private int consumerManageThreadPoolNums = 32;
private int flushConsumerOffsetInterval = 1000 * 5;
private int flushConsumerOffsetHistoryInterval = 1000 * 60;
@ImportantField
private boolean rejectTransactionMessage = false;
@ImportantField
private boolean fetchNamesrvAddrByAddressServer = false;
private int sendThreadPoolQueueCapacity = 10000;
private int pullThreadPoolQueueCapacity = 100000;
private int clientManagerThreadPoolQueueCapacity = 1000000;
private int consumerManagerThreadPoolQueueCapacity = 1000000;
private int filterServerNums = 0;
private boolean longPollingEnable = true;
private long shortPollingTimeMills = 1000;
private boolean notifyConsumerIdsChangedEnable = true;
private boolean highSpeedMode = false;
private boolean commercialEnable = true;
private int commercialTimerCount = 1;
private int commercialTransCount = 1;
private int commercialBigCount = 1;
private int commercialBaseCount = 1;
private boolean transferMsgByHeap = true;
private int maxDelayTime = 40;
// TODO 疑问:这个是干啥的
private String regionId = MixAll.DEFAULT_TRACE_REGION_ID;
private int registerBrokerTimeoutMills = 6000;
private boolean slaveReadEnable = false;
private boolean disableConsumeIfConsumerReadSlowly = false;
private long consumerFallbehindThreshold = 1024L * 1024 * 1024 * 16;
private long waitTimeMillsInSendQueue = 200;
/**
* 开始接收请求时间
* TODO 疑问:什么时候设置的
*/
private long startAcceptSendRequestTimeStamp = 0L;
private boolean traceOn = true;
public static String localHostName() {
try {
return InetAddress.getLocalHost().getHostName();
} catch (UnknownHostException e) {
e.printStackTrace();
}
return "DEFAULT_BROKER";
}
public boolean isTraceOn() {
return traceOn;
}
public void setTraceOn(final boolean traceOn) {<|fim▁hole|> return startAcceptSendRequestTimeStamp;
}
public void setStartAcceptSendRequestTimeStamp(final long startAcceptSendRequestTimeStamp) {
this.startAcceptSendRequestTimeStamp = startAcceptSendRequestTimeStamp;
}
public long getWaitTimeMillsInSendQueue() {
return waitTimeMillsInSendQueue;
}
public void setWaitTimeMillsInSendQueue(final long waitTimeMillsInSendQueue) {
this.waitTimeMillsInSendQueue = waitTimeMillsInSendQueue;
}
public long getConsumerFallbehindThreshold() {
return consumerFallbehindThreshold;
}
public void setConsumerFallbehindThreshold(final long consumerFallbehindThreshold) {
this.consumerFallbehindThreshold = consumerFallbehindThreshold;
}
public boolean isDisableConsumeIfConsumerReadSlowly() {
return disableConsumeIfConsumerReadSlowly;
}
public void setDisableConsumeIfConsumerReadSlowly(final boolean disableConsumeIfConsumerReadSlowly) {
this.disableConsumeIfConsumerReadSlowly = disableConsumeIfConsumerReadSlowly;
}
public boolean isSlaveReadEnable() {
return slaveReadEnable;
}
public void setSlaveReadEnable(final boolean slaveReadEnable) {
this.slaveReadEnable = slaveReadEnable;
}
public int getRegisterBrokerTimeoutMills() {
return registerBrokerTimeoutMills;
}
public void setRegisterBrokerTimeoutMills(final int registerBrokerTimeoutMills) {
this.registerBrokerTimeoutMills = registerBrokerTimeoutMills;
}
public String getRegionId() {
return regionId;
}
public void setRegionId(final String regionId) {
this.regionId = regionId;
}
public boolean isTransferMsgByHeap() {
return transferMsgByHeap;
}
public void setTransferMsgByHeap(final boolean transferMsgByHeap) {
this.transferMsgByHeap = transferMsgByHeap;
}
public String getMessageStorePlugIn() {
return messageStorePlugIn;
}
public void setMessageStorePlugIn(String messageStorePlugIn) {
this.messageStorePlugIn = messageStorePlugIn;
}
public boolean isHighSpeedMode() {
return highSpeedMode;
}
public void setHighSpeedMode(final boolean highSpeedMode) {
this.highSpeedMode = highSpeedMode;
}
public String getRocketmqHome() {
return rocketmqHome;
}
public void setRocketmqHome(String rocketmqHome) {
this.rocketmqHome = rocketmqHome;
}
public String getBrokerName() {
return brokerName;
}
public void setBrokerName(String brokerName) {
this.brokerName = brokerName;
}
public int getBrokerPermission() {
return brokerPermission;
}
public void setBrokerPermission(int brokerPermission) {
this.brokerPermission = brokerPermission;
}
public int getDefaultTopicQueueNums() {
return defaultTopicQueueNums;
}
public void setDefaultTopicQueueNums(int defaultTopicQueueNums) {
this.defaultTopicQueueNums = defaultTopicQueueNums;
}
public boolean isAutoCreateTopicEnable() {
return autoCreateTopicEnable;
}
public void setAutoCreateTopicEnable(boolean autoCreateTopic) {
this.autoCreateTopicEnable = autoCreateTopic;
}
public String getBrokerClusterName() {
return brokerClusterName;
}
public void setBrokerClusterName(String brokerClusterName) {
this.brokerClusterName = brokerClusterName;
}
public String getBrokerIP1() {
return brokerIP1;
}
public void setBrokerIP1(String brokerIP1) {
this.brokerIP1 = brokerIP1;
}
public String getBrokerIP2() {
return brokerIP2;
}
public void setBrokerIP2(String brokerIP2) {
this.brokerIP2 = brokerIP2;
}
public int getSendMessageThreadPoolNums() {
return sendMessageThreadPoolNums;
}
public void setSendMessageThreadPoolNums(int sendMessageThreadPoolNums) {
this.sendMessageThreadPoolNums = sendMessageThreadPoolNums;
}
public int getPullMessageThreadPoolNums() {
return pullMessageThreadPoolNums;
}
public void setPullMessageThreadPoolNums(int pullMessageThreadPoolNums) {
this.pullMessageThreadPoolNums = pullMessageThreadPoolNums;
}
public int getAdminBrokerThreadPoolNums() {
return adminBrokerThreadPoolNums;
}
public void setAdminBrokerThreadPoolNums(int adminBrokerThreadPoolNums) {
this.adminBrokerThreadPoolNums = adminBrokerThreadPoolNums;
}
public int getFlushConsumerOffsetInterval() {
return flushConsumerOffsetInterval;
}
public void setFlushConsumerOffsetInterval(int flushConsumerOffsetInterval) {
this.flushConsumerOffsetInterval = flushConsumerOffsetInterval;
}
public int getFlushConsumerOffsetHistoryInterval() {
return flushConsumerOffsetHistoryInterval;
}
public void setFlushConsumerOffsetHistoryInterval(int flushConsumerOffsetHistoryInterval) {
this.flushConsumerOffsetHistoryInterval = flushConsumerOffsetHistoryInterval;
}
public boolean isClusterTopicEnable() {
return clusterTopicEnable;
}
public void setClusterTopicEnable(boolean clusterTopicEnable) {
this.clusterTopicEnable = clusterTopicEnable;
}
public String getNamesrvAddr() {
return namesrvAddr;
}
public void setNamesrvAddr(String namesrvAddr) {
this.namesrvAddr = namesrvAddr;
}
public long getBrokerId() {
return brokerId;
}
public void setBrokerId(long brokerId) {
this.brokerId = brokerId;
}
public boolean isAutoCreateSubscriptionGroup() {
return autoCreateSubscriptionGroup;
}
public void setAutoCreateSubscriptionGroup(boolean autoCreateSubscriptionGroup) {
this.autoCreateSubscriptionGroup = autoCreateSubscriptionGroup;
}
public boolean isRejectTransactionMessage() {
return rejectTransactionMessage;
}
public void setRejectTransactionMessage(boolean rejectTransactionMessage) {
this.rejectTransactionMessage = rejectTransactionMessage;
}
public boolean isFetchNamesrvAddrByAddressServer() {
return fetchNamesrvAddrByAddressServer;
}
public void setFetchNamesrvAddrByAddressServer(boolean fetchNamesrvAddrByAddressServer) {
this.fetchNamesrvAddrByAddressServer = fetchNamesrvAddrByAddressServer;
}
public int getSendThreadPoolQueueCapacity() {
return sendThreadPoolQueueCapacity;
}
public void setSendThreadPoolQueueCapacity(int sendThreadPoolQueueCapacity) {
this.sendThreadPoolQueueCapacity = sendThreadPoolQueueCapacity;
}
public int getPullThreadPoolQueueCapacity() {
return pullThreadPoolQueueCapacity;
}
public void setPullThreadPoolQueueCapacity(int pullThreadPoolQueueCapacity) {
this.pullThreadPoolQueueCapacity = pullThreadPoolQueueCapacity;
}
public boolean isBrokerTopicEnable() {
return brokerTopicEnable;
}
public void setBrokerTopicEnable(boolean brokerTopicEnable) {
this.brokerTopicEnable = brokerTopicEnable;
}
public int getFilterServerNums() {
return filterServerNums;
}
public void setFilterServerNums(int filterServerNums) {
this.filterServerNums = filterServerNums;
}
public boolean isLongPollingEnable() {
return longPollingEnable;
}
public void setLongPollingEnable(boolean longPollingEnable) {
this.longPollingEnable = longPollingEnable;
}
public boolean isNotifyConsumerIdsChangedEnable() {
return notifyConsumerIdsChangedEnable;
}
public void setNotifyConsumerIdsChangedEnable(boolean notifyConsumerIdsChangedEnable) {
this.notifyConsumerIdsChangedEnable = notifyConsumerIdsChangedEnable;
}
public long getShortPollingTimeMills() {
return shortPollingTimeMills;
}
public void setShortPollingTimeMills(long shortPollingTimeMills) {
this.shortPollingTimeMills = shortPollingTimeMills;
}
public int getClientManageThreadPoolNums() {
return clientManageThreadPoolNums;
}
public void setClientManageThreadPoolNums(int clientManageThreadPoolNums) {
this.clientManageThreadPoolNums = clientManageThreadPoolNums;
}
public boolean isCommercialEnable() {
return commercialEnable;
}
public void setCommercialEnable(final boolean commercialEnable) {
this.commercialEnable = commercialEnable;
}
public int getCommercialTimerCount() {
return commercialTimerCount;
}
public void setCommercialTimerCount(final int commercialTimerCount) {
this.commercialTimerCount = commercialTimerCount;
}
public int getCommercialTransCount() {
return commercialTransCount;
}
public void setCommercialTransCount(final int commercialTransCount) {
this.commercialTransCount = commercialTransCount;
}
public int getCommercialBigCount() {
return commercialBigCount;
}
public void setCommercialBigCount(final int commercialBigCount) {
this.commercialBigCount = commercialBigCount;
}
public int getMaxDelayTime() {
return maxDelayTime;
}
public void setMaxDelayTime(final int maxDelayTime) {
this.maxDelayTime = maxDelayTime;
}
public int getClientManagerThreadPoolQueueCapacity() {
return clientManagerThreadPoolQueueCapacity;
}
public void setClientManagerThreadPoolQueueCapacity(int clientManagerThreadPoolQueueCapacity) {
this.clientManagerThreadPoolQueueCapacity = clientManagerThreadPoolQueueCapacity;
}
public int getConsumerManagerThreadPoolQueueCapacity() {
return consumerManagerThreadPoolQueueCapacity;
}
public void setConsumerManagerThreadPoolQueueCapacity(int consumerManagerThreadPoolQueueCapacity) {
this.consumerManagerThreadPoolQueueCapacity = consumerManagerThreadPoolQueueCapacity;
}
public int getConsumerManageThreadPoolNums() {
return consumerManageThreadPoolNums;
}
public void setConsumerManageThreadPoolNums(int consumerManageThreadPoolNums) {
this.consumerManageThreadPoolNums = consumerManageThreadPoolNums;
}
public int getCommercialBaseCount() {
return commercialBaseCount;
}
public void setCommercialBaseCount(int commercialBaseCount) {
this.commercialBaseCount = commercialBaseCount;
}
}<|fim▁end|>
|
this.traceOn = traceOn;
}
public long getStartAcceptSendRequestTimeStamp() {
|
<|file_name|>config.py<|end_file_name|><|fim▁begin|>"""Module to help with parsing and generating configuration files."""
import asyncio
import logging
import os
import shutil
from types import MappingProxyType
# pylint: disable=unused-import
from typing import Any, Tuple # NOQA
import voluptuous as vol
from homeassistant.const import (
CONF_LATITUDE, CONF_LONGITUDE, CONF_NAME, CONF_UNIT_SYSTEM,
CONF_TIME_ZONE, CONF_CUSTOMIZE, CONF_ELEVATION, CONF_UNIT_SYSTEM_METRIC,
CONF_UNIT_SYSTEM_IMPERIAL, CONF_TEMPERATURE_UNIT, TEMP_CELSIUS,
__version__)
from homeassistant.core import valid_entity_id
from homeassistant.exceptions import HomeAssistantError
from homeassistant.util.yaml import load_yaml
import homeassistant.helpers.config_validation as cv
from homeassistant.helpers.entity import set_customize
from homeassistant.util import dt as date_util, location as loc_util
from homeassistant.util.unit_system import IMPERIAL_SYSTEM, METRIC_SYSTEM
_LOGGER = logging.getLogger(__name__)
YAML_CONFIG_FILE = 'configuration.yaml'
VERSION_FILE = '.HA_VERSION'
CONFIG_DIR_NAME = '.homeassistant'
DEFAULT_CORE_CONFIG = (
# Tuples (attribute, default, auto detect property, description)
(CONF_NAME, 'Home', None, 'Name of the location where Home Assistant is '
'running'),
(CONF_LATITUDE, 0, 'latitude', 'Location required to calculate the time'
' the sun rises and sets'),
(CONF_LONGITUDE, 0, 'longitude', None),
(CONF_ELEVATION, 0, None, 'Impacts weather/sunrise data'
' (altitude above sea level in meters)'),
(CONF_UNIT_SYSTEM, CONF_UNIT_SYSTEM_METRIC, None,
'{} for Metric, {} for Imperial'.format(CONF_UNIT_SYSTEM_METRIC,
CONF_UNIT_SYSTEM_IMPERIAL)),
(CONF_TIME_ZONE, 'UTC', 'time_zone', 'Pick yours from here: http://en.wiki'
'pedia.org/wiki/List_of_tz_database_time_zones'),
) # type: Tuple[Tuple[str, Any, Any, str], ...]
DEFAULT_CONFIG = """
# Show links to resources in log and frontend
introduction:
# Enables the frontend
frontend:
http:
# Uncomment this to add a password (recommended!)
# api_password: PASSWORD
# Checks for available updates
updater:
# Discover some devices automatically
discovery:
# Allows you to issue voice commands from the frontend in enabled browsers
conversation:
# Enables support for tracking state changes over time.
history:
# View all events in a logbook
logbook:
# Track the sun
sun:
# Weather Prediction
sensor:
platform: yr
"""
def _valid_customize(value):
"""Config validator for customize."""
if not isinstance(value, dict):
raise vol.Invalid('Expected dictionary')
for key, val in value.items():
if not valid_entity_id(key):
raise vol.Invalid('Invalid entity ID: {}'.format(key))
if not isinstance(val, dict):
raise vol.Invalid('Value of {} is not a dictionary'.format(key))
return value
CORE_CONFIG_SCHEMA = vol.Schema({
CONF_NAME: vol.Coerce(str),
CONF_LATITUDE: cv.latitude,
CONF_LONGITUDE: cv.longitude,
CONF_ELEVATION: vol.Coerce(int),
vol.Optional(CONF_TEMPERATURE_UNIT): cv.temperature_unit,
CONF_UNIT_SYSTEM: cv.unit_system,
CONF_TIME_ZONE: cv.time_zone,
vol.Required(CONF_CUSTOMIZE,
default=MappingProxyType({})): _valid_customize,
})
def get_default_config_dir() -> str:
"""Put together the default configuration directory based on OS."""
data_dir = os.getenv('APPDATA') if os.name == "nt" \
else os.path.expanduser('~')
return os.path.join(data_dir, CONFIG_DIR_NAME)
def ensure_config_exists(config_dir: str, detect_location: bool=True) -> str:
"""Ensure a config file exists in given configuration directory.
Creating a default one if needed.
Return path to the config file.
"""
config_path = find_config_file(config_dir)
if config_path is None:
print("Unable to find configuration. Creating default one in",
config_dir)
config_path = create_default_config(config_dir, detect_location)
return config_path
def create_default_config(config_dir, detect_location=True):
"""Create a default configuration file in given configuration directory.
Return path to new config file if success, None if failed.
This method needs to run in an executor.
"""
config_path = os.path.join(config_dir, YAML_CONFIG_FILE)
version_path = os.path.join(config_dir, VERSION_FILE)
info = {attr: default for attr, default, _, _ in DEFAULT_CORE_CONFIG}
location_info = detect_location and loc_util.detect_location_info()
if location_info:
if location_info.use_metric:
info[CONF_UNIT_SYSTEM] = CONF_UNIT_SYSTEM_METRIC
else:
info[CONF_UNIT_SYSTEM] = CONF_UNIT_SYSTEM_IMPERIAL
for attr, default, prop, _ in DEFAULT_CORE_CONFIG:
if prop is None:
continue
info[attr] = getattr(location_info, prop) or default
if location_info.latitude and location_info.longitude:
info[CONF_ELEVATION] = loc_util.elevation(location_info.latitude,
location_info.longitude)
# Writing files with YAML does not create the most human readable results
# So we're hard coding a YAML template.
try:
with open(config_path, 'w') as config_file:
config_file.write("homeassistant:\n")
for attr, _, _, description in DEFAULT_CORE_CONFIG:
if info[attr] is None:
continue
elif description:
config_file.write(" # {}\n".format(description))
config_file.write(" {}: {}\n".format(attr, info[attr]))
config_file.write(DEFAULT_CONFIG)
with open(version_path, 'wt') as version_file:
version_file.write(__version__)
return config_path
except IOError:
print('Unable to create default configuration file', config_path)
return None
@asyncio.coroutine
def async_hass_config_yaml(hass):
"""Load YAML from hass config File.
This function allow component inside asyncio loop to reload his config by
self.
This method is a coroutine.
"""
def _load_hass_yaml_config():
path = find_config_file(hass.config.config_dir)
conf = load_yaml_config_file(path)
return conf
conf = yield from hass.loop.run_in_executor(None, _load_hass_yaml_config)
return conf
def find_config_file(config_dir):
"""Look in given directory for supported configuration files.
Async friendly.
"""
config_path = os.path.join(config_dir, YAML_CONFIG_FILE)
return config_path if os.path.isfile(config_path) else None
def load_yaml_config_file(config_path):
"""Parse a YAML configuration file.
This method needs to run in an executor.
"""
conf_dict = load_yaml(config_path)
if not isinstance(conf_dict, dict):
msg = 'The configuration file {} does not contain a dictionary'.format(
os.path.basename(config_path))
_LOGGER.error(msg)
raise HomeAssistantError(msg)
return conf_dict
def process_ha_config_upgrade(hass):
"""Upgrade config if necessary.
This method needs to run in an executor.
"""
version_path = hass.config.path(VERSION_FILE)
try:
with open(version_path, 'rt') as inp:
conf_version = inp.readline().strip()
except FileNotFoundError:
# Last version to not have this file
conf_version = '0.7.7'
if conf_version == __version__:
return
_LOGGER.info('Upgrading config directory from %s to %s', conf_version,
__version__)
lib_path = hass.config.path('deps')
if os.path.isdir(lib_path):
shutil.rmtree(lib_path)
with open(version_path, 'wt') as outp:
outp.write(__version__)
@asyncio.coroutine
def async_process_ha_core_config(hass, config):
"""Process the [homeassistant] section from the config.
This method is a coroutine.
"""
config = CORE_CONFIG_SCHEMA(config)
hac = hass.config
def set_time_zone(time_zone_str):
"""Helper method to set time zone."""
if time_zone_str is None:
return
time_zone = date_util.get_time_zone(time_zone_str)
if time_zone:
hac.time_zone = time_zone
date_util.set_default_time_zone(time_zone)
else:
_LOGGER.error('Received invalid time zone %s', time_zone_str)
for key, attr in ((CONF_LATITUDE, 'latitude'),
(CONF_LONGITUDE, 'longitude'),
(CONF_NAME, 'location_name'),
(CONF_ELEVATION, 'elevation')):
if key in config:
setattr(hac, attr, config[key])
<|fim▁hole|> set_time_zone(config.get(CONF_TIME_ZONE))
set_customize(config.get(CONF_CUSTOMIZE) or {})
if CONF_UNIT_SYSTEM in config:
if config[CONF_UNIT_SYSTEM] == CONF_UNIT_SYSTEM_IMPERIAL:
hac.units = IMPERIAL_SYSTEM
else:
hac.units = METRIC_SYSTEM
elif CONF_TEMPERATURE_UNIT in config:
unit = config[CONF_TEMPERATURE_UNIT]
if unit == TEMP_CELSIUS:
hac.units = METRIC_SYSTEM
else:
hac.units = IMPERIAL_SYSTEM
_LOGGER.warning("Found deprecated temperature unit in core config, "
"expected unit system. Replace '%s: %s' with "
"'%s: %s'", CONF_TEMPERATURE_UNIT, unit,
CONF_UNIT_SYSTEM, hac.units.name)
# Shortcut if no auto-detection necessary
if None not in (hac.latitude, hac.longitude, hac.units,
hac.time_zone, hac.elevation):
return
discovered = []
# If we miss some of the needed values, auto detect them
if None in (hac.latitude, hac.longitude, hac.units,
hac.time_zone):
info = yield from hass.loop.run_in_executor(
None, loc_util.detect_location_info)
if info is None:
_LOGGER.error('Could not detect location information')
return
if hac.latitude is None and hac.longitude is None:
hac.latitude, hac.longitude = (info.latitude, info.longitude)
discovered.append(('latitude', hac.latitude))
discovered.append(('longitude', hac.longitude))
if hac.units is None:
hac.units = METRIC_SYSTEM if info.use_metric else IMPERIAL_SYSTEM
discovered.append((CONF_UNIT_SYSTEM, hac.units.name))
if hac.location_name is None:
hac.location_name = info.city
discovered.append(('name', info.city))
if hac.time_zone is None:
set_time_zone(info.time_zone)
discovered.append(('time_zone', info.time_zone))
if hac.elevation is None and hac.latitude is not None and \
hac.longitude is not None:
elevation = yield from hass.loop.run_in_executor(
None, loc_util.elevation, hac.latitude, hac.longitude)
hac.elevation = elevation
discovered.append(('elevation', elevation))
if discovered:
_LOGGER.warning(
'Incomplete core config. Auto detected %s',
', '.join('{}: {}'.format(key, val) for key, val in discovered))<|fim▁end|>
|
if CONF_TIME_ZONE in config:
|
<|file_name|>Buginese-code-points.js<|end_file_name|><|fim▁begin|>// All code points in the Buginese block as per Unicode v5.1.0:
[
0x1A00,
0x1A01,
0x1A02,
0x1A03,
0x1A04,
0x1A05,
0x1A06,
0x1A07,
0x1A08,
0x1A09,
0x1A0A,
0x1A0B,
0x1A0C,
0x1A0D,
0x1A0E,
0x1A0F,
0x1A10,
0x1A11,
0x1A12,
0x1A13,
0x1A14,<|fim▁hole|> 0x1A17,
0x1A18,
0x1A19,
0x1A1A,
0x1A1B,
0x1A1C,
0x1A1D,
0x1A1E,
0x1A1F
];<|fim▁end|>
|
0x1A15,
0x1A16,
|
<|file_name|>attr_wrong_item.rs<|end_file_name|><|fim▁begin|>use juniper::graphql_object;
#[graphql_object]
enum Character {}
<|fim▁hole|><|fim▁end|>
|
fn main() {}
|
<|file_name|>client.go<|end_file_name|><|fim▁begin|>// Package logic implements the Azure ARM Logic service API version 2016-06-01.
//
// REST API for Azure Logic Apps.
package logic
// Copyright (c) Microsoft and contributors. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.<|fim▁hole|>//
// 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.
//
// Code generated by Microsoft (R) AutoRest Code Generator 1.0.1.0
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.
import (
"github.com/Azure/go-autorest/autorest"
"github.com/Azure/go-autorest/autorest/azure"
"net/http"
)
const (
// DefaultBaseURI is the default URI used for the service Logic
DefaultBaseURI = "https://management.azure.com"
)
// ManagementClient is the base client for Logic.
type ManagementClient struct {
autorest.Client
BaseURI string
SubscriptionID string
}
// New creates an instance of the ManagementClient client.
func New(subscriptionID string) ManagementClient {
return NewWithBaseURI(DefaultBaseURI, subscriptionID)
}
// NewWithBaseURI creates an instance of the ManagementClient client.
func NewWithBaseURI(baseURI string, subscriptionID string) ManagementClient {
return ManagementClient{
Client: autorest.NewClientWithUserAgent(UserAgent()),
BaseURI: baseURI,
SubscriptionID: subscriptionID,
}
}
// ListOperations lists all of the available Logic REST API operations.
func (client ManagementClient) ListOperations() (result OperationListResult, err error) {
req, err := client.ListOperationsPreparer()
if err != nil {
return result, autorest.NewErrorWithError(err, "logic.ManagementClient", "ListOperations", nil, "Failure preparing request")
}
resp, err := client.ListOperationsSender(req)
if err != nil {
result.Response = autorest.Response{Response: resp}
return result, autorest.NewErrorWithError(err, "logic.ManagementClient", "ListOperations", resp, "Failure sending request")
}
result, err = client.ListOperationsResponder(resp)
if err != nil {
err = autorest.NewErrorWithError(err, "logic.ManagementClient", "ListOperations", resp, "Failure responding to request")
}
return
}
// ListOperationsPreparer prepares the ListOperations request.
func (client ManagementClient) ListOperationsPreparer() (*http.Request, error) {
const APIVersion = "2016-06-01"
queryParameters := map[string]interface{}{
"api-version": APIVersion,
}
preparer := autorest.CreatePreparer(
autorest.AsGet(),
autorest.WithBaseURL(client.BaseURI),
autorest.WithPath("/providers/Microsoft.Logic/operations"),
autorest.WithQueryParameters(queryParameters))
return preparer.Prepare(&http.Request{})
}
// ListOperationsSender sends the ListOperations request. The method will close the
// http.Response Body if it receives an error.
func (client ManagementClient) ListOperationsSender(req *http.Request) (*http.Response, error) {
return autorest.SendWithSender(client, req)
}
// ListOperationsResponder handles the response to the ListOperations request. The method always
// closes the http.Response Body.
func (client ManagementClient) ListOperationsResponder(resp *http.Response) (result OperationListResult, err error) {
err = autorest.Respond(
resp,
client.ByInspecting(),
azure.WithErrorUnlessStatusCode(http.StatusOK),
autorest.ByUnmarshallingJSON(&result),
autorest.ByClosing())
result.Response = autorest.Response{Response: resp}
return
}
// ListOperationsNextResults retrieves the next set of results, if any.
func (client ManagementClient) ListOperationsNextResults(lastResults OperationListResult) (result OperationListResult, err error) {
req, err := lastResults.OperationListResultPreparer()
if err != nil {
return result, autorest.NewErrorWithError(err, "logic.ManagementClient", "ListOperations", nil, "Failure preparing next results request")
}
if req == nil {
return
}
resp, err := client.ListOperationsSender(req)
if err != nil {
result.Response = autorest.Response{Response: resp}
return result, autorest.NewErrorWithError(err, "logic.ManagementClient", "ListOperations", resp, "Failure sending next results request")
}
result, err = client.ListOperationsResponder(resp)
if err != nil {
err = autorest.NewErrorWithError(err, "logic.ManagementClient", "ListOperations", resp, "Failure responding to next results request")
}
return
}<|fim▁end|>
|
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
|
<|file_name|>gal-file.py<|end_file_name|><|fim▁begin|>import pandas as pd<|fim▁hole|>import os
# -*- coding: utf-8 -*-
from flutype.data_management.fill_master import Master
import numpy as np
def print_full(x):
pd.set_option('display.max_rows', len(x))
print(x)
pd.reset_option('display.max_rows')
def extract_peptide_batch(ma):
gal_lig_fix = ma.read_gal_ligand("170725_N13", index=False)
unique_peptides = gal_lig_fix[0].drop_duplicates(subset=["ID"])
unique_peptides = unique_peptides[unique_peptides.ID != "Empty"]
unique_peptides.ID = unique_peptides.ID.astype(int)
unique_peptides.sort_values(by = "ID", inplace=True)
unique_peptides.Name = unique_peptides.Name.str.replace('FAIL_', "")
unique_peptides['Concentration'] = unique_peptides.Name.str.rpartition('_')[0]
unique_peptides['Concentration'] = unique_peptides.Concentration.str.partition('_')[0]
peptide_batch = pd.DataFrame(unique_peptides[["Name","Concentration"]].values,columns=["sid","concentration"])
peptide_batch["labeling"] = ""
peptide_batch["buffer"] = ""
peptide_batch["ph"] = ""
peptide_batch["purity"] = ""
peptide_batch["produced_by"] = ""
peptide_batch["comment"] = ""
peptide_batch["ligand"] = ""
peptide_batch["ligand"] = unique_peptides.Name.str.partition('_')[2].values
return peptide_batch
def gal_reformat(ma):
gal_lig_fix = ma.read_gal_ligand("170725_N15", index= False)
gal_lig_fix_new = pd.DataFrame(gal_lig_fix[0][["Block","Row","Column","Name"]])
mapping = {"Empty":"NO",
"Panama":"Pan3",
"California":"Cal2",
"Aichi":"Ach1",
"1.0_Kloe_Amid":"KLOA025",
"0.5_Kloe_Amid":"KLOA050",
"0.25_Kloe_Amid":"KLOA025",
"1.0_pep_Nenad":"NEN100",
"0.5_pep_Nenad":"NEN050",
"0.25_pep_Nenad":"NEN025",
"1.0_Fetuin":"P012-1",
"0.5_Fetuin":"P012-05",
"0.25_Fetuin":"P012-025",
"1.0_Leuchtefix":"DYE100",
"0.5_Leuchtefix":"DYE050",
"0.25_Leuchtefix":"DYE025",
'FAIL_': ""
}
for key in mapping:
gal_lig_fix_new.Name = gal_lig_fix_new.Name.str.replace(key, mapping[key])
mapping = {"1.0_Kloe_S":"KLOS100",
"0.5_Kloe_S":"KLOS050",
"0.25_Kloe_S":"KLOS025"
}
for key in mapping:
gal_lig_fix_new.loc[gal_lig_fix_new["Name"].str.contains(key), "Name"] = mapping[key]
return gal_lig_fix_new
def peptide_batches_not_in_master(ma,gal_lig_fix):
s_gal = set(gal_lig_fix["Name"].values)
data_dic = ma.read_data_tables()
s_pb = set(data_dic["peptide_batch"]["sid"].values)
s_ab = set(data_dic["antibody_batch"]["sid"].values)
s_vb = set(data_dic["virus_batch"]["sid"].values)
s_b = s_pb
s_b.update(s_ab)
s_b.update(s_vb)
return(s_gal - s_b)
def reshape_gal_file(shape, gal_file):
a = []
b = []
for i in range(shape[1]):
for ii in range(shape[0]):
a.append(i )
b.append(ii )
gal_file["row_factor"] = 0
gal_file["column_factor"] = 0
print(a)
print(b)
for block_num,block_factor in enumerate(a):
gal_file.loc[gal_file["Block"] == block_num+1, "row_factor"] = block_factor
for block_num, block_factor in enumerate(b):
gal_file.loc[gal_file["Block"] == block_num+1, "column_factor"] = block_factor
gal_file["Row"]=gal_file["Row"]+(gal_file["Row"].max()*gal_file["row_factor"])
gal_file["Column"]=gal_file["Column"]+(gal_file["Column"].max()*gal_file["column_factor"])
return gal_file
def three_viruses_gal(gal_file):
virus_map = {}
for i in range(1,33):
if i <= 12:
virus_map[i] = "Ach1"
elif 12 < i <= 24:
virus_map[i] = "Cal2"
elif 24 < i:
virus_map[i] = "Pan3"
for key in virus_map.keys():
gal_file.loc[gal_file["Block"]== key , "Name"] =virus_map[key]
return gal_file
####################################################################
if __name__ == "__main__":
ma_path = "../master_uncomplete/"
ma = Master(ma_path)
#peptide_batch = extract_peptide_batch(ma)
# print_full(peptide_batch)
#fp = os.path.join(ma.collections_path,"170725_N13","peptides_batch.csv")
# peptide_batch.to_csv(fp)
ma_path_standard = "../master/"
ma_standard = Master(ma_path_standard)
gal_lig_fix = gal_reformat(ma)
#subset = peptide_batches_not_in_master(ma_standard,gal_lig_fix)
gal_lig_fix= reshape_gal_file((4,8), gal_lig_fix)
gal_lig_fix = gal_lig_fix.reset_index(drop=True)
fp = os.path.join(ma.collections_path,"170725_P7","lig_fix_012.txt")
gal_lig_fix.to_csv(fp, sep='\t',index=True , index_label="ID")
#gal_lig_fix = three_viruses_gal(gal_lig_fix)
gal_lig_fix["Name"] = "Ach1"
fp2 = os.path.join(ma.collections_path,"170725_P7","lig_mob_016.txt")
gal_lig_fix.to_csv(fp2, sep='\t', index=True,index_label="ID")<|fim▁end|>
| |
<|file_name|>my_exception.py<|end_file_name|><|fim▁begin|>class NoResultScraped(Exception):<|fim▁hole|>
class NotCompleteParse(Exception):
pass
class CouldNotAuthorize(Exception):
pass<|fim▁end|>
|
pass
|
<|file_name|>eval.rs<|end_file_name|><|fim▁begin|>use libc::c_int;
use crate::object::PyObject;
#[cfg_attr(windows, link(name = "pythonXY"))]
extern "C" {
pub fn PyEval_EvalCode(
arg1: *mut PyObject,
arg2: *mut PyObject,
arg3: *mut PyObject,
) -> *mut PyObject;
pub fn PyEval_EvalCodeEx(
co: *mut PyObject,
globals: *mut PyObject,
locals: *mut PyObject,
args: *const *mut PyObject,<|fim▁hole|> kwdc: c_int,
defs: *const *mut PyObject,
defc: c_int,
kwdefs: *mut PyObject,
closure: *mut PyObject,
) -> *mut PyObject;
}<|fim▁end|>
|
argc: c_int,
kwds: *const *mut PyObject,
|
<|file_name|>TokenAction.java<|end_file_name|><|fim▁begin|>package pipe.actions.gui;
import pipe.controllers.PetriNetController;
import pipe.controllers.PlaceController;
import uk.ac.imperial.pipe.models.petrinet.Connectable;
import uk.ac.imperial.pipe.models.petrinet.Place;
import java.awt.event.MouseEvent;
import java.util.Map;
/**
* Abstract action responsible for adding and deleting tokens to places
*/
public abstract class TokenAction extends CreateAction {
/**
*
* @param name image name
* @param tooltip tooltip message
* @param key keyboard shortcut
* @param modifiers keyboard accelerator
* @param applicationModel current PIPE application model
*/<|fim▁hole|> super(name, tooltip, key, modifiers, applicationModel);
}
/**
* Noop action when a component has not been clicked on
* @param event mouse event
* @param petriNetController controller for the petri net
*/
@Override
public void doAction(MouseEvent event, PetriNetController petriNetController) {
// Do nothing unless clicked a connectable
}
/**
* Performs the subclass token action on the place
* @param connectable item clicked
* @param petriNetController controller for the petri net
*/
@Override
public void doConnectableAction(Connectable connectable, PetriNetController petriNetController) {
//TODO: Maybe a method, connectable.containsTokens() or visitor pattern
if (connectable instanceof Place) {
Place place = (Place) connectable;
String token = petriNetController.getSelectedToken();
performTokenAction(petriNetController.getPlaceController(place), token);
}
}
/**
* Subclasses should perform their relevant action on the token e.g. add/delete
*
* @param placeController
* @param token
*/
protected abstract void performTokenAction(PlaceController placeController, String token);
/**
* Sets the place to contain counts.
* <p/>
* Creates a new history edit
*
* @param placeController
* @param counts
*/
protected void setTokenCounts(PlaceController placeController, Map<String, Integer> counts) {
placeController.setTokenCounts(counts);
}
}<|fim▁end|>
|
public TokenAction(String name, String tooltip, int key, int modifiers, PipeApplicationModel applicationModel) {
|
<|file_name|>conf.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*-
#
# 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.
#
# murano documentation build configuration file, created by
# sphinx-quickstart on Sat May 1 15:17:47 2010.
#
# This file is execfile()d with the current directory set to
# its containing dir.
#
# Note that not all possible configuration values are present in this
# autogenerated file.
#
# All configuration values have a default; values that are commented out
# serve to show the default.
import os
import sys
extensions = [
'os_api_ref',
'openstackdocstheme'
]
html_theme = 'openstackdocs'
html_theme_options = {
"sidebar_mode": "toc",
}
# openstackdocstheme options
openstackdocs_repo_name = 'openstack/murano'
openstackdocs_bug_project = 'murano'
openstackdocs_bug_tag = 'api-ref'
# If extensions (or modules to document with autodoc) are in another directory,
# add these directories to sys.path here. If the directory is relative to the
# documentation root, use os.path.abspath to make it absolute, like shown here.
sys.path.insert(0, os.path.abspath('../../'))
sys.path.insert(0, os.path.abspath('../'))
sys.path.insert(0, os.path.abspath('./'))
# -- General configuration ----------------------------------------------------
# Add any Sphinx extension module names here, as strings. They can be
# extensions coming with Sphinx (named 'sphinx.ext.*') or your custom ones.
# The suffix of source filenames.
source_suffix = '.rst'
# The encoding of source files.
#
# source_encoding = 'utf-8'
# The master toctree document.
master_doc = 'index'
# General information about the project.
copyright = u'2016-present, OpenStack Foundation'
# The language for content autogenerated by Sphinx. Refer to documentation
# for a list of supported languages.
#
# language = None
# There are two options for replacing |today|: either, you set today to some
# non-false value, then it is used:
# today = ''
# Else, today_fmt is used as the format for a strftime call.
# today_fmt = '%B %d, %Y'
# The reST default role (used for this markup: `text`) to use
# for all documents.
# default_role = None
# If true, '()' will be appended to :func: etc. cross-reference text.
# add_function_parentheses = True
# If true, the current module name will be prepended to all description
# unit titles (such as .. function::).
add_module_names = False
# If true, sectionauthor and moduleauthor directives will be shown in the
# output. They are ignored by default.
show_authors = False
# The name of the Pygments (syntax highlighting) style to use.
pygments_style = 'native'
# -- Options for man page output ----------------------------------------------
# Grouping the document tree for man pages.
# List of tuples 'sourcefile', 'target', u'title', u'Authors name', 'manual'
# -- Options for HTML output --------------------------------------------------
# The theme to use for HTML and HTML Help pages. Major themes that come with
# Sphinx are currently 'default' and 'sphinxdoc'.
# html_theme_path = ["."]
# html_theme = '_theme'
# Theme options are theme-specific and customize the look and feel of a theme
# further. For a list of options available for each theme, see the
# documentation.
# html_theme_options = {}
# Add any paths that contain custom themes here, relative to this directory.
# html_theme_path = []
# The name for this set of Sphinx documents. If None, it defaults to
# "<project> v<release> documentation".
# html_title = None
# A shorter title for the navigation bar. Default is the same as html_title.
# html_short_title = None
# The name of an image file (relative to this directory) to place at the top
# of the sidebar.
# html_logo = None
# The name of an image file (within the static path) to use as favicon of the
# docs. This file should be a Windows icon file (.ico) being 16x16 or 32x32
# pixels large.
# html_favicon = None
# Add any paths that contain custom static files (such as style sheets) here,
# relative to this directory. They are copied after the builtin static files,
# so a file named "default.css" will overwrite the builtin "default.css".
# html_static_path = ['_static']
# If true, SmartyPants will be used to convert quotes and dashes to
# typographically correct entities.
# html_use_smartypants = True
# Custom sidebar templates, maps document names to template names.
# html_sidebars = {}
# Additional templates that should be rendered to pages, maps page names to
# template names.
# html_additional_pages = {}
# If false, no module index is generated.
# html_use_modindex = True
# If false, no index is generated.
# html_use_index = True
# If true, the index is split into individual pages for each letter.
# html_split_index = False
# If true, links to the reST sources are added to the pages.
# html_show_sourcelink = True
# If true, an OpenSearch description file will be output, and all pages will
# contain a <link> tag referring to it. The value of this option must be the
# base URL from which the finished HTML is served.
# html_use_opensearch = ''
# If nonempty, this is the file name suffix for HTML files (e.g. ".xhtml").
# html_file_suffix = ''
# Output file base name for HTML help builder.
htmlhelp_basename = 'muranodoc'
# -- Options for LaTeX output -------------------------------------------------
# The paper size ('letter' or 'a4').
# latex_paper_size = 'letter'
# The font size ('10pt', '11pt' or '12pt').<|fim▁hole|>
# Grouping the document tree into LaTeX files. List of tuples
# (source start file, target name, title, author, documentclass
# [howto/manual]).
latex_documents = [
('index', 'Murano.tex', u'OpenStack Application Catalog API Documentation',
u'OpenStack Foundation', 'manual'),
]
# The name of an image file (relative to this directory) to place at the top of
# the title page.
# latex_logo = None
# For "manual" documents, if this is true, then toplevel headings are parts,
# not chapters.
# latex_use_parts = False
# Additional stuff for the LaTeX preamble.
# latex_preamble = ''
# Documents to append as an appendix to all manuals.
# latex_appendices = []
# If false, no module index is generated.
# latex_use_modindex = True<|fim▁end|>
|
# latex_font_size = '10pt'
|
<|file_name|>code.py<|end_file_name|><|fim▁begin|># -*- coding:utf-8 -*-
'''Created on 2014-8-7 @author: Administrator '''
from sys import path as sys_path
if not '..' in sys_path:sys_path.append("..") #用于import上级目录的模块
import web
#早起的把一个文件分成多个文件,再把class导入
from login.login import (index,login,loginCheck,In,reset,register,find_password)
from blog.blog import (write_blog,upload,blog_content_manage,Get,Del,blog_single_self,blog_single_other)
from admin.admin import (adminAdd,adminGet,adminDel,adminEdit)
#后期应用web.py 的子应用
from wiki.view import wiki_app
<|fim▁hole|>from bbs.bbs import bbs_app
urls=(
'/','index',
'/login','login',
'/loginCheck','loginCheck',
'/(admin|user_blog)','In',
'/reset/(.*)','reset',
'/register','register',
'/find_password','find_password',
'/write_blog','write_blog',
'/upload','upload',
'/blog_content_manage','blog_content_manage',
'/Get/classification','Get',
'/Del/blog_content','Del',
'/blog_single_self','blog_single_self',
'/blog_single_other','blog_single_other',
'/admin/add','adminAdd',
'/admin/get','adminGet',
'/admin/del','adminDel',
'/admin/edit','adminEdit',
'/wiki',wiki_app,
'/download',download_app,
'/meeting',meeting_app,
'/bbs',bbs_app,
)
app = web.application(urls ,locals())
#session 在web.config.debug = False模式下可用 可以用一下方式解决 生产中 一般设置web.config.debug = False
web.config.debug = True
if web.config.get('_session') is None:
session = web.session.Session(app,web.session.DiskStore('sessions'))
web.config._session=session
else:
session=web.config._session
#用以下方式可以解决多文件之间传递session的问题
def session_hook():web.ctx.session=session
app.add_processor(web.loadhook(session_hook))
if __name__=='__main__':
app.run()<|fim▁end|>
|
from download.download import download_app
from meeting.meeting import meeting_app
|
<|file_name|>htmlinputelement.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::activation::Activatable;
use dom::attr::{Attr, AttrValue};
use dom::bindings::cell::DOMRefCell;
use dom::bindings::codegen::Bindings::AttrBinding::AttrMethods;
use dom::bindings::codegen::Bindings::EventBinding::EventMethods;
use dom::bindings::codegen::Bindings::HTMLInputElementBinding;
use dom::bindings::codegen::Bindings::HTMLInputElementBinding::HTMLInputElementMethods;
use dom::bindings::codegen::Bindings::KeyboardEventBinding::KeyboardEventMethods;
use dom::bindings::codegen::InheritTypes::KeyboardEventCast;
use dom::bindings::codegen::InheritTypes::{ElementCast, HTMLElementCast, HTMLInputElementCast, NodeCast};
use dom::bindings::codegen::InheritTypes::{HTMLInputElementDerived, HTMLFieldSetElementDerived, EventTargetCast};
use dom::bindings::global::GlobalRef;
use dom::bindings::js::{JS, LayoutJS, Root, RootedReference};
use dom::document::Document;
use dom::element::{Element, ElementTypeId, RawLayoutElementHelpers};
use dom::event::{Event, EventBubbles, EventCancelable};
use dom::eventtarget::{EventTarget, EventTargetTypeId};
use dom::htmlelement::{HTMLElement, HTMLElementTypeId};
use dom::htmlformelement::{FormSubmitter, FormControl, HTMLFormElement};
use dom::htmlformelement::{SubmittedFrom, ResetFrom};
use dom::keyboardevent::KeyboardEvent;
use dom::node::{Node, NodeDamage, NodeTypeId};
use dom::node::{document_from_node, window_from_node};
use dom::virtualmethods::VirtualMethods;
use msg::constellation_msg::ConstellationChan;
use textinput::KeyReaction::{TriggerDefaultAction, DispatchInput, Nothing};
use textinput::Lines::Single;
use textinput::TextInput;
use string_cache::Atom;
use util::str::DOMString;
use std::borrow::ToOwned;
use std::cell::Cell;
const DEFAULT_SUBMIT_VALUE: &'static str = "Submit";
const DEFAULT_RESET_VALUE: &'static str = "Reset";
#[derive(JSTraceable, PartialEq, Copy, Clone)]
#[allow(dead_code)]
#[derive(HeapSizeOf)]
enum InputType {
InputSubmit,
InputReset,
InputButton,
InputText,
InputFile,
InputImage,
InputCheckbox,
InputRadio,
InputPassword
}
#[dom_struct]
pub struct HTMLInputElement {
htmlelement: HTMLElement,
input_type: Cell<InputType>,
checked: Cell<bool>,
checked_changed: Cell<bool>,
placeholder: DOMRefCell<DOMString>,
indeterminate: Cell<bool>,
value_changed: Cell<bool>,
size: Cell<u32>,
#[ignore_heap_size_of = "#7193"]
textinput: DOMRefCell<TextInput<ConstellationChan>>,
activation_state: DOMRefCell<InputActivationState>,
}
impl PartialEq for HTMLInputElement {
fn eq(&self, other: &HTMLInputElement) -> bool {
self as *const HTMLInputElement == &*other
}
}
#[derive(JSTraceable)]
#[must_root]
#[derive(HeapSizeOf)]
struct InputActivationState {
indeterminate: bool,
checked: bool,
checked_changed: bool,
checked_radio: Option<JS<HTMLInputElement>>,
// In case mutability changed
was_mutable: bool,
// In case the type changed
old_type: InputType,
}
impl InputActivationState {
fn new() -> InputActivationState {
InputActivationState {
indeterminate: false,
checked: false,
checked_changed: false,
checked_radio: None,
was_mutable: false,
old_type: InputType::InputText
}
}
}
impl HTMLInputElementDerived for EventTarget {
fn is_htmlinputelement(&self) -> bool {
*self.type_id() ==
EventTargetTypeId::Node(
NodeTypeId::Element(ElementTypeId::HTMLElement(HTMLElementTypeId::HTMLInputElement)))
}
}
static DEFAULT_INPUT_SIZE: u32 = 20;
impl HTMLInputElement {
fn new_inherited(localName: DOMString, prefix: Option<DOMString>, document: &Document) -> HTMLInputElement {
let chan = document.window().r().constellation_chan();
HTMLInputElement {
htmlelement: HTMLElement::new_inherited(HTMLElementTypeId::HTMLInputElement, localName, prefix, document),
input_type: Cell::new(InputType::InputText),
checked: Cell::new(false),
placeholder: DOMRefCell::new("".to_owned()),
indeterminate: Cell::new(false),
checked_changed: Cell::new(false),
value_changed: Cell::new(false),
size: Cell::new(DEFAULT_INPUT_SIZE),
textinput: DOMRefCell::new(TextInput::new(Single, "".to_owned(), chan)),
activation_state: DOMRefCell::new(InputActivationState::new())
}
}
#[allow(unrooted_must_root)]
pub fn new(localName: DOMString,
prefix: Option<DOMString>,
document: &Document) -> Root<HTMLInputElement> {
let element = HTMLInputElement::new_inherited(localName, prefix, document);
Node::reflect_node(box element, document, HTMLInputElementBinding::Wrap)
}
}
pub trait LayoutHTMLInputElementHelpers {
#[allow(unsafe_code)]
unsafe fn get_value_for_layout(self) -> String;
#[allow(unsafe_code)]
unsafe fn get_size_for_layout(self) -> u32;
}
pub trait RawLayoutHTMLInputElementHelpers {
#[allow(unsafe_code)]
unsafe fn get_checked_state_for_layout(&self) -> bool;
#[allow(unsafe_code)]
unsafe fn get_indeterminate_state_for_layout(&self) -> bool;
#[allow(unsafe_code)]
unsafe fn get_size_for_layout(&self) -> u32;
}
impl LayoutHTMLInputElementHelpers for LayoutJS<HTMLInputElement> {
#[allow(unsafe_code)]
unsafe fn get_value_for_layout(self) -> String {
#[allow(unsafe_code)]
unsafe fn get_raw_textinput_value(input: LayoutJS<HTMLInputElement>) -> String {
let textinput = (*input.unsafe_get()).textinput.borrow_for_layout().get_content();
if !textinput.is_empty() {
textinput
} else {
(*input.unsafe_get()).placeholder.borrow_for_layout().to_owned()
}
}
#[allow(unsafe_code)]
unsafe fn get_raw_attr_value(input: LayoutJS<HTMLInputElement>) -> Option<String> {
let elem = ElementCast::from_layout_js(&input);
(*elem.unsafe_get()).get_attr_val_for_layout(&ns!(""), &atom!("value"))
.map(|s| s.to_owned())
}
match (*self.unsafe_get()).input_type.get() {
InputType::InputCheckbox | InputType::InputRadio => "".to_owned(),
InputType::InputFile | InputType::InputImage => "".to_owned(),
InputType::InputButton => get_raw_attr_value(self).unwrap_or_else(|| "".to_owned()),
InputType::InputSubmit => get_raw_attr_value(self).unwrap_or_else(|| DEFAULT_SUBMIT_VALUE.to_owned()),
InputType::InputReset => get_raw_attr_value(self).unwrap_or_else(|| DEFAULT_RESET_VALUE.to_owned()),
InputType::InputPassword => {
let raw = get_raw_textinput_value(self);
raw.chars().map(|_| '●').collect()
}
_ => get_raw_textinput_value(self),
}
}
#[allow(unrooted_must_root)]
#[allow(unsafe_code)]
unsafe fn get_size_for_layout(self) -> u32 {
(*self.unsafe_get()).get_size_for_layout()
}
}
impl RawLayoutHTMLInputElementHelpers for HTMLInputElement {
#[allow(unrooted_must_root)]
#[allow(unsafe_code)]
unsafe fn get_checked_state_for_layout(&self) -> bool {
self.checked.get()
}
#[allow(unrooted_must_root)]
#[allow(unsafe_code)]
unsafe fn get_indeterminate_state_for_layout(&self) -> bool {
self.indeterminate.get()
}
#[allow(unrooted_must_root)]
#[allow(unsafe_code)]
unsafe fn get_size_for_layout(&self) -> u32 {
self.size.get()
}
}
impl HTMLInputElementMethods for HTMLInputElement {
// https://www.whatwg.org/html/#dom-fe-disabled
make_bool_getter!(Disabled);
// https://www.whatwg.org/html/#dom-fe-disabled
make_bool_setter!(SetDisabled, "disabled");
// https://html.spec.whatwg.org/multipage/#dom-input-defaultchecked
make_bool_getter!(DefaultChecked, "checked");
// https://html.spec.whatwg.org/multipage/#dom-input-defaultchecked
make_bool_setter!(SetDefaultChecked, "checked");
// https://html.spec.whatwg.org/multipage/#dom-input-checked
fn Checked(&self) -> bool {
self.checked.get()
}
// https://html.spec.whatwg.org/multipage/#dom-input-checked
fn SetChecked(&self, checked: bool) {
self.update_checked_state(checked, true);
}
// https://html.spec.whatwg.org/multipage/#dom-input-readonly
make_bool_getter!(ReadOnly);
// https://html.spec.whatwg.org/multipage/#dom-input-readonly
make_bool_setter!(SetReadOnly, "readonly");
// https://html.spec.whatwg.org/multipage/#dom-input-size
make_uint_getter!(Size, "size", DEFAULT_INPUT_SIZE);
make_limited_uint_setter!(SetSize, "size", DEFAULT_INPUT_SIZE);
// https://html.spec.whatwg.org/multipage/#dom-input-type
make_enumerated_getter!(Type, "text", ("hidden") | ("search") | ("tel") |
("url") | ("email") | ("password") |
("datetime") | ("date") | ("month") |
("week") | ("time") | ("datetime-local") |
("number") | ("range") | ("color") |
("checkbox") | ("radio") | ("file") |
("submit") | ("image") | ("reset") | ("button"));
// https://html.spec.whatwg.org/multipage/#dom-input-type
make_setter!(SetType, "type");
// https://html.spec.whatwg.org/multipage/#dom-input-value
fn Value(&self) -> DOMString {
self.textinput.borrow().get_content()
}
// https://html.spec.whatwg.org/multipage/#dom-input-value
fn SetValue(&self, value: DOMString) {
self.textinput.borrow_mut().set_content(value);
self.value_changed.set(true);
self.force_relayout();
}
// https://html.spec.whatwg.org/multipage/#dom-input-defaultvalue
make_getter!(DefaultValue, "value");
// https://html.spec.whatwg.org/multipage/#dom-input-defaultvalue
make_setter!(SetDefaultValue, "value");
// https://html.spec.whatwg.org/multipage/#attr-fe-name
make_getter!(Name);
// https://html.spec.whatwg.org/multipage/#attr-fe-name
make_setter!(SetName, "name");
// https://html.spec.whatwg.org/multipage/#attr-input-placeholder
make_getter!(Placeholder);
// https://html.spec.whatwg.org/multipage/#attr-input-placeholder
make_setter!(SetPlaceholder, "placeholder");
// https://html.spec.whatwg.org/multipage/#dom-input-formaction
make_url_or_base_getter!(FormAction);
// https://html.spec.whatwg.org/multipage/#dom-input-formaction
make_setter!(SetFormAction, "formaction");
// https://html.spec.whatwg.org/multipage/#dom-input-formenctype
make_enumerated_getter!(
FormEnctype, "application/x-www-form-urlencoded", ("text/plain") | ("multipart/form-data"));
// https://html.spec.whatwg.org/multipage/#dom-input-formenctype
make_setter!(SetFormEnctype, "formenctype");
// https://html.spec.whatwg.org/multipage/#dom-input-formmethod
make_enumerated_getter!(FormMethod, "get", ("post") | ("dialog"));
// https://html.spec.whatwg.org/multipage/#dom-input-formmethod
make_setter!(SetFormMethod, "formmethod");
// https://html.spec.whatwg.org/multipage/#dom-input-formtarget
make_getter!(FormTarget);
// https://html.spec.whatwg.org/multipage/#dom-input-formtarget
make_setter!(SetFormTarget, "formtarget");
// https://html.spec.whatwg.org/multipage/#dom-input-indeterminate
fn Indeterminate(&self) -> bool {
self.indeterminate.get()
}
// https://html.spec.whatwg.org/multipage/#dom-input-indeterminate
fn SetIndeterminate(&self, val: bool) {
self.indeterminate.set(val)
}
}
#[allow(unsafe_code)]
fn broadcast_radio_checked(broadcaster: &HTMLInputElement, group: Option<&str>) {
//TODO: if not in document, use root ancestor instead of document
let owner = broadcaster.form_owner();
let doc = document_from_node(broadcaster);
let doc_node = NodeCast::from_ref(doc.r());
// This function is a workaround for lifetime constraint difficulties.
fn do_broadcast(doc_node: &Node, broadcaster: &HTMLInputElement,
owner: Option<&HTMLFormElement>, group: Option<&str>) {
// There is no DOM tree manipulation here, so this is safe
let iter = unsafe {
doc_node.query_selector_iter("input[type=radio]".to_owned()).unwrap()
.filter_map(HTMLInputElementCast::to_root)
.filter(|r| in_same_group(r.r(), owner, group) && broadcaster != r.r())
};
for ref r in iter {
if r.r().Checked() {
r.r().SetChecked(false);
}
}
}
do_broadcast(doc_node, broadcaster, owner.r(), group)
}
fn in_same_group<'a,'b>(other: &'a HTMLInputElement,
owner: Option<&'b HTMLFormElement>,
group: Option<&str>) -> bool {
let other_owner = other.form_owner();
let other_owner = other_owner.r();
other.input_type.get() == InputType::InputRadio &&
// TODO Both a and b are in the same home subtree.
other_owner == owner &&
// TODO should be a unicode compatibility caseless match
match (other.get_radio_group_name(), group) {
(Some(ref s1), Some(s2)) => &**s1 == s2,
(None, None) => true,
_ => false
}
}
impl HTMLInputElement {
pub fn force_relayout(&self) {
let doc = document_from_node(self);
let node = NodeCast::from_ref(self);
doc.r().content_changed(node, NodeDamage::OtherNodeDamage)
}
pub fn radio_group_updated(&self, group: Option<&str>) {
if self.Checked() {
broadcast_radio_checked(self, group);
}
}
pub fn get_radio_group_name(&self) -> Option<String> {
//TODO: determine form owner
let elem = ElementCast::from_ref(self);
elem.get_attribute(&ns!(""), &atom!("name"))
.map(|name| name.r().Value())
}
pub fn update_checked_state(&self, checked: bool, dirty: bool) {
self.checked.set(checked);
if dirty {
self.checked_changed.set(true);
}
if self.input_type.get() == InputType::InputRadio && checked {
broadcast_radio_checked(self,
self.get_radio_group_name()
.as_ref()
.map(|group| &**group));
}
self.force_relayout();
//TODO: dispatch change event
}
pub fn get_size(&self) -> u32 {
self.size.get()
}
pub fn get_indeterminate_state(&self) -> bool {
self.indeterminate.get()
}
// https://html.spec.whatwg.org/multipage/#concept-fe-mutable
pub fn mutable(&self) -> bool {
// https://html.spec.whatwg.org/multipage/#the-input-element:concept-fe-mutable
// https://html.spec.whatwg.org/multipage/#the-readonly-attribute:concept-fe-mutable
let node = NodeCast::from_ref(self);
!(node.get_disabled_state() || self.ReadOnly())
}
// https://html.spec.whatwg.org/multipage/#the-input-element:concept-form-reset-control
pub fn reset(&self) {
match self.input_type.get() {
InputType::InputRadio | InputType::InputCheckbox => {
self.update_checked_state(self.DefaultChecked(), false);
self.checked_changed.set(false);
},
InputType::InputImage => (),
_ => ()
}
self.SetValue(self.DefaultValue());
self.value_changed.set(false);
self.force_relayout();
}
}
impl VirtualMethods for HTMLInputElement {
fn super_type<'b>(&'b self) -> Option<&'b VirtualMethods> {
let htmlelement: &HTMLElement = HTMLElementCast::from_ref(self);
Some(htmlelement as &VirtualMethods)
}
fn after_set_attr(&self, attr: &Attr) {
if let Some(ref s) = self.super_type() {
s.after_set_attr(attr);
}
match attr.local_name() {
&atom!("disabled") => {
let node = NodeCast::from_ref(self);
node.set_disabled_state(true);
node.set_enabled_state(false);
}<|fim▁hole|> &atom!("checked") => {
// https://html.spec.whatwg.org/multipage/#the-input-element:concept-input-checked-dirty
if !self.checked_changed.get() {
self.update_checked_state(true, false);
}
}
&atom!("size") => {
match *attr.value() {
AttrValue::UInt(_, value) => self.size.set(value),
_ => panic!("Expected an AttrValue::UInt"),
}
}
&atom!("type") => {
let value = attr.value();
self.input_type.set(match &**value {
"button" => InputType::InputButton,
"submit" => InputType::InputSubmit,
"reset" => InputType::InputReset,
"file" => InputType::InputFile,
"radio" => InputType::InputRadio,
"checkbox" => InputType::InputCheckbox,
"password" => InputType::InputPassword,
_ => InputType::InputText,
});
if self.input_type.get() == InputType::InputRadio {
self.radio_group_updated(self.get_radio_group_name()
.as_ref()
.map(|group| &**group));
}
}
&atom!("value") => {
if !self.value_changed.get() {
self.textinput.borrow_mut().set_content((**attr.value()).to_owned());
}
}
&atom!("name") => {
if self.input_type.get() == InputType::InputRadio {
let value = attr.value();
self.radio_group_updated(Some(&value));
}
}
_ if attr.local_name() == &Atom::from_slice("placeholder") => {
let value = attr.value();
let stripped = value.chars()
.filter(|&c| c != '\n' && c != '\r')
.collect::<String>();
*self.placeholder.borrow_mut() = stripped;
}
_ => ()
}
}
fn before_remove_attr(&self, attr: &Attr) {
if let Some(ref s) = self.super_type() {
s.before_remove_attr(attr);
}
match attr.local_name() {
&atom!("disabled") => {
let node = NodeCast::from_ref(self);
node.set_disabled_state(false);
node.set_enabled_state(true);
node.check_ancestors_disabled_state_for_form_control();
}
&atom!("checked") => {
// https://html.spec.whatwg.org/multipage/#the-input-element:concept-input-checked-dirty
if !self.checked_changed.get() {
self.update_checked_state(false, false);
}
}
&atom!("size") => {
self.size.set(DEFAULT_INPUT_SIZE);
}
&atom!("type") => {
if self.input_type.get() == InputType::InputRadio {
broadcast_radio_checked(self,
self.get_radio_group_name()
.as_ref()
.map(|group| &**group));
}
self.input_type.set(InputType::InputText);
}
&atom!("value") => {
if !self.value_changed.get() {
self.textinput.borrow_mut().set_content("".to_owned());
}
}
&atom!("name") => {
if self.input_type.get() == InputType::InputRadio {
self.radio_group_updated(None);
}
}
_ if attr.local_name() == &Atom::from_slice("placeholder") => {
self.placeholder.borrow_mut().clear();
}
_ => ()
}
}
fn parse_plain_attribute(&self, name: &Atom, value: DOMString) -> AttrValue {
match name {
&atom!("size") => AttrValue::from_limited_u32(value, DEFAULT_INPUT_SIZE),
_ => self.super_type().unwrap().parse_plain_attribute(name, value),
}
}
fn bind_to_tree(&self, tree_in_doc: bool) {
if let Some(ref s) = self.super_type() {
s.bind_to_tree(tree_in_doc);
}
let node = NodeCast::from_ref(self);
node.check_ancestors_disabled_state_for_form_control();
}
fn unbind_from_tree(&self, tree_in_doc: bool) {
if let Some(ref s) = self.super_type() {
s.unbind_from_tree(tree_in_doc);
}
let node = NodeCast::from_ref(self);
if node.ancestors().any(|ancestor| ancestor.r().is_htmlfieldsetelement()) {
node.check_ancestors_disabled_state_for_form_control();
} else {
node.check_disabled_attribute();
}
}
fn handle_event(&self, event: &Event) {
if let Some(s) = self.super_type() {
s.handle_event(event);
}
if &*event.Type() == "click" && !event.DefaultPrevented() {
match self.input_type.get() {
InputType::InputRadio => self.update_checked_state(true, true),
_ => {}
}
// TODO: Dispatch events for non activatable inputs
// https://html.spec.whatwg.org/multipage/#common-input-element-events
//TODO: set the editing position for text inputs
let doc = document_from_node(self);
doc.r().request_focus(ElementCast::from_ref(self));
} else if &*event.Type() == "keydown" && !event.DefaultPrevented() &&
(self.input_type.get() == InputType::InputText ||
self.input_type.get() == InputType::InputPassword) {
let keyevent: Option<&KeyboardEvent> = KeyboardEventCast::to_ref(event);
keyevent.map(|keyevent| {
// This can't be inlined, as holding on to textinput.borrow_mut()
// during self.implicit_submission will cause a panic.
let action = self.textinput.borrow_mut().handle_keydown(keyevent);
match action {
TriggerDefaultAction => {
self.implicit_submission(keyevent.CtrlKey(),
keyevent.ShiftKey(),
keyevent.AltKey(),
keyevent.MetaKey());
},
DispatchInput => {
self.value_changed.set(true);
self.force_relayout();
event.PreventDefault();
}
Nothing => (),
}
});
}
}
}
impl<'a> FormControl<'a> for &'a HTMLInputElement {
fn to_element(self) -> &'a Element {
ElementCast::from_ref(self)
}
}
impl Activatable for HTMLInputElement {
fn as_element<'b>(&'b self) -> &'b Element {
ElementCast::from_ref(self)
}
fn is_instance_activatable(&self) -> bool {
match self.input_type.get() {
// https://html.spec.whatwg.org/multipage/#submit-button-state-%28type=submit%29:activation-behaviour-2
// https://html.spec.whatwg.org/multipage/#reset-button-state-%28type=reset%29:activation-behaviour-2
// https://html.spec.whatwg.org/multipage/#checkbox-state-%28type=checkbox%29:activation-behaviour-2
// https://html.spec.whatwg.org/multipage/#radio-button-state-%28type=radio%29:activation-behaviour-2
InputType::InputSubmit | InputType::InputReset
| InputType::InputCheckbox | InputType::InputRadio => self.mutable(),
_ => false
}
}
// https://html.spec.whatwg.org/multipage/#run-pre-click-activation-steps
#[allow(unsafe_code)]
fn pre_click_activation(&self) {
let mut cache = self.activation_state.borrow_mut();
let ty = self.input_type.get();
cache.old_type = ty;
cache.was_mutable = self.mutable();
if cache.was_mutable {
match ty {
// https://html.spec.whatwg.org/multipage/#submit-button-state-(type=submit):activation-behavior
// InputType::InputSubmit => (), // No behavior defined
// https://html.spec.whatwg.org/multipage/#reset-button-state-(type=reset):activation-behavior
// InputType::InputSubmit => (), // No behavior defined
InputType::InputCheckbox => {
/*
https://html.spec.whatwg.org/multipage/#checkbox-state-(type=checkbox):pre-click-activation-steps
cache current values of `checked` and `indeterminate`
we may need to restore them later
*/
cache.indeterminate = self.Indeterminate();
cache.checked = self.Checked();
cache.checked_changed = self.checked_changed.get();
self.SetIndeterminate(false);
self.SetChecked(!cache.checked);
},
// https://html.spec.whatwg.org/multipage/#radio-button-state-(type=radio):pre-click-activation-steps
InputType::InputRadio => {
//TODO: if not in document, use root ancestor instead of document
let owner = self.form_owner();
let doc = document_from_node(self);
let doc_node = NodeCast::from_ref(doc.r());
let group = self.get_radio_group_name();;
// Safe since we only manipulate the DOM tree after finding an element
let checked_member = unsafe {
doc_node.query_selector_iter("input[type=radio]".to_owned()).unwrap()
.filter_map(HTMLInputElementCast::to_root)
.find(|r| {
in_same_group(r.r(), owner.r(), group.as_ref().map(|gr| &**gr)) &&
r.r().Checked()
})
};
cache.checked_radio = checked_member.r().map(JS::from_ref);
cache.checked_changed = self.checked_changed.get();
self.SetChecked(true);
}
_ => ()
}
}
}
// https://html.spec.whatwg.org/multipage/#run-canceled-activation-steps
fn canceled_activation(&self) {
let cache = self.activation_state.borrow();
let ty = self.input_type.get();
if cache.old_type != ty {
// Type changed, abandon ship
// https://www.w3.org/Bugs/Public/show_bug.cgi?id=27414
return;
}
match ty {
// https://html.spec.whatwg.org/multipage/#submit-button-state-(type=submit):activation-behavior
// InputType::InputSubmit => (), // No behavior defined
// https://html.spec.whatwg.org/multipage/#reset-button-state-(type=reset):activation-behavior
// InputType::InputReset => (), // No behavior defined
// https://html.spec.whatwg.org/multipage/#checkbox-state-(type=checkbox):canceled-activation-steps
InputType::InputCheckbox => {
// We want to restore state only if the element had been changed in the first place
if cache.was_mutable {
self.SetIndeterminate(cache.indeterminate);
self.SetChecked(cache.checked);
self.checked_changed.set(cache.checked_changed);
}
},
// https://html.spec.whatwg.org/multipage/#radio-button-state-(type=radio):canceled-activation-steps
InputType::InputRadio => {
// We want to restore state only if the element had been changed in the first place
if cache.was_mutable {
let old_checked: Option<Root<HTMLInputElement>> = cache.checked_radio.map(|t| t.root());
let name = self.get_radio_group_name();
match old_checked {
Some(ref o) => {
// Avoiding iterating through the whole tree here, instead
// we can check if the conditions for radio group siblings apply
if name == o.r().get_radio_group_name() && // TODO should be compatibility caseless
self.form_owner() == o.r().form_owner() &&
// TODO Both a and b are in the same home subtree
o.r().input_type.get() == InputType::InputRadio {
o.r().SetChecked(true);
} else {
self.SetChecked(false);
}
},
None => self.SetChecked(false)
};
self.checked_changed.set(cache.checked_changed);
}
}
_ => ()
}
}
// https://html.spec.whatwg.org/multipage/#run-post-click-activation-steps
fn activation_behavior(&self, _event: &Event, _target: &EventTarget) {
let ty = self.input_type.get();
if self.activation_state.borrow().old_type != ty {
// Type changed, abandon ship
// https://www.w3.org/Bugs/Public/show_bug.cgi?id=27414
return;
}
match ty {
InputType::InputSubmit => {
// https://html.spec.whatwg.org/multipage/#submit-button-state-(type=submit):activation-behavior
// FIXME (Manishearth): support document owners (needs ability to get parent browsing context)
if self.mutable() /* and document owner is fully active */ {
self.form_owner().map(|o| {
o.r().submit(SubmittedFrom::NotFromFormSubmitMethod,
FormSubmitter::InputElement(self.clone()))
});
}
},
InputType::InputReset => {
// https://html.spec.whatwg.org/multipage/#reset-button-state-(type=reset):activation-behavior
// FIXME (Manishearth): support document owners (needs ability to get parent browsing context)
if self.mutable() /* and document owner is fully active */ {
self.form_owner().map(|o| {
o.r().reset(ResetFrom::NotFromFormResetMethod)
});
}
},
InputType::InputCheckbox | InputType::InputRadio => {
// https://html.spec.whatwg.org/multipage/#checkbox-state-(type=checkbox):activation-behavior
// https://html.spec.whatwg.org/multipage/#radio-button-state-(type=radio):activation-behavior
if self.mutable() {
let win = window_from_node(self);
let event = Event::new(GlobalRef::Window(win.r()),
"input".to_owned(),
EventBubbles::Bubbles,
EventCancelable::NotCancelable);
let target = EventTargetCast::from_ref(self);
event.r().fire(target);
let event = Event::new(GlobalRef::Window(win.r()),
"change".to_owned(),
EventBubbles::Bubbles,
EventCancelable::NotCancelable);
let target = EventTargetCast::from_ref(self);
event.r().fire(target);
}
},
_ => ()
}
}
// https://html.spec.whatwg.org/multipage/#implicit-submission
#[allow(unsafe_code)]
fn implicit_submission(&self, ctrlKey: bool, shiftKey: bool, altKey: bool, metaKey: bool) {
let doc = document_from_node(self);
let node = NodeCast::from_ref(doc.r());
let owner = self.form_owner();
let form = match owner {
None => return,
Some(ref f) => f
};
let elem = ElementCast::from_ref(self);
if elem.click_in_progress() {
return;
}
// This is safe because we are stopping after finding the first element
// and only then performing actions which may modify the DOM tree
let submit_button;
unsafe {
submit_button = node.query_selector_iter("input[type=submit]".to_owned()).unwrap()
.filter_map(HTMLInputElementCast::to_root)
.find(|r| r.r().form_owner() == owner);
}
match submit_button {
Some(ref button) => {
if button.r().is_instance_activatable() {
button.r().synthetic_click_activation(ctrlKey, shiftKey, altKey, metaKey)
}
}
None => {
unsafe {
// Safe because we don't perform any DOM modification
// until we're done with the iterator.
let inputs = node.query_selector_iter("input".to_owned()).unwrap()
.filter_map(HTMLInputElementCast::to_root)
.filter(|input| {
input.r().form_owner() == owner && match &*input.r().Type() {
"text" | "search" | "url" | "tel" |
"email" | "password" | "datetime" |
"date" | "month" | "week" | "time" |
"datetime-local" | "number"
=> true,
_ => false
}
});
if inputs.skip(1).next().is_some() {
// lazily test for > 1 submission-blocking inputs
return;
}
}
form.r().submit(SubmittedFrom::NotFromFormSubmitMethod,
FormSubmitter::FormElement(form.r()));
}
}
}
}<|fim▁end|>
| |
<|file_name|>checkbutton.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python
# example checkbutton.py
import pygtk
pygtk.require('2.0')
import gtk
<|fim▁hole|>class CheckButton:
# Our callback.
# The data passed to this method is printed to stdout
def callback(self, widget, data=None):
print "%s was toggled %s" % (data, ("OFF", "ON")[widget.get_active()])
# This callback quits the program
def delete_event(self, widget, event, data=None):
gtk.main_quit()
return False
def __init__(self):
# Create a new window
self.window = gtk.Window(gtk.WINDOW_TOPLEVEL)
# Set the window title
self.window.set_title("Check Button")
# Set a handler for delete_event that immediately
# exits GTK.
self.window.connect("delete_event", self.delete_event)
# Sets the border width of the window.
self.window.set_border_width(20)
# Create a vertical box
vbox = gtk.VBox(True, 2)
# Put the vbox in the main window
self.window.add(vbox)
# Create first button
button = gtk.CheckButton("check button 1")
# When the button is toggled, we call the "callback" method
# with a pointer to "button" as its argument
button.connect("toggled", self.callback, "check button 1")
# Insert button 1
vbox.pack_start(button, True, True, 2)
button.show()
# Create second button
button = gtk.CheckButton("check button 2")
# When the button is toggled, we call the "callback" method
# with a pointer to "button 2" as its argument
button.connect("toggled", self.callback, "check button 2")
# Insert button 2
vbox.pack_start(button, True, True, 2)
button.show()
# Create "Quit" button
button = gtk.Button("Quit")
# When the button is clicked, we call the mainquit function
# and the program exits
button.connect("clicked", lambda wid: gtk.main_quit())
# Insert the quit button
vbox.pack_start(button, True, True, 2)
button.show()
vbox.show()
self.window.show()
def main():
gtk.main()
return 0
if __name__ == "__main__":
CheckButton()
main()<|fim▁end|>
| |
<|file_name|>conf.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python3
# -*- coding: utf-8 -*-
#
# uzmq documentation build configuration file, created by
# sphinx-quickstart on Wed Nov 7 00:32:37 2012.
#
# This file is execfile()d with the current directory set to its containing dir.
#
# Note that not all possible configuration values are present in this
# autogenerated file.
#
# All configuration values have a default; values that are commented out
# serve to show the default.
import sys, os
import sys
class Mock(object):
def __init__(self, *args, **kwargs):
pass
def __call__(self, *args, **kwargs):
return Mock()
@classmethod
def __getattr__(cls, name):
if name in ('__file__', '__path__'):
return '/dev/null'
elif name[0] == name[0].upper():
mockType = type(name, (), {})
mockType.__module__ = __name__
return mockType
else:
return Mock()
MOCK_MODULES = ['zmq']
for mod_name in MOCK_MODULES:
sys.modules[mod_name] = Mock()
on_rtd = os.environ.get('READTHEDOCS', None) == 'True'
skip_coverage = os.environ.get('SKIP_COVERAGE', None) == 'True'
if on_rtd:
for mod_name in MOCK_MODULES:
sys.modules[mod_name] = Mock()
CURDIR = os.path.abspath(os.path.dirname(__file__))
sys.path.append(os.path.join(CURDIR, '..', '..'))
sys.path.append(os.path.join(CURDIR, '..'))
sys.path.append(os.path.join(CURDIR, '.'))
import uzmq
# If extensions (or modules to document with autodoc) are in another directory,<|fim▁hole|>
# -- General configuration -----------------------------------------------------
# If your documentation needs a minimal Sphinx version, state it here.
#needs_sphinx = '1.0'
# Add any Sphinx extension module names here, as strings. They can be extensions
# coming with Sphinx (named 'sphinx.ext.*') or your custom ones.
extensions = ['sphinx.ext.autodoc', 'sphinx.ext.viewcode']
# Add any paths that contain templates here, relative to this directory.
templates_path = ['_templates']
# The suffix of source filenames.
source_suffix = '.rst'
# The encoding of source files.
#source_encoding = 'utf-8-sig'
# The master toctree document.
master_doc = 'index'
# General information about the project.
project = 'uzmq'
copyright = '2012, Author'
# The version info for the project you're documenting, acts as replacement for
# |version| and |release|, also used in various other places throughout the
# built documents.
#
# The short X.Y version.
version = "%s.%s" % (uzmq.version_info[0], uzmq.version_info[1])
# The full version, including alpha/beta/rc tags.
release = ''
# The language for content autogenerated by Sphinx. Refer to documentation
# for a list of supported languages.
#language = None
# There are two options for replacing |today|: either, you set today to some
# non-false value, then it is used:
#today = ''
# Else, today_fmt is used as the format for a strftime call.
#today_fmt = '%B %d, %Y'
# List of patterns, relative to source directory, that match files and
# directories to ignore when looking for source files.
exclude_patterns = ['_build']
# The reST default role (used for this markup: `text`) to use for all documents.
#default_role = None
# If true, '()' will be appended to :func: etc. cross-reference text.
#add_function_parentheses = True
# If true, the current module name will be prepended to all description
# unit titles (such as .. function::).
#add_module_names = True
# If true, sectionauthor and moduleauthor directives will be shown in the
# output. They are ignored by default.
#show_authors = False
# The name of the Pygments (syntax highlighting) style to use.
pygments_style = 'sphinx'
# A list of ignored prefixes for module index sorting.
#modindex_common_prefix = []
# -- Options for HTML output ---------------------------------------------------
# The theme to use for HTML and HTML Help pages. See the documentation for
# a list of builtin themes.
html_theme = 'default'
# Theme options are theme-specific and customize the look and feel of a theme
# further. For a list of options available for each theme, see the
# documentation.
#html_theme_options = {}
# Add any paths that contain custom themes here, relative to this directory.
#html_theme_path = []
# The name for this set of Sphinx documents. If None, it defaults to
# "<project> v<release> documentation".
#html_title = None
# A shorter title for the navigation bar. Default is the same as html_title.
#html_short_title = None
# The name of an image file (relative to this directory) to place at the top
# of the sidebar.
#html_logo = None
# The name of an image file (within the static path) to use as favicon of the
# docs. This file should be a Windows icon file (.ico) being 16x16 or 32x32
# pixels large.
#html_favicon = None
# Add any paths that contain custom static files (such as style sheets) here,
# relative to this directory. They are copied after the builtin static files,
# so a file named "default.css" will overwrite the builtin "default.css".
html_static_path = ['_static']
# If not '', a 'Last updated on:' timestamp is inserted at every page bottom,
# using the given strftime format.
#html_last_updated_fmt = '%b %d, %Y'
# If true, SmartyPants will be used to convert quotes and dashes to
# typographically correct entities.
#html_use_smartypants = True
# Custom sidebar templates, maps document names to template names.
#html_sidebars = {}
# Additional templates that should be rendered to pages, maps page names to
# template names.
#html_additional_pages = {}
# If false, no module index is generated.
#html_domain_indices = True
# If false, no index is generated.
#html_use_index = True
# If true, the index is split into individual pages for each letter.
#html_split_index = False
# If true, links to the reST sources are added to the pages.
#html_show_sourcelink = True
# If true, "Created using Sphinx" is shown in the HTML footer. Default is True.
#html_show_sphinx = True
# If true, "(C) Copyright ..." is shown in the HTML footer. Default is True.
#html_show_copyright = True
# If true, an OpenSearch description file will be output, and all pages will
# contain a <link> tag referring to it. The value of this option must be the
# base URL from which the finished HTML is served.
#html_use_opensearch = ''
# This is the file name suffix for HTML files (e.g. ".xhtml").
#html_file_suffix = None
# Output file base name for HTML help builder.
htmlhelp_basename = 'uzmqdoc'
# -- Options for LaTeX output --------------------------------------------------
latex_elements = {
# The paper size ('letterpaper' or 'a4paper').
#'papersize': 'letterpaper',
# The font size ('10pt', '11pt' or '12pt').
#'pointsize': '10pt',
# Additional stuff for the LaTeX preamble.
#'preamble': '',
}
# Grouping the document tree into LaTeX files. List of tuples
# (source start file, target name, title, author, documentclass [howto/manual]).
latex_documents = [
('index', 'uzmq.tex', 'uzmq Documentation',
'Author', 'manual'),
]
# The name of an image file (relative to this directory) to place at the top of
# the title page.
#latex_logo = None
# For "manual" documents, if this is true, then toplevel headings are parts,
# not chapters.
#latex_use_parts = False
# If true, show page references after internal links.
#latex_show_pagerefs = False
# If true, show URL addresses after external links.
#latex_show_urls = False
# Documents to append as an appendix to all manuals.
#latex_appendices = []
# If false, no module index is generated.
#latex_domain_indices = True
# -- Options for manual page output --------------------------------------------
# One entry per manual page. List of tuples
# (source start file, name, description, authors, manual section).
man_pages = [
('index', 'uzmq', 'uzmq Documentation',
['Author'], 1)
]
# If true, show URL addresses after external links.
#man_show_urls = False
# -- Options for Texinfo output ------------------------------------------------
# Grouping the document tree into Texinfo files. List of tuples
# (source start file, target name, title, author,
# dir menu entry, description, category)
texinfo_documents = [
('index', 'uzmq', 'uzmq Documentation',
'Author', 'uzmq', 'One line description of project.',
'Miscellaneous'),
]
# Documents to append as an appendix to all manuals.
#texinfo_appendices = []
# If false, no module index is generated.
#texinfo_domain_indices = True
# How to display URL addresses: 'footnote', 'no', or 'inline'.
#texinfo_show_urls = 'footnote'
# -- Options for Epub output ---------------------------------------------------
# Bibliographic Dublin Core info.
epub_title = 'uzmq'
epub_author = 'Author'
epub_publisher = 'Author'
epub_copyright = '2012, Author'
# The language of the text. It defaults to the language option
# or en if the language is not set.
#epub_language = ''
# The scheme of the identifier. Typical schemes are ISBN or URL.
#epub_scheme = ''
# The unique identifier of the text. This can be a ISBN number
# or the project homepage.
#epub_identifier = ''
# A unique identification for the text.
#epub_uid = ''
# A tuple containing the cover image and cover page html template filenames.
#epub_cover = ()
# HTML files that should be inserted before the pages created by sphinx.
# The format is a list of tuples containing the path and title.
#epub_pre_files = []
# HTML files shat should be inserted after the pages created by sphinx.
# The format is a list of tuples containing the path and title.
#epub_post_files = []
# A list of files that should not be packed into the epub file.
#epub_exclude_files = []
# The depth of the table of contents in toc.ncx.
#epub_tocdepth = 3
# Allow duplicate toc entries.
#epub_tocdup = True<|fim▁end|>
|
# add these directories to sys.path here. If the directory is relative to the
# documentation root, use os.path.abspath to make it absolute, like shown here.
#sys.path.insert(0, os.path.abspath('.'))
|
<|file_name|>bloomierHasher.cpp<|end_file_name|><|fim▁begin|>#include <iostream>
#include <locale>
#include <sstream>
#include "hash.h"<|fim▁hole|>using namespace std;
namespace bloomier
{
void BloomierHasher::getNeighborhood(string key, unsigned char result[])
{
Hash::getHash(key, hashSeed, m, k, result);
// for (int i = 0; i < k; i++)
// {
// cout << result[i] << endl;
// }
}
void BloomierHasher::getM(string key, unsigned char array[], int byteSize)
{
locale loc;
const collate<char>& coll = use_facet<collate<char> >(loc);
int seed = coll.hash(key.data(),key.data()+key.length());
srand (seed);
for (int i = 0; i < byteSize; i++)
array[i] = rand() % 255;
}
}<|fim▁end|>
|
#include "bloomierHasher.h"
|
<|file_name|>tree_sortable.rs<|end_file_name|><|fim▁begin|>// This file was generated by gir (5c017c9) from gir-files (71d73f0)
// DO NOT EDIT
use TreeModel;
use ffi;
use glib;
use glib::object::Downcast;
use glib::object::IsA;
use glib::signal::connect;
use glib::translate::*;
use glib_ffi;
use std::boxed::Box as Box_;
use std::mem::transmute;
glib_wrapper! {
pub struct TreeSortable(Object<ffi::GtkTreeSortable>): TreeModel;
match fn {
get_type => || ffi::gtk_tree_sortable_get_type(),
}
}
pub trait TreeSortableExt {
fn has_default_sort_func(&self) -> bool;
//fn set_default_sort_func<'a, P: Into<Option</*Unimplemented*/Fundamental: Pointer>>, Q: Into<Option<&'a /*Ignored*/glib::DestroyNotify>>>(&self, sort_func: /*Unknown conversion*//*Unimplemented*/TreeIterCompareFunc, user_data: P, destroy: Q);
//fn set_sort_func<'a, P: Into<Option</*Unimplemented*/Fundamental: Pointer>>, Q: Into<Option<&'a /*Ignored*/glib::DestroyNotify>>>(&self, sort_column_id: i32, sort_func: /*Unknown conversion*//*Unimplemented*/TreeIterCompareFunc, user_data: P, destroy: Q);
fn sort_column_changed(&self);
fn connect_sort_column_changed<F: Fn(&Self) + 'static>(&self, f: F) -> u64;
}
impl<O: IsA<TreeSortable> + IsA<glib::object::Object>> TreeSortableExt for O {
fn has_default_sort_func(&self) -> bool {
unsafe {
from_glib(ffi::gtk_tree_sortable_has_default_sort_func(self.to_glib_none().0))
}
}
//fn set_default_sort_func<'a, P: Into<Option</*Unimplemented*/Fundamental: Pointer>>, Q: Into<Option<&'a /*Ignored*/glib::DestroyNotify>>>(&self, sort_func: /*Unknown conversion*//*Unimplemented*/TreeIterCompareFunc, user_data: P, destroy: Q) {
// unsafe { TODO: call ffi::gtk_tree_sortable_set_default_sort_func() }
//}
//fn set_sort_func<'a, P: Into<Option</*Unimplemented*/Fundamental: Pointer>>, Q: Into<Option<&'a /*Ignored*/glib::DestroyNotify>>>(&self, sort_column_id: i32, sort_func: /*Unknown conversion*//*Unimplemented*/TreeIterCompareFunc, user_data: P, destroy: Q) {
// unsafe { TODO: call ffi::gtk_tree_sortable_set_sort_func() }
//}
fn sort_column_changed(&self) {
unsafe {
ffi::gtk_tree_sortable_sort_column_changed(self.to_glib_none().0);
}
}
fn connect_sort_column_changed<F: Fn(&Self) + 'static>(&self, f: F) -> u64 {
unsafe {<|fim▁hole|> }
}
}
unsafe extern "C" fn sort_column_changed_trampoline<P>(this: *mut ffi::GtkTreeSortable, f: glib_ffi::gpointer)
where P: IsA<TreeSortable> {
callback_guard!();
let f: &Box_<Fn(&P) + 'static> = transmute(f);
f(&TreeSortable::from_glib_none(this).downcast_unchecked())
}<|fim▁end|>
|
let f: Box_<Box_<Fn(&Self) + 'static>> = Box_::new(Box_::new(f));
connect(self.to_glib_none().0, "sort-column-changed",
transmute(sort_column_changed_trampoline::<Self> as usize), Box_::into_raw(f) as *mut _)
|
<|file_name|>Options.java<|end_file_name|><|fim▁begin|>package edu.stanford.nlp.parser.lexparser;
import edu.stanford.nlp.trees.CompositeTreeTransformer;
import edu.stanford.nlp.trees.TreebankLanguagePack;
import edu.stanford.nlp.trees.TreeTransformer;
import edu.stanford.nlp.util.Function;
import edu.stanford.nlp.util.ReflectionLoading;
import edu.stanford.nlp.util.StringUtils;
import java.io.*;
import java.util.*;
import org.apache.log4j.Logger;
/**
* This class contains options to the parser which MUST be the SAME at
* both training and testing (parsing) time in order for the parser to
* work properly. It also contains an object which stores the options
* used by the parser at training time and an object which contains
* default options for test use.
*
* @author Dan Klein
* @author Christopher Manning
* @author John Bauer
*/
public class Options implements Serializable {
protected static Logger logger = Logger.getRootLogger();
public Options() {
this(new EnglishTreebankParserParams());
}
public Options(TreebankLangParserParams tlpParams) {
this.tlpParams = tlpParams;
}
/**
* Set options based on a String array in the style of
* commandline flags. This method goes through the array until it ends,
* processing options, as for {@link #setOption}.
*
* @param flags Array of options (or as a varargs list of arguments).
* The options passed in should
* be specified like command-line arguments, including with an initial
* minus sign for example,
* {"-outputFormat", "typedDependencies", "-maxLength", "70"}
* @throws IllegalArgumentException If an unknown flag is passed in
*/
public void setOptions(String... flags) {
setOptions(flags, 0, flags.length);
}
/**
* Set options based on a String array in the style of
* commandline flags. This method goes through the array until it ends,
* processing options, as for {@link #setOption}.
*
* @param flags Array of options. The options passed in should
* be specified like command-line arguments, including with an initial
* minus sign for example,
* {"-outputFormat", "typedDependencies", "-maxLength", "70"}
* @param startIndex The index in the array to begin processing options at
* @param endIndexPlusOne A number one greater than the last array index at
* which options should be processed
* @throws IllegalArgumentException If an unknown flag is passed in
*/
public void setOptions(final String[] flags, final int startIndex, final int endIndexPlusOne) {
for (int i = startIndex; i < endIndexPlusOne;) {
i = setOption(flags, i);
}
}
/**
* Set options based on a String array in the style of
* commandline flags. This method goes through the array until it ends,
* processing options, as for {@link #setOption}.
*
* @param flags Array of options (or as a varargs list of arguments).
* The options passed in should
* be specified like command-line arguments, including with an initial
* minus sign for example,
* {"-outputFormat", "typedDependencies", "-maxLength", "70"}
* @throws IllegalArgumentException If an unknown flag is passed in
*/
public void setOptionsOrWarn(String... flags) {
setOptionsOrWarn(flags, 0, flags.length);
}
/**
* Set options based on a String array in the style of
* commandline flags. This method goes through the array until it ends,
* processing options, as for {@link #setOption}.
*
* @param flags Array of options. The options passed in should
* be specified like command-line arguments, including with an initial
* minus sign for example,
* {"-outputFormat", "typedDependencies", "-maxLength", "70"}
* @param startIndex The index in the array to begin processing options at
* @param endIndexPlusOne A number one greater than the last array index at
* which options should be processed
* @throws IllegalArgumentException If an unknown flag is passed in
*/
public void setOptionsOrWarn(final String[] flags, final int startIndex, final int endIndexPlusOne) {
for (int i = startIndex; i < endIndexPlusOne;) {
i = setOptionOrWarn(flags, i);
}
}
/**
* Set an option based on a String array in the style of
* commandline flags. The option may
* be either one known by the Options object, or one recognized by the
* TreebankLangParserParams which has already been set up inside the Options
* object, and then the option is set in the language-particular
* TreebankLangParserParams.
* Note that despite this method being an instance method, many flags
* are actually set as static class variables in the Train and Test
* classes (this should be fixed some day).
* Some options (there are many others; see the source code):
* <ul>
* <li> <code>-maxLength n</code> set the maximum length sentence to parse (inclusively)
* <li> <code>-printTT</code> print the training trees in raw, annotated, and annotated+binarized form. Useful for debugging and other miscellany.
* <li> <code>-printAnnotated filename</code> use only in conjunction with -printTT. Redirects printing of annotated training trees to <code>filename</code>.
* <li> <code>-forceTags</code> when the parser is tested against a set of gold standard trees, use the tagged yield, instead of just the yield, as input.
* </ul>
*
* @param flags An array of options arguments, command-line style. E.g. {"-maxLength", "50"}.
* @param i The index in flags to start at when processing an option
* @return The index in flags of the position after the last element used in
* processing this option. If the current array position cannot be processed as a valid
* option, then a warning message is printed to stderr and the return value is <code>i+1</code>
*/
public int setOptionOrWarn(String[] flags, int i) {
int j = setOptionFlag(flags, i);
if (j == i) {
j = tlpParams.setOptionFlag(flags, i);
}
if (j == i) {
System.err.println("WARNING! lexparser.Options: Unknown option ignored: " + flags[i]);
j++;
}
return j;
}
/**
* Set an option based on a String array in the style of
* commandline flags. The option may
* be either one known by the Options object, or one recognized by the
* TreebankLangParserParams which has already been set up inside the Options
* object, and then the option is set in the language-particular
* TreebankLangParserParams.
* Note that despite this method being an instance method, many flags
* are actually set as static class variables in the Train and Test
* classes (this should be fixed some day).
* Some options (there are many others; see the source code):
* <ul>
* <li> <code>-maxLength n</code> set the maximum length sentence to parse (inclusively)
* <li> <code>-printTT</code> print the training trees in raw, annotated, and annotated+binarized form. Useful for debugging and other miscellany.
* <li> <code>-printAnnotated filename</code> use only in conjunction with -printTT. Redirects printing of annotated training trees to <code>filename</code>.
* <li> <code>-forceTags</code> when the parser is tested against a set of gold standard trees, use the tagged yield, instead of just the yield, as input.
* </ul>
*
* @param flags An array of options arguments, command-line style. E.g. {"-maxLength", "50"}.
* @param i The index in flags to start at when processing an option
* @return The index in flags of the position after the last element used in
* processing this option.
* @throws IllegalArgumentException If the current array position cannot be
* processed as a valid option
*/
public int setOption(String[] flags, int i) {
int j = setOptionFlag(flags, i);
if (j == i) {
j = tlpParams.setOptionFlag(flags, i);
}
if (j == i) {
throw new IllegalArgumentException("Unknown option: " + flags[i]);
}
return j;
}
/**
* Set an option in this object, based on a String array in the style of
* commandline flags. The option is only processed with respect to
* options directly known by the Options object.
* Some options (there are many others; see the source code):
* <ul>
* <li> <code>-maxLength n</code> set the maximum length sentence to parse (inclusively)
* <li> <code>-printTT</code> print the training trees in raw, annotated, and annotated+binarized form. Useful for debugging and other miscellany.
* <li> <code>-printAnnotated filename</code> use only in conjunction with -printTT. Redirects printing of annotated training trees to <code>filename</code>.
* <li> <code>-forceTags</code> when the parser is tested against a set of gold standard trees, use the tagged yield, instead of just the yield, as input.
* </ul>
*
* @param args An array of options arguments, command-line style. E.g. {"-maxLength", "50"}.
* @param i The index in args to start at when processing an option
* @return The index in args of the position after the last element used in
* processing this option, or the value i unchanged if a valid option couldn't
* be processed starting at position i.
*/
private int setOptionFlag(String[] args, int i) {
if (args[i].equalsIgnoreCase("-PCFG")) {
doDep = false;
doPCFG = true;
i++;
} else if (args[i].equalsIgnoreCase("-dep")) {
doDep = true;
doPCFG = false;
i++;
} else if (args[i].equalsIgnoreCase("-factored")) {
doDep = true;
doPCFG = true;
testOptions.useFastFactored = false;
i++;
} else if (args[i].equalsIgnoreCase("-fastFactored")) {
doDep = true;
doPCFG = true;
testOptions.useFastFactored = true;
i++;
} else if (args[i].equalsIgnoreCase("-noRecoveryTagging")) {
testOptions.noRecoveryTagging = true;
i++;
} else if (args[i].equalsIgnoreCase("-useLexiconToScoreDependencyPwGt")) {
testOptions.useLexiconToScoreDependencyPwGt = true;
i++;
} else if (args[i].equalsIgnoreCase("-useSmoothTagProjection")) {
useSmoothTagProjection = true;
i++;
} else if (args[i].equalsIgnoreCase("-useUnigramWordSmoothing")) {
useUnigramWordSmoothing = true;
i++;
} else if (args[i].equalsIgnoreCase("-useNonProjectiveDependencyParser")) {
testOptions.useNonProjectiveDependencyParser = true;
i++;
} else if (args[i].equalsIgnoreCase("-maxLength") && (i + 1 < args.length)) {
testOptions.maxLength = Integer.parseInt(args[i + 1]);
i += 2;
} else if (args[i].equalsIgnoreCase("-MAX_ITEMS") && (i + 1 < args.length)) {
testOptions.MAX_ITEMS = Integer.parseInt(args[i + 1]);
i += 2;
} else if (args[i].equalsIgnoreCase("-trainLength") && (i + 1 < args.length)) {
// train on only short sentences
trainOptions.trainLengthLimit = Integer.parseInt(args[i + 1]);
i += 2;
} else if (args[i].equalsIgnoreCase("-lengthNormalization")) {
testOptions.lengthNormalization = true;
i++;
} else if (args[i].equalsIgnoreCase("-iterativeCKY")) {
testOptions.iterativeCKY = true;
i++;
} else if (args[i].equalsIgnoreCase("-vMarkov") && (i + 1 < args.length)) {
int order = Integer.parseInt(args[i + 1]);
if (order <= 1) {
trainOptions.PA = false;
trainOptions.gPA = false;
} else if (order == 2) {
trainOptions.PA = true;
trainOptions.gPA = false;
} else if (order >= 3) {
trainOptions.PA = true;
trainOptions.gPA = true;
}
i += 2;
} else if (args[i].equalsIgnoreCase("-vSelSplitCutOff") && (i + 1 < args.length)) {
trainOptions.selectiveSplitCutOff = Double.parseDouble(args[i + 1]);
trainOptions.selectiveSplit = trainOptions.selectiveSplitCutOff > 0.0;
i += 2;
} else if (args[i].equalsIgnoreCase("-vSelPostSplitCutOff") && (i + 1 < args.length)) {
trainOptions.selectivePostSplitCutOff = Double.parseDouble(args[i + 1]);
trainOptions.selectivePostSplit = trainOptions.selectivePostSplitCutOff > 0.0;
i += 2;
} else if (args[i].equalsIgnoreCase("-deleteSplitters") && (i+1 < args.length)) {
String[] toDel = args[i+1].split(" *, *");
trainOptions.deleteSplitters = new HashSet<String>(Arrays.asList(toDel));
i += 2;
} else if (args[i].equalsIgnoreCase("-postSplitWithBaseCategory")) {
trainOptions.postSplitWithBaseCategory = true;
i += 1;
} else if (args[i].equalsIgnoreCase("-vPostMarkov") && (i + 1 < args.length)) {
int order = Integer.parseInt(args[i + 1]);
if (order <= 1) {
trainOptions.postPA = false;
trainOptions.postGPA = false;
} else if (order == 2) {
trainOptions.postPA = true;
trainOptions.postGPA = false;
} else if (order >= 3) {
trainOptions.postPA = true;
trainOptions.postGPA = true;
}
i += 2;
} else if (args[i].equalsIgnoreCase("-hMarkov") && (i + 1 < args.length)) {
int order = Integer.parseInt(args[i + 1]);
if (order >= 0) {
trainOptions.markovOrder = order;
trainOptions.markovFactor = true;
} else {
trainOptions.markovFactor = false;
}
i += 2;
} else if (args[i].equalsIgnoreCase("-distanceBins") && (i + 1 < args.length)) {
int numBins = Integer.parseInt(args[i + 1]);
if (numBins <= 1) {
distance = false;
} else if (numBins == 4) {
distance = true;
coarseDistance = true;
} else if (numBins == 5) {
distance = true;
coarseDistance = false;
} else {
throw new IllegalArgumentException("Invalid value for -distanceBin: " + args[i+1]);
}
i += 2;
} else if (args[i].equalsIgnoreCase("-noStop")) {
genStop = false;
i++;
} else if (args[i].equalsIgnoreCase("-nonDirectional")) {
directional = false;
i++;
} else if (args[i].equalsIgnoreCase("-depWeight") && (i + 1 < args.length)) {
testOptions.depWeight = Double.parseDouble(args[i + 1]);
i += 2;
} else if (args[i].equalsIgnoreCase("-printPCFGkBest") && (i + 1 < args.length)) {
testOptions.printPCFGkBest = Integer.parseInt(args[i + 1]);
i += 2;
} else if (args[i].equalsIgnoreCase("-evalPCFGkBest") && (i + 1 < args.length)) {
testOptions.evalPCFGkBest = Integer.parseInt(args[i + 1]);
i += 2;
} else if (args[i].equalsIgnoreCase("-printFactoredKGood") && (i + 1 < args.length)) {
testOptions.printFactoredKGood = Integer.parseInt(args[i + 1]);
i += 2;
} else if (args[i].equalsIgnoreCase("-smoothTagsThresh") && (i + 1 < args.length)) {
lexOptions.smoothInUnknownsThreshold = Integer.parseInt(args[i + 1]);
i += 2;
} else if (args[i].equalsIgnoreCase("-unseenSmooth") && (i + 1 < args.length)) {
testOptions.unseenSmooth = Double.parseDouble(args[i + 1]);
i += 2;
} else if (args[i].equalsIgnoreCase("-fractionBeforeUnseenCounting") && (i + 1 < args.length)) {
trainOptions.fractionBeforeUnseenCounting = Double.parseDouble(args[i + 1]);
i += 2;
} else if (args[i].equalsIgnoreCase("-hSelSplitThresh") && (i + 1 < args.length)) {
trainOptions.HSEL_CUT = Integer.parseInt(args[i + 1]);
trainOptions.hSelSplit = trainOptions.HSEL_CUT > 0;
i += 2;
} else if (args[i].equalsIgnoreCase("-tagPA")) {
trainOptions.tagPA = true;
i += 1;
} else if (args[i].equalsIgnoreCase("-tagSelSplitCutOff") && (i + 1 < args.length)) {
trainOptions.tagSelectiveSplitCutOff = Double.parseDouble(args[i + 1]);
trainOptions.tagSelectiveSplit = trainOptions.tagSelectiveSplitCutOff > 0.0;
i += 2;
} else if (args[i].equalsIgnoreCase("-tagSelPostSplitCutOff") && (i + 1 < args.length)) {
trainOptions.tagSelectivePostSplitCutOff = Double.parseDouble(args[i + 1]);
trainOptions.tagSelectivePostSplit = trainOptions.tagSelectivePostSplitCutOff > 0.0;
i += 2;
} else if (args[i].equalsIgnoreCase("-noTagSplit")) {
trainOptions.noTagSplit = true;
i += 1;
} else if (args[i].equalsIgnoreCase("-uwm") && (i + 1 < args.length)) {
lexOptions.useUnknownWordSignatures = Integer.parseInt(args[i + 1]);
i += 2;
} else if (args[i].equalsIgnoreCase("-unknownSuffixSize") && (i + 1 < args.length)) {
lexOptions.unknownSuffixSize = Integer.parseInt(args[i + 1]);
i += 2;
} else if (args[i].equalsIgnoreCase("-unknownPrefixSize") && (i + 1 < args.length)) {
lexOptions.unknownPrefixSize = Integer.parseInt(args[i + 1]);
i += 2;
} else if (args[i].equalsIgnoreCase("-uwModelTrainer") && (i + 1 < args.length)) {
lexOptions.uwModelTrainer = args[i+1];
i += 2;
} else if (args[i].equalsIgnoreCase("-openClassThreshold") && (i + 1 < args.length)) {
trainOptions.openClassTypesThreshold = Integer.parseInt(args[i + 1]);
i += 2;
} else if (args[i].equalsIgnoreCase("-unary") && i+1 < args.length) {
trainOptions.markUnary = Integer.parseInt(args[i+1]);
i += 2;
} else if (args[i].equalsIgnoreCase("-unaryTags")) {
trainOptions.markUnaryTags = true;
i += 1;
} else if (args[i].equalsIgnoreCase("-mutate")) {
lexOptions.smartMutation = true;
i += 1;
} else if (args[i].equalsIgnoreCase("-useUnicodeType")) {
lexOptions.useUnicodeType = true;
i += 1;
} else if (args[i].equalsIgnoreCase("-rightRec")) {
trainOptions.rightRec = true;
i += 1;
} else if (args[i].equalsIgnoreCase("-noRightRec")) {
trainOptions.rightRec = false;
i += 1;
} else if (args[i].equalsIgnoreCase("-preTag")) {
testOptions.preTag = true;
i += 1;
} else if (args[i].equalsIgnoreCase("-forceTags")) {
testOptions.forceTags = true;
i += 1;
} else if (args[i].equalsIgnoreCase("-taggerSerializedFile")) {
testOptions.taggerSerializedFile = args[i+1];
i += 2;
} else if (args[i].equalsIgnoreCase("-forceTagBeginnings")) {
testOptions.forceTagBeginnings = true;
i += 1;
} else if (args[i].equalsIgnoreCase("-noFunctionalForcing")) {
testOptions.noFunctionalForcing = true;
i += 1;
} else if (args[i].equalsIgnoreCase("-scTags")) {
dcTags = false;
i += 1;
} else if (args[i].equalsIgnoreCase("-dcTags")) {
dcTags = true;
i += 1;
} else if (args[i].equalsIgnoreCase("-basicCategoryTagsInDependencyGrammar")) {
trainOptions.basicCategoryTagsInDependencyGrammar = true;
i+= 1;
} else if (args[i].equalsIgnoreCase("-evalb")) {
testOptions.evalb = true;
i += 1;
} else if (args[i].equalsIgnoreCase("-v") || args[i].equalsIgnoreCase("-verbose")) {
testOptions.verbose = true;
i += 1;
} else if (args[i].equalsIgnoreCase("-outputFilesDirectory") && i+1 < args.length) {
testOptions.outputFilesDirectory = args[i+1];
i += 2;
} else if (args[i].equalsIgnoreCase("-outputFilesExtension") && i+1 < args.length) {
testOptions.outputFilesExtension = args[i+1];
i += 2;
} else if (args[i].equalsIgnoreCase("-outputFilesPrefix") && i+1 < args.length) {
testOptions.outputFilesPrefix = args[i+1];
i += 2;
} else if (args[i].equalsIgnoreCase("-outputkBestEquivocation") && i+1 < args.length) {
testOptions.outputkBestEquivocation = args[i+1];
i += 2;
} else if (args[i].equalsIgnoreCase("-writeOutputFiles")) {
testOptions.writeOutputFiles = true;
i += 1;
} else if (args[i].equalsIgnoreCase("-printAllBestParses")) {
testOptions.printAllBestParses = true;
i += 1;
} else if (args[i].equalsIgnoreCase("-outputTreeFormat") || args[i].equalsIgnoreCase("-outputFormat")) {
testOptions.outputFormat = args[i + 1];
i += 2;
} else if (args[i].equalsIgnoreCase("-outputTreeFormatOptions") || args[i].equalsIgnoreCase("-outputFormatOptions")) {
testOptions.outputFormatOptions = args[i + 1];
i += 2;
} else if (args[i].equalsIgnoreCase("-addMissingFinalPunctuation")) {
testOptions.addMissingFinalPunctuation = true;
i += 1;
} else if (args[i].equalsIgnoreCase("-flexiTag")) {
lexOptions.flexiTag = true;
i += 1;
} else if (args[i].equalsIgnoreCase("-lexiTag")) {
lexOptions.flexiTag = false;
i += 1;
} else if (args[i].equalsIgnoreCase("-useSignatureForKnownSmoothing")) {
lexOptions.useSignatureForKnownSmoothing = true;
i += 1;
} else if (args[i].equalsIgnoreCase("-compactGrammar")) {
trainOptions.compactGrammar = Integer.parseInt(args[i + 1]);
i += 2;
} else if (args[i].equalsIgnoreCase("-markFinalStates")) {
trainOptions.markFinalStates = args[i + 1].equalsIgnoreCase("true");
i += 2;
} else if (args[i].equalsIgnoreCase("-leftToRight")) {
trainOptions.leftToRight = args[i + 1].equals("true");
i += 2;
} else if (args[i].equalsIgnoreCase("-cnf")) {
forceCNF = true;
i += 1;
} else if(args[i].equalsIgnoreCase("-smoothRules")) {
trainOptions.ruleSmoothing = true;
trainOptions.ruleSmoothingAlpha = Double.valueOf(args[i+1]);
i += 2;
} else if (args[i].equalsIgnoreCase("-nodePrune") && i+1 < args.length) {
nodePrune = args[i+1].equalsIgnoreCase("true");
i += 2;
} else if (args[i].equalsIgnoreCase("-noDoRecovery")) {
testOptions.doRecovery = false;
i += 1;
} else if (args[i].equalsIgnoreCase("-acl03chinese")) {
trainOptions.markovOrder = 1;
trainOptions.markovFactor = true;
// no increment
} else if (args[i].equalsIgnoreCase("-wordFunction")) {
wordFunction = ReflectionLoading.loadByReflection(args[i + 1]);
i += 2;
} else if (args[i].equalsIgnoreCase("-acl03pcfg")) {
doDep = false;
doPCFG = true;
// lexOptions.smoothInUnknownsThreshold = 30;
trainOptions.markUnary = 1;
trainOptions.PA = true;
trainOptions.gPA = false;
trainOptions.tagPA = true;
trainOptions.tagSelectiveSplit = false;
trainOptions.rightRec = true;
trainOptions.selectiveSplit = true;
trainOptions.selectiveSplitCutOff = 400.0;
trainOptions.markovFactor = true;
trainOptions.markovOrder = 2;
trainOptions.hSelSplit = true;
lexOptions.useUnknownWordSignatures = 2;
lexOptions.flexiTag = true;
// DAN: Tag double-counting is BAD for PCFG-only parsing
dcTags = false;
// don't increment i so it gets language specific stuff as well
} else if (args[i].equalsIgnoreCase("-jenny")) {
doDep = false;
doPCFG = true;
// lexOptions.smoothInUnknownsThreshold = 30;
trainOptions.markUnary = 1;
trainOptions.PA = false;
trainOptions.gPA = false;
trainOptions.tagPA = false;
trainOptions.tagSelectiveSplit = false;
trainOptions.rightRec = true;
trainOptions.selectiveSplit = false;
// trainOptions.selectiveSplitCutOff = 400.0;
trainOptions.markovFactor = false;
// trainOptions.markovOrder = 2;
trainOptions.hSelSplit = false;
lexOptions.useUnknownWordSignatures = 2;
lexOptions.flexiTag = true;
// DAN: Tag double-counting is BAD for PCFG-only parsing
dcTags = false;
// don't increment i so it gets language specific stuff as well
} else if (args[i].equalsIgnoreCase("-goodPCFG")) {
doDep = false;
doPCFG = true;
// op.lexOptions.smoothInUnknownsThreshold = 30;
trainOptions.markUnary = 1;
trainOptions.PA = true;
trainOptions.gPA = false;
trainOptions.tagPA = true;
trainOptions.tagSelectiveSplit = false;
trainOptions.rightRec = true;
trainOptions.selectiveSplit = true;
trainOptions.selectiveSplitCutOff = 400.0;
trainOptions.markovFactor = true;
trainOptions.markovOrder = 2;
trainOptions.hSelSplit = true;
lexOptions.useUnknownWordSignatures = 2;
lexOptions.flexiTag = true;
// DAN: Tag double-counting is BAD for PCFG-only parsing
dcTags = false;
String[] delSplit = { "-deleteSplitters", "VP^NP,VP^VP,VP^SINV,VP^SQ" };
if (this.setOptionFlag(delSplit, 0) != 2) {
System.err.println("Error processing deleteSplitters");
}
// don't increment i so it gets language specific stuff as well
} else if (args[i].equalsIgnoreCase("-linguisticPCFG")) {
doDep = false;
doPCFG = true;
// op.lexOptions.smoothInUnknownsThreshold = 30;
trainOptions.markUnary = 1;
trainOptions.PA = true;
trainOptions.gPA = false;
trainOptions.tagPA = true; // on at the moment, but iffy
trainOptions.tagSelectiveSplit = false;
trainOptions.rightRec = false; // not for linguistic
trainOptions.selectiveSplit = true;
trainOptions.selectiveSplitCutOff = 400.0;
trainOptions.markovFactor = true;
trainOptions.markovOrder = 2;
trainOptions.hSelSplit = true;
lexOptions.useUnknownWordSignatures = 5; // different from acl03pcfg
lexOptions.flexiTag = false; // different from acl03pcfg
// DAN: Tag double-counting is BAD for PCFG-only parsing
dcTags = false;
// don't increment i so it gets language specific stuff as well
} else if (args[i].equalsIgnoreCase("-ijcai03")) {
doDep = true;
doPCFG = true;
trainOptions.markUnary = 0;
trainOptions.PA = true;
trainOptions.gPA = false;
trainOptions.tagPA = false;
trainOptions.tagSelectiveSplit = false;
trainOptions.rightRec = false;
trainOptions.selectiveSplit = true;
trainOptions.selectiveSplitCutOff = 300.0;
trainOptions.markovFactor = true;
trainOptions.markovOrder = 2;
trainOptions.hSelSplit = true;
trainOptions.compactGrammar = 0; /// cdm: May 2005 compacting bad for factored?
lexOptions.useUnknownWordSignatures = 2;
lexOptions.flexiTag = false;
dcTags = true;
// op.nodePrune = true; // cdm: May 2005: this doesn't help
// don't increment i so it gets language specific stuff as well
} else if (args[i].equalsIgnoreCase("-goodFactored")) {
doDep = true;
doPCFG = true;
trainOptions.markUnary = 0;
trainOptions.PA = true;
trainOptions.gPA = false;
trainOptions.tagPA = false;
trainOptions.tagSelectiveSplit = false;
trainOptions.rightRec = false;
trainOptions.selectiveSplit = true;
trainOptions.selectiveSplitCutOff = 300.0;
trainOptions.markovFactor = true;
trainOptions.markovOrder = 2;
trainOptions.hSelSplit = true;
trainOptions.compactGrammar = 0; /// cdm: May 2005 compacting bad for factored?
lexOptions.useUnknownWordSignatures = 5; // different from ijcai03
lexOptions.flexiTag = false;
dcTags = true;
// op.nodePrune = true; // cdm: May 2005: this doesn't help
// don't increment i so it gets language specific stuff as well
} else if (args[i].equalsIgnoreCase("-chineseFactored")) {
// Single counting tag->word rewrite is also much better for Chinese
// Factored. Bracketing F1 goes up about 0.7%.
dcTags = false;
lexOptions.useUnicodeType = true;
trainOptions.markovOrder = 2;
trainOptions.hSelSplit = true;
trainOptions.markovFactor = true;
trainOptions.HSEL_CUT = 50;
// trainOptions.openClassTypesThreshold=1; // so can get unseen punctuation
// trainOptions.fractionBeforeUnseenCounting=0.0; // so can get unseen punctuation
// don't increment i so it gets language specific stuff as well
} else if (args[i].equalsIgnoreCase("-arabicFactored")) {
doDep = true;
doPCFG = true;
dcTags = false; // "false" seems to help Arabic about 0.1% F1
trainOptions.markovFactor = true;
trainOptions.markovOrder = 2;
trainOptions.hSelSplit = true;
trainOptions.HSEL_CUT = 75; // 75 bit better than 50, 100 a bit worse
trainOptions.PA = true;
trainOptions.gPA = false;
trainOptions.selectiveSplit = true;
trainOptions.selectiveSplitCutOff = 300.0;
trainOptions.markUnary = 1; // Helps PCFG and marginally factLB
// trainOptions.compactGrammar = 0; // Doesn't seem to help or only 0.05% F1
lexOptions.useUnknownWordSignatures = 9;
lexOptions.unknownPrefixSize = 1;
lexOptions.unknownSuffixSize = 1;
testOptions.MAX_ITEMS = 500000; // Arabic sentences are long enough that this helps a fraction
// don't increment i so it gets language specific stuff as well
} else if (args[i].equalsIgnoreCase("-frenchFactored")) {
doDep = true;
doPCFG = true;
dcTags = false; //wsg2011: Setting to false improves F1 by 0.5%
trainOptions.markovFactor = true;
trainOptions.markovOrder = 2;
trainOptions.hSelSplit = true;
trainOptions.HSEL_CUT = 75;
trainOptions.PA = true;
trainOptions.gPA = false;
trainOptions.selectiveSplit = true;
trainOptions.selectiveSplitCutOff = 300.0;
trainOptions.markUnary = 0; //Unary rule marking bad for french..setting to 0 gives +0.3 F1
lexOptions.useUnknownWordSignatures = 1;
lexOptions.unknownPrefixSize = 1;
lexOptions.unknownSuffixSize = 2;
} else if (args[i].equalsIgnoreCase("-chinesePCFG")) {
trainOptions.markovOrder = 2;
trainOptions.markovFactor = true;
trainOptions.HSEL_CUT = 5;
trainOptions.PA = true;
trainOptions.gPA = true;
trainOptions.selectiveSplit = false;
doDep = false;
doPCFG = true;
// Single counting tag->word rewrite is also much better for Chinese PCFG
// Bracketing F1 is up about 2% and tag accuracy about 1% (exact by 6%)
dcTags = false;
// no increment
} else if (args[i].equalsIgnoreCase("-printTT") && (i+1 < args.length)) {
trainOptions.printTreeTransformations = Integer.parseInt(args[i + 1]);
i += 2;
} else if (args[i].equalsIgnoreCase("-printAnnotatedRuleCounts")) {
trainOptions.printAnnotatedRuleCounts = true;
i++;
} else if (args[i].equalsIgnoreCase("-printAnnotatedStateCounts")) {
trainOptions.printAnnotatedStateCounts = true;
i++;
} else if (args[i].equalsIgnoreCase("-printAnnotated") && (i + 1 < args.length)) {
try {
trainOptions.printAnnotatedPW = tlpParams.pw(new FileOutputStream(args[i + 1]));
} catch (IOException ioe) {
trainOptions.printAnnotatedPW = null;
}
i += 2;
} else if (args[i].equalsIgnoreCase("-printBinarized") && (i + 1 < args.length)) {
try {
trainOptions.printBinarizedPW = tlpParams.pw(new FileOutputStream(args[i + 1]));
} catch (IOException ioe) {
trainOptions.printBinarizedPW = null;
}
i += 2;
} else if (args[i].equalsIgnoreCase("-printStates")) {
trainOptions.printStates = true;
i++;
} else if (args[i].equalsIgnoreCase("-preTransformer") && (i + 1 < args.length)) {
String[] classes = args[i + 1].split(",");
i += 2;
if (classes.length == 1) {
trainOptions.preTransformer =
ReflectionLoading.loadByReflection(classes[0], this);
} else if (classes.length > 1) {
CompositeTreeTransformer composite = new CompositeTreeTransformer();
trainOptions.preTransformer = composite;
for (String clazz : classes) {
TreeTransformer transformer =
ReflectionLoading.loadByReflection(clazz, this);
composite.addTransformer(transformer);
}
}
} else if (args[i].equalsIgnoreCase("-taggedFiles") && (i + 1 < args.length)) {
trainOptions.taggedFiles = args[i + 1];
i += 2;
} else if (args[i].equalsIgnoreCase("-predictSplits")) {
// This is an experimental (and still in development)
// reimplementation of Berkeley's state splitting grammar.
trainOptions.predictSplits = true;
trainOptions.compactGrammar = 0;
i++;
} else if (args[i].equalsIgnoreCase("-splitCount")) {
trainOptions.splitCount = Integer.parseInt(args[i + 1]);
i += 2;
} else if (args[i].equalsIgnoreCase("-splitRecombineRate")) {
trainOptions.splitRecombineRate = Double.parseDouble(args[i + 1]);
i +=2;
} else if (args[i].equalsIgnoreCase("-splitTrainingThreads")) {
trainOptions.splitTrainingThreads = Integer.parseInt(args[i + 1]);
i +=2;
} else if (args[i].equalsIgnoreCase("-evals")) {
testOptions.evals = StringUtils.stringToProperties(args[i+1], testOptions.evals);
i += 2;
} else if (args[i].equalsIgnoreCase("-fastFactoredCandidateMultiplier")) {
testOptions.fastFactoredCandidateMultiplier = Integer.parseInt(args[i + 1]);
i += 2;
} else if (args[i].equalsIgnoreCase("-fastFactoredCandidateAddend")) {
testOptions.fastFactoredCandidateAddend = Integer.parseInt(args[i + 1]);
i += 2;
} else if (args[i].equalsIgnoreCase("-simpleBinarizedLabels")) {
trainOptions.simpleBinarizedLabels = true;
i += 1;
} else if (args[i].equalsIgnoreCase("-noRebinarization")) {
trainOptions.noRebinarization = true;
i += 1;
}
return i;
}
public static class LexOptions implements Serializable {
/**
* Whether to use suffix and capitalization information for unknowns.
* Within the BaseLexicon model options have the following meaning:
* 0 means a single unknown token. 1 uses suffix, and capitalization.
* 2 uses a variant (richer) form of signature. Good.
* Use this one. Using the richer signatures in versions 3 or 4 seems
* to have very marginal or no positive value.
* 3 uses a richer form of signature that mimics the NER word type
* patterns. 4 is a variant of 2. 5 is another with more English
* specific morphology (good for English unknowns!).
* 6-9 are options for Arabic. 9 codes some patterns for numbers and
* derivational morphology, but also supports unknownPrefixSize and
* unknownSuffixSize.
* For German, 0 means a single unknown token, and non-zero means to use
* capitalization of first letter and a suffix of length
* unknownSuffixSize.
*/
public int useUnknownWordSignatures = 0;
/**
* Words more common than this are tagged with MLE P(t|w). Default 100. The
* smoothing is sufficiently slight that changing this has little effect.
* But set this to 0 to be able to use the parser as a vanilla PCFG with
* no smoothing (not as a practical parser but for exposition or debugging).
*/
public int smoothInUnknownsThreshold = 100;
/**
* Smarter smoothing for rare words.<|fim▁hole|> * Make use of unicode code point types in smoothing.
*/
public boolean useUnicodeType = false;
/** For certain Lexicons, a certain number of word-final letters are
* used to subclassify the unknown token. This gives the number of
* letters.
*/
public int unknownSuffixSize = 1;
/** For certain Lexicons, a certain number of word-initial letters are
* used to subclassify the unknown token. This gives the number of
* letters.
*/
public int unknownPrefixSize = 1;
/**
* Trainer which produces model for unknown words that the lexicon
* should use
*/
public String uwModelTrainer; // = null;
/* If this option is false, then all words that were seen in the training
* data (even once) are constrained to only have seen tags. That is,
* mle is used for the lexicon.
* If this option is true, then if a word has been seen more than
* smoothInUnknownsThreshold, then it will still only get tags with which
* it has been seen, but rarer words will get all tags for which the
* unknown word model (or smart mutation) does not give a score of -Inf.
* This will normally be all open class tags.
* If floodTags is invoked by the parser, all other tags will also be
* given a minimal non-zero, non-infinite probability.
*/
public boolean flexiTag = false;
/** Whether to use signature rather than just being unknown as prior in
* known word smoothing. Currently only works if turned on for English.
*/
public boolean useSignatureForKnownSmoothing;
private static final long serialVersionUID = 2805351374506855632L;
private static final String[] params = { "useUnknownWordSignatures",
"smoothInUnknownsThreshold",
"smartMutation",
"useUnicodeType",
"unknownSuffixSize",
"unknownPrefixSize",
"flexiTag",
"useSignatureForKnownSmoothing"};
@Override
public String toString() {
return params[0] + " " + useUnknownWordSignatures + "\n" +
params[1] + " " + smoothInUnknownsThreshold + "\n" +
params[2] + " " + smartMutation + "\n" +
params[3] + " " + useUnicodeType + "\n" +
params[4] + " " + unknownSuffixSize + "\n" +
params[5] + " " + unknownPrefixSize + "\n" +
params[6] + " " + flexiTag + "\n" +
params[7] + " " + useSignatureForKnownSmoothing + "\n";
}
public void readData(BufferedReader in) throws IOException {
for (int i = 0; i < params.length; i++) {
String line = in.readLine();
int idx = line.indexOf(' ');
String key = line.substring(0, idx);
String value = line.substring(idx + 1);
if ( ! key.equalsIgnoreCase(params[i])) {
System.err.println("Yikes!!! Expected " + params[i] + " got " + key);
}
switch (i) {
case 0:
useUnknownWordSignatures = Integer.parseInt(value);
break;
case 1:
smoothInUnknownsThreshold = Integer.parseInt(value);
break;
case 2:
smartMutation = Boolean.parseBoolean(value);
break;
case 3:
useUnicodeType = Boolean.parseBoolean(value);
break;
case 4:
unknownSuffixSize = Integer.parseInt(value);
break;
case 5:
unknownPrefixSize = Integer.parseInt(value);
break;
case 6:
flexiTag = Boolean.parseBoolean(value);
}
}
}
} // end class LexOptions
public LexOptions lexOptions = new LexOptions();
/**
* The treebank-specific parser parameters to use.
*/
public TreebankLangParserParams tlpParams;
/**
* @return The treebank language pack for the treebank the parser
* is trained on.
*/
public TreebankLanguagePack langpack() {
return tlpParams.treebankLanguagePack();
}
/**
* Forces parsing with strictly CNF grammar -- unary chains are converted
* to XP&YP symbols and back
*/
public boolean forceCNF = false;
/**
* Do a PCFG parse of the sentence. If both variables are on,
* also do a combined parse of the sentence.
*/
public boolean doPCFG = true;
/**
* Do a dependency parse of the sentence.
*/
public boolean doDep = true;
/**
* if true, any child can be the head (seems rather bad!)
*/
public boolean freeDependencies = false;
/**
* Whether dependency grammar considers left/right direction. Good.
*/
public boolean directional = true;
public boolean genStop = true;
public boolean useSmoothTagProjection = false;
public boolean useUnigramWordSmoothing = false;
/**
* Use distance bins in the dependency calculations
*/
public boolean distance = true;
/**
* Use coarser distance (4 bins) in dependency calculations
*/
public boolean coarseDistance = false;
/**
* "double count" tags rewrites as word in PCFG and Dep parser. Good for
* combined parsing only (it used to not kick in for PCFG parsing). This
* option is only used at Test time, but it is now in Options, so the
* correct choice for a grammar is recorded by a serialized parser.
* You should turn this off for a vanilla PCFG parser.
*/
public boolean dcTags = true;
/**
* If true, inside the factored parser, remove any node from the final
* chosen tree which improves the PCFG score. This was added as the
* dependency factor tends to encourage 'deep' trees.
*/
public boolean nodePrune = false;
public TrainOptions trainOptions = new TrainOptions();
/**
* Note that the TestOptions is transient. This means that whatever
* options get set at creation time are forgotten when the parser is
* serialized. If you want an option to be remembered when the
* parser is reloaded, put it in either TrainOptions or in this
* class itself.
*/
public transient TestOptions testOptions = new TestOptions();
/**
* A function that maps words used in training and testing to new
* words. For example, it could be a function to lowercase text,
* such as edu.stanford.nlp.util.LowercaseFunction (which makes the
* parser case insensitive). This function is applied in
* LexicalizedParserQuery.parse and in the training methods which
* build a new parser.
*/
public Function<String, String> wordFunction = null;
/**
* Making the TestOptions transient means it won't even be
* constructed when you deserialize an Options, so we need to
* construct it on our own when deserializing
*/
private void readObject(ObjectInputStream in)
throws IOException, ClassNotFoundException
{
in.defaultReadObject();
testOptions = new TestOptions();
}
public void display() {
// try {
logger.trace("Options parameters:");
writeData();
/* } catch (IOException e) {
e.printStackTrace();
}*/
}
public void writeData() {//throws IOException {
StringBuilder sb = new StringBuilder();
sb.append(lexOptions.toString());
sb.append("parserParams ").append(tlpParams.getClass().getName()).append("\n");
sb.append("forceCNF ").append(forceCNF).append("\n");
sb.append("doPCFG ").append(doPCFG).append("\n");
sb.append("doDep ").append(doDep).append("\n");
sb.append("freeDependencies ").append(freeDependencies).append("\n");
sb.append("directional ").append(directional).append("\n");
sb.append("genStop ").append(genStop).append("\n");
sb.append("distance ").append(distance).append("\n");
sb.append("coarseDistance ").append(coarseDistance).append("\n");
sb.append("dcTags ").append(dcTags).append("\n");
sb.append("nPrune ").append(nodePrune).append("\n");
logger.trace(sb.toString());
}
/**
* Populates data in this Options from the character stream.
* @param in The Reader
* @throws IOException If there is a problem reading data
*/
public void readData(BufferedReader in) throws IOException {
String line, value;
// skip old variables if still present
lexOptions.readData(in);
line = in.readLine();
value = line.substring(line.indexOf(' ') + 1);
try {
tlpParams = (TreebankLangParserParams) Class.forName(value).newInstance();
} catch (Exception e) {
IOException ioe = new IOException("Problem instantiating parserParams: " + line);
ioe.initCause(e);
throw ioe;
}
line = in.readLine();
// ensure backwards compatibility
if (line.matches("^forceCNF.*")) {
value = line.substring(line.indexOf(' ') + 1);
forceCNF = Boolean.parseBoolean(value);
line = in.readLine();
}
value = line.substring(line.indexOf(' ') + 1);
doPCFG = Boolean.parseBoolean(value);
line = in.readLine();
value = line.substring(line.indexOf(' ') + 1);
doDep = Boolean.parseBoolean(value);
line = in.readLine();
value = line.substring(line.indexOf(' ') + 1);
freeDependencies = Boolean.parseBoolean(value);
line = in.readLine();
value = line.substring(line.indexOf(' ') + 1);
directional = Boolean.parseBoolean(value);
line = in.readLine();
value = line.substring(line.indexOf(' ') + 1);
genStop = Boolean.parseBoolean(value);
line = in.readLine();
value = line.substring(line.indexOf(' ') + 1);
distance = Boolean.parseBoolean(value);
line = in.readLine();
value = line.substring(line.indexOf(' ') + 1);
coarseDistance = Boolean.parseBoolean(value);
line = in.readLine();
value = line.substring(line.indexOf(' ') + 1);
dcTags = Boolean.parseBoolean(value);
line = in.readLine();
if ( ! line.matches("^nPrune.*")) {
throw new RuntimeException("Expected nPrune, found: " + line);
}
value = line.substring(line.indexOf(' ') + 1);
nodePrune = Boolean.parseBoolean(value);
line = in.readLine(); // get rid of last line
if (line.length() != 0) {
throw new RuntimeException("Expected blank line, found: " + line);
}
}
private static final long serialVersionUID = 4L;
} // end class Options<|fim▁end|>
|
*/
public boolean smartMutation = false;
/**
|
<|file_name|>Battery20Rounded.js<|end_file_name|><|fim▁begin|>import React from 'react';<|fim▁hole|> <React.Fragment><path fill="none" d="M0 0h24v24H0V0z" /><g><path d="M7 17v3.67C7 21.4 7.6 22 8.33 22h7.33c.74 0 1.34-.6 1.34-1.33V17H7z" /><path fillOpacity=".3" d="M17 5.33C17 4.6 16.4 4 15.67 4H14V3c0-.55-.45-1-1-1h-2c-.55 0-1 .45-1 1v1H8.33C7.6 4 7 4.6 7 5.33V17h10V5.33z" /></g></React.Fragment>
, 'Battery20Rounded');<|fim▁end|>
|
import createSvgIcon from './utils/createSvgIcon';
export default createSvgIcon(
|
<|file_name|>columnWidget.js<|end_file_name|><|fim▁begin|>import React from 'react';
import PropTypes from 'prop-types';
import ColumnChart from './columnChart';
import Tooltip from './../tooltip/tooltip';
import {dateFormats} from './../../utils/displayFormats';
import './columnWidget.css';
const ColumnWidget = ({
chartTitle,
chartDescription,
chartUpdatedDate,
series,
xAxis,
yAxis,
viewport,<|fim▁hole|> <article role="article" className="D_widget">
<header>
{chartDescription && <div className="D_CW_infoContainer"><Tooltip text={chartDescription} viewport={viewport} /></div>}
<h1 className="highcharts-title">{chartTitle}</h1>
<span className="highcharts-subtitle">Last updated at <time dateTime={dateFormats.dateTime(chartUpdatedDate)}>{dateFormats.dayMonthYear(chartUpdatedDate)}</time></span>
</header>
<section>
<ColumnChart series={series}
xAxis={xAxis}
yAxis={yAxis}
chartDescription={chartDescription}
displayHighContrast={displayHighContrast} />
</section>
</article>
)
};
if (__DEV__) {
ColumnWidget.propTypes = {
chartTitle: PropTypes.string,
chartDescription: PropTypes.string,
chartUpdatedDate: PropTypes.string,
series: PropTypes.arrayOf(PropTypes.shape({
name: PropTypes.string.isRequired,
units: PropTypes.string,
color: PropTypes.string,
data: PropTypes.array.isRequired,
})).isRequired,
xAxis: PropTypes.arrayOf(PropTypes.shape({
categories: PropTypes.array,
})),
yAxis: PropTypes.arrayOf(PropTypes.shape({
title: PropTypes.object,
})),
viewport: PropTypes.oneOf(['sm', 'md', 'lg', 'xl']),
displayHighContrast: PropTypes.bool,
};
}
export default ColumnWidget;<|fim▁end|>
|
displayHighContrast,
}) => {
return (
|
<|file_name|>discover.py<|end_file_name|><|fim▁begin|>'''Find valid tags and usernames.
The file will contain things like:
tag:12345:romance
'''
import gzip
import re
import requests
import string
import sys
import time
import random
DEFAULT_HEADERS = {'User-Agent': 'ArchiveTeam'}
class FetchError(Exception):
'''Custom error class when fetching does not meet our expectation.'''
def main():
# Take the program arguments given to this script
# Normal programs use 'argparse' but this keeps things simple
start_num = int(sys.argv[1])
end_num = int(sys.argv[2])
output_filename = sys.argv[3] # this should be something like myfile.txt.gz
assert start_num <= end_num
print('Starting', start_num, end_num)
gzip_file = gzip.GzipFile(output_filename, 'wb')
for shortcode in check_range(start_num, end_num):
# Write the valid result one per line to the file
line = '{0}\n'.format(shortcode)
gzip_file.write(line.encode('ascii'))
gzip_file.close()
print('Done')
def check_range(start_num, end_num):
'''Check if page exists.
Each line is like tag:12345:romance
'''
for num in range(start_num, end_num + 1):
shortcode = num
url = 'http://www.panoramio.com/user/{0}'.format(shortcode)
counter = 0
while True:
# Try 20 times before giving up
if counter > 20:
# This will stop the script with an error
raise Exception('Giving up!')
try:
text = fetch(url)
except FetchError:
# The server may be overloaded so wait a bit
print('Sleeping... If you see this')
time.sleep(10)
else:
if text:
for user in extract_user(text) for tag in extract_tags(text):<|fim▁hole|> yield 'tag:{0}:{1}'.format(user, tag)
break # stop the while loop
counter += 1
def fetch(url):
'''Fetch the URL and check if it returns OK.
Returns True, returns the response text. Otherwise, returns None
'''
print('Fetch', url)
response = requests.get(url, headers=DEFAULT_HEADERS)
# response doesn't have a reason attribute all the time??
print('Got', response.status_code, getattr(response, 'reason'))
if response.status_code == 200:
# The item exists
if not response.text:
# If HTML is empty maybe server broke
raise FetchError()
return response.text
elif response.status_code == 404:
# Does not exist
return
else:
# Problem
raise FetchError()
def extract_user(text):
'''Return a list of tags from the text.'''
# Search for <a href="/user/1707816/tags/Bell%27Italia">Bell'Italia</a>
return re.findall(r'"/user/([^/]+)/tags/', text)
def extract_tags(text):
'''Return a list of tags from the text.'''
# Search for <a href="/user/1707816/tags/Bell%27Italia">Bell'Italia</a>
return re.findall(r'"/user/[0-9]+/tags/([^"]+)"', text)
if __name__ == '__main__':
main()<|fim▁end|>
| |
<|file_name|>mod.rs<|end_file_name|><|fim▁begin|>//! Defines the trait implemented by all textured values
use std::ops::{Add, Mul};
use film::Colorf;
pub use self::image::Image;
pub use self::animated_image::AnimatedImage;
pub mod image;
pub mod animated_image;
/// scalars or Colors can be computed on some image texture
/// or procedural generator
pub trait Texture {
/// Sample the textured value at texture coordinates u,v
/// at some time. u and v should be in [0, 1]
fn sample_f32(&self, u: f32, v: f32, time: f32) -> f32;
fn sample_color(&self, u: f32, v: f32, time: f32) -> Colorf;
}
fn bilinear_interpolate<T, F>(x: f32, y: f32, get: F) -> T
where T: Copy + Add<T, Output=T> + Mul<f32, Output=T>,
F: Fn(u32, u32) -> T
{
let p00 = (x as u32, y as u32);
let p10 = (p00.0 + 1, p00.1);
let p01 = (p00.0, p00.1 + 1);
let p11 = (p00.0 + 1, p00.1 + 1);
let s00 = get(p00.0, p00.1);
let s10 = get(p10.0, p10.1);
let s01 = get(p01.0, p01.1);
let s11 = get(p11.0, p11.1);
let sx = x - p00.0 as f32;
let sy = y - p00.1 as f32;
s00 * (1.0 - sx) * (1.0 - sy) + s10 * sx * (1.0 - sy)
+ s01 * (1.0 - sx) * sy + s11 * sx * sy
}
/// A single valued, solid scalar texture
pub struct ConstantScalar {
val: f32,
}
impl ConstantScalar {
pub fn new(val: f32) -> ConstantScalar {
ConstantScalar { val: val }
}
}
impl Texture for ConstantScalar {
fn sample_f32(&self, _: f32, _: f32, _: f32) -> f32 {
self.val
}
fn sample_color(&self, _: f32, _: f32, _: f32) -> Colorf {
Colorf::broadcast(self.val)
}
}
/// A single valued, solid color texture<|fim▁hole|> val: Colorf,
}
impl ConstantColor {
pub fn new(val: Colorf) -> ConstantColor {
ConstantColor { val: val }
}
}
impl Texture for ConstantColor {
fn sample_f32(&self, _: f32, _: f32, _: f32) -> f32 {
self.val.luminance()
}
fn sample_color(&self, _: f32, _: f32, _: f32) -> Colorf {
self.val
}
}
pub struct UVColor;
impl Texture for UVColor {
fn sample_f32(&self, u: f32, v: f32, _: f32) -> f32 {
Colorf::new(u, v, 0.0).luminance()
}
fn sample_color(&self, u: f32, v: f32, _: f32) -> Colorf {
Colorf::new(u, v, 0.0)
}
}<|fim▁end|>
|
pub struct ConstantColor {
|
<|file_name|>9_billion_names_of_god_the_integer.rs<|end_file_name|><|fim▁begin|>// http://rosettacode.org/wiki/9_billion_names_of_God_the_integer
extern crate num;
use std::cmp::min;
use num::{BigUint, Zero, One};
pub struct Solver {
// The `cache` is a private implementation detail,
// it would be an improvement to throw away unused values
// from the cache (to reduce memory for larger inputs)
cache: Vec<Vec<BigUint>>
}
impl Solver {
pub fn new() -> Solver {
// Setup the cache with the initial row
Solver { cache: vec![vec![One::one()]] }
}
// Returns a string representing a line
pub fn row_string(&mut self, idx: usize) -> String {
let r = self.cumulative(idx);
(0..idx).map(|i| &r[i+1] - &r[i])
.map(|n| n.to_string())
.collect::<Vec<String>>()
.join(", ")
}
// Convenience method to access the last column in a culmulated calculation
pub fn row_sum(&mut self, idx: usize) -> &BigUint {
// This can never fail as we always add zero or one, so it's never empty.
self.cumulative(idx).last().unwrap()
}<|fim▁hole|>
for x in 1..l + 1 {
let w = {
let y = &r[x-1];
let z = &self.cache[l-x][min(x, l-x)];
y + z
};
r.push(w)
}
self.cache.push(r);
}
&self.cache[idx][..]
}
}
#[cfg(not(test))]
fn main() {
let mut solver = Solver::new();
println!("rows");
for n in 1..11 {
println!("{}: {}", n, solver.row_string(n));
}
println!("sums");
for &y in &[23, 123, 1234, 12345] {
println!("{}: {}", y, solver.row_sum(y));
}
}
#[cfg(test)]
mod test {
use super::Solver;
use num::BigUint;
#[test]
fn test_cumulative() {
let mut solver = Solver::new();
let mut t = |n: usize, expected: &str| {
assert_eq!(solver.row_sum(n), &expected.parse::<BigUint>().unwrap());
};
t(23, "1255");
t(123, "2552338241");
t(1234, "156978797223733228787865722354959930");
}
#[test]
fn test_row() {
let mut solver = Solver::new();
let mut t = |n: usize, expected: &str| {
assert_eq!(solver.row_string(n), expected);
};
t(1, "1");
t(2, "1, 1");
t(3, "1, 1, 1");
t(4, "1, 2, 1, 1");
t(5, "1, 2, 2, 1, 1");
t(6, "1, 3, 3, 2, 1, 1");
}
}<|fim▁end|>
|
fn cumulative(&mut self, idx: usize) -> &[BigUint] {
for l in self.cache.len()..idx + 1 {
let mut r : Vec<BigUint> = vec![Zero::zero()];
|
<|file_name|>BenchmarkTest08472.java<|end_file_name|><|fim▁begin|>/**
* OWASP Benchmark Project v1.1
*
* This file is part of the Open Web Application Security Project (OWASP)
* Benchmark Project. For details, please see
* <a href="https://www.owasp.org/index.php/Benchmark">https://www.owasp.org/index.php/Benchmark</a>.
*
* The Benchmark 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, version 2.
*
* The Benchmark 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
*
* @author Dave Wichers <a href="https://www.aspectsecurity.com">Aspect Security</a>
* @created 2015
*/
package org.owasp.benchmark.testcode;
import java.io.IOException;
<|fim▁hole|>import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
@WebServlet("/BenchmarkTest08472")
public class BenchmarkTest08472 extends HttpServlet {
private static final long serialVersionUID = 1L;
@Override
public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doPost(request, response);
}
@Override
public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String param = "";
java.util.Enumeration<String> headerNames = request.getHeaderNames();
if (headerNames.hasMoreElements()) {
param = headerNames.nextElement(); // just grab first element
}
String bar = new Test().doSomething(param);
try {
java.util.Properties Benchmarkprops = new java.util.Properties();
Benchmarkprops.load(this.getClass().getClassLoader().getResourceAsStream("Benchmark.properties"));
String algorithm = Benchmarkprops.getProperty("cryptoAlg1", "DESede/ECB/PKCS5Padding");
javax.crypto.Cipher c = javax.crypto.Cipher.getInstance(algorithm);
} catch (java.security.NoSuchAlgorithmException e) {
System.out.println("Problem executing crypto - javax.crypto.Cipher.getInstance(java.lang.String) Test Case");
throw new ServletException(e);
} catch (javax.crypto.NoSuchPaddingException e) {
System.out.println("Problem executing crypto - javax.crypto.Cipher.getInstance(java.lang.String) Test Case");
throw new ServletException(e);
}
response.getWriter().println("Crypto Test javax.crypto.Cipher.getInstance(java.lang.String) executed");
} // end doPost
private class Test {
public String doSomething(String param) throws ServletException, IOException {
String bar = org.springframework.web.util.HtmlUtils.htmlEscape(param);
return bar;
}
} // end innerclass Test
} // end DataflowThruInnerClass<|fim▁end|>
| |
<|file_name|>bitcoin_eo.ts<|end_file_name|><|fim▁begin|><?xml version="1.0" ?><!DOCTYPE TS><TS language="eo" version="2.0">
<defaultcodec>UTF-8</defaultcodec>
<context>
<name>AboutDialog</name>
<message>
<location filename="../forms/aboutdialog.ui" line="+14"/>
<source>About BitTor</source>
<translation>Pri BitTor</translation>
</message>
<message>
<location line="+39"/>
<source><b>BitTor</b> version</source>
<translation><b>BitTor</b>-a versio</translation>
</message>
<message>
<location line="+57"/>
<source>
This is experimental software.
Distributed under the MIT/X11 software license, see the accompanying file COPYING or http://www.opensource.org/licenses/mit-license.php.
This product includes software developed by the OpenSSL Project for use in the OpenSSL Toolkit (http://www.openssl.org/) and cryptographic software written by Eric Young ([email protected]) and UPnP software written by Thomas Bernard.</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../aboutdialog.cpp" line="+14"/>
<source>Copyright</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+0"/>
<source>The BitTor developers</source>
<translation type="unfinished"/>
</message>
</context>
<context>
<name>AddressBookPage</name>
<message>
<location filename="../forms/addressbookpage.ui" line="+14"/>
<source>Address Book</source>
<translation>Adresaro</translation>
</message>
<message>
<location line="+19"/>
<source>Double-click to edit address or label</source>
<translation>Duoble-klaku por redakti adreson aŭ etikedon</translation>
</message>
<message>
<location line="+27"/>
<source>Create a new address</source>
<translation>Kreu novan adreson</translation>
</message>
<message>
<location line="+14"/>
<source>Copy the currently selected address to the system clipboard</source>
<translation>Kopiu elektitan adreson al la tondejo</translation>
</message>
<message>
<location line="-11"/>
<source>&New Address</source>
<translation>&Nova Adreso</translation>
</message>
<message>
<location filename="../addressbookpage.cpp" line="+63"/>
<source>These are your BitTor addresses for receiving payments. You may want to give a different one to each sender so you can keep track of who is paying you.</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../forms/addressbookpage.ui" line="+14"/>
<source>&Copy Address</source>
<translation>&Kopiu Adreson</translation>
</message>
<message>
<location line="+11"/>
<source>Show &QR Code</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+11"/>
<source>Sign a message to prove you own a BitTor address</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Sign &Message</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+25"/>
<source>Delete the currently selected address from the list</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+27"/>
<source>Export the data in the current tab to a file</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>&Export</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-44"/>
<source>Verify a message to ensure it was signed with a specified BitTor address</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>&Verify Message</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+14"/>
<source>&Delete</source>
<translation>&Forviŝu</translation>
</message>
<message>
<location filename="../addressbookpage.cpp" line="-5"/>
<source>These are your BitTor addresses for sending payments. Always check the amount and the receiving address before sending coins.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+13"/>
<source>Copy &Label</source>
<translation>Kopiu &Etikedon</translation>
</message>
<message>
<location line="+1"/>
<source>&Edit</source>
<translation>&Redaktu</translation>
</message>
<message>
<location line="+1"/>
<source>Send &Coins</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+260"/>
<source>Export Address Book Data</source>
<translation>Eksportu Adresarajn Datumojn</translation>
</message>
<message>
<location line="+1"/>
<source>Comma separated file (*.csv)</source>
<translation>Diskoma dosiero (*.csv)</translation>
</message>
<message>
<location line="+13"/>
<source>Error exporting</source>
<translation>Eraro dum eksportado</translation>
</message>
<message>
<location line="+0"/>
<source>Could not write to file %1.</source>
<translation>Ne eblis skribi al dosiero %1.</translation>
</message>
</context>
<context>
<name>AddressTableModel</name>
<message>
<location filename="../addresstablemodel.cpp" line="+144"/>
<source>Label</source>
<translation>Etikedo</translation>
</message>
<message>
<location line="+0"/>
<source>Address</source>
<translation>Adreso</translation>
</message>
<message>
<location line="+36"/>
<source>(no label)</source>
<translation>(ne etikedo)</translation>
</message>
</context>
<context>
<name>AskPassphraseDialog</name>
<message>
<location filename="../forms/askpassphrasedialog.ui" line="+26"/>
<source>Passphrase Dialog</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+21"/>
<source>Enter passphrase</source>
<translation>Enigu pasfrazon</translation>
</message>
<message>
<location line="+14"/>
<source>New passphrase</source>
<translation>Nova pasfrazo</translation>
</message>
<message>
<location line="+14"/>
<source>Repeat new passphrase</source>
<translation>Ripetu novan pasfrazon</translation>
</message>
<message>
<location filename="../askpassphrasedialog.cpp" line="+33"/>
<source>Enter the new passphrase to the wallet.<br/>Please use a passphrase of <b>10 or more random characters</b>, or <b>eight or more words</b>.</source>
<translation>Enigu novan pasfrazon por la monujo.<br/>Bonvolu, uzu pasfrazon kun <b>10 aŭ pli hazardaj signoj</b>, aŭ <b>ok aŭ pli vortoj</b>.</translation>
</message>
<message>
<location line="+1"/>
<source>Encrypt wallet</source>
<translation>Ĉifru monujon</translation>
</message>
<message>
<location line="+3"/>
<source>This operation needs your wallet passphrase to unlock the wallet.</source>
<translation>Ĉi tiu operacio devas vian monujan pasfrazon, por malŝlosi la monujon.</translation>
</message>
<message>
<location line="+5"/>
<source>Unlock wallet</source>
<translation>Malŝlosu monujon</translation>
</message>
<message>
<location line="+3"/>
<source>This operation needs your wallet passphrase to decrypt the wallet.</source>
<translation>Ĉi tiu operacio devas vian monujan pasfrazon, por malĉifri la monujon.</translation>
</message>
<message>
<location line="+5"/>
<source>Decrypt wallet</source>
<translation>Malĉifru monujon</translation>
</message>
<message>
<location line="+3"/>
<source>Change passphrase</source>
<translation>Anstataŭigu pasfrazon</translation>
</message>
<message>
<location line="+1"/>
<source>Enter the old and new passphrase to the wallet.</source>
<translation>Enigu la malnovan kaj novan monujan pasfrazon.</translation>
</message>
<message>
<location line="+46"/>
<source>Confirm wallet encryption</source>
<translation>Konfirmu ĉifrado de monujo</translation>
</message>
<message>
<location line="+1"/>
<source>Warning: If you encrypt your wallet and lose your passphrase, you will <b>LOSE ALL OF YOUR BITTORS</b>!</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+0"/>
<source>Are you sure you wish to encrypt your wallet?</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+15"/>
<source>IMPORTANT: Any previous backups you have made of your wallet file should be replaced with the newly generated, encrypted wallet file. For security reasons, previous backups of the unencrypted wallet file will become useless as soon as you start using the new, encrypted wallet.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+100"/>
<location line="+24"/>
<source>Warning: The Caps Lock key is on!</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-130"/>
<location line="+58"/>
<source>Wallet encrypted</source>
<translation>Monujo ĉifrita</translation>
</message>
<message>
<location line="-56"/>
<source>BitTor will close now to finish the encryption process. Remember that encrypting your wallet cannot fully protect your bittors from being stolen by malware infecting your computer.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+13"/>
<location line="+7"/>
<location line="+42"/>
<location line="+6"/>
<source>Wallet encryption failed</source>
<translation>Monujo ĉifrado fiaskis</translation>
</message>
<message>
<location line="-54"/>
<source>Wallet encryption failed due to an internal error. Your wallet was not encrypted.</source>
<translation>Ĉifrado de monujo fiaskis, kaŭze de interna eraro. Via monujo ne ĉifritas.</translation>
</message>
<message>
<location line="+7"/>
<location line="+48"/>
<source>The supplied passphrases do not match.</source>
<translation>La pasfrazoj enigitaj ne samas.</translation>
</message>
<message>
<location line="-37"/>
<source>Wallet unlock failed</source>
<translation>Monujo malŝlosado fiaskis</translation>
</message>
<message>
<location line="+1"/>
<location line="+11"/>
<location line="+19"/>
<source>The passphrase entered for the wallet decryption was incorrect.</source>
<translation>La pasfrazo enigita por ĉifrado de monujo ne konformas.</translation>
</message>
<message>
<location line="-20"/>
<source>Wallet decryption failed</source>
<translation>Monujo malĉifrado fiaskis</translation>
</message>
<message>
<location line="+14"/>
<source>Wallet passphrase was successfully changed.</source>
<translation type="unfinished"/>
</message>
</context>
<context>
<name>BitcoinGUI</name>
<message>
<location filename="../bitcoingui.cpp" line="+233"/>
<source>Sign &message...</source>
<translation>Subskribu &mesaĝon...</translation>
</message>
<message>
<location line="+280"/>
<source>Synchronizing with network...</source>
<translation>Sinkronigante kun reto...</translation>
</message>
<message>
<location line="-349"/>
<source>&Overview</source>
<translation>&Superrigardo</translation>
</message>
<message>
<location line="+1"/>
<source>Show general overview of wallet</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+20"/>
<source>&Transactions</source>
<translation>&Transakcioj</translation>
</message>
<message>
<location line="+1"/>
<source>Browse transaction history</source>
<translation>Esploru historion de transakcioj</translation>
</message>
<message>
<location line="+7"/>
<source>Edit the list of stored addresses and labels</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-14"/>
<source>Show the list of addresses for receiving payments</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+31"/>
<source>E&xit</source>
<translation>&Eliru</translation>
</message>
<message>
<location line="+1"/>
<source>Quit application</source>
<translation>Eliru de aplikaĵo</translation>
</message>
<message>
<location line="+4"/>
<source>Show information about BitTor</source>
<translation>Vidigu informaĵon pri Bitmono</translation>
</message>
<message>
<location line="+2"/>
<source>About &Qt</source>
<translation>Pri &QT</translation>
</message>
<message>
<location line="+1"/>
<source>Show information about Qt</source>
<translation>Vidigu informaĵon pri Qt</translation>
</message>
<message>
<location line="+2"/>
<source>&Options...</source>
<translation>&Opcioj...</translation>
</message>
<message>
<location line="+6"/>
<source>&Encrypt Wallet...</source>
<translation>&Ĉifru Monujon...</translation>
</message>
<message>
<location line="+3"/>
<source>&Backup Wallet...</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>&Change Passphrase...</source>
<translation>&Anstataŭigu pasfrazon...</translation>
</message>
<message>
<location line="+285"/>
<source>Importing blocks from disk...</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Reindexing blocks on disk...</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-347"/>
<source>Send coins to a BitTor address</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+49"/>
<source>Modify configuration options for BitTor</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+9"/>
<source>Backup wallet to another location</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>Change the passphrase used for wallet encryption</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+6"/>
<source>&Debug window</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Open debugging and diagnostic console</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-4"/>
<source>&Verify message...</source>
<translation>&Kontrolu mesaĝon...</translation>
</message>
<message>
<location line="-165"/>
<location line="+530"/>
<source>BitTor</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-530"/>
<source>Wallet</source>
<translation>Monujo</translation>
</message>
<message>
<location line="+101"/>
<source>&Send</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+7"/>
<source>&Receive</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+14"/>
<source>&Addresses</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+22"/>
<source>&About BitTor</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+9"/>
<source>&Show / Hide</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Show or hide the main Window</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Encrypt the private keys that belong to your wallet</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+7"/>
<source>Sign messages with your BitTor addresses to prove you own them</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>Verify messages to ensure they were signed with specified BitTor addresses</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+28"/>
<source>&File</source>
<translation>&Dosiero</translation>
</message>
<message>
<location line="+7"/>
<source>&Settings</source>
<translation>&Agordoj</translation>
</message>
<message>
<location line="+6"/>
<source>&Help</source>
<translation>&Helpo</translation>
</message>
<message>
<location line="+9"/>
<source>Tabs toolbar</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+17"/>
<location line="+10"/>
<source>[testnet]</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+47"/>
<source>BitTor client</source>
<translation type="unfinished"/>
</message>
<message numerus="yes">
<location line="+141"/>
<source>%n active connection(s) to BitTor network</source>
<translation type="unfinished"><numerusform></numerusform><numerusform></numerusform></translation>
</message>
<message>
<location line="+22"/>
<source>No block source available...</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+12"/>
<source>Processed %1 of %2 (estimated) blocks of transaction history.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+4"/>
<source>Processed %1 blocks of transaction history.</source>
<translation type="unfinished"/>
</message>
<message numerus="yes">
<location line="+20"/>
<source>%n hour(s)</source>
<translation><numerusform>%n horo</numerusform><numerusform>%n horoj</numerusform></translation>
</message>
<message numerus="yes">
<location line="+4"/>
<source>%n day(s)</source>
<translation><numerusform>%n tago</numerusform><numerusform>%n tagoj</numerusform></translation>
</message>
<message numerus="yes">
<location line="+4"/>
<source>%n week(s)</source>
<translation><numerusform>%n semajno</numerusform><numerusform>%n semajnoj</numerusform></translation>
</message>
<message>
<location line="+4"/>
<source>%1 behind</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+14"/>
<source>Last received block was generated %1 ago.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>Transactions after this will not yet be visible.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+22"/>
<source>Error</source>
<translation>Eraro</translation>
</message>
<message>
<location line="+3"/>
<source>Warning</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Information</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+70"/>
<source>This transaction is over the size limit. You can still send it for a fee of %1, which goes to the nodes that process your transaction and helps to support the network. Do you want to pay the fee?</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-140"/>
<source>Up to date</source>
<translation>Ĝisdata</translation>
</message>
<message>
<location line="+31"/>
<source>Catching up...</source>
<translation>Ĝisdatigante...</translation>
</message>
<message>
<location line="+113"/>
<source>Confirm transaction fee</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+8"/>
<source>Sent transaction</source>
<translation>Sendita transakcio</translation>
</message>
<message>
<location line="+0"/>
<source>Incoming transaction</source>
<translation>Envenanta transakcio</translation>
</message>
<message>
<location line="+1"/>
<source>Date: %1
Amount: %2
Type: %3
Address: %4
</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+33"/>
<location line="+23"/>
<source>URI handling</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-23"/>
<location line="+23"/>
<source>URI can not be parsed! This can be caused by an invalid BitTor address or malformed URI parameters.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+17"/>
<source>Wallet is <b>encrypted</b> and currently <b>unlocked</b></source>
<translation>Monujo estas <b>ĉifrita</b> kaj nun <b>malŝlosita</b></translation>
</message>
<message>
<location line="+8"/>
<source>Wallet is <b>encrypted</b> and currently <b>locked</b></source>
<translation>Monujo estas <b>ĉifrita</b> kaj nun <b>ŝlosita</b></translation>
</message>
<message>
<location filename="../bitcoin.cpp" line="+111"/>
<source>A fatal error occurred. BitTor can no longer continue safely and will quit.</source>
<translation type="unfinished"/>
</message>
</context>
<context>
<name>ClientModel</name>
<message>
<location filename="../clientmodel.cpp" line="+104"/>
<source>Network Alert</source>
<translation>Reta Averto</translation>
</message>
</context>
<context>
<name>EditAddressDialog</name>
<message>
<location filename="../forms/editaddressdialog.ui" line="+14"/>
<source>Edit Address</source>
<translation>Redaktu Adreson</translation>
</message>
<message>
<location line="+11"/>
<source>&Label</source>
<translation>&Etikedo</translation>
</message>
<message>
<location line="+10"/>
<source>The label associated with this address book entry</source>
<translation>La etikedo interrilatita kun ĉi tiun adreso</translation>
</message>
<message>
<location line="+7"/>
<source>&Address</source>
<translation>&Adreso</translation>
</message>
<message>
<location line="+10"/>
<source>The address associated with this address book entry. This can only be modified for sending addresses.</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../editaddressdialog.cpp" line="+21"/>
<source>New receiving address</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+4"/>
<source>New sending address</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Edit receiving address</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+4"/>
<source>Edit sending address</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+76"/>
<source>The entered address "%1" is already in the address book.</source>
<translation>La adreso enigita "%1" jam ekzistas en la adresaro.</translation>
</message>
<message>
<location line="-5"/>
<source>The entered address "%1" is not a valid BitTor address.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+10"/>
<source>Could not unlock wallet.</source>
<translation>Ne eblis malŝlosi monujon</translation>
</message>
<message>
<location line="+5"/>
<source>New key generation failed.</source>
<translation type="unfinished"/>
</message>
</context>
<context>
<name>GUIUtil::HelpMessageBox</name>
<message>
<location filename="../guiutil.cpp" line="+424"/>
<location line="+12"/>
<source>BitTor-Qt</source>
<translation>BitTor-Qt</translation>
</message>
<message>
<location line="-12"/>
<source>version</source>
<translation>versio</translation>
</message>
<message>
<location line="+2"/>
<source>Usage:</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>command-line options</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+4"/>
<source>UI options</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Set language, for example "de_DE" (default: system locale)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Start minimized</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Show splash screen on startup (default: 1)</source>
<translation type="unfinished"/>
</message>
</context>
<context>
<name>OptionsDialog</name>
<message>
<location filename="../forms/optionsdialog.ui" line="+14"/>
<source>Options</source>
<translation>Opcioj</translation>
</message>
<message>
<location line="+16"/>
<source>&Main</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+6"/>
<source>Optional transaction fee per kB that helps make sure your transactions are processed quickly. Most transactions are 1 kB.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+15"/>
<source>Pay transaction &fee</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+31"/>
<source>Automatically start BitTor after logging in to the system.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>&Start BitTor on system login</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+35"/>
<source>Reset all client options to default.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>&Reset Options</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+13"/>
<source>&Network</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+6"/>
<source>Automatically open the BitTor client port on the router. This only works when your router supports UPnP and it is enabled.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Map port using &UPnP</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+7"/>
<source>Connect to the BitTor network through a SOCKS proxy (e.g. when connecting through Tor).</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>&Connect through SOCKS proxy:</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+9"/>
<source>Proxy &IP:</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+19"/>
<source>IP address of the proxy (e.g. 127.0.0.1)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+7"/>
<source>&Port:</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+19"/>
<source>Port of the proxy (e.g. 9050)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+7"/>
<source>SOCKS &Version:</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+13"/>
<source>SOCKS version of the proxy (e.g. 5)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+36"/>
<source>&Window</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+6"/>
<source>Show only a tray icon after minimizing the window.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>&Minimize to the tray instead of the taskbar</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+7"/>
<source>Minimize instead of exit the application when the window is closed. When this option is enabled, the application will be closed only after selecting Quit in the menu.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>M&inimize on close</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+21"/>
<source>&Display</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+8"/>
<source>User Interface &language:</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+13"/>
<source>The user interface language can be set here. This setting will take effect after restarting BitTor.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+11"/>
<source>&Unit to show amounts in:</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+13"/>
<source>Choose the default subdivision unit to show in the interface and when sending coins.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+9"/>
<source>Whether to show BitTor addresses in the transaction list or not.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>&Display addresses in transaction list</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+71"/>
<source>&OK</source>
<translation>&OK</translation>
</message>
<message>
<location line="+7"/>
<source>&Cancel</source>
<translation>&Nuligu</translation>
</message>
<message>
<location line="+10"/>
<source>&Apply</source>
<translation>&Apliku</translation>
</message>
<message>
<location filename="../optionsdialog.cpp" line="+53"/>
<source>default</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+130"/>
<source>Confirm options reset</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Some settings may require a client restart to take effect.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+0"/>
<source>Do you want to proceed?</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+42"/>
<location line="+9"/>
<source>Warning</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-9"/>
<location line="+9"/>
<source>This setting will take effect after restarting BitTor.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+29"/>
<source>The supplied proxy address is invalid.</source>
<translation type="unfinished"/>
</message>
</context>
<context>
<name>OverviewPage</name>
<message>
<location filename="../forms/overviewpage.ui" line="+14"/>
<source>Form</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+50"/>
<location line="+166"/>
<source>The displayed information may be out of date. Your wallet automatically synchronizes with the BitTor network after a connection is established, but this process has not completed yet.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-124"/>
<source>Balance:</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+29"/>
<source>Unconfirmed:</source>
<translation>Nekonfirmita:</translation>
</message>
<message>
<location line="-78"/>
<source>Wallet</source>
<translation>Monujo</translation>
</message>
<message>
<location line="+107"/>
<source>Immature:</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+13"/>
<source>Mined balance that has not yet matured</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+46"/>
<source><b>Recent transactions</b></source>
<translation><b>Lastaj transakcioj</b></translation>
</message>
<message>
<location line="-101"/>
<source>Your current balance</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+29"/>
<source>Total of transactions that have yet to be confirmed, and do not yet count toward the current balance</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../overviewpage.cpp" line="+116"/>
<location line="+1"/>
<source>out of sync</source>
<translation type="unfinished"/>
</message>
</context>
<context>
<name>PaymentServer</name>
<message>
<location filename="../paymentserver.cpp" line="+107"/>
<source>Cannot start bittor: click-to-pay handler</source>
<translation type="unfinished"/>
</message>
</context>
<context>
<name>QRCodeDialog</name>
<message>
<location filename="../forms/qrcodedialog.ui" line="+14"/>
<source>QR Code Dialog</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+59"/>
<source>Request Payment</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+56"/>
<source>Amount:</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-44"/>
<source>Label:</source>
<translation>Etikedo:</translation>
</message>
<message>
<location line="+19"/>
<source>Message:</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+71"/>
<source>&Save As...</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../qrcodedialog.cpp" line="+62"/>
<source>Error encoding URI into QR Code.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+40"/>
<source>The entered amount is invalid, please check.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+23"/>
<source>Resulting URI too long, try to reduce the text for label / message.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+25"/>
<source>Save QR Code</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+0"/>
<source>PNG Images (*.png)</source>
<translation type="unfinished"/>
</message>
</context>
<context>
<name>RPCConsole</name>
<message>
<location filename="../forms/rpcconsole.ui" line="+46"/>
<source>Client name</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+10"/>
<location line="+23"/>
<location line="+26"/>
<location line="+23"/>
<location line="+23"/>
<location line="+36"/>
<location line="+53"/>
<location line="+23"/>
<location line="+23"/>
<location filename="../rpcconsole.cpp" line="+339"/>
<source>N/A</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-217"/>
<source>Client version</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-45"/>
<source>&Information</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+68"/>
<source>Using OpenSSL version</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+49"/>
<source>Startup time</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+29"/>
<source>Network</source>
<translation>Reto</translation>
</message>
<message>
<location line="+7"/>
<source>Number of connections</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+23"/>
<source>On testnet</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+23"/>
<source>Block chain</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+7"/>
<source>Current number of blocks</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+23"/>
<source>Estimated total blocks</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+23"/>
<source>Last block time</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+52"/>
<source>&Open</source>
<translation>&Malfermu</translation>
</message>
<message>
<location line="+16"/>
<source>Command-line options</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+7"/>
<source>Show the BitTor-Qt help message to get a list with possible BitTor command-line options.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>&Show</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+24"/>
<source>&Console</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-260"/>
<source>Build date</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-104"/>
<source>BitTor - Debug window</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+25"/>
<source>BitTor Core</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+279"/>
<source>Debug log file</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+7"/>
<source>Open the BitTor debug log file from the current data directory. This can take a few seconds for large log files.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+102"/>
<source>Clear console</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../rpcconsole.cpp" line="-30"/>
<source>Welcome to the BitTor RPC console.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Use up and down arrows to navigate history, and <b>Ctrl-L</b> to clear screen.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Type <b>help</b> for an overview of available commands.</source>
<translation type="unfinished"/>
</message>
</context>
<context>
<name>SendCoinsDialog</name>
<message>
<location filename="../forms/sendcoinsdialog.ui" line="+14"/>
<location filename="../sendcoinsdialog.cpp" line="+124"/>
<location line="+5"/>
<location line="+5"/>
<location line="+5"/>
<location line="+6"/>
<location line="+5"/>
<location line="+5"/>
<source>Send Coins</source>
<translation>Sendu Monojn</translation>
</message>
<message>
<location line="+50"/>
<source>Send to multiple recipients at once</source>
<translation>Sendu samtempe al multaj ricevantoj</translation>
</message>
<message>
<location line="+3"/>
<source>Add &Recipient</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+20"/>
<source>Remove all transaction fields</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Clear &All</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+22"/>
<source>Balance:</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+10"/>
<source>123.456 BTC</source>
<translation>123,456 BTC</translation>
</message>
<message>
<location line="+31"/>
<source>Confirm the send action</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>S&end</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../sendcoinsdialog.cpp" line="-59"/>
<source><b>%1</b> to %2 (%3)</source>
<translation><b>%1</b> al %2 (%3)</translation>
</message>
<message>
<location line="+5"/>
<source>Confirm send coins</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Are you sure you want to send %1?</source>
<translation>Ĉu vi vere volas sendi %1?</translation>
</message>
<message>
<location line="+0"/>
<source> and </source>
<translation>kaj</translation>
</message>
<message>
<location line="+23"/>
<source>The recipient address is not valid, please recheck.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+5"/>
<source>The amount to pay must be larger than 0.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+5"/>
<source>The amount exceeds your balance.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+5"/>
<source>The total exceeds your balance when the %1 transaction fee is included.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+6"/>
<source>Duplicate address found, can only send to each address once per send operation.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+5"/>
<source>Error: Transaction creation failed!</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+5"/>
<source>Error: The transaction was rejected. This might happen if some of the coins in your wallet were already spent, such as if you used a copy of wallet.dat and coins were spent in the copy but not marked as spent here.</source>
<translation type="unfinished"/>
</message>
</context>
<context>
<name>SendCoinsEntry</name>
<message>
<location filename="../forms/sendcoinsentry.ui" line="+14"/>
<source>Form</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+15"/>
<source>A&mount:</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+13"/>
<source>Pay &To:</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+34"/>
<source>The address to send the payment to (e.g. Ler4HNAEfwYhBmGXcFP2Po1NpRUEiK8km2)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+60"/>
<location filename="../sendcoinsentry.cpp" line="+26"/>
<source>Enter a label for this address to add it to your address book</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-78"/>
<source>&Label:</source>
<translation>&Etikedo:</translation>
</message>
<message>
<location line="+28"/>
<source>Choose address from address book</source>
<translation>Elektu adreson el adresaro</translation>
</message>
<message>
<location line="+10"/>
<source>Alt+A</source>
<translation>Alt+A</translation>
</message>
<message>
<location line="+7"/>
<source>Paste address from clipboard</source>
<translation>Algluu adreson de tondejo</translation>
</message>
<message>
<location line="+10"/>
<source>Alt+P</source>
<translation>Alt+P</translation>
</message>
<message>
<location line="+7"/>
<source>Remove this recipient</source>
<translation>Forigu ĉi tiun ricevanton</translation>
</message>
<message>
<location filename="../sendcoinsentry.cpp" line="+1"/>
<source>Enter a BitTor address (e.g. Ler4HNAEfwYhBmGXcFP2Po1NpRUEiK8km2)</source>
<translation type="unfinished"/>
</message>
</context>
<context>
<name>SignVerifyMessageDialog</name>
<message>
<location filename="../forms/signverifymessagedialog.ui" line="+14"/>
<source>Signatures - Sign / Verify a Message</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+13"/>
<source>&Sign Message</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+6"/>
<source>You can sign messages with your addresses to prove you own them. Be careful not to sign anything vague, as phishing attacks may try to trick you into signing your identity over to them. Only sign fully-detailed statements you agree to.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+18"/>
<source>The address to sign the message with (e.g. Ler4HNAEfwYhBmGXcFP2Po1NpRUEiK8km2)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+10"/>
<location line="+213"/>
<source>Choose an address from the address book</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-203"/>
<location line="+213"/>
<source>Alt+A</source>
<translation>Alt+A</translation>
</message>
<message>
<location line="-203"/>
<source>Paste address from clipboard</source>
<translation>Algluu adreson de tondejo</translation>
</message>
<message>
<location line="+10"/>
<source>Alt+P</source>
<translation>Alt+P</translation>
</message>
<message>
<location line="+12"/>
<source>Enter the message you want to sign here</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+7"/>
<source>Signature</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+27"/>
<source>Copy the current signature to the system clipboard</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+21"/>
<source>Sign the message to prove you own this BitTor address</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Sign &Message</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+14"/>
<source>Reset all sign message fields</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<location line="+146"/>
<source>Clear &All</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-87"/>
<source>&Verify Message</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+6"/>
<source>Enter the signing address, message (ensure you copy line breaks, spaces, tabs, etc. exactly) and signature below to verify the message. Be careful not to read more into the signature than what is in the signed message itself, to avoid being tricked by a man-in-the-middle attack.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+21"/>
<source>The address the message was signed with (e.g. Ler4HNAEfwYhBmGXcFP2Po1NpRUEiK8km2)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+40"/>
<source>Verify the message to ensure it was signed with the specified BitTor address</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Verify &Message</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+14"/>
<source>Reset all verify message fields</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../signverifymessagedialog.cpp" line="+27"/>
<location line="+3"/>
<source>Enter a BitTor address (e.g. Ler4HNAEfwYhBmGXcFP2Po1NpRUEiK8km2)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-2"/>
<source>Click "Sign Message" to generate signature</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Enter BitTor signature</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+82"/>
<location line="+81"/>
<source>The entered address is invalid.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-81"/>
<location line="+8"/>
<location line="+73"/>
<location line="+8"/>
<source>Please check the address and try again.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-81"/>
<location line="+81"/>
<source>The entered address does not refer to a key.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-73"/>
<source>Wallet unlock was cancelled.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+8"/>
<source>Private key for the entered address is not available.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+12"/>
<source>Message signing failed.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+5"/>
<source>Message signed.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+59"/>
<source>The signature could not be decoded.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+0"/>
<location line="+13"/>
<source>Please check the signature and try again.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+0"/>
<source>The signature did not match the message digest.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+7"/>
<source>Message verification failed.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+5"/>
<source>Message verified.</source>
<translation type="unfinished"/>
</message>
</context>
<context>
<name>SplashScreen</name>
<message>
<location filename="../splashscreen.cpp" line="+22"/>
<source>The BitTor developers</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>[testnet]</source>
<translation type="unfinished"/>
</message>
</context>
<context>
<name>TransactionDesc</name>
<message>
<location filename="../transactiondesc.cpp" line="+20"/>
<source>Open until %1</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+6"/>
<source>%1/offline</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>%1/unconfirmed</source>
<translation>%1/nekonfirmita</translation>
</message>
<message>
<location line="+2"/>
<source>%1 confirmations</source>
<translation>%1 konfirmoj</translation>
</message>
<message>
<location line="+18"/>
<source>Status</source>
<translation type="unfinished"/>
</message>
<message numerus="yes">
<location line="+7"/>
<source>, broadcast through %n node(s)</source>
<translation type="unfinished"><numerusform></numerusform><numerusform></numerusform></translation>
</message>
<message>
<location line="+4"/>
<source>Date</source>
<translation>Dato</translation>
</message>
<message>
<location line="+7"/>
<source>Source</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+0"/>
<source>Generated</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+5"/>
<location line="+17"/>
<source>From</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<location line="+22"/>
<location line="+58"/>
<source>To</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-77"/>
<location line="+2"/>
<source>own address</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-2"/>
<source>label</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+37"/>
<location line="+12"/>
<location line="+45"/>
<location line="+17"/>
<location line="+30"/>
<source>Credit</source>
<translation type="unfinished"/>
</message>
<message numerus="yes">
<location line="-102"/>
<source>matures in %n more block(s)</source>
<translation type="unfinished"><numerusform></numerusform><numerusform></numerusform></translation>
</message>
<message>
<location line="+2"/>
<source>not accepted</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+44"/>
<location line="+8"/>
<location line="+15"/>
<location line="+30"/>
<source>Debit</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-39"/>
<source>Transaction fee</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+16"/>
<source>Net amount</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+6"/>
<source>Message</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>Comment</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>Transaction ID</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Generated coins must mature 120 blocks before they can be spent. When you generated this block, it was broadcast to the network to be added to the block chain. If it fails to get into the chain, its state will change to "not accepted" and it won't be spendable. This may occasionally happen if another node generates a block within a few seconds of yours.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+7"/>
<source>Debug information</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+8"/>
<source>Transaction</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Inputs</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+23"/>
<source>Amount</source>
<translation>Sumo</translation>
</message>
<message>
<location line="+1"/>
<source>true</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+0"/>
<source>false</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-209"/>
<source>, has not been successfully broadcast yet</source>
<translation>, ankoraŭ ne elsendita sukcese</translation>
</message>
<message numerus="yes">
<location line="-35"/>
<source>Open for %n more block(s)</source>
<translation type="unfinished"><numerusform></numerusform><numerusform></numerusform></translation>
</message>
<message>
<location line="+70"/>
<source>unknown</source>
<translation>nekonata</translation>
</message>
</context>
<context>
<name>TransactionDescDialog</name>
<message>
<location filename="../forms/transactiondescdialog.ui" line="+14"/>
<source>Transaction details</source>
<translation>Transakciaj detaloj</translation>
</message>
<message>
<location line="+6"/>
<source>This pane shows a detailed description of the transaction</source>
<translation type="unfinished"/>
</message>
</context>
<context>
<name>TransactionTableModel</name>
<message>
<location filename="../transactiontablemodel.cpp" line="+225"/>
<source>Date</source>
<translation>Dato</translation>
</message>
<message>
<location line="+0"/>
<source>Type</source>
<translation>Tipo</translation>
</message>
<message>
<location line="+0"/>
<source>Address</source>
<translation>Adreso</translation>
</message>
<message>
<location line="+0"/>
<source>Amount</source>
<translation>Sumo</translation>
</message>
<message numerus="yes">
<location line="+57"/>
<source>Open for %n more block(s)</source>
<translation type="unfinished"><numerusform></numerusform><numerusform></numerusform></translation>
</message>
<message>
<location line="+3"/>
<source>Open until %1</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Offline (%1 confirmations)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Unconfirmed (%1 of %2 confirmations)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Confirmed (%1 confirmations)</source>
<translation type="unfinished"/>
</message>
<message numerus="yes">
<location line="+8"/>
<source>Mined balance will be available when it matures in %n more block(s)</source>
<translation type="unfinished"><numerusform></numerusform><numerusform></numerusform></translation>
</message>
<message>
<location line="+5"/>
<source>This block was not received by any other nodes and will probably not be accepted!</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Generated but not accepted</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+43"/>
<source>Received with</source>
<translation>Ricevita kun</translation>
</message>
<message>
<location line="+2"/>
<source>Received from</source>
<translation>Ricevita de</translation>
</message>
<message>
<location line="+3"/>
<source>Sent to</source>
<translation>Sendita al</translation>
</message>
<message>
<location line="+2"/>
<source>Payment to yourself</source>
<translation>Pago al vi mem</translation>
</message>
<message>
<location line="+2"/>
<source>Mined</source>
<translation>Minita</translation>
</message>
<message>
<location line="+38"/>
<source>(n/a)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+199"/>
<source>Transaction status. Hover over this field to show number of confirmations.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>Date and time that the transaction was received.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>Type of transaction.</source>
<translation>Transakcia tipo.</translation>
</message>
<message>
<location line="+2"/>
<source>Destination address of transaction.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>Amount removed from or added to balance.</source>
<translation type="unfinished"/>
</message>
</context>
<context>
<name>TransactionView</name>
<message>
<location filename="../transactionview.cpp" line="+52"/>
<location line="+16"/>
<source>All</source>
<translation>Ĉiuj</translation>
</message>
<message>
<location line="-15"/>
<source>Today</source>
<translation>Hodiaŭ</translation>
</message>
<message>
<location line="+1"/>
<source>This week</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>This month</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Last month</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>This year</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Range...</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+11"/>
<source>Received with</source>
<translation>Ricevita kun</translation>
</message>
<message>
<location line="+2"/>
<source>Sent to</source>
<translation>Sendita al</translation>
</message>
<message>
<location line="+2"/>
<source>To yourself</source>
<translation>Al vi mem</translation>
</message>
<message>
<location line="+1"/>
<source>Mined</source>
<translation>Minita</translation>
</message>
<message>
<location line="+1"/>
<source>Other</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+7"/>
<source>Enter address or label to search</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+7"/>
<source>Min amount</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+34"/>
<source>Copy address</source>
<translation>Kopiu adreson</translation>
</message>
<message>
<location line="+1"/>
<source>Copy label</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Copy amount</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Copy transaction ID</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Edit label</source>
<translation>Redaktu etikedon</translation>
</message>
<message>
<location line="+1"/>
<source>Show transaction details</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+139"/>
<source>Export Transaction Data</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Comma separated file (*.csv)</source>
<translation>Diskoma dosiero (*.csv)</translation>
</message>
<message>
<location line="+8"/>
<source>Confirmed</source>
<translation>Konfirmita</translation>
</message>
<message>
<location line="+1"/>
<source>Date</source>
<translation>Dato</translation>
</message>
<message>
<location line="+1"/>
<source>Type</source>
<translation>Tipo</translation>
</message>
<message>
<location line="+1"/>
<source>Label</source>
<translation>Etikedo</translation>
</message>
<message>
<location line="+1"/>
<source>Address</source>
<translation>Adreso</translation>
</message>
<message>
<location line="+1"/>
<source>Amount</source>
<translation>Sumo</translation>
</message>
<message>
<location line="+1"/>
<source>ID</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+4"/>
<source>Error exporting</source>
<translation>Eraro dum eksportado</translation>
</message>
<message>
<location line="+0"/>
<source>Could not write to file %1.</source>
<translation>Ne eblis skribi al dosiero %1.</translation>
</message>
<message>
<location line="+100"/>
<source>Range:</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+8"/>
<source>to</source>
<translation type="unfinished"/>
</message>
</context>
<context>
<name>WalletModel</name>
<message>
<location filename="../walletmodel.cpp" line="+193"/>
<source>Send Coins</source>
<translation type="unfinished"/>
</message>
</context>
<context>
<name>WalletView</name>
<message>
<location filename="../walletview.cpp" line="+42"/>
<source>&Export</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Export the data in the current tab to a file</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+193"/>
<source>Backup Wallet</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+0"/>
<source>Wallet Data (*.dat)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Backup Failed</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+0"/>
<source>There was an error trying to save the wallet data to the new location.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+4"/>
<source>Backup Successful</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+0"/>
<source>The wallet data was successfully saved to the new location.</source>
<translation type="unfinished"/>
</message>
</context>
<context>
<name>bitcoin-core</name>
<message>
<location filename="../bitcoinstrings.cpp" line="+94"/>
<source>BitTor version</source>
<translation>BitTor-a versio</translation>
</message>
<message>
<location line="+102"/>
<source>Usage:</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-29"/>
<source>Send command to -server or bittord</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-23"/>
<source>List commands</source>
<translation>Listigu instrukciojn</translation>
</message>
<message>
<location line="-12"/>
<source>Get help for a command</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+24"/>
<source>Options:</source>
<translation>Opcioj:</translation>
</message>
<message>
<location line="+24"/>
<source>Specify configuration file (default: bittor.conf)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Specify pid file (default: bittord.pid)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-1"/>
<source>Specify data directory</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-9"/>
<source>Set database cache size in megabytes (default: 25)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-28"/>
<source>Listen for connections on <port> (default: 4693 or testnet: 14693)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+5"/>
<source>Maintain at most <n> connections to peers (default: 125)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-48"/>
<source>Connect to a node to retrieve peer addresses, and disconnect</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+82"/>
<source>Specify your own public address</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Threshold for disconnecting misbehaving peers (default: 100)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-134"/>
<source>Number of seconds to keep misbehaving peers from reconnecting (default: 86400)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-29"/>
<source>An error occurred while setting up the RPC port %u for listening on IPv4: %s</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+27"/>
<source>Listen for JSON-RPC connections on <port> (default: 4694 or testnet: 14694)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+37"/>
<source>Accept command line and JSON-RPC commands</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+76"/>
<source>Run in the background as a daemon and accept commands</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+37"/>
<source>Use the test network</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-112"/>
<source>Accept connections from outside (default: 1 if no -proxy or -connect)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-80"/>
<source>%s, you must set a rpcpassword in the configuration file:
%s
It is recommended you use the following random password:
rpcuser=bittorrpc
rpcpassword=%s
(you do not need to remember this password)
The username and password MUST NOT be the same.
If the file does not exist, create it with owner-readable-only file permissions.
It is also recommended to set alertnotify so you are notified of problems;
for example: alertnotify=echo %%s | mail -s "BitTor Alert" [email protected]
</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+17"/>
<source>An error occurred while setting up the RPC port %u for listening on IPv6, falling back to IPv4: %s</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Bind to given address and always listen on it. Use [host]:port notation for IPv6</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Cannot obtain a lock on data directory %s. BitTor is probably already running.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Error: The transaction was rejected! This might happen if some of the coins in your wallet were already spent, such as if you used a copy of wallet.dat and coins were spent in the copy but not marked as spent here.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+4"/>
<source>Error: This transaction requires a transaction fee of at least %s because of its amount, complexity, or use of recently received funds!</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Execute command when a relevant alert is received (%s in cmd is replaced by message)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Execute command when a wallet transaction changes (%s in cmd is replaced by TxID)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+11"/>
<source>Set maximum size of high-priority/low-fee transactions in bytes (default: 27000)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+6"/>
<source>This is a pre-release test build - use at your own risk - do not use for mining or merchant applications</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+5"/>
<source>Warning: -paytxfee is set very high! This is the transaction fee you will pay if you send a transaction.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Warning: Displayed transactions may not be correct! You may need to upgrade, or other nodes may need to upgrade.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Warning: Please check that your computer's date and time are correct! If your clock is wrong BitTor will not work properly.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Warning: error reading wallet.dat! All keys read correctly, but transaction data or address book entries might be missing or incorrect.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Warning: wallet.dat corrupt, data salvaged! Original wallet.dat saved as wallet.{timestamp}.bak in %s; if your balance or transactions are incorrect you should restore from a backup.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+14"/>
<source>Attempt to recover private keys from a corrupt wallet.dat</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>Block creation options:</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+5"/>
<source>Connect only to the specified node(s)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Corrupted block database detected</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Discover own IP address (default: 1 when listening and no -externalip)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Do you want to rebuild the block database now?</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>Error initializing block database</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Error initializing wallet database environment %s!</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Error loading block database</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+4"/>
<source>Error opening block database</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>Error: Disk space is low!</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Error: Wallet locked, unable to create transaction!</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Error: system error: </source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Failed to listen on any port. Use -listen=0 if you want this.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Failed to read block info</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/><|fim▁hole|> <source>Failed to read block</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Failed to sync block index</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Failed to write block index</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Failed to write block info</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Failed to write block</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Failed to write file info</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Failed to write to coin database</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Failed to write transaction index</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Failed to write undo data</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>Find peers using DNS lookup (default: 1 unless -connect)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Generate coins (default: 0)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>How many blocks to check at startup (default: 288, 0 = all)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>How thorough the block verification is (0-4, default: 3)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+19"/>
<source>Not enough file descriptors available.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+8"/>
<source>Rebuild block chain index from current blk000??.dat files</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+16"/>
<source>Set the number of threads to service RPC calls (default: 4)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+26"/>
<source>Verifying blocks...</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Verifying wallet...</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-69"/>
<source>Imports blocks from external blk000??.dat file</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-76"/>
<source>Set the number of script verification threads (up to 16, 0 = auto, <0 = leave that many cores free, default: 0)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+77"/>
<source>Information</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Invalid -tor address: '%s'</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Invalid amount for -minrelaytxfee=<amount>: '%s'</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Invalid amount for -mintxfee=<amount>: '%s'</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+8"/>
<source>Maintain a full transaction index (default: 0)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>Maximum per-connection receive buffer, <n>*1000 bytes (default: 5000)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Maximum per-connection send buffer, <n>*1000 bytes (default: 1000)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>Only accept block chain matching built-in checkpoints (default: 1)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Only connect to nodes in network <net> (IPv4, IPv6 or Tor)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>Output extra debugging information. Implies all other -debug* options</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Output extra network debugging information</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>Prepend debug output with timestamp</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+5"/>
<source>SSL options: (see the BitTor Wiki for SSL setup instructions)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Select the version of socks proxy to use (4-5, default: 5)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Send trace/debug info to console instead of debug.log file</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Send trace/debug info to debugger</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+5"/>
<source>Set maximum block size in bytes (default: 250000)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Set minimum block size in bytes (default: 0)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>Shrink debug.log file on client startup (default: 1 when no -debug)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Signing transaction failed</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>Specify connection timeout in milliseconds (default: 5000)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+4"/>
<source>System error: </source>
<translation type="unfinished"/>
</message>
<message>
<location line="+4"/>
<source>Transaction amount too small</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Transaction amounts must be positive</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Transaction too large</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+7"/>
<source>Use UPnP to map the listening port (default: 0)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Use UPnP to map the listening port (default: 1 when listening)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Use proxy to reach tor hidden services (default: same as -proxy)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>Username for JSON-RPC connections</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+4"/>
<source>Warning</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Warning: This version is obsolete, upgrade required!</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>You need to rebuild the databases using -reindex to change -txindex</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>wallet.dat corrupt, salvage failed</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-50"/>
<source>Password for JSON-RPC connections</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-67"/>
<source>Allow JSON-RPC connections from specified IP address</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+76"/>
<source>Send commands to node running on <ip> (default: 127.0.0.1)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-120"/>
<source>Execute command when the best block changes (%s in cmd is replaced by block hash)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+147"/>
<source>Upgrade wallet to latest format</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-21"/>
<source>Set key pool size to <n> (default: 100)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-12"/>
<source>Rescan the block chain for missing wallet transactions</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+35"/>
<source>Use OpenSSL (https) for JSON-RPC connections</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-26"/>
<source>Server certificate file (default: server.cert)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Server private key (default: server.pem)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-151"/>
<source>Acceptable ciphers (default: TLSv1+HIGH:!SSLv2:!aNULL:!eNULL:!AH:!3DES:@STRENGTH)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+165"/>
<source>This help message</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+6"/>
<source>Unable to bind to %s on this computer (bind returned error %d, %s)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-91"/>
<source>Connect through socks proxy</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-10"/>
<source>Allow DNS lookups for -addnode, -seednode and -connect</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+55"/>
<source>Loading addresses...</source>
<translation>Ŝarĝante adresojn...</translation>
</message>
<message>
<location line="-35"/>
<source>Error loading wallet.dat: Wallet corrupted</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Error loading wallet.dat: Wallet requires newer version of BitTor</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+93"/>
<source>Wallet needed to be rewritten: restart BitTor to complete</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-95"/>
<source>Error loading wallet.dat</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+28"/>
<source>Invalid -proxy address: '%s'</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+56"/>
<source>Unknown network specified in -onlynet: '%s'</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-1"/>
<source>Unknown -socks proxy version requested: %i</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-96"/>
<source>Cannot resolve -bind address: '%s'</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Cannot resolve -externalip address: '%s'</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+44"/>
<source>Invalid amount for -paytxfee=<amount>: '%s'</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Invalid amount</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-6"/>
<source>Insufficient funds</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+10"/>
<source>Loading block index...</source>
<translation>Ŝarĝante blok-indekson...</translation>
</message>
<message>
<location line="-57"/>
<source>Add a node to connect to and attempt to keep the connection open</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-25"/>
<source>Unable to bind to %s on this computer. BitTor is probably already running.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+64"/>
<source>Fee per KB to add to transactions you send</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+19"/>
<source>Loading wallet...</source>
<translation>Ŝarĝante monujon...</translation>
</message>
<message>
<location line="-52"/>
<source>Cannot downgrade wallet</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Cannot write default address</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+64"/>
<source>Rescanning...</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-57"/>
<source>Done loading</source>
<translation>Ŝarĝado finitas</translation>
</message>
<message>
<location line="+82"/>
<source>To use the %s option</source>
<translation>Por uzi la opcion %s</translation>
</message>
<message>
<location line="-74"/>
<source>Error</source>
<translation>Eraro</translation>
</message>
<message>
<location line="-31"/>
<source>You must set rpcpassword=<password> in the configuration file:
%s
If the file does not exist, create it with owner-readable-only file permissions.</source>
<translation type="unfinished"/>
</message>
</context>
</TS><|fim▁end|>
| |
<|file_name|>GenomeAFS.py<|end_file_name|><|fim▁begin|>'''
Copyleft Feb 11, 2017 Arya Iranmehr, PhD Student, Bafna Lab, UC San Diego, Email: [email protected]
'''
import numpy as np;
np.set_printoptions(linewidth=200, precision=5, suppress=True)
import pandas as pd;
pd.options.display.max_rows = 20;
pd.options.display.expand_frame_repr = False
import pylab as plt;
import os;
home = os.path.expanduser('~') + '/'<|fim▁hole|>import Scripts.KyrgysHAPH.Plot as kplt
kplt.savefig()
reload(est)
a=pd.read_pickle(kutl.path+'/data/freq.df')
def plotSFSall(chrom=None):
f=est.Estimate.getSAFS
a=pd.read_pickle(kutl.path+'/data/freq.df')
if chrom is not None:
suff='.chr{}'.format(chrom)
a=a.loc[[chrom]]
kplt.plotSFSold2(a, fold=False, fname='AFS' + suff);
kplt.plotSFSold2(a, fold=False, fname='Scaled-AFS' + suff, f=f)
kplt.plotSFSold2(a, fold=True, fname='AFS' + suff, );
kplt.plotSFSold2(a, fold=True, fname='Scaled-AFS' + suff, f=f)
def plotChromAll():
a.apply(lambda x: kplt.SFSChromosomwise(x, False, False))
a.apply(lambda x: kplt.SFSChromosomwise(x, False, True))
a.apply(lambda x: kplt.SFSChromosomwise(x, True, False))
a.apply(lambda x: kplt.SFSChromosomwise(x, True, True))
def SFS():
plotSFSall()
plotSFSall('X')
plotSFSall('Y')
plotChromAll()<|fim▁end|>
|
import Utils.Estimate as est
import Utils.Plots as pplt
import Scripts.KyrgysHAPH.Utils as kutl
|
<|file_name|>network.cpp<|end_file_name|><|fim▁begin|>//
//
//
#include "network.hpp"
#include "session.hpp"
namespace led_d
{
network_t::network_t (asio::io_service &io_service,
core::port_t::value_t port,
queue_t &queue)
: m_acceptor (io_service, asio::ip::tcp::endpoint (asio::ip::tcp::v4 (), port)),
m_socket (io_service),
m_queue (queue)
{
do_accept ();
}
void network_t::do_accept ()
{
m_acceptor.async_accept
(m_socket,
[this] (std::error_code err_code)
{
if (!err_code) {
std::make_shared<session_t>(std::move (m_socket), m_queue)->start ();
}<|fim▁hole|> do_accept ();
}
);
}
} // namespace led_d<|fim▁end|>
| |
<|file_name|>VarsHistory.ts<|end_file_name|><|fim▁begin|>// Copyright 2017 David Holmes. All Rights Reserved.
// Copyright 2016 Erik Neumann. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the 'License');
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at<|fim▁hole|>// 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.
/**
* @hidden
*/
export default class VarsHistory {
/**
*
*/
constructor() {
// Do nothing yet.
}
}<|fim▁end|>
|
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.