prompt
large_stringlengths 70
991k
| completion
large_stringlengths 0
1.02k
|
---|---|
<|file_name|>hessian_identity_list.py<|end_file_name|><|fim▁begin|>from dolfin import *
from dolfin_adjoint import *
parameters["adjoint"]["cache_factorizations"] = True
mesh = UnitSquareMesh(3, 3)
V = FunctionSpace(mesh, "R", 0)
test = TestFunction(V)
trial = TrialFunction(V)
def main(m):
u = interpolate(Constant(0.1), V, name="Solution")
F = inner(u*u, test)*dx - inner(m, test)*dx
solve(F == 0, u)<|fim▁hole|> solve(lhs(F) == rhs(F), u)
return u
if __name__ == "__main__":
m = interpolate(Constant(2.13), V, name="Parameter1")
u = main(m)
parameters["adjoint"]["stop_annotating"] = True
J = Functional((inner(u, u))**3*dx + inner(m, m)*dx, name="NormSquared")
Jm = assemble(inner(u, u)**3*dx + inner(m, m)*dx)
controls = [Control(m)]
dJdm = compute_gradient(J, controls, forget=None)
HJm = hessian(J, controls, warn=False)
def Jhat(m):
m = m[0] # the control is a list of length one, so Jhat will have to
# except a list as well
u = main(m)
return assemble(inner(u, u)**3*dx + inner(m, m)*dx)
direction = [interpolate(Constant(0.1), V)]
minconv = taylor_test(Jhat, controls, Jm, dJdm, HJm=HJm,
perturbation_direction=direction)
assert minconv > 2.9<|fim▁end|> | F = inner(sin(u)*u*u*trial, test)*dx - inner(u**4, test)*dx |
<|file_name|>shard.go<|end_file_name|><|fim▁begin|>/*
Copyright 2017 Google 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 agreedto in writing, software
distributed under the License is distributed on an "AS IS" BASIS,<|fim▁hole|>See the License for the specific language governing permissions and
limitations under the License.
*/
package test
import (
"testing"
"golang.org/x/net/context"
"github.com/golang/protobuf/proto"
"vitess.io/vitess/go/vt/topo"
topodatapb "vitess.io/vitess/go/vt/proto/topodata"
)
// checkShard verifies the Shard operations work correctly
func checkShard(t *testing.T, ts *topo.Server) {
ctx := context.Background()
if err := ts.CreateKeyspace(ctx, "test_keyspace", &topodatapb.Keyspace{}); err != nil {
t.Fatalf("CreateKeyspace: %v", err)
}
// Check GetShardNames returns [], nil for existing keyspace with no shards.
if names, err := ts.GetShardNames(ctx, "test_keyspace"); err != nil || len(names) != 0 {
t.Errorf("GetShardNames(keyspace with no shards) didn't return [] nil: %v %v", names, err)
}
if err := ts.CreateShard(ctx, "test_keyspace", "b0-c0"); err != nil {
t.Fatalf("CreateShard: %v", err)
}
if err := ts.CreateShard(ctx, "test_keyspace", "b0-c0"); err != topo.ErrNodeExists {
t.Errorf("CreateShard called second time, got: %v", err)
}
// Delete shard and see if we can re-create it.
if err := ts.DeleteShard(ctx, "test_keyspace", "b0-c0"); err != nil {
t.Fatalf("DeleteShard: %v", err)
}
if err := ts.DeleteShard(ctx, "test_keyspace", "b0-c0"); err != topo.ErrNoNode {
t.Errorf("DeleteShard(again): %v", err)
}
if err := ts.CreateShard(ctx, "test_keyspace", "b0-c0"); err != nil {
t.Fatalf("CreateShard: %v", err)
}
// Test getting an invalid shard returns ErrNoNode.
if _, err := ts.GetShard(ctx, "test_keyspace", "666"); err != topo.ErrNoNode {
t.Errorf("GetShard(666): %v", err)
}
// Test UpdateShardFields works.
other := &topodatapb.TabletAlias{Cell: "ny", Uid: 82873}
_, err := ts.UpdateShardFields(ctx, "test_keyspace", "b0-c0", func(si *topo.ShardInfo) error {
si.MasterAlias = other
return nil
})
if err != nil {
t.Fatalf("UpdateShardFields error: %v", err)
}
si, err := ts.GetShard(ctx, "test_keyspace", "b0-c0")
if err != nil {
t.Fatalf("GetShard: %v", err)
}
if !proto.Equal(si.Shard.MasterAlias, other) {
t.Fatalf("shard.MasterAlias = %v, want %v", si.Shard.MasterAlias, other)
}
// test GetShardNames
shards, err := ts.GetShardNames(ctx, "test_keyspace")
if err != nil {
t.Errorf("GetShardNames: %v", err)
}
if len(shards) != 1 || shards[0] != "b0-c0" {
t.Errorf(`GetShardNames: want [ "b0-c0" ], got %v`, shards)
}
if _, err := ts.GetShardNames(ctx, "test_keyspace666"); err != topo.ErrNoNode {
t.Errorf("GetShardNames(666): %v", err)
}
}<|fim▁end|> | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
<|file_name|>treeshaking_spec.ts<|end_file_name|><|fim▁begin|>/**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
import '@angular/compiler';
import * as fs from 'fs';
import * as path from 'path';
const UTF8 = {
encoding: 'utf-8'
};
const PACKAGE = 'angular/packages/core/test/bundling/hello_world_r2';
describe('treeshaking with uglify', () => {
let content: string;
const contentPath = require.resolve(path.join(PACKAGE, 'bundle.debug.min.js'));
beforeAll(() => {
content = fs.readFileSync(contentPath, UTF8);
});
it('should drop unused TypeScript helpers', () => {
expect(content).not.toContain('__asyncGenerator');
});
it('should not contain rxjs from commonjs distro', () => {
expect(content).not.toContain('commonjsGlobal');
expect(content).not.toContain('createCommonjsModule');<|fim▁hole|><|fim▁end|> | });
}); |
<|file_name|>app.ts<|end_file_name|><|fim▁begin|>/// <reference path="../../src/bobril.d.ts"/>
/// <reference path="../../src/bobril.mouse.d.ts"/>
module MouseOwnerApp {
var button: IBobrilComponent = {
init(ctx: any, me: IBobrilNode): void {
ctx.backColor = "#f0f0f0";
},
render(ctx: any, me: IBobrilNode): void {
me.tag = "div";
me.style = b.assign({}, ctx.data.style);
me.children = ctx.data.children;
me.style.backgroundColor = ctx.backColor;
},
onMouseDown(ctx: any): boolean {
ctx.backColor = "red";
b.registerMouseOwner(ctx);
b.invalidate(ctx);
return true;
},
onMouseUp(ctx: any): boolean {
ctx.backColor = "#f0f0f0";
if (b.isMouseOwner(ctx)) {
b.releaseMouseOwner();
}
b.invalidate(ctx);<|fim▁hole|>
function twice(obj: any): any[] { return [obj, b.cloneNode(obj)]; }
b.init(() => {
return twice({
tag: "div",
style: { height: 500, width: 500, border: "solid 1px", position: "relative", cssFloat: "left" },
children: {
component: button, data: {
style: { width: 120, height: 20, position: "absolute", border: "1px solid #000", left: 190, top: 240 },
children: "Click and drag out"
}
}
});
});
}<|fim▁end|> | return true;
}
}; |
<|file_name|>evernote_exporter.py<|end_file_name|><|fim▁begin|>from fnmatch import fnmatch
import os
from sys import exit
import html2text
import re
import urllib
import shutil
import logging
import sqlite3
from sys import stdout
logging.basicConfig(filename='error_log.log', filemode='a')
class BackupEvernote(object):
def __init__(self, evernote_dir, db_dir='', output_dir=''):
self.forbidden = ["?", "#", "/", "\\", "*", '"', "<", ">", "|", "%", " "]
self.fb_w_trail = self.forbidden
del self.fb_w_trail[2]
self.evernote_dir = evernote_dir
self.db_dir = db_dir<|fim▁hole|> stdout.flush()
def _exception(self, msg, file_path, e):
logging.error(e)
while True:
inp = input('Cannot %s: %s\n'
'Error: %s\n'
'Skip & continue? y/n: ' % (msg, file_path, e))
if inp == 'y':
break
else:
exit(0)
return
def _multi_asterisk_fix(self, matchobj):
return matchobj.group(0)[1:]
def _get_pt(self, string):
path = string.split('[')[1].split(']')[0]
title = string.split('(')[1].split(')')[0]
return path, title
def _image_url_fix(self, matchobj):
url = ''
string = matchobj.group(0)
# remove escape chars
if '\n' in string:
string = string.replace('\n', ' ')
# this is a url
if '![' not in string:
url, _ = self._get_pt(string)
return '%s' % url
# image contains url
url_pat = re.compile(r'.(\[.*\])\(.*\)\(.*\)$', re.MULTILINE)
if re.match(url_pat, string):
url = string.rpartition('(')[-1].strip(')')
# image with or without url
title, path = self._get_pt(string)
path = '%s/%s/%s' % (self.output_dir, 'uncategorized', path)
# todo: image path (remove random dash? -_) i.e t seal img
path = self._remove_chars(path, self.fb_w_trail, trail=True)
path += '?800'
if not url:
return '{{%s|%s}}' % (path, title)
else:
return '[[%s|{{%s|%s}}]]' % (url, path, title)
def _remove_asterisks(self, matchobj):
return re.sub(r'\**', '', matchobj.group(0))
def _fix_spacing(self, matchobj):
# todo: add wider bullet conversions i.e imac note
string = matchobj.group(0)
s_len = len(string) - 1
if s_len <= 1:
return string
elif s_len == 2:
return '*'
elif s_len == 6:
return ' *'
elif s_len == 7:
return ' *'
elif s_len == 11:
return ' *'
else:
return string
def to_zim_syntax(self, content):
""" Consider editing this func to fit the syntax of your chosen note taking software"""
# headers
# todo: remove heading chars / do not add heading if proceeded by image or url
# todo: only ensure 1 h1 header (first), replace other h1's with h2
new_c = content.replace('####', '=').('### ', '== ').replace('## ', '==== ').replace('# ', '====== ')
# line separation?
# todo: remake regex r'[#*_-]{3,}' not proceeded by words (\W) i.e jsand
line_pat = re.compile(r'^\*[^\S\n]*\*[^\S\n]*\*\n', re.MULTILINE)
new_c = re.sub(line_pat, ('-' * 80), new_c)
# todo: regex to replace 3+ line breaks with 2
# todo: regex for bold text, 2 * followed by words then 2 *
# todo: replace \- at start of the line with bullet
# fix bullet lists
new_c = re.sub(r'\*[^\S\n]+?\*', self._multi_asterisk_fix, new_c) # multiple asterisks on same line
spaces = re.compile(r'^[^\S\n]*\*', re.MULTILINE)
new_c = re.sub(spaces, self._fix_spacing, new_c)
# fix urls and images
new_c = re.sub(r'\*{2}(\[)|\)\*{2}', self._remove_asterisks, new_c)
# new_c = re.sub(r'!*\[[^\]]*\]\([^\)]*\)', self._image_url_fix, new_c)
new_c = re.sub(r'!*[\\\[]*\[[^\]]*[\\\]]*\([^\)]*[\]\)]*(\([^\)]*\))*', self._image_url_fix, new_c)
return new_c
def edit_file(self, full_path, filename, to_zim=False):
text_maker = html2text.HTML2Text()
with open(full_path, 'r') as f:
html = f.read()
content = ''
if html:
try:
content = text_maker.handle(unicode(html, errors='ignore'))
content = content.encode('ascii', 'ignore')
content = content.split('\00')[0] # remove null chars
content = content.replace('\.', '.') # remove escape chars
except Exception as e:
self._exception('convert content of note to markdown', full_path, e)
else:
content = ''
if to_zim:
content = self.to_zim_syntax(content)
fn_path = self._rename_file(full_path, filename)
with open(fn_path, 'w') as f:
try:
f.write(content.encode('ascii', 'ignore'))
except Exception as e:
self._exception('save note', fn_path, e)
return
def _remove_chars(self, stack_or_nb, folder_chars, trail=False):
try:
if not trail:
stack_or_nb = stack_or_nb.replace('/', '&')
for char in folder_chars:
if char in stack_or_nb:
stack_or_nb = stack_or_nb.replace(char, '_')
except Exception:
raise
finally:
return stack_or_nb
def _rename_file(self, full_path, filename, trail=False):
filename = self._remove_chars(filename, self.forbidden, trail)
renamed = filename.replace('.html', '.txt')
old_filename = full_path.rpartition('/')[-1]
return full_path.replace(old_filename, renamed)
def nbooks_to_dirs(self):
""" creates notebook & notebook stack folder structure containing all respective notes"""
print "\nOrganizing notes by directory (based on notebooks & stacks)..."
copied = []
con = sqlite3.connect(self.db_dir)
notebooks = con.execute("SELECT * FROM notebook_attr;").fetchall()
folder_chars = self.forbidden
del folder_chars[2]
for ind, i in enumerate(notebooks):
nb_id, notebook, stack = i[0], i[1], i[2]
stack = self._remove_chars(stack, folder_chars)
notebook = self._remove_chars(notebook, folder_chars)
nb_notes = con.execute('SELECT * FROM note_attr WHERE note_attr.notebook_uid = %s;' % nb_id)
notes_set = {i[1] for i in nb_notes}
s_dir = ''
if notebook and not stack:
notebook_dir = self.output_dir + '/' + notebook
if not os.path.isdir(notebook_dir):
os.mkdir(notebook_dir)
s_dir = notebook_dir
else:
if stack:
stack_path = self.output_dir + '/' + stack
if not os.path.isdir(stack_path):
os.mkdir(stack_path)
s_dir = stack_path
if notebook:
nb_in_stack = self.output_dir + '/%s/%s' % (stack, notebook)
if not os.path.isdir(nb_in_stack):
os.mkdir(nb_in_stack)
s_dir = nb_in_stack
for p, d, files in os.walk(self.evernote_dir):
for f in files:
fl = urllib.unquote(f)
fl_name = fl.rpartition('.')[0]
f_path = os.path.join(p, f)
if fl_name in notes_set:
copied.append(fl)
out_path = os.path.join(s_dir, f)
shutil.copy(f_path, out_path)
os.rename(out_path, os.path.join(s_dir, fl))
self._counter(ind, 'notebooks/stacks exported')
self.transfer_uncategorized(copied)
return
def transfer_uncategorized(self, copied):
print "\nTransfering the rest of the files that do not belong to a notebook..."
uncategorized = os.path.join(self.output_dir, 'uncategorized')
os.mkdir(uncategorized)
ind = 0
for fl in os.listdir(self.evernote_dir):
if fl not in copied:
f_path = os.path.join(self.evernote_dir, fl)
out_path = os.path.join(uncategorized, fl)
try:
shutil.copy(f_path, out_path)
except IOError:
shutil.copytree(f_path, out_path)
finally:
ind += 1
self._counter(ind, 'copied files/dirs')
# rename all files and folders within output folder
for p, dirs, files in os.walk(self.output_dir):
for d in dirs:
new_d = self._remove_chars(d, self.forbidden)
new_d = new_d.replace('.html', '.txt')
os.rename(os.path.join(p, d), os.path.join(p, new_d))
for p, dirs, files in os.walk(self.output_dir):
for f in files:
new_f = self._remove_chars(f, self.forbidden)
new_f = new_f.replace('.html', '.txt')
os.rename(os.path.join(p, f), os.path.join(p, new_f))
return
def to_markdown(self, zim_sintax=False):
print "\nConverting note syntax..."
c_dir = self.output_dir or self.evernote_dir
ind = 0
for p, d, files in os.walk(c_dir):
for f in files:
fl_path = os.path.join(p, f)
if fnmatch(f, '*.txt'):
self.edit_file(fl_path, f, zim_sintax)
ind += 1
self._counter(ind, 'edited files')
def backup(self, notebooks_to_dirs=True, to_markdown=False, zim_sintax=False):
if notebooks_to_dirs:
self.nbooks_to_dirs()
if to_markdown or zim_sintax:
self.to_markdown(zim_sintax)
return
if __name__ == '__main__':
notes_dir = '/media/truecrypt2'
db_dir = '/home/unknown/evernote_backup/Databases/shawnx22.exb'
output_dir = '/home/unknown/tmp_notes'
# output_dir = '/home/evernote_backup/Notes'
ev = BackupEvernote(notes_dir, db_dir, output_dir)
ev.backup()
ev.to_markdown(zim_sintax=True)<|fim▁end|> | self.output_dir = output_dir
def _counter(self, ind, msg):
stdout.write('\r' + '\t%s: %s' % (msg, ind)) |
<|file_name|>nvp_qos_queue.py<|end_file_name|><|fim▁begin|># vim: tabstop=4 shiftwidth=4 softtabstop=4
# Copyright 2013 Nicira Inc.
# All Rights Reserved
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
import logging
from quantumclient.quantum import v2_0 as quantumv20
class ListQoSQueue(quantumv20.ListCommand):
"""List queues that belong to a given tenant."""
resource = 'qos_queue'
log = logging.getLogger(__name__ + '.ListQoSQueue')
_formatters = {}
list_columns = ['id', 'name', 'min', 'max',
'qos_marking', 'dscp', 'default']
class ShowQoSQueue(quantumv20.ShowCommand):
"""Show information of a given queue."""
resource = 'qos_queue'
log = logging.getLogger(__name__ + '.ShowQoSQueue')
allow_names = True
<|fim▁hole|>class CreateQoSQueue(quantumv20.CreateCommand):
"""Create a queue."""
resource = 'qos_queue'
log = logging.getLogger(__name__ + '.CreateQoSQueue')
def add_known_arguments(self, parser):
parser.add_argument(
'name', metavar='NAME',
help='Name of queue')
parser.add_argument(
'--min',
help='min-rate'),
parser.add_argument(
'--max',
help='max-rate'),
parser.add_argument(
'--qos-marking',
help='qos marking untrusted/trusted'),
parser.add_argument(
'--default',
default=False,
help=('If true all ports created with be the size of this queue'
' if queue is not specified')),
parser.add_argument(
'--dscp',
help='Differentiated Services Code Point'),
def args2body(self, parsed_args):
params = {'name': parsed_args.name,
'default': parsed_args.default}
if parsed_args.min:
params['min'] = parsed_args.min
if parsed_args.max:
params['max'] = parsed_args.max
if parsed_args.qos_marking:
params['qos_marking'] = parsed_args.qos_marking
if parsed_args.dscp:
params['dscp'] = parsed_args.dscp
if parsed_args.tenant_id:
params['tenant_id'] = parsed_args.tenant_id
return {'qos_queue': params}
class DeleteQoSQueue(quantumv20.DeleteCommand):
"""Delete a given queue."""
log = logging.getLogger(__name__ + '.DeleteQoSQueue')
resource = 'qos_queue'
allow_names = True<|fim▁end|> | |
<|file_name|>page-two.component.ts<|end_file_name|><|fim▁begin|>import {Component, OnInit} from '@angular/core';
@Component({
selector: 'test-page-two',
templateUrl: './page-two.component.html',
styleUrls: [
'./page-two.component.scss'
]
})
export class PageTwoComponent implements OnInit {
message: string;
constructor() {
this.message = '';
}
ngOnInit(): void {
this.message = 'PageTwoComponent message';
}
<|fim▁hole|>}<|fim▁end|> | |
<|file_name|>types_swagger_doc_generated.go<|end_file_name|><|fim▁begin|>/*
Copyright 2016 The Kubernetes Authors.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package v1alpha1
// This file contains a collection of methods that can be used from go-restful to
// generate Swagger API documentation for its models. Please read this PR for more
// information on the implementation: https://github.com/emicklei/go-restful/pull/215
//
// TODOs are ignored from the parser (e.g. TODO(andronat):... || TODO:...) if and only if
// they are on one line! For multiple line or blocks that you want to ignore use ---.
// Any context after a --- is ignored.
//
// Those methods can be generated by using hack/update-generated-swagger-docs.sh
// AUTO-GENERATED FUNCTIONS START HERE
var map_AdmissionHookClientConfig = map[string]string{
"": "AdmissionHookClientConfig contains the information to make a TLS connection with the webhook",
"service": "Service is a reference to the service for this webhook. If there is only one port open for the service, that port will be used. If there are multiple ports open, port 443 will be used if it is open, otherwise it is an error. Required",
"urlPath": "URLPath is an optional field that specifies the URL path to use when posting the AdmissionReview object.",
"caBundle": "CABundle is a PEM encoded CA bundle which will be used to validate webhook's server certificate. Required",
}
func (AdmissionHookClientConfig) SwaggerDoc() map[string]string {
return map_AdmissionHookClientConfig
}
var map_ExternalAdmissionHook = map[string]string{
"": "ExternalAdmissionHook describes an external admission webhook and the resources and operations it applies to.",
"name": "The name of the external admission webhook. Name should be fully qualified, e.g., imagepolicy.kubernetes.io, where \"imagepolicy\" is the name of the webhook, and kubernetes.io is the name of the organization. Required.",
"clientConfig": "ClientConfig defines how to communicate with the hook. Required",
"rules": "Rules describes what operations on what resources/subresources the webhook cares about. The webhook cares about an operation if it matches _any_ Rule.",
"failurePolicy": "FailurePolicy defines how unrecognized errors from the admission endpoint are handled - allowed values are Ignore or Fail. Defaults to Ignore.",
}
func (ExternalAdmissionHook) SwaggerDoc() map[string]string {
return map_ExternalAdmissionHook
}
var map_ExternalAdmissionHookConfiguration = map[string]string{
"": "ExternalAdmissionHookConfiguration describes the configuration of initializers.",
"metadata": "Standard object metadata; More info: https://git.k8s.io/community/contributors/devel/api-conventions.md#metadata.",
"externalAdmissionHooks": "ExternalAdmissionHooks is a list of external admission webhooks and the affected resources and operations.",
}
func (ExternalAdmissionHookConfiguration) SwaggerDoc() map[string]string {
return map_ExternalAdmissionHookConfiguration
}
var map_ExternalAdmissionHookConfigurationList = map[string]string{
"": "ExternalAdmissionHookConfigurationList is a list of ExternalAdmissionHookConfiguration.",
"metadata": "Standard list metadata. More info: https://git.k8s.io/community/contributors/devel/api-conventions.md#types-kinds",
"items": "List of ExternalAdmissionHookConfiguration.",
}
func (ExternalAdmissionHookConfigurationList) SwaggerDoc() map[string]string {
return map_ExternalAdmissionHookConfigurationList
}
var map_Initializer = map[string]string{
"": "Initializer describes the name and the failure policy of an initializer, and what resources it applies to.",
"name": "Name is the identifier of the initializer. It will be added to the object that needs to be initialized. Name should be fully qualified, e.g., alwayspullimages.kubernetes.io, where \"alwayspullimages\" is the name of the webhook, and kubernetes.io is the name of the organization. Required",
"rules": "Rules describes what resources/subresources the initializer cares about. The initializer cares about an operation if it matches _any_ Rule. Rule.Resources must not include subresources.",
}
func (Initializer) SwaggerDoc() map[string]string {
return map_Initializer
}
var map_InitializerConfiguration = map[string]string{
"": "InitializerConfiguration describes the configuration of initializers.",
"metadata": "Standard object metadata; More info: https://git.k8s.io/community/contributors/devel/api-conventions.md#metadata.",
"initializers": "Initializers is a list of resources and their default initializers Order-sensitive. When merging multiple InitializerConfigurations, we sort the initializers from different InitializerConfigurations by the name of the InitializerConfigurations; the order of the initializers from the same InitializerConfiguration is preserved.",
}
func (InitializerConfiguration) SwaggerDoc() map[string]string {
return map_InitializerConfiguration
}
var map_InitializerConfigurationList = map[string]string{
"": "InitializerConfigurationList is a list of InitializerConfiguration.",
"metadata": "Standard list metadata. More info: https://git.k8s.io/community/contributors/devel/api-conventions.md#types-kinds",
"items": "List of InitializerConfiguration.",
}
func (InitializerConfigurationList) SwaggerDoc() map[string]string {
return map_InitializerConfigurationList
}
var map_Rule = map[string]string{
"": "Rule is a tuple of APIGroups, APIVersion, and Resources.It is recommended to make sure that all the tuple expansions are valid.",
"apiGroups": "APIGroups is the API groups the resources belong to. '*' is all groups. If '*' is present, the length of the slice must be one. Required.",
"apiVersions": "APIVersions is the API versions the resources belong to. '*' is all versions. If '*' is present, the length of the slice must be one. Required.",
"resources": "Resources is a list of resources this rule applies to.\n\nFor example: 'pods' means pods. 'pods/log' means the log subresource of pods. '*' means all resources, but not subresources. 'pods/*' means all subresources of pods. '*/scale' means all scale subresources. '*/*' means all resources and their subresources.\n\nIf wildcard is present, the validation rule will ensure resources do not overlap with each other.\n\nDepending on the enclosing object, subresources might not be allowed. Required.",
}
func (Rule) SwaggerDoc() map[string]string {
return map_Rule
}
var map_RuleWithOperations = map[string]string{
"": "RuleWithOperations is a tuple of Operations and Resources. It is recommended to make sure that all the tuple expansions are valid.",
"operations": "Operations is the operations the admission hook cares about - CREATE, UPDATE, or * for all operations. If '*' is present, the length of the slice must be one. Required.",
}
func (RuleWithOperations) SwaggerDoc() map[string]string {<|fim▁hole|> "": "ServiceReference holds a reference to Service.legacy.k8s.io",
"namespace": "Namespace is the namespace of the service Required",
"name": "Name is the name of the service Required",
}
func (ServiceReference) SwaggerDoc() map[string]string {
return map_ServiceReference
}
// AUTO-GENERATED FUNCTIONS END HERE<|fim▁end|> | return map_RuleWithOperations
}
var map_ServiceReference = map[string]string{ |
<|file_name|>FormDialog.messages.js<|end_file_name|><|fim▁begin|>import { defineMessages } from 'react-intl';
export default defineMessages({
save: {
id: 'cboard.components.FormDialog.save',
defaultMessage: 'Save'
},
cancel: {
id: 'cboard.components.FormDialog.cancel',<|fim▁hole|><|fim▁end|> | defaultMessage: 'Cancel'
}
}); |
<|file_name|>linearDirection.H<|end_file_name|><|fim▁begin|>/*---------------------------------------------------------------------------*\
========= |
\\ / F ield | OpenFOAM: The Open Source CFD Toolbox
\\ / O peration |
\\ / A nd | Copyright (C) 2011-2015 OpenFOAM Foundation
\\/ M anipulation |
-------------------------------------------------------------------------------
License
This file is part of OpenFOAM.
OpenFOAM 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.
OpenFOAM 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 OpenFOAM. If not, see <http://www.gnu.org/licenses/>.
Class
Foam::extrudeModels::linearDirection
Description
Extrudes by transforming points in a specified direction by a given distance
\*---------------------------------------------------------------------------*/
#ifndef linearDirection_H
#define linearDirection_H
#include "point.H"
#include "extrudeModel.H"
// * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * //
namespace Foam
{
namespace extrudeModels
{
/*---------------------------------------------------------------------------*\
Class linearDirection Declaration
\*---------------------------------------------------------------------------*/
class linearDirection
:
public extrudeModel
{
// Private data
//- Extrude direction
vector direction_;
//- Layer thickness
scalar thickness_;
public:
//- Runtime type information
TypeName("linearDirection");
// Constructors
//- Construct from dictionary
linearDirection(const dictionary& dict);<|fim▁hole|> virtual ~linearDirection();
// Member Operators
point operator()
(
const point& surfacePoint,
const vector& surfaceNormal,
const label layer
) const;
};
// * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * //
} // End namespace extrudeModels
} // End namespace Foam
// * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * //
#endif
// ************************************************************************* //<|fim▁end|> |
//- Destructor |
<|file_name|>worker.py<|end_file_name|><|fim▁begin|>#!/usr/bin/python
# -*- coding: utf-8 -*-
#
# Copyright (c) 2013 ASMlover. 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 ofconditions 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 materialsprovided with the
# distribution.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
# FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
# COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
# INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
# BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
# LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
# LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
# ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
# POSSIBILITY OF SUCH DAMAGE.
import zmq
import time
if __name__ == '__main__':
ctx = zmq.Context()
worker = ctx.socket(zmq.PULL)
worker.connect('tcp://localhost:5555')
<|fim▁hole|> sinker = ctx.socket(zmq.PUSH)
sinker.connect('tcp://localhost:6666')
print 'all workers are ready ...'
while True:
try:
msg = worker.recv()
print 'begin to work on task use `%s ms`' % msg
time.sleep(int(msg) * 0.001)
print '\tfinished this task'
sinker.send('finished task which used `%s ms`' % msg)
except KeyboardInterrupt:
break
sinker.close()
worker.close()<|fim▁end|> | |
<|file_name|>single_server_kill_reconnect.js<|end_file_name|><|fim▁begin|>var mongodb = process.env['TEST_NATIVE'] != null ? require('../../lib/mongodb').native() : require('../../lib/mongodb').pure();
var testCase = require('../../deps/nodeunit').testCase,
debug = require('util').debug,
inspect = require('util').inspect,
nodeunit = require('../../deps/nodeunit'),
gleak = require('../../tools/gleak'),
Db = mongodb.Db,
Cursor = mongodb.Cursor,
Collection = mongodb.Collection,
Server = mongodb.Server,
ServerManager = require('../../test/tools/server_manager').ServerManager,
Step = require("../../deps/step/lib/step");
var MONGODB = 'integration_tests';
var client = new Db(MONGODB, new Server("127.0.0.1", 27017, {auto_reconnect: true, poolSize: 1}), {native_parser: (process.env['TEST_NATIVE'] != null)});
var serverManager = null;
// Define the tests, we want them to run as a nested test so we only clean up the
// db connection once
var tests = testCase({
setUp: function(callback) {
callback();
},
tearDown: function(callback) {
// serverManager.stop(9, function(err, result) {
callback();
// });
},
shouldCorrectlyKeepInsertingDocumentsWhenServerDiesAndComesUp : function(test) {
var db1 = new Db('mongo-ruby-test-single-server', new Server("127.0.0.1", 27017, {auto_reconnect: true}), {native_parser: (process.env['TEST_NATIVE'] != null)});
// All inserted docs
var docs = [];
var errs = [];
var insertDocs = [];
// Start server
serverManager = new ServerManager({auth:false, purgedirectories:true, journal:true})
serverManager.start(true, function() {
db1.open(function(err, db) {
// Startup the insert of documents
var intervalId = setInterval(function() {
db.collection('inserts', function(err, collection) {
var doc = {timestamp:new Date().getTime()};
insertDocs.push(doc);
// Insert document
collection.insert(doc, {safe:{fsync:true}}, function(err, result) {
// Save errors
if(err != null) errs.push(err);
if(err == null) {
docs.push(result[0]);
}
})
});
}, 500);
// Wait for a second and then kill the server
setTimeout(function() {
// Kill server instance
serverManager.stop(9, function(err, result) {
// Server down for 1 second
setTimeout(function() {
// Restart server
serverManager = new ServerManager({auth:false, purgedirectories:false, journal:true});
serverManager.start(true, function() {
// Wait for it
setTimeout(function() {
// Drop db
db.dropDatabase(function(err, result) {
// Close db
db.close();
// Check that we got at least one error
// test.ok(errs.length > 0);
test.ok(docs.length > 0);
test.ok(insertDocs.length > 0);
// Finish up
test.done();
});
}, 5000)
})
}, 1000);
});
}, 3000);
})
});
},
shouldCorrectlyInsertKillServerFailThenRestartServerAndSucceed : function(test) {
var db = new Db('test-single-server-recovery', new Server("127.0.0.1", 27017, {auto_reconnect: true}), {numberOfRetries:3, retryMiliSeconds:500, native_parser: (process.env['TEST_NATIVE'] != null)});
// All inserted docs
var docs = [];
var errs = [];
var insertDocs = [];
// Start server
serverManager = new ServerManager({auth:false, purgedirectories:true, journal:true})
serverManager.start(true, function() {
db.open(function(err, db) {
// Add an error handler
db.on("error", function(err) {
console.log("----------------------------------------------- received error")
console.dir(err)
errs.push(err);
});
db.collection('inserts', function(err, collection) {
var doc = {timestamp:new Date().getTime(), a:1};
collection.insert(doc, {safe:true}, function(err, result) {
test.equal(null, err);
<|fim▁hole|> // Attemp insert (should timeout)
var doc = {timestamp:new Date().getTime(), b:1};
collection.insert(doc, {safe:true}, function(err, result) {
test.ok(err != null);
test.equal(null, result);
// Restart server
serverManager = new ServerManager({auth:false, purgedirectories:false, journal:true});
serverManager.start(true, function() {
// Attemp insert again
collection.insert(doc, {safe:true}, function(err, result) {
// Fetch the documents
collection.find({b:1}).toArray(function(err, items) {
test.equal(null, err);
test.equal(1, items[0].b);
test.done();
});
});
});
});
});
})
});
});
});
},
noGlobalsLeaked : function(test) {
var leaks = gleak.detectNew();
test.equal(0, leaks.length, "global var leak detected: " + leaks.join(', '));
test.done();
}
})
// Assign out tests
module.exports = tests;<|fim▁end|> | // Kill server instance
serverManager.stop(9, function(err, result) { |
<|file_name|>mdProject.cpp<|end_file_name|><|fim▁begin|>///////////////////////////////////////////////////////////////////////////////
//
//
//
//
///////////////////////////////////////////////////////////////////////////////
// Includes
#include "include/mdShared.h"
#include "include/mdBreakPoint.h"
#include "include/mdSpy.h"
#include "include/mdSymbol.h"
#include "include/mdSymbolPair.h"
#include "include/mdListLine.h"
#include "include/mdSection.h"
#include "include/mdSpiesPanel.h"
#include "include/mdFrmMain.h"
#include "include/mdApp.h"
#include "include/mdEmu.h"
#include "include/mdProject.h"
///////////////////////////////////////////////////////////////////////////////
// Events
///////////////////////////////////////////////////////////////////////////////
mdProject::mdProject()
{
AddDefaultSymbols();
}
mdProject::~mdProject()
{
ClearAllSpies();
ClearAllBreakPoints();
ClearAllSymbols();
}
///////////////////////////////////////////////////////////////////////////////
// Gestion des symboles
///////////////////////////////////////////////////////////////////////////////
void mdProject::AddDefaultSymbols()
{
// Ajoute des symboles par défaut
wxString b;
b=_T("VDP_DATA");
InsertSymbol(NULL,b,0xc00000,0,false);
b=_T("VDP_DATA");
InsertSymbol(NULL,b,0xc00002,0,false);
b=_T("VDP_CTRL");
InsertSymbol(NULL,b,0xc00004,0,false);
b=_T("VDP_CTRL");
InsertSymbol(NULL,b,0xc00006,0,false);
b=_T("HV_COUNTER");
InsertSymbol(NULL,b,0xc00008,0,false);
b=_T("HV_COUNTER");
InsertSymbol(NULL,b,0xc0000a,0,false);
b=_T("HV_COUNTER");
InsertSymbol(NULL,b,0xc0000c,0,false);
b=_T("HV_COUNTER");
InsertSymbol(NULL,b,0xc0000e,0,false);
b=_T("SN76489_PSG");
InsertSymbol(NULL,b,0xc00011,0,false);
b=_T("SN76489_PSG");
InsertSymbol(NULL,b,0xc00013,0,false);
b=_T("SN76489_PSG");
InsertSymbol(NULL,b,0xc00015,0,false);
b=_T("SN76489_PSG");
InsertSymbol(NULL,b,0xc00017,0,false);
b=_T("Z80_BUSREQ");
InsertSymbol(NULL,b,0xa11100,0,false);
b=_T("Z80_RESET");
InsertSymbol(NULL,b,0xa11200,0,false);
b=_T("MD_VERSION");
InsertSymbol(NULL,b,0xa10001,0,false);
b=_T("DATA_PORT_A");
InsertSymbol(NULL,b,0xa10003,0,false);
b=_T("DATA_PORT_B");
InsertSymbol(NULL,b,0xa10005,0,false);
b=_T("DATA_PORT_C");
InsertSymbol(NULL,b,0xa10007,0,false);
b=_T("CTRL_PORT_A");
InsertSymbol(NULL,b,0xa10009,0,false);
b=_T("CTRL_PORT_B");
InsertSymbol(NULL,b,0xa1000b,0,false);
b=_T("CTRL_PORT_C");
InsertSymbol(NULL,b,0xa1000d,0,false);
b=_T("TxDATA_PORT_A");
InsertSymbol(NULL,b,0xa10000,0,false);
b=_T("RxDATA_PORT_A");
InsertSymbol(NULL,b,0xa10011,0,false);
b=_T("S_CTRL_PORT_A");
InsertSymbol(NULL,b,0xa10013,0,false);
b=_T("TxDATA_PORT_B");
InsertSymbol(NULL,b,0xa10015,0,false);
b=_T("RxDATA_PORT_B");
InsertSymbol(NULL,b,0xa10017,0,false);
b=_T("S_CTRL_PORT_B");
InsertSymbol(NULL,b,0xa10019,0,false);
b=_T("TxDATA_PORT_C");
InsertSymbol(NULL,b,0xa1001b,0,false);
b=_T("RxDATA_PORT_C");
InsertSymbol(NULL,b,0xa1001d,0,false);
b=_T("S_CTRL_PORT_C");
InsertSymbol(NULL,b,0xa1001f,0,false);
DumpFile_Rom=_T("");
DumpFile_68kRam=_T("");
DumpFile_Z80Ram=_T("");
DumpFile_CRam=_T("");
DumpFile_VRam=_T("");
DumpFile_VSRam=_T("");
}
void mdProject::ClearAllSymbols(void)
{
mdSymbolList::iterator it;
for( it = m_Symbols.begin(); it != m_Symbols.end(); ++it )
{ mdSymbolPair *s=(mdSymbolPair*) it->second;
if(s!=NULL)
{
if(s->Label!=NULL)
delete(s->Label);
if(s->Variable!=NULL)
delete(s->Variable);
delete(s);
}
}
m_Symbols.clear();
}
int mdProject::CountSymbols(void)
{
return m_Symbols.size();
}
mdSymbol* mdProject::GetSymbol(int type,int pc)
{
mdSymbolPair *sp=GetSymbolPair(pc);
if(sp!=NULL)
{ if(type==0)
return sp->Variable;
else
return sp->Label;
}
return NULL;
}
mdSymbolPair* mdProject::GetSymbolPair(int pc)
{
mdSymbolList::iterator it;
it=m_Symbols.find(pc);
if(it!=m_Symbols.end())
{ return (mdSymbolPair*) it->second;
}
return NULL;
}
mdSymbol* mdProject::InsertSymbol(mdSection *Section_ID,wxString &Name,unsigned int Address,int Type,bool UserCreated)
{
mdSymbol *s=new mdSymbol();
s->Section=Section_ID;<|fim▁hole|> s->Address=Address;
s->Name=Name;
s->UserCreated=UserCreated;
// vérifie si on a un symbol racine
mdSymbolPair *sp=GetSymbolPair(Address);
if(sp==NULL)
{ sp=new mdSymbolPair();
if(Type==0)
sp->Variable=s;
else
sp->Label=s;
m_Symbols[Address]=sp;
}
else
{ if(Type==0)
{ if(sp->Variable!=NULL)
delete(sp->Variable);
sp->Variable=s;
}
else
{ if(sp->Label!=NULL)
delete(sp->Label);
sp->Label=s;
}
}
return s;
}
bool mdProject::CheckSymbolPairExist(int pc)
{
mdBreakPointList::iterator it;
it=m_BreakPoints.find(pc);
if(it!=m_BreakPoints.end())
return true;
return false;
}
char* mdProject::GetSymbolName(int pc)
{
mdSymbolPair *sp=NULL;
mdSymbolList::iterator it;
it=m_Symbols.find(pc);
if(it!=m_Symbols.end())
{ sp=(mdSymbolPair*) it->second;
if(sp->Label!=NULL)
return (char*)sp->Label->Name.c_str();
if(sp->Variable!=NULL)
return (char*)sp->Variable->Name.c_str();
}
return NULL;
}
char* mdProject::GetSymbolLabelName(int pc)
{
mdSymbolPair *sp=NULL;
mdSymbolList::iterator it;
it=m_Symbols.find(pc);
if(it!=m_Symbols.end())
{ sp=(mdSymbolPair*) it->second;
if(sp->Label!=NULL)
return (char*)sp->Label->Name.c_str();
else
{
if(sp->Variable!=NULL)
return (char*)sp->Variable->Name.c_str();
}
}
return NULL;
}
char* mdProject::GetSymbolVariableName(int pc)
{
mdSymbolPair *sp=NULL;
mdSymbolList::iterator it;
it=m_Symbols.find(pc);
if(it!=m_Symbols.end())
{ sp=(mdSymbolPair*) it->second;
if(sp->Variable!=NULL)
return (char*)sp->Variable->Name.c_str();
}
return NULL;
}
void mdProject::RemoveSymbol(int type,int pc)
{
//m_Spies.erase(IntIndex);
mdSymbolPair *sp=GetSymbolPair(pc);
if(sp!=NULL)
{
if(type==0)
{ if(sp->Variable!=NULL)
{ if(sp->Variable->UserCreated==true)
{ delete(sp->Variable);
sp->Variable=NULL;
}
}
}
if(type==1)
{ if(sp->Label!=NULL)
{ delete(sp->Label);
sp->Label=NULL;
}
}
if(sp->Label==NULL && sp->Variable==NULL)
{ m_Symbols.erase(pc);
delete(sp);
}
}
}
///////////////////////////////////////////////////////////////////////////////
// Gestion des watchers
///////////////////////////////////////////////////////////////////////////////
mdSpy* mdProject::InsertSpy( int IntIndex,
mdSection *Section,
wxString &name,
unsigned int address,
int length,
bool isfromarray)
{
mdSpy *Spy=new mdSpy();
Spy->SetName(name);
Spy->SetAddress(address,true);
Spy->m_Symbol->Section=Section;
Spy->m_Length=length;
Spy->m_ListIndex=IntIndex;
Spy->m_IsFromArray=isfromarray;
Spy->m_Value=0;
m_Spies[IntIndex]=Spy;
return Spy;
}
mdSpy* mdProject::GetSpy(int IntIndex)
{ return (mdSpy*)m_Spies[IntIndex];
}
void mdProject::RemoveSpy(int IntIndex)
{
m_Spies.erase(IntIndex);
}
void mdProject::ClearAllSpies(void)
{
mdSpiesList::iterator it;
for( it = m_Spies.begin(); it != m_Spies.end(); ++it )
{ mdSpy *s=(mdSpy*) it->second;
if(s!=NULL)
delete(s);
}
m_Spies.clear();
}
int mdProject::CountSpies(void)
{
return m_Spies.size();
}
///////////////////////////////////////////////////////////////////////////////
// Gestion des BerakPoints
///////////////////////////////////////////////////////////////////////////////
mdBreakPoint* mdProject::InsertBreakPoint(int IntIndex)
{
mdBreakPointList::iterator it;
it=m_BreakPoints.find(IntIndex);
if(it==m_BreakPoints.end())
{ mdBreakPoint *bk=new mdBreakPoint();
bk->m_Hits=0;
bk->m_Enabled=TRUE;
m_BreakPoints[IntIndex]=bk;
return bk;
}
return NULL;
}
bool mdProject::CheckGotBreakPoint(int pc)
{
mdBreakPointList::iterator it;
it=m_BreakPoints.find(pc);
if(it!=m_BreakPoints.end())
return true;
return false;
}
void mdProject::RemoveBreakPoint(int IntIndex)
{
m_BreakPoints.erase(IntIndex);
}
int mdProject::CountBreakPoint(void)
{
return m_BreakPoints.size();
}
void mdProject::ClearAllBreakPoints(void)
{
mdBreakPointList::iterator it;
for( it = m_BreakPoints.begin(); it != m_BreakPoints.end(); ++it )
{ mdBreakPoint *s=(mdBreakPoint*) it->second;
if(s!=NULL)
delete(s);
}
m_BreakPoints.clear();
}
mdBreakPoint* mdProject::GetBreakPoint(int pc)
{
return(mdBreakPoint*) m_BreakPoints[pc];
}
int mdProject::ExecuteBreakPoint(int pc)
{
mdBreakPointList::iterator it;
it=m_BreakPoints.find(pc);
if(it!=m_BreakPoints.end())
{ // trouver breakpoint incrémente le hits
mdBreakPoint *value =(mdBreakPoint*) it->second;
if(value->m_Enabled==true)
{ value->m_Hits++;
return 1;
}
}
return 0;
}
///////////////////////////////////////////////////////////////////////////////
// Load les symboles et étiquettes
///////////////////////////////////////////////////////////////////////////////
int mdProject::LoadSymbols(int type,wxString& FileName)
{
// nasm pour commencer
wxString str="";
wxTextFile file;
file.Open(FileName);
int etat=-1;
int ligne_cnt=0;
wxString Section="";
ClearAllSymbols();
AddDefaultSymbols();
for ( str = file.GetFirstLine(); !file.Eof(); str = file.GetNextLine() )
{
if(ligne_cnt==0)
{
switch(etat)
{
case -1:
{
// traite le fichier
if(str.Contains(" Section ")==true)
{ // doit virer
etat=1;
Section=str.BeforeLast('\'');
Section=Section.AfterFirst('\'');
ligne_cnt=5;
}
else
{
if(str.Contains("Value Type Class Symbol Refs Line File")==true)
{ etat=1;
Section=_T("");
ligne_cnt=2;
}
}
}break;
case 1:
{
if(str.Trim().Length()==0)
etat=-1;
else
{ wxString var_name="";
wxString taille=str.SubString(12,18);
wxString index=str.SubString(0,9);
long value=0;
int addr_index= index.ToLong(&value,16);
int addresse=value;
taille=taille.Trim();
var_name=str.SubString(25,48);
var_name=var_name.Trim(true);
if(taille.Trim().Length()>0)
{
int size=0;
if(taille.CmpNoCase("byte")==0)
{ size=1;
}
if(taille.CmpNoCase("word")==0)
{ size=2;
}
if(taille.CmpNoCase("long")==0)
{ size=4;
}
if(size>0)
{
if(Section.CmpNoCase("vars")==0)
{ addresse = 0xff0000 + value; }
// attribue une section
gFrmMain->GetSpiesPanel()->InsertSpy(NULL,var_name,addresse,size,1,false);
}
}
else
{
// étiquette
InsertSymbol(NULL,var_name,value,1,false);
}
}
}break;
}
}
else
{ ligne_cnt--; }
}
file.Close();
return 0;
}
int mdProject::LoadList(wxString& FileName)
{
//// nasm pour commencer
//wxString str="";
//wxTextFile file;
//file.Open(FileName);
//int nbligne=file.GetLineCount();
//for ( str = file.GetFirstLine(); !file.Eof(); str = file.GetNextLine() )
//{
// wxString *s=new wxString(str);
//}
//file.Close();
return 0;
}<|fim▁end|> | |
<|file_name|>mock_registry.go<|end_file_name|><|fim▁begin|>// Copyright 2015 flannel authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package subnet
import (
"fmt"
"path"
"sort"
"strings"
"time"
etcd "github.com/coreos/flannel/Godeps/_workspace/src/github.com/coreos/etcd/client"
"github.com/coreos/flannel/Godeps/_workspace/src/golang.org/x/net/context"
)
type MockSubnetRegistry struct {
networks map[string]*etcd.Node
events chan *etcd.Response
index uint64
ttl time.Duration
}
const networkKeyPrefix = "/coreos.com/network"
func NewMockRegistry(ttlOverride time.Duration, network, config string, initialSubnets []*etcd.Node) *MockSubnetRegistry {
index := uint64(0)
node := &etcd.Node{Key: normalizeNetKey(network), Value: config, ModifiedIndex: 0, Nodes: make([]*etcd.Node, 0, 20)}
for _, n := range initialSubnets {
if n.ModifiedIndex > index {
index = n.ModifiedIndex
}
node.Nodes = append(node.Nodes, n)
}
msr := &MockSubnetRegistry{
events: make(chan *etcd.Response, 1000),
index: index + 1,
ttl: ttlOverride,
}
msr.networks = make(map[string]*etcd.Node)
msr.networks[network] = node
return msr
}
func (msr *MockSubnetRegistry) getNetworkConfig(ctx context.Context, network string) (*etcd.Response, error) {
return &etcd.Response{
Index: msr.index,
Node: msr.networks[network],<|fim▁hole|>func (msr *MockSubnetRegistry) setConfig(network, config string) error {
n, ok := msr.networks[network]
if !ok {
return fmt.Errorf("Network %s not found", network)
}
n.Value = config
return nil
}
func (msr *MockSubnetRegistry) getSubnets(ctx context.Context, network string) (*etcd.Response, error) {
n, ok := msr.networks[network]
if !ok {
return nil, fmt.Errorf("Network %s not found", network)
}
return &etcd.Response{
Node: n,
Index: msr.index,
}, nil
}
func (msr *MockSubnetRegistry) createSubnet(ctx context.Context, network, sn, data string, ttl time.Duration) (*etcd.Response, error) {
n, ok := msr.networks[network]
if !ok {
return nil, fmt.Errorf("Network %s not found", network)
}
msr.index += 1
if msr.ttl > 0 {
ttl = msr.ttl
}
exp := time.Now().Add(ttl)
node := &etcd.Node{
Key: sn,
Value: data,
ModifiedIndex: msr.index,
Expiration: &exp,
}
n.Nodes = append(n.Nodes, node)
msr.events <- &etcd.Response{
Action: "add",
Node: node,
}
return &etcd.Response{
Node: node,
Index: msr.index,
}, nil
}
func (msr *MockSubnetRegistry) updateSubnet(ctx context.Context, network, sn, data string, ttl time.Duration) (*etcd.Response, error) {
n, ok := msr.networks[network]
if !ok {
return nil, fmt.Errorf("Network %s not found", network)
}
msr.index += 1
exp := time.Now().Add(ttl)
for _, sub := range n.Nodes {
if sub.Key == sn {
sub.Value = data
sub.ModifiedIndex = msr.index
sub.Expiration = &exp
msr.events <- &etcd.Response{
Action: "add",
Node: sub,
}
return &etcd.Response{
Node: sub,
Index: msr.index,
}, nil
}
}
return nil, fmt.Errorf("Subnet not found")
}
func (msr *MockSubnetRegistry) deleteSubnet(ctx context.Context, network, sn string) (*etcd.Response, error) {
n, ok := msr.networks[network]
if !ok {
return nil, fmt.Errorf("Network %s not found", network)
}
msr.index += 1
for i, sub := range n.Nodes {
if sub.Key == sn {
n.Nodes[i] = n.Nodes[len(n.Nodes)-1]
n.Nodes = n.Nodes[:len(n.Nodes)-1]
sub.ModifiedIndex = msr.index
msr.events <- &etcd.Response{
Action: "delete",
Node: sub,
}
return &etcd.Response{
Node: sub,
Index: msr.index,
}, nil
}
}
return nil, fmt.Errorf("Subnet not found")
}
func (msr *MockSubnetRegistry) watch(ctx context.Context, network string, since uint64) (*etcd.Response, error) {
for {
if since < msr.index {
return nil, etcd.Error{
Code: etcd.ErrorCodeEventIndexCleared,
Cause: "out of date",
Message: "cursor is out of date",
Index: msr.index,
}
}
select {
case <-ctx.Done():
return nil, ctx.Err()
case r := <-msr.events:
if r.Node.ModifiedIndex <= since {
continue
}
return r, nil
}
}
}
func (msr *MockSubnetRegistry) hasSubnet(network, sn string) bool {
n, ok := msr.networks[network]
if !ok {
return false
}
for _, sub := range n.Nodes {
if sub.Key == sn {
return true
}
}
return false
}
func (msr *MockSubnetRegistry) expireSubnet(network, sn string) {
n, ok := msr.networks[network]
if !ok {
return
}
for i, sub := range n.Nodes {
if sub.Key == sn {
msr.index += 1
n.Nodes[i] = n.Nodes[len(n.Nodes)-1]
n.Nodes = n.Nodes[:len(n.Nodes)-2]
sub.ModifiedIndex = msr.index
msr.events <- &etcd.Response{
Action: "expire",
Node: sub,
}
return
}
}
}
func configKeyToNetworkKey(configKey string) string {
if !strings.HasSuffix(configKey, "/config") {
return ""
}
return strings.TrimSuffix(configKey, "/config")
}
func (msr *MockSubnetRegistry) getNetworks(ctx context.Context) (*etcd.Response, error) {
var keys []string
for k := range msr.networks {
keys = append(keys, k)
}
sort.Strings(keys)
// mimic etcd by returning a multi-level response where each top-level
// node is a network node, and each network node has a single child
// 'config' node. eg:
//
// /coreos.com/network
// /coreos.com/network/blue
// /coreos.com/network/blue/config
// /coreos.com/network/red
// /coreos.com/network/red/config
//
toplevel := &etcd.Node{Key: networkKeyPrefix, Value: "", ModifiedIndex: msr.index, Nodes: make([]*etcd.Node, 0, len(keys))}
for _, k := range keys {
netKey := configKeyToNetworkKey(msr.networks[k].Key)
if netKey == "" {
continue
}
network := &etcd.Node{
Key: netKey,
Value: "",
ModifiedIndex: msr.index,
Nodes: []*etcd.Node{msr.networks[k]},
}
toplevel.Nodes = append(toplevel.Nodes, network)
}
return &etcd.Response{
Node: toplevel,
Index: msr.index,
}, nil
}
func (msr *MockSubnetRegistry) getNetwork(ctx context.Context, network string) (*etcd.Response, error) {
n, ok := msr.networks[network]
if !ok {
return nil, fmt.Errorf("Network %s not found", network)
}
return &etcd.Response{
Node: n,
Index: msr.index,
}, nil
}
func (msr *MockSubnetRegistry) CreateNetwork(ctx context.Context, network, config string) (*etcd.Response, error) {
_, ok := msr.networks[network]
if ok {
return nil, fmt.Errorf("Network %s already exists", network)
}
msr.index += 1
node := &etcd.Node{
Key: normalizeNetKey(network),
Value: config,
ModifiedIndex: msr.index,
}
msr.networks[network] = node
msr.events <- &etcd.Response{
Action: "add",
Node: node,
}
return &etcd.Response{
Node: node,
Index: msr.index,
}, nil
}
func (msr *MockSubnetRegistry) DeleteNetwork(ctx context.Context, network string) (*etcd.Response, error) {
n, ok := msr.networks[network]
if !ok {
return nil, fmt.Errorf("Network %s not found", network)
}
msr.index += 1
n.ModifiedIndex = msr.index
delete(msr.networks, network)
msr.events <- &etcd.Response{
Action: "delete",
Node: n,
}
return &etcd.Response{
Node: n,
Index: msr.index,
}, nil
}
func normalizeNetKey(key string) string {
match := networkKeyPrefix
newKey := key
if !strings.HasPrefix(newKey, match+"/") {
newKey = path.Join(match, key)
}
if !strings.HasSuffix(newKey, "/config") {
newKey = path.Join(newKey, "config")
}
return newKey
}<|fim▁end|> | }, nil
}
|
<|file_name|>binary-tree-tilt.py<|end_file_name|><|fim▁begin|># Time: O(n)
# Space: O(n)
# Given a binary tree, return the tilt of the whole tree.
#
# The tilt of a tree node is defined as the absolute difference
# between the sum of all left subtree node values and
# the sum of all right subtree node values. Null node has tilt 0.
#
# The tilt of the whole tree is defined as the sum of all nodes' tilt.
#<|fim▁hole|># Input:
# 1
# / \
# 2 3
# Output: 1
# Explanation:
# Tilt of node 2 : 0
# Tilt of node 3 : 0
# Tilt of node 1 : |2-3| = 1
# Tilt of binary tree : 0 + 0 + 1 = 1
# Note:
#
# The sum of node values in any subtree won't exceed
# the range of 32-bit integer.
# Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution(object):
def findTilt(self, root):
"""
:type root: TreeNode
:rtype: int
"""
def postOrderTraverse(root, tilt):
if not root:
return 0, tilt
left, tilt = postOrderTraverse(root.left, tilt)
right, tilt = postOrderTraverse(root.right, tilt)
tilt += abs(left-right)
return left+right+root.val, tilt
return postOrderTraverse(root, 0)[1]<|fim▁end|> | # Example: |
<|file_name|>trobador.py<|end_file_name|><|fim▁begin|>from gi.repository import GObject, Gtk, Gtranslator, PeasGtk
from panel import Panel
import sys
from gettext import _
class TrobadorPlugin(GObject.Object, Gtranslator.TabActivatable, PeasGtk.Configurable):
__gtype_name__ = "TrobadorPlugin"
tab = GObject.property(type=Gtranslator.Tab)
handler_id = None
project = ''
version = ''
host = ''
default_host = 'trobador.trasno.net'
check = Gtk.CheckButton()
project_entry = Gtk.Entry()
version_entry = Gtk.Entry()
host_entry = Gtk.Entry()
save_button = Gtk.Button(label="Save")
save_host_button = Gtk.Button(label="Save")
def __init__(self):
GObject.Object.__init__(self)
def do_activate(self):
self.window = self.tab.get_toplevel()
self.create_panel()
TrobadorPlugin.host = self.default_host
self.tab.add_widget(self.panel, "GtrTrobador", _("Trobador"), "results panel", Gtranslator.TabPlacement.RIGHT)
def do_deactivate(self):
print "Removing..."
self.tab.remove_widget(self.panel)
self.tab.disconnect(self.handler_id)
def do_update_state(self):
pass
def check_checkButton_state(self, check):
if self.check.get_active():
print "activate"
self.project_entry.set_editable(True)
self.version_entry.set_editable(True)
self.save_button.set_sensitive(True)
else:
print "deactivate"
self.project_entry.set_text("")
self.version_entry.set_text("")
self.project_entry.set_editable(False)
self.version_entry.set_editable(False)
self.save_button.set_sensitive(False)
TrobadorPlugin.project = ''
TrobadorPlugin.version = ''
def do_create_configure_widget(self):
table = Gtk.Table(8, 2, True)
if not self.check.get_active():
self.project_entry.set_editable(False)
self.version_entry.set_editable(False)
self.save_button.set_sensitive(False)
#self.check = Gtk.CheckButton("Seleccionar proyecto y version")
self.check.set_label("Select project & version")
self.check.set_border_width(6)
self.check.connect("clicked", self.check_checkButton_state)
project_label = Gtk.Label("Project")
#self.proyectoEntry = Gtk.Entry()
self.project_entry.set_text(TrobadorPlugin.project)
version_label = Gtk.Label("Version")
#self.version_entry = Gtk.Entry()<|fim▁hole|> self.save_button.set_label("Save")
self.save_host_button.set_label("Save")
hostLabel = Gtk.Label("Host")
if self.host == '':
self.host_entry.set_text(TrobadorPlugin.default_host)
else:
self.host_entry.set_text(TrobadorPlugin.host)
info_label1 = Gtk.Label("Project settings")
info_label2 = Gtk.Label("Host settings")
table.attach(info_label1, 0, 2, 0, 1)
table.attach(self.check, 0, 2, 1, 2)
table.attach(project_label, 0, 1, 2, 3)
table.attach(self.project_entry, 1, 2, 2, 3)
table.attach(version_label, 0, 1, 3, 4)
table.attach(self.version_entry, 1, 2, 3, 4)
table.attach(self.save_button, 0, 1, 4, 5)
table.attach(info_label2, 0, 2, 5, 6)
table.attach(hostLabel, 0, 1, 6, 7)
table.attach(self.host_entry, 1, 2, 6, 7)
table.attach(self.save_host_button, 0, 1, 7, 8)
self.save_button.connect("clicked", self.save_config, self.project_entry.get_text(), self.version_entry.get_text())
self.save_host_button.connect("clicked", self.save_host_config, self.host_entry.get_text())
return table
def save_config(self, save_button, project, version):
TrobadorPlugin.project = self.project_entry.get_text()
TrobadorPlugin.version = self.version_entry.get_text()
def save_host_config(self, save_host_button, host):
if self.host_entry.get_text() != '':
TrobadorPlugin.host = self.host_entry.get_text()
else:
TrobadorPlugin.host = self.default_host
self.host_entry.set_text(TrobadorPlugin.host)
def create_panel(self):
self.panel = Panel()
self.panel.set_host(TrobadorPlugin.default_host)
tree = self.panel.get_tree()
tree.connect("row-activated", self.set_buffer)
self.get_translation_unit
self.handler_id = self.tab.connect("showed-message", self.get_translation_unit)
self.panel.show()
def set_buffer(self, tree, row, col):
iterator = self.panel.get_iterator()
# l = tree.get_model()
#rootiter = l.get_iter_first()
selection, iterator = tree.get_selection().get_selected()
if iterator != None:
view = self.window.get_active_view()
if not view or not view.get_editable():
return "no editable"
document = view.get_buffer()
document.begin_user_action()
iters = document.get_selection_bounds()
if iters:
document.delete_interactive(iters[0], iters[1], view.get_editable())
document.insert_interactive_at_cursor(selection.get_value(iterator, 0), -1, view.get_editable())
document.end_user_action()
def get_translation_unit(self, tab, msg):
po_file = GObject.property(type=Gtranslator.Po)
po_file = self.tab.get_po()
print msg.get_msgid()
msg = po_file.get_current_message()
c = msg[0].get_msgid()
self.panel.set_translation_unit(c)
self.panel.set_project(self.project)
self.panel.set_version(self.version)
self.panel.set_host(self.host)
print "hola: " + self.panel.get_host()
# Updating the results
self.panel.update_data()
# ex:et:ts=4:<|fim▁end|> | self.version_entry.set_text(TrobadorPlugin.version)
#save_button = Gtk.Button(label="Guardar") |
<|file_name|>ResponseError-test.js<|end_file_name|><|fim▁begin|>/* describe, it, afterEach, beforeEach */<|fim▁hole|>import chai from 'chai';
import chaiAsPromised from 'chai-as-promised';
chai.use(chaiAsPromised);
let expect = chai.expect;
import config from '../config';
import util from './util';
import ResponseError from '../../src/ResponseError';
import Endpoint from '../../src/Endpoint';
describe(__filename, function () {
this.timeout(config.testTimeout);
it('should get a proper response error', function() {
var message = 'oh hello there';
var response = { _status: 200, _body: 'a response body' };
var userConfig = util.getScriptUserConfig();
var endpoint = new Endpoint(userConfig,
userConfig.serverOAuth,
'get',
'/some/path',
{}, // headers
{ some: 'args' });
var responseError = new ResponseError(message,
response,
endpoint);
expect(responseError instanceof ResponseError);
expect(responseError.status).to.eql(200);
expect(responseError.url).to.eql('https://oauth.reddit.com/some/path');
expect(responseError.args).to.eql({ some: 'args', api_type: 'json' });
expect(responseError.message.indexOf('oh hello there')).to.not.eql(-1);
expect(responseError.message.indexOf('Response Status')).to.not.eql(-1);
expect(responseError.message.indexOf('Endpoint URL')).to.not.eql(-1);
expect(responseError.message.indexOf('Arguments')).to.not.eql(-1);
expect(responseError.message.indexOf('Response Body')).to.not.eql(-1);
});
});<|fim▁end|> | import './snoocore-mocha';
|
<|file_name|>CourseResult.java<|end_file_name|><|fim▁begin|>package bms.player.beatoraja.result;
import static bms.player.beatoraja.ClearType.*;
import static bms.player.beatoraja.skin.SkinProperty.*;
import java.util.*;
import java.util.logging.Logger;
import bms.player.beatoraja.input.KeyCommand;
import com.badlogic.gdx.utils.FloatArray;
import bms.model.BMSModel;
import bms.player.beatoraja.*;
import bms.player.beatoraja.MainController.IRStatus;
import bms.player.beatoraja.input.BMSPlayerInputProcessor;
import bms.player.beatoraja.input.KeyBoardInputProcesseor.ControlKeys;
import bms.player.beatoraja.ir.*;
import bms.player.beatoraja.select.MusicSelector;
import bms.player.beatoraja.skin.SkinType;
import bms.player.beatoraja.skin.property.EventFactory.EventType;
/**
* コースリザルト
*
* @author exch
*/
public class CourseResult extends AbstractResult {
private List<IRSendStatus> irSendStatus = new ArrayList<IRSendStatus>();
private ResultKeyProperty property;
public CourseResult(MainController main) {
super(main);
}
public void create() {
final PlayerResource resource = main.getPlayerResource();
for(int i = 0;i < REPLAY_SIZE;i++) {
saveReplay[i] = main.getPlayDataAccessor().existsReplayData(resource.getCourseBMSModels(),
resource.getPlayerConfig().getLnmode(), i ,resource.getConstraint()) ? ReplayStatus.EXIST : ReplayStatus.NOT_EXIST ;
}
setSound(SOUND_CLEAR, "course_clear.wav", SoundType.SOUND,false);
setSound(SOUND_FAIL, "course_fail.wav", SoundType.SOUND, false);
setSound(SOUND_CLOSE, "course_close.wav", SoundType.SOUND, false);
loadSkin(SkinType.COURSE_RESULT);
for(int i = resource.getCourseGauge().size;i < resource.getCourseBMSModels().length;i++) {
FloatArray[] list = new FloatArray[resource.getGrooveGauge().getGaugeTypeLength()];
for(int type = 0; type < list.length; type++) {
list[type] = new FloatArray();
for(int l = 0;l < (resource.getCourseBMSModels()[i].getLastNoteTime() + 500) / 500;l++) {
list[type].add(0f);
}
}
resource.getCourseGauge().add(list);
}
property = ResultKeyProperty.get(resource.getBMSModel().getMode());
if(property == null) {
property = ResultKeyProperty.BEAT_7K;
}
updateScoreDatabase();
// リプレイの自動保存
if(resource.getPlayMode().mode == BMSPlayerMode.Mode.PLAY){
for(int i=0;i<REPLAY_SIZE;i++){
if(MusicResult.ReplayAutoSaveConstraint.get(resource.getPlayerConfig().getAutoSaveReplay()[i]).isQualified(oldscore ,getNewScore())) {
saveReplayData(i);
}
}
}
gaugeType = resource.getGrooveGauge().getType();
}
public void prepare() {
state = STATE_OFFLINE;
final PlayerResource resource = main.getPlayerResource();
final PlayerConfig config = resource.getPlayerConfig();
final ScoreData newscore = getNewScore();
ranking = resource.getRankingData() != null && resource.getCourseBMSModels() != null ? resource.getRankingData() : new RankingData();
rankingOffset = 0;
final IRStatus[] ir = main.getIRStatus();
if (ir.length > 0 && resource.getPlayMode().mode == BMSPlayerMode.Mode.PLAY) {
state = STATE_IR_PROCESSING;
boolean uln = false;
for(BMSModel model : resource.getCourseBMSModels()) {
if(model.containsUndefinedLongNote()) {
uln = true;
break;
}
}
final int lnmode = uln ? config.getLnmode() : 0;
for(IRStatus irc : ir) {
boolean send = resource.isUpdateCourseScore() && resource.getCourseData().isRelease();
switch(irc.config.getIrsend()) {
case IRConfig.IR_SEND_ALWAYS:
break;
case IRConfig.IR_SEND_COMPLETE_SONG:
// FloatArray gauge = resource.getGauge()[resource.getGrooveGauge().getType()];
// send &= gauge.get(gauge.size - 1) > 0.0;
break;
case IRConfig.IR_SEND_UPDATE_SCORE:
// send &= (newscore.getExscore() > oldscore.getExscore() || newscore.getClear() > oldscore.getClear()
// || newscore.getCombo() > oldscore.getCombo() || newscore.getMinbp() < oldscore.getMinbp());
break;
}
if(send) {
irSendStatus.add(new IRSendStatus(irc.connection, resource.getCourseData(), lnmode, newscore));
}
}
Thread irprocess = new Thread(() -> {
try {
int irsend = 0;
boolean succeed = true;
List<IRSendStatus> removeIrSendStatus = new ArrayList<IRSendStatus>();
for(IRSendStatus irc : irSendStatus) {
if(irsend == 0) {
main.switchTimer(TIMER_IR_CONNECT_BEGIN, true);
}
irsend++;
succeed &= irc.send();
if(irc.retry < 0 || irc.retry > main.getConfig().getIrSendCount()) {
removeIrSendStatus.add(irc);
}
}
irSendStatus.removeAll(removeIrSendStatus);
if(irsend > 0) {
main.switchTimer(succeed ? TIMER_IR_CONNECT_SUCCESS : TIMER_IR_CONNECT_FAIL, true);
IRResponse<bms.player.beatoraja.ir.IRScoreData[]> response = ir[0].connection.getCoursePlayData(null, new IRCourseData(resource.getCourseData(), lnmode));
if(response.isSucceeded()) {
ranking.updateScore(response.getData(), newscore.getExscore() > oldscore.getExscore() ? newscore : oldscore);
rankingOffset = ranking.getRank() > 10 ? ranking.getRank() - 5 : 0;
Logger.getGlobal().warning("IRからのスコア取得成功 : " + response.getMessage());
} else {
Logger.getGlobal().warning("IRからのスコア取得失敗 : " + response.getMessage());
}
}
} catch (Exception e) {
Logger.getGlobal().severe(e.getMessage());
} finally {
state = STATE_IR_FINISHED;
}
});
irprocess.start();
}
play(newscore.getClear() != Failed.id ? SOUND_CLEAR : SOUND_FAIL);
}
public void render() {
long time = main.getNowTime();
main.switchTimer(TIMER_RESULTGRAPH_BEGIN, true);
main.switchTimer(TIMER_RESULTGRAPH_END, true);
main.switchTimer(TIMER_RESULT_UPDATESCORE, true);
if(time > getSkin().getInput()){
main.switchTimer(TIMER_STARTINPUT, true);
}
if (main.isTimerOn(TIMER_FADEOUT)) {
if (main.getNowTime(TIMER_FADEOUT) > getSkin().getFadeout()) {
main.getPlayerResource().getPlayerConfig().setGauge(main.getPlayerResource().getOrgGaugeOption());
stop(SOUND_CLEAR);
stop(SOUND_FAIL);
stop(SOUND_CLOSE);
main.changeState(MainStateType.MUSICSELECT);
}
} else if (time > getSkin().getScene()) {
main.switchTimer(TIMER_FADEOUT, true);
if(getSound(SOUND_CLOSE) != null) {
stop(SOUND_CLEAR);
stop(SOUND_FAIL);
play(SOUND_CLOSE);
}
}
}
public void input() {
super.input();
final PlayerResource resource = main.getPlayerResource();
final BMSPlayerInputProcessor inputProcessor = main.getInputProcessor();
if (!main.isTimerOn(TIMER_FADEOUT) && main.isTimerOn(TIMER_STARTINPUT)) {
boolean ok = false;
for (int i = 0; i < property.getAssignLength(); i++) {
if (property.getAssign(i) == ResultKeyProperty.ResultKey.CHANGE_GRAPH && inputProcessor.getKeyState(i) && inputProcessor.resetKeyChangedTime(i)) {
gaugeType = (gaugeType - 5) % 3 + 6;
} else if (property.getAssign(i) != null && inputProcessor.getKeyState(i) && inputProcessor.resetKeyChangedTime(i)) {
ok = true;
}
}
if (inputProcessor.isControlKeyPressed(ControlKeys.ESCAPE) || inputProcessor.isControlKeyPressed(ControlKeys.ENTER)) {
ok = true;
}
if (resource.getScoreData() == null || ok) {
if (((CourseResultSkin) getSkin()).getRankTime() != 0 && !main.isTimerOn(TIMER_RESULT_UPDATESCORE)) {
main.switchTimer(TIMER_RESULT_UPDATESCORE, true);
} else if (state == STATE_OFFLINE || state == STATE_IR_FINISHED){
main.switchTimer(TIMER_FADEOUT, true);
if(getSound(SOUND_CLOSE) != null) {
stop(SOUND_CLEAR);
stop(SOUND_FAIL);
play(SOUND_CLOSE);
}
}
}
if(inputProcessor.isControlKeyPressed(ControlKeys.NUM1)) {
saveReplayData(0);
} else if(inputProcessor.isControlKeyPressed(ControlKeys.NUM2)) {
saveReplayData(1);
} else if(inputProcessor.isControlKeyPressed(ControlKeys.NUM3)) {
saveReplayData(2);
} else if(inputProcessor.isControlKeyPressed(ControlKeys.NUM4)) {
saveReplayData(3);
}
if(inputProcessor.isActivated(KeyCommand.OPEN_IR)) {
this.executeEvent(EventType.open_ir);
}
}
}
public void updateScoreDatabase() {
final PlayerResource resource = main.getPlayerResource();
final PlayerConfig config = resource.getPlayerConfig();
BMSModel[] models = resource.getCourseBMSModels();
final ScoreData newscore = getNewScore();
if (newscore == null) {
return;
}
boolean dp = false;
for (BMSModel model : models) {
dp |= model.getMode().player == 2;<|fim▁hole|> newscore.setCombo(resource.getMaxcombo());
int random = 0;
if (config.getRandom() > 0
|| (dp && (config.getRandom2() > 0 || config.getDoubleoption() > 0))) {
random = 2;
}
if (config.getRandom() == 1
&& (!dp || (config.getRandom2() == 1 && config.getDoubleoption() == 1))) {
random = 1;
}
final ScoreData score = main.getPlayDataAccessor().readScoreData(models,
config.getLnmode(), random, resource.getConstraint());
oldscore = score != null ? score : new ScoreData();
getScoreDataProperty().setTargetScore(oldscore.getExscore(), resource.getRivalScoreData() != null ? resource.getRivalScoreData().getExscore() : 0,
Arrays.asList(resource.getCourseData().getSong()).stream().mapToInt(sd -> sd.getNotes()).sum());
getScoreDataProperty().update(newscore);
main.getPlayDataAccessor().writeScoreDara(newscore, models, config.getLnmode(),
random, resource.getConstraint(), resource.isUpdateCourseScore());
Logger.getGlobal().info("スコアデータベース更新完了 ");
}
public int getJudgeCount(int judge, boolean fast) {
final PlayerResource resource = main.getPlayerResource();
ScoreData score = resource.getCourseScoreData();
if (score != null) {
switch (judge) {
case 0:
return fast ? score.getEpg() : score.getLpg();
case 1:
return fast ? score.getEgr() : score.getLgr();
case 2:
return fast ? score.getEgd() : score.getLgd();
case 3:
return fast ? score.getEbd() : score.getLbd();
case 4:
return fast ? score.getEpr() : score.getLpr();
case 5:
return fast ? score.getEms() : score.getLms();
}
}
return 0;
}
@Override
public void dispose() {
super.dispose();
}
public void saveReplayData(int index) {
final PlayerResource resource = main.getPlayerResource();
if (resource.getPlayMode().mode == BMSPlayerMode.Mode.PLAY && resource.getCourseScoreData() != null) {
if (saveReplay[index] != ReplayStatus.SAVED && resource.isUpdateCourseScore()) {
// 保存されているリプレイデータがない場合は、EASY以上で自動保存
ReplayData[] rd = resource.getCourseReplay();
for(int i = 0; i < rd.length; i++) {
rd[i].gauge = resource.getPlayerConfig().getGauge();
}
main.getPlayDataAccessor().wrireReplayData(rd, resource.getCourseBMSModels(),
resource.getPlayerConfig().getLnmode(), index, resource.getConstraint());
saveReplay[index] = ReplayStatus.SAVED;
}
}
}
public ScoreData getNewScore() {
return main.getPlayerResource().getCourseScoreData();
}
static class IRSendStatus {
public final IRConnection ir;
public final CourseData course;
public final int lnmode;
public final ScoreData score;
public int retry = 0;
public IRSendStatus(IRConnection ir, CourseData course, int lnmode, ScoreData score) {
this.ir = ir;
this.course = course;
this.lnmode = lnmode;
this.score = score;
}
public boolean send() {
Logger.getGlobal().info("IRへスコア送信中 : " + course.getName());
IRResponse<Object> send1 = ir.sendCoursePlayData(new IRCourseData(course, lnmode), new bms.player.beatoraja.ir.IRScoreData(score));
if(send1.isSucceeded()) {
Logger.getGlobal().info("IRスコア送信完了 : " + course.getName());
retry = -255;
return true;
} else {
Logger.getGlobal().warning("IRスコア送信失敗 : " + send1.getMessage());
retry++;
return false;
}
}
}
}<|fim▁end|> | } |
<|file_name|>simp_test.cpp<|end_file_name|><|fim▁begin|>/*
* sample program to write out the calibration table and then
* reload it again, verify that the data is in fact reversed
*
*
*
*/
#include <aiousb.h>
#include <stdio.h>
#include <unistd.h>
#include <exception>
#include <iostream>
#include "TestCaseSetup.h"
using namespace AIOUSB;
int main( int argc, char **argv ) {
// printf("Sample test for Checking the Calibration on the board: %s, %s", AIOUSB_GetVersion(), AIOUSB_GetVersionDate());
unsigned long result = AIOUSB_Init();
if( result == AIOUSB_SUCCESS ) {
unsigned long deviceMask = GetDevices();
if( deviceMask != 0 ) {
// at least one ACCES device detected, but we want one of a specific type
AIOUSB_ListDevices();
TestCaseSetup tcs;
try {
tcs.findDevice();
tcs.doPreSetup();
tcs.doBulkConfigBlock();
tcs.doSetAutoCalibration();
tcs.doVerifyGroundCalibration();
tcs.doVerifyReferenceCalibration();
while(1) {
tcs.doCSVReadVoltages();
usleep(10);
}<|fim▁hole|> }
}
}
}<|fim▁end|> | } catch ( Error &e ) {
std::cout << "Errors" << e.what() << std::endl; |
<|file_name|>is_IS.tsx<|end_file_name|><|fim▁begin|>import isIS from '../../date-picker/locale/is_IS';
<|fim▁hole|>export default isIS;<|fim▁end|> | |
<|file_name|>settings.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*-
from django.conf import settings
from django.contrib.sites.models import Site
from django.core.exceptions import ImproperlyConfigured
<|fim▁hole|>
FREEZE_ROOT = getattr(settings, 'FREEZE_ROOT', os.path.abspath(os.path.join(settings.MEDIA_ROOT, '../freeze/')) )
if not os.path.isabs(FREEZE_ROOT):
raise ImproperlyConfigured('settings.FREEZE_ROOT should be an absolute path')
if settings.MEDIA_ROOT.find(FREEZE_ROOT) == 0 or settings.STATIC_ROOT.find(FREEZE_ROOT) == 0:
raise ImproperlyConfigured('settings.FREEZE_ROOT cannot be a subdirectory of MEDIA_ROOT or STATIC_ROOT')
FREEZE_MEDIA_ROOT = settings.MEDIA_ROOT
FREEZE_MEDIA_URL = settings.MEDIA_URL
FREEZE_STATIC_ROOT = settings.STATIC_ROOT
FREEZE_STATIC_URL = settings.STATIC_URL
FREEZE_USE_HTTPS = getattr(settings, 'FREEZE_USE_HTTPS', False)
FREEZE_PROTOCOL = 'https://' if FREEZE_USE_HTTPS else 'http://'
FREEZE_SITE_URL = getattr(settings, 'FREEZE_SITE_URL', None)
if(FREEZE_SITE_URL == None):
# handled this way to remove DB dependency unless strictly needed. If FREEZE_SITE_URL is set then collectstatic
# can be called without needing a db setup, which is useful for build servers
FREEZE_SITE_URL = '%s%s' % (FREEZE_PROTOCOL, Site.objects.get_current().domain,)
FREEZE_BASE_URL = getattr(settings, 'FREEZE_BASE_URL', None)
if FREEZE_BASE_URL:
if FREEZE_BASE_URL.startswith('/') or FREEZE_BASE_URL.startswith('http'):
if not FREEZE_BASE_URL.endswith('/'):
FREEZE_BASE_URL += '/'
else:
raise ImproperlyConfigured('settings.FREEZE_BASE_URL should start with \'/\' or \'http\' or be an empty string')
FREEZE_RELATIVE_URLS = getattr(settings, 'FREEZE_RELATIVE_URLS', False)
if FREEZE_RELATIVE_URLS and FREEZE_BASE_URL != None:
raise ImproperlyConfigured('settings.FREEZE_RELATIVE_URLS cannot be set to True if FREEZE_BASE_URL is specified')
FREEZE_LOCAL_URLS = getattr(settings, 'FREEZE_LOCAL_URLS', False)
if FREEZE_LOCAL_URLS and not FREEZE_RELATIVE_URLS:
raise ImproperlyConfigured('settings.FREEZE_LOCAL_URLS cannot be set to True if FREEZE_RELATIVE_URLS is set to False')
FREEZE_FOLLOW_SITEMAP_URLS = getattr(settings, 'FREEZE_FOLLOW_SITEMAP_URLS', True)
FREEZE_FOLLOW_HTML_URLS = getattr(settings, 'FREEZE_FOLLOW_HTML_URLS', True)
FREEZE_REPORT_INVALID_URLS = getattr(settings, 'FREEZE_REPORT_INVALID_URLS', False)
FREEZE_REPORT_INVALID_URLS_SUBJECT = getattr(settings, 'FREEZE_REPORT_INVALID_URLS_SUBJECT', '[freeze] invalid urls')
FREEZE_INCLUDE_MEDIA = getattr(settings, 'FREEZE_INCLUDE_MEDIA', True)
FREEZE_INCLUDE_STATIC = getattr(settings, 'FREEZE_INCLUDE_STATIC', True)
FREEZE_ZIP_ALL = getattr(settings, 'FREEZE_ZIP_ALL', False)
FREEZE_ZIP_NAME = getattr(settings, 'FREEZE_ZIP_NAME', 'freeze')
if len(FREEZE_ZIP_NAME) >= 4 and FREEZE_ZIP_NAME[-4:].lower() != '.zip':
FREEZE_ZIP_NAME += '.zip'
FREEZE_ZIP_PATH = os.path.abspath(os.path.join(FREEZE_ROOT, FREEZE_ZIP_NAME))
FREEZE_REQUEST_HEADERS = getattr(settings, 'FREEZE_REQUEST_HEADERS', {'user-agent': 'django-freeze'})<|fim▁end|> | import os |
<|file_name|>issue-65041-empty-vis-matcher-in-enum.rs<|end_file_name|><|fim▁begin|>// check-pass
// Here we check that a `:vis` macro matcher subsititued for the empty visibility
// (`VisibilityKind::Inherited`) is accepted when used before an enum variant.
fn main() {}
macro_rules! mac_variant {
($vis:vis MARKER) => {
enum Enum {
$vis Unit,
$vis Tuple(u8, u16),
$vis Struct { f: u8 },
}
}<|fim▁hole|>// We also accept visibilities on variants syntactically but not semantically.
#[cfg(FALSE)]
enum E {
pub U,
pub(crate) T(u8),
pub(super) T { f: String }
}<|fim▁end|> | }
mac_variant!(MARKER);
|
<|file_name|>setup.py<|end_file_name|><|fim▁begin|>import re
from setuptools import setup, find_packages
__version__ = re.search(r"__version__.*\s*=\s*[']([^']+)[']",
open('dateparser/__init__.py').read()).group(1)
introduction = re.sub(r':members:.+|..\sautomodule::.+|:class:|:func:|:ref:',
'', open('docs/introduction.rst').read())
history = re.sub(r':mod:|:class:|:func:', '', open('HISTORY.rst').read())
test_requirements = open('tests/requirements.txt').read().splitlines()
setup(
name='dateparser',
version=__version__,
description='Date parsing library designed to parse dates from HTML pages',
long_description=introduction + '\n\n' + history,
author='Scrapinghub',
author_email='[email protected]',
url='https://github.com/scrapinghub/dateparser',
project_urls={
'History': 'https://dateparser.readthedocs.io/en/latest/history.html',
},
packages=find_packages(exclude=('tests', 'tests.*')),
include_package_data=True,
install_requires=[
'python-dateutil',
'pytz',
# https://bitbucket.org/mrabarnett/mrab-regex/issues/314/import-error-no-module-named
'regex !=2019.02.19,!=2021.8.27',
'tzlocal',
],
entry_points={
'console_scripts': ['dateparser-download = dateparser_cli.cli:entrance'],
},
extras_require={
'calendars:python_version<"3.6"': ['convertdate'],
'calendars:python_version>="3.6"': ['hijri-converter', 'convertdate'],
'fasttext': ['fasttext'],
'langdetect': ['langdetect'],
},
license="BSD",
zip_safe=False,
keywords='dateparser',
python_requires='>=3.5',
classifiers=[
'Development Status :: 5 - Production/Stable',
'Intended Audience :: Developers',
'License :: OSI Approved :: BSD License',
'Natural Language :: English',
'Programming Language :: Python :: 3',<|fim▁hole|> 'Programming Language :: Python :: 3.7',
'Programming Language :: Python :: 3.8',
'Programming Language :: Python :: 3.9',
'Programming Language :: Python :: Implementation :: CPython',
],
)<|fim▁end|> | 'Programming Language :: Python :: 3.5',
'Programming Language :: Python :: 3.6', |
<|file_name|>DatabaseSchemaExplorerView.java<|end_file_name|><|fim▁begin|>/*
* Copyright 2016 Red Hat, Inc. and/or its affiliates.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.kie.workbench.common.screens.datasource.management.client.dbexplorer.schemas;
import com.google.gwt.view.client.AsyncDataProvider;
import org.uberfire.client.mvp.UberElement;
import org.uberfire.ext.widgets.common.client.common.HasBusyIndicator;
public interface DatabaseSchemaExplorerView
extends UberElement< DatabaseSchemaExplorerView.Presenter >, HasBusyIndicator {
interface Presenter {
void onOpen( DatabaseSchemaRow row );
}
<|fim▁hole|>
void setDataProvider( AsyncDataProvider< DatabaseSchemaRow > dataProvider );
void redraw( );
}<|fim▁end|> | interface Handler {
void onOpen( String schemaName );
} |
<|file_name|>index.ts<|end_file_name|><|fim▁begin|>import { useContext } from '../ContextProvider';
import { UseVariablesResult } from './types';
function useVariables(): UseVariablesResult {
const {
search: { variables },
} = useContext();
return { variables };
}<|fim▁hole|><|fim▁end|> |
export default useVariables;
export * from './types'; |
<|file_name|>ButtonProperty.java<|end_file_name|><|fim▁begin|>/*
* Freeplane - mind map editor
* Copyright (C) 2008 Joerg Mueller, Daniel Polansky, Christian Foltin, Dimitry Polivaev
*
* This file is modified by Felix Natter in 2013.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package org.freeplane.core.resources.components;
import javax.swing.JButton;
import com.jgoodies.forms.builder.DefaultFormBuilder;
public class ButtonProperty extends PropertyBean implements IPropertyControl {
final JButton mButton;
/**<|fim▁hole|> mButton = button;
}
@Override
public String getValue() {
return "";
}
public void appendToForm(final DefaultFormBuilder builder) {
appendToForm(builder, mButton);
}
public void setEnabled(final boolean pEnabled) {
mButton.setEnabled(pEnabled);
super.setEnabled(pEnabled);
}
@Override
public void setValue(final String value) {
}
public void setToolTipText(String text) {
mButton.setToolTipText(text);
}
}<|fim▁end|> | */
public ButtonProperty(final String name, JButton button) {
super(name); |
<|file_name|>IdempotentPredicate.java<|end_file_name|><|fim▁begin|>/*
* JBoss, Home of Professional Open Source.
* Copyright 2014 Red Hat, Inc., and individual contributors
* as indicated by the @author tags.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.undertow.predicate;
import java.util.Collections;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import io.undertow.server.HttpServerExchange;
import io.undertow.util.HttpString;
import io.undertow.util.Methods;
/**
* A predicate that returns true if the request is idempotent
* according to the HTTP RFC.
*
* @author Stuart Douglas
*/
public class IdempotentPredicate implements Predicate {
public static final IdempotentPredicate INSTANCE = new IdempotentPredicate();
private static final Set<HttpString> METHODS;
static {
Set<HttpString> methods = new HashSet<>();
methods.add(Methods.GET);
methods.add(Methods.DELETE);
methods.add(Methods.PUT);
methods.add(Methods.HEAD);
methods.add(Methods.OPTIONS);
METHODS = Collections.unmodifiableSet(methods);
}
@Override
public boolean resolve(HttpServerExchange value) {
return METHODS.contains(value.getRequestMethod());<|fim▁hole|> public static class Builder implements PredicateBuilder {
@Override
public String name() {
return "idempotent";
}
@Override
public Map<String, Class<?>> parameters() {
return Collections.emptyMap();
}
@Override
public Set<String> requiredParameters() {
return Collections.emptySet();
}
@Override
public String defaultParameter() {
return null;
}
@Override
public Predicate build(Map<String, Object> config) {
return INSTANCE;
}
}
}<|fim▁end|> | }
|
<|file_name|>lib.rs<|end_file_name|><|fim▁begin|>#![crate_id = "oauth"]
#![crate_type="lib"]
//! A gated server request handler
//!
//! All requests will be passed through a basic oAuth 'gate'
//! before being allowed to see the request handler.
// This allows for debug macros
// Use the macros by setting your RUST_LOG environment variable appropriately
#![feature(phase)]<|fim▁hole|>#[phase(syntax, link)] extern crate log;
extern crate http;
extern crate url;
pub mod server;<|fim▁end|> | |
<|file_name|>generic.py<|end_file_name|><|fim▁begin|>"""
Custom Authenticator to use generic OAuth2 with JupyterHub
"""
import base64
import os
from urllib.parse import urlencode
from jupyterhub.auth import LocalAuthenticator
from tornado.httpclient import AsyncHTTPClient
from tornado.httpclient import HTTPRequest
from tornado.httputil import url_concat
from traitlets import Bool
from traitlets import default
from traitlets import Dict
from traitlets import List
from traitlets import Unicode
from traitlets import Union
from .oauth2 import OAuthenticator
from .traitlets import Callable
class GenericOAuthenticator(OAuthenticator):
login_service = Unicode("OAuth 2.0", config=True)
extra_params = Dict(help="Extra parameters for first POST request").tag(config=True)
claim_groups_key = Union(
[Unicode(os.environ.get('OAUTH2_GROUPS_KEY', 'groups')), Callable()],
config=True,
help="""
Userdata groups claim key from returned json for USERDATA_URL.
Can be a string key name or a callable that accepts the returned
json (as a dict) and returns the groups list. The callable is useful
e.g. for extracting the groups from a nested object in the response.
""",
)
allowed_groups = List(
Unicode(),
config=True,
help="Automatically allow members of selected groups",
)
admin_groups = List(
Unicode(),
config=True,
help="Groups whose members should have Jupyterhub admin privileges",
)
username_key = Union(
[Unicode(os.environ.get('OAUTH2_USERNAME_KEY', 'username')), Callable()],
config=True,
help="""
Userdata username key from returned json for USERDATA_URL.
<|fim▁hole|> Can be a string key name or a callable that accepts the returned
json (as a dict) and returns the username. The callable is useful
e.g. for extracting the username from a nested object in the
response.
""",
)
userdata_params = Dict(
help="Userdata params to get user data login information"
).tag(config=True)
userdata_token_method = Unicode(
os.environ.get('OAUTH2_USERDATA_REQUEST_TYPE', 'header'),
config=True,
help="Method for sending access token in userdata request. Supported methods: header, url. Default: header",
)
tls_verify = Bool(
os.environ.get('OAUTH2_TLS_VERIFY', 'True').lower() in {'true', '1'},
config=True,
help="Disable TLS verification on http request",
)
basic_auth = Bool(
os.environ.get('OAUTH2_BASIC_AUTH', 'True').lower() in {'true', '1'},
config=True,
help="Disable basic authentication for access token request",
)
@default("http_client")
def _default_http_client(self):
return AsyncHTTPClient(
force_instance=True, defaults=dict(validate_cert=self.tls_verify)
)
def _get_headers(self):
headers = {"Accept": "application/json", "User-Agent": "JupyterHub"}
if self.basic_auth:
b64key = base64.b64encode(
bytes("{}:{}".format(self.client_id, self.client_secret), "utf8")
)
headers.update({"Authorization": "Basic {}".format(b64key.decode("utf8"))})
return headers
def _get_token(self, headers, params):
if self.token_url:
url = self.token_url
else:
raise ValueError("Please set the $OAUTH2_TOKEN_URL environment variable")
req = HTTPRequest(
url,
method="POST",
headers=headers,
body=urlencode(params),
)
return self.fetch(req, "fetching access token")
def _get_user_data(self, token_response):
access_token = token_response['access_token']
token_type = token_response['token_type']
# Determine who the logged in user is
headers = {
"Accept": "application/json",
"User-Agent": "JupyterHub",
"Authorization": "{} {}".format(token_type, access_token),
}
if self.userdata_url:
url = url_concat(self.userdata_url, self.userdata_params)
else:
raise ValueError("Please set the OAUTH2_USERDATA_URL environment variable")
if self.userdata_token_method == "url":
url = url_concat(self.userdata_url, dict(access_token=access_token))
req = HTTPRequest(url, headers=headers)
return self.fetch(req, "fetching user data")
@staticmethod
def _create_auth_state(token_response, user_data_response):
access_token = token_response['access_token']
refresh_token = token_response.get('refresh_token', None)
scope = token_response.get('scope', '')
if isinstance(scope, str):
scope = scope.split(' ')
return {
'access_token': access_token,
'refresh_token': refresh_token,
'oauth_user': user_data_response,
'scope': scope,
}
@staticmethod
def check_user_in_groups(member_groups, allowed_groups):
return bool(set(member_groups) & set(allowed_groups))
async def authenticate(self, handler, data=None):
code = handler.get_argument("code")
params = dict(
redirect_uri=self.get_callback_url(handler),
code=code,
grant_type='authorization_code',
)
params.update(self.extra_params)
headers = self._get_headers()
token_resp_json = await self._get_token(headers, params)
user_data_resp_json = await self._get_user_data(token_resp_json)
if callable(self.username_key):
name = self.username_key(user_data_resp_json)
else:
name = user_data_resp_json.get(self.username_key)
if not name:
self.log.error(
"OAuth user contains no key %s: %s",
self.username_key,
user_data_resp_json,
)
return
user_info = {
'name': name,
'auth_state': self._create_auth_state(token_resp_json, user_data_resp_json),
}
if self.allowed_groups:
self.log.info(
'Validating if user claim groups match any of {}'.format(
self.allowed_groups
)
)
if callable(self.claim_groups_key):
groups = self.claim_groups_key(user_data_resp_json)
else:
groups = user_data_resp_json.get(self.claim_groups_key)
if not groups:
self.log.error(
"No claim groups found for user! Something wrong with the `claim_groups_key` {}? {}".format(
self.claim_groups_key, user_data_resp_json
)
)
groups = []
if self.check_user_in_groups(groups, self.allowed_groups):
user_info['admin'] = self.check_user_in_groups(
groups, self.admin_groups
)
else:
user_info = None
return user_info
class LocalGenericOAuthenticator(LocalAuthenticator, GenericOAuthenticator):
"""A version that mixes in local system user creation"""
pass<|fim▁end|> | |
<|file_name|>YearItemType.java<|end_file_name|><|fim▁begin|>/**
* Copyright (c) 2016, The National Archives <[email protected]>
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following
* conditions are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* * Neither the name of the The National Archives nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
//
// This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.1-b02-fcs
// See <a href="http://java.sun.com/xml/jaxb">http://java.sun.com/xml/jaxb</a>
// Any modifications to this file will be lost upon recompilation of the source schema.
// Generated on: 2010.03.22 at 11:40:59 AM GMT
//
package uk.gov.nationalarchives.droid.report.planets.domain;
import java.math.BigDecimal;
import java.math.BigInteger;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlSchemaType;
import javax.xml.bind.annotation.XmlType;
import javax.xml.datatype.XMLGregorianCalendar;
/**
* <p>Java class for YearItemType complex type.
*
* <p>The following schema fragment specifies the expected content contained within this class.
*
* <pre>
* <complexType name="YearItemType">
* <complexContent>
* <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
* <sequence>
* <element name="year" type="{http://www.w3.org/2001/XMLSchema}gYear"/>
* <element name="numFiles" type="{http://www.w3.org/2001/XMLSchema}integer"/>
* <element name="totalFileSize" type="{http://www.w3.org/2001/XMLSchema}decimal"/>
* </sequence>
* </restriction>
* </complexContent>
* </complexType>
* </pre>
*
* @deprecated PLANETS XML is now generated using XSLT over normal report xml files.
*/
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "YearItemType", propOrder = {
"year",
"numFiles",
"totalFileSize"
})
@Deprecated
public class YearItemType {
@XmlElement(required = true)
@XmlSchemaType(name = "gYear")
protected XMLGregorianCalendar year;
@XmlElement(required = true)
protected BigInteger numFiles;
<|fim▁hole|> /**
* Gets the value of the year property.
*
* @return
* possible object is
* {@link XMLGregorianCalendar }
*
*/
public XMLGregorianCalendar getYear() {
return year;
}
/**
* Sets the value of the year property.
*
* @param value
* allowed object is
* {@link XMLGregorianCalendar }
*
*/
public void setYear(XMLGregorianCalendar value) {
this.year = value;
}
/**
* Gets the value of the numFiles property.
*
* @return
* possible object is
* {@link BigInteger }
*
*/
public BigInteger getNumFiles() {
return numFiles;
}
/**
* Sets the value of the numFiles property.
*
* @param value
* allowed object is
* {@link BigInteger }
*
*/
public void setNumFiles(BigInteger value) {
this.numFiles = value;
}
/**
* Gets the value of the totalFileSize property.
*
* @return
* possible object is
* {@link BigDecimal }
*
*/
public BigDecimal getTotalFileSize() {
return totalFileSize;
}
/**
* Sets the value of the totalFileSize property.
*
* @param value
* allowed object is
* {@link BigDecimal }
*
*/
public void setTotalFileSize(BigDecimal value) {
this.totalFileSize = value;
}
}<|fim▁end|> | @XmlElement(required = true)
protected BigDecimal totalFileSize;
|
<|file_name|>bootstrap-formhelpers-countries.en_US.js<|end_file_name|><|fim▁begin|>/* ==========================================================
* bootstrap-formhelpers-countries.en_US.js
* https://github.com/vlamanna/BootstrapFormHelpers
* ==========================================================
* Copyright 2012 Vincent Lamanna
*
* 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.
* ========================================================== */
var BFHCountriesList = {
'AF': 'Afghanistan',
'AL': 'Albania',
'DZ': 'Algeria',
'AS': 'American Samoa',
'AD': 'Andorra',
'AO': 'Angola',
'AI': 'Anguilla',
'AQ': 'Antarctica',
'AG': 'Antigua and Barbuda',
'AR': 'Argentina',
'AM': 'Armenia',
'AW': 'Aruba',
'AU': 'Australia',
'AT': 'Austria',
'AZ': 'Azerbaijan',
'BH': 'Bahrain',
'BD': 'Bangladesh',
'BB': 'Barbados',
'BY': 'Belarus',
'BE': 'Belgium',
'BZ': 'Belize',
'BJ': 'Benin',
'BM': 'Bermuda',
'BT': 'Bhutan',
'BO': 'Bolivia',
'BA': 'Bosnia and Herzegovina',
'BW': 'Botswana',
'BV': 'Bouvet Island',
'BR': 'Brazil',
'IO': 'British Indian Ocean Territory',
'VG': 'British Virgin Islands',
'BN': 'Brunei',
'BG': 'Bulgaria',
'BF': 'Burkina Faso',
'BI': 'Burundi',
'CI': 'Côte d\'Ivoire',
'KH': 'Cambodia',
'CM': 'Cameroon',
'CA': 'Canada',
'CV': 'Cape Verde',
'KY': 'Cayman Islands',
'CF': 'Central African Republic',
'TD': 'Chad',
'CL': 'Chile',
'CN': 'China',
'CX': 'Christmas Island',
'CC': 'Cocos (Keeling) Islands',
'CO': 'Colombia',
'KM': 'Comoros',
'CG': 'Congo',
'CK': 'Cook Islands',
'CR': 'Costa Rica',
'HR': 'Croatia',
'CU': 'Cuba',
'CY': 'Cyprus',
'CZ': 'Czech Republic',
'CD': 'Democratic Republic of the Congo',
'DK': 'Denmark',
'DJ': 'Djibouti',
'DM': 'Dominica',
'DO': 'Dominican Republic',<|fim▁hole|> 'SV': 'El Salvador',
'GQ': 'Equatorial Guinea',
'ER': 'Eritrea',
'EE': 'Estonia',
'ET': 'Ethiopia',
'FO': 'Faeroe Islands',
'FK': 'Falkland Islands',
'FJ': 'Fiji',
'FI': 'Finland',
'MK': 'Former Yugoslav Republic of Macedonia',
'FR': 'France',
'FX': 'France, Metropolitan',
'GF': 'French Guiana',
'PF': 'French Polynesia',
'TF': 'French Southern Territories',
'GA': 'Gabon',
'GE': 'Georgia',
'DE': 'Germany',
'GH': 'Ghana',
'GI': 'Gibraltar',
'GR': 'Greece',
'GL': 'Greenland',
'GD': 'Grenada',
'GP': 'Guadeloupe',
'GU': 'Guam',
'GT': 'Guatemala',
'GN': 'Guinea',
'GW': 'Guinea-Bissau',
'GY': 'Guyana',
'HT': 'Haiti',
'HM': 'Heard and Mc Donald Islands',
'HN': 'Honduras',
'HK': 'Hong Kong',
'HU': 'Hungary',
'IS': 'Iceland',
'IN': 'India',
'ID': 'Indonesia',
'IR': 'Iran',
'IQ': 'Iraq',
'IE': 'Ireland',
'IL': 'Israel',
'IT': 'Italy',
'JM': 'Jamaica',
'JP': 'Japan',
'JO': 'Jordan',
'KZ': 'Kazakhstan',
'KE': 'Kenya',
'KI': 'Kiribati',
'KW': 'Kuwait',
'KG': 'Kyrgyzstan',
'LA': 'Laos',
'LV': 'Latvia',
'LB': 'Lebanon',
'LS': 'Lesotho',
'LR': 'Liberia',
'LY': 'Libya',
'LI': 'Liechtenstein',
'LT': 'Lithuania',
'LU': 'Luxembourg',
'MO': 'Macau',
'MG': 'Madagascar',
'MW': 'Malawi',
'MY': 'Malaysia',
'MV': 'Maldives',
'ML': 'Mali',
'MT': 'Malta',
'MH': 'Marshall Islands',
'MQ': 'Martinique',
'MR': 'Mauritania',
'MU': 'Mauritius',
'YT': 'Mayotte',
'MX': 'Mexico',
'FM': 'Micronesia',
'MD': 'Moldova',
'MC': 'Monaco',
'MN': 'Mongolia',
'ME': 'Montenegro',
'MS': 'Montserrat',
'MA': 'Morocco',
'MZ': 'Mozambique',
'MM': 'Myanmar',
'NA': 'Namibia',
'NR': 'Nauru',
'NP': 'Nepal',
'NL': 'Netherlands',
'AN': 'Netherlands Antilles',
'NC': 'New Caledonia',
'NZ': 'New Zealand',
'NI': 'Nicaragua',
'NE': 'Niger',
'NG': 'Nigeria',
'NU': 'Niue',
'NF': 'Norfolk Island',
'KP': 'North Korea',
'MP': 'Northern Marianas',
'NO': 'Norway',
'OM': 'Oman',
'PK': 'Pakistan',
'PW': 'Palau',
'PS': 'Palestine',
'PA': 'Panama',
'PG': 'Papua New Guinea',
'PY': 'Paraguay',
'PE': 'Peru',
'PH': 'Philippines',
'PN': 'Pitcairn Islands',
'PL': 'Poland',
'PT': 'Portugal',
'PR': 'Puerto Rico',
'QA': 'Qatar',
'RE': 'Reunion',
'RO': 'Romania',
'RU': 'Russia',
'RW': 'Rwanda',
'ST': 'São Tomé and Príncipe',
'SH': 'Saint Helena',
'PM': 'St. Pierre and Miquelon',
'KN': 'Saint Kitts and Nevis',
'LC': 'Saint Lucia',
'VC': 'Saint Vincent and the Grenadines',
'WS': 'Samoa',
'SM': 'San Marino',
'SA': 'Saudi Arabia',
'SN': 'Senegal',
'RS': 'Serbia',
'SC': 'Seychelles',
'SL': 'Sierra Leone',
'SG': 'Singapore',
'SK': 'Slovakia',
'SI': 'Slovenia',
'SB': 'Solomon Islands',
'SO': 'Somalia',
'ZA': 'South Africa',
'GS': 'South Georgia and the South Sandwich Islands',
'KR': 'South Korea',
'ES': 'Spain',
'LK': 'Sri Lanka',
'SD': 'Sudan',
'SR': 'Suriname',
'SJ': 'Svalbard and Jan Mayen Islands',
'SZ': 'Swaziland',
'SE': 'Sweden',
'CH': 'Switzerland',
'SY': 'Syria',
'TW': 'Taiwan',
'TJ': 'Tajikistan',
'TZ': 'Tanzania',
'TH': 'Thailand',
'BS': 'The Bahamas',
'GM': 'The Gambia',
'TG': 'Togo',
'TK': 'Tokelau',
'TO': 'Tonga',
'TT': 'Trinidad and Tobago',
'TN': 'Tunisia',
'TR': 'Turkey',
'TM': 'Turkmenistan',
'TC': 'Turks and Caicos Islands',
'TV': 'Tuvalu',
'VI': 'US Virgin Islands',
'UG': 'Uganda',
'UA': 'Ukraine',
'AE': 'United Arab Emirates',
'GB': 'United Kingdom',
'US': 'United States',
'UM': 'United States Minor Outlying Islands',
'UY': 'Uruguay',
'UZ': 'Uzbekistan',
'VU': 'Vanuatu',
'VA': 'Vatican City',
'VE': 'Venezuela',
'VN': 'Vietnam',
'WF': 'Wallis and Futuna Islands',
'EH': 'Western Sahara',
'YE': 'Yemen',
'ZM': 'Zambia',
'ZW': 'Zimbabwe'
};<|fim▁end|> | 'TP': 'East Timor',
'EC': 'Ecuador',
'EG': 'Egypt', |
<|file_name|>BanquetController.java<|end_file_name|><|fim▁begin|><|fim▁hole|>package com.jerry.controller;
import com.jerry.model.TBanquet;
import com.jerry.service.BanquetService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import java.util.List;
@RestController
@RequestMapping("/banquet")
public class BanquetController {
@Autowired
BanquetService banquetService;
@GetMapping("/listBanquetByRestaurantId")
public List<TBanquet> listBanquetByRestaurantId(String restaurantId) {
return banquetService.listBanquetByRestaurantId(restaurantId);
}
@GetMapping("/findOne")
public TBanquet findOne(String banquetId) {
return banquetService.findOne(banquetId);
}
}<|fim▁end|> | |
<|file_name|>bpf.rs<|end_file_name|><|fim▁begin|>// Copyright (c) 2014 Robert Clipsham <[email protected]>
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
#![allow(non_camel_case_types)]
#![allow(non_snake_case)]
#![allow(dead_code)]
extern crate libc;
use sockets;
pub const AF_LINK: libc::c_int = 18;
const IF_NAMESIZE: usize = 16;
const IFNAMSIZ: usize = IF_NAMESIZE;
const IOC_IN: libc::c_ulong = 0x80000000;
const IOC_OUT: libc::c_ulong = 0x40000000;
const IOC_INOUT: libc::c_ulong = IOC_IN | IOC_OUT;
const IOCPARM_SHIFT: libc::c_ulong = 13;
const IOCPARM_MASK: libc::c_ulong = (1 << (IOCPARM_SHIFT as usize)) - 1;
const SIZEOF_TIMEVAL: libc::c_ulong = 16;
const SIZEOF_IFREQ: libc::c_ulong = 32;
const SIZEOF_C_UINT: libc::c_ulong = 4;
#[cfg(target_os = "freebsd")]
const SIZEOF_C_LONG: libc::c_int = 8;
pub const BIOCSETIF: libc::c_ulong = IOC_IN | ((SIZEOF_IFREQ & IOCPARM_MASK) << 16usize) |
(('B' as libc::c_ulong) << 8usize) |
108;
pub const BIOCIMMEDIATE: libc::c_ulong = IOC_IN | ((SIZEOF_C_UINT & IOCPARM_MASK) << 16) |
(('B' as libc::c_ulong) << 8) |
112;
pub const BIOCGBLEN: libc::c_ulong = IOC_OUT | ((SIZEOF_C_UINT & IOCPARM_MASK) << 16) |
(('B' as libc::c_ulong) << 8) |
102;
pub const BIOCGDLT: libc::c_ulong = IOC_OUT | ((SIZEOF_C_UINT & IOCPARM_MASK) << 16) |
(('B' as libc::c_ulong) << 8) |
106;
pub const BIOCSBLEN: libc::c_ulong = IOC_INOUT | ((SIZEOF_C_UINT & IOCPARM_MASK) << 16) |
(('B' as libc::c_ulong) << 8) |
102;
pub const BIOCSHDRCMPLT: libc::c_ulong = IOC_IN | ((SIZEOF_C_UINT & IOCPARM_MASK) << 16) |
(('B' as libc::c_ulong) << 8) |
117;
pub const BIOCSRTIMEOUT: libc::c_ulong = IOC_IN | ((SIZEOF_TIMEVAL & IOCPARM_MASK) << 16) |
(('B' as libc::c_ulong) << 8) |
109;
#[cfg(target_os = "freebsd")]
pub const BIOCFEEDBACK: libc::c_ulong = IOC_IN | ((SIZEOF_C_UINT & IOCPARM_MASK) << 16) |
(('B' as libc::c_ulong) << 8) |
124;
// NOTE Could use BIOCSSEESENT on OS X, though set to 1 by default anyway
pub const DLT_NULL: libc::c_uint = 0;
#[cfg(target_os = "freebsd")]
const BPF_ALIGNMENT: libc::c_int = SIZEOF_C_LONG;
#[cfg(any(target_os = "macos", windows))]
const BPF_ALIGNMENT: libc::c_int = 4;
pub fn BPF_WORDALIGN(x: isize) -> isize {
let bpf_alignment = BPF_ALIGNMENT as isize;
let one = 1;
(x + (bpf_alignment - one)) & !(bpf_alignment - one)
}
// See /usr/include/net/if.h
pub struct ifreq {
pub ifr_name: [libc::c_char; IFNAMSIZ],
pub ifru_addr: sockets::SockAddr, // NOTE Should be a union
}
// See /usr/include/net/if_dl.h
// sdl_data does not match if_dl.h on OS X, since the size of 12 is a minimum.
// Will be unsafe
// when sdl_nlen > 40.
#[cfg(any(target_os = "freebsd", target_os = "macos"))]
pub struct sockaddr_dl {
pub sdl_len: libc::c_uchar,
pub sdl_family: libc::c_uchar,
pub sdl_index: libc::c_ushort,
pub sdl_type: libc::c_uchar,
pub sdl_nlen: libc::c_uchar,
pub sdl_alen: libc::c_uchar,
pub sdl_slen: libc::c_uchar,
pub sdl_data: [libc::c_char; 46],
}
// See man 4 bpf or /usr/include/net/bpf.h [windows: or Common/Packet32.h]
#[cfg(any(target_os = "freebsd", all(target_os = "macos", target_pointer_width = "32"), windows))]
pub struct bpf_hdr {
pub bh_tstamp: libc::timeval,
pub bh_caplen: u32,
pub bh_datalen: u32,
pub bh_hdrlen: libc::c_ushort,
}
pub struct timeval32 {
pub tv_sec: i32,
pub tv_usec: i32,
}
#[cfg(all(target_os = "macos", target_pointer_width = "64"))]
pub struct bpf_hdr {
pub bh_tstamp: timeval32,
pub bh_caplen: u32,
pub bh_datalen: u32,
pub bh_hdrlen: libc::c_ushort,<|fim▁hole|> pub fn ioctl(d: libc::c_int, request: libc::c_ulong, ...) -> libc::c_int;
}<|fim▁end|> | }
#[cfg(not(windows))]
extern { |
<|file_name|>new.js<|end_file_name|><|fim▁begin|><p><|fim▁hole|><p>
<form method="POST" action="/quizzes/<%=quiz.id%>/comments/">
<input type="text" id="comment" name="comment[text]" value="" placeholder="Comentario" /> <p>
<button type="submit">Enviar</button>
</form>
</p><|fim▁end|> | Añadir nuevo comentario:
</p>
|
<|file_name|>gaussian.py<|end_file_name|><|fim▁begin|>import numpy as np
def gauss(win, sigma):
x = np.arange(0, win, 1, float)
y = x[:,np.newaxis]
x0 = y0 = win // 2
g=1/(2*np.pi*sigma**2)*np.exp((((x-x0)**2+(y-y0)**2))/2*sigma**2)
return g
<|fim▁hole|> x0 = y0 = win // 2
gx=(x-x0)/(2*np.pi*sigma**4)*np.exp((((x-x0)**2+(y-y0)**2))/2*sigma**2)
return gx
def gaussy(win, sigma):
x = np.arange(0, win, 1, float)
y = x[:,np.newaxis]
x0 = y0 = win // 2
gy=(y-y0)/(2*np.pi*sigma**4)*np.exp((((x-x0)**2+(y-y0)**2))/2*sigma**2)
return gy<|fim▁end|> | def gaussx(win, sigma):
x = np.arange(0, win, 1, float)
y = x[:,np.newaxis]
|
<|file_name|>docker.rs<|end_file_name|><|fim▁begin|>use std::io;
use std::io::prelude::*;
use std::mem;
use std::process::{Output, Command, Stdio, ExitStatus};
use std::sync::{Arc, Mutex};
use std::thread;
use std::time::{Duration, Instant};
use wait_timeout::ChildExt;
pub struct Container {
id: String,
}
impl Container {
pub fn new(cmd: &str,
args: &[String],
env: &[(String, String)],
name: &str) -> io::Result<Container> {
let out = try!(run(Command::new("docker")
.arg("create")
.arg("--cap-drop=ALL")
.arg("--memory=128m")
.arg("--net=none")
.arg("--pids-limit=20")
.arg("--security-opt=no-new-privileges")
.arg("--interactive")
.args(&env.iter().map(|&(ref k, ref v)| format!("--env={}={}", k, v)).collect::<Vec<_>>())
.arg(name)
.arg(cmd)
.stderr(Stdio::inherit())
.args(args)));
let stdout = String::from_utf8_lossy(&out.stdout);
Ok(Container {
id: stdout.trim().to_string(),
})
}<|fim▁hole|> input: &[u8],
timeout: Duration)
-> io::Result<(ExitStatus, Vec<u8>, bool)> {
let mut cmd = Command::new("docker");
cmd.arg("start")
.arg("--attach")
.arg("--interactive")
.arg(&self.id)
.stdin(Stdio::piped())
.stdout(Stdio::piped())
.stderr(Stdio::piped());
debug!("attaching with {:?}", cmd);
let start = Instant::now();
let mut cmd = try!(cmd.spawn());
try!(cmd.stdin.take().unwrap().write_all(input));
debug!("input written, now waiting");
let mut stdout = cmd.stdout.take().unwrap();
let mut stderr = cmd.stderr.take().unwrap();
let sink = Arc::new(Mutex::new(Vec::new()));
let sink2 = sink.clone();
let stdout = thread::spawn(move || append(&sink2, &mut stdout));
let sink2 = sink.clone();
let stderr = thread::spawn(move || append(&sink2, &mut stderr));
let (status, timeout) = match try!(cmd.wait_timeout(timeout)) {
Some(status) => {
debug!("finished before timeout");
// TODO: document this
(unsafe { mem::transmute(status) }, false)
}
None => {
debug!("timeout, going to kill");
try!(run(Command::new("docker").arg("kill").arg(&self.id)));
(try!(cmd.wait()), true)
}
};
stdout.join().unwrap();
stderr.join().unwrap();
debug!("timing: {:?}", start.elapsed());
let mut lock = sink.lock().unwrap();
let output = mem::replace(&mut *lock, Vec::new());
debug!("status: {}", status);
{
let output_lossy = String::from_utf8_lossy(&output);
if output_lossy.len() < 1024 {
debug!("output: {}", output_lossy);
} else {
let s = output_lossy.chars().take(1024).collect::<String>();
debug!("output (truncated): {}...", s);
}
}
Ok((status, output, timeout))
}
}
fn append(into: &Mutex<Vec<u8>>, from: &mut Read) {
let mut buf = [0; 1024];
while let Ok(amt) = from.read(&mut buf) {
if amt == 0 {
break
}
into.lock().unwrap().extend_from_slice(&buf[..amt]);
}
}
impl Drop for Container {
fn drop(&mut self) {
run(Command::new("docker")
.arg("rm")
.arg("--force")
.arg(&self.id)).unwrap();
}
}
fn run(cmd: &mut Command) -> io::Result<Output> {
debug!("spawning: {:?}", cmd);
let start = Instant::now();
let out = try!(cmd.output());
debug!("done in: {:?}", start.elapsed());
debug!("output: {:?}", out);
if !out.status.success() {
let msg = format!("process failed: {:?}\n{:?}", cmd, out);
return Err(io::Error::new(io::ErrorKind::Other, msg))
}
Ok(out)
}<|fim▁end|> |
pub fn run(&self, |
<|file_name|>lib.rs<|end_file_name|><|fim▁begin|><|fim▁hole|>}
#[cfg(not(feature = "mockbuild"))]
pub fn non_sysroot_api() {
core::custom_api();
alloc::custom_api();
}<|fim▁end|> | #[cfg(feature = "mockbuild")]
pub fn custom_api() { |
<|file_name|>legend_highlighter.py<|end_file_name|><|fim▁begin|># proxy module<|fim▁hole|>from chaco.tools.legend_highlighter import *<|fim▁end|> | from __future__ import absolute_import |
<|file_name|>DeckModule.ts<|end_file_name|><|fim▁begin|>import * as _ from 'lodash';
import Vuex from 'vuex';
import {Deck} from '../models/Deck'
import DeckState from '../models/state/DeckState'
const store =
{
state: new DeckState(),
mutations:
{
addToDeck(state, card)
{
if (!card) { return; }<|fim▁hole|>
state.currentDeck.cards.push(card);
if (!_.some(state.allDecks, thatDeck => thatDeck == state.currentDeck))
{
state.allDecks.push(state.currentDeck);
}
localStorage["currentDeck"] = JSON.stringify(state.currentDeck);
},
removeFromDeck(state, card)
{
if (card == undefined) { return; }
let cardIndex = state.currentDeck.cards.indexOf(card);
if (cardIndex < 0) { return; }
state.currentDeck.cards.splice(cardIndex, 1);
localStorage["currentDeck"] = JSON.stringify(state.currentDeck);
},
removeAllFromDeck(state, card)
{
if (card == undefined) { return; }
var filtered = state.currentDeck.cards.filter(c => c.multiverseid != card.multiverseid);
state.currentDeck.cards = filtered;
localStorage["currentDeck"] = JSON.stringify(state.currentDeck);
},
loadDeck(state, deck)
{
if (deck == undefined) { return; }
state.allDecks.push(deck);
state.currentDeck = state.allDecks[state.allDecks.length - 1];
},
deleteCurrentDeck(state)
{
var deckIndex = state.allDecks.indexOf(state.currentDeck);
state.allDecks.splice(deckIndex, 1);
},
clearDeck(state)
{
state.currentDeck.cards = [];
localStorage["currentDeck"] = JSON.stringify(state.currentDeck);
},
setCurrentDeck(state, deck)
{
if (deck == undefined) { return; }
state.currentDeck = deck;
localStorage["currentDeck"] = JSON.stringify(state.currentDeck);
}
}
};
export default store<|fim▁end|> | |
<|file_name|>conftest.py<|end_file_name|><|fim▁begin|># Licensed under a 3-clause BSD style license - see LICENSE.rst
# This file is the main file used when running tests with pytest directly,
# in particular if running e.g. ``pytest docs/``.
from importlib.util import find_spec
import os
import pkg_resources
import tempfile
try:
from pytest_astropy_header.display import PYTEST_HEADER_MODULES
except ImportError:
PYTEST_HEADER_MODULES = {}
import astropy
if find_spec('asdf') is not None:
from asdf import __version__ as asdf_version
if asdf_version >= astropy.__minimum_asdf_version__:
entry_points = []
for entry_point in pkg_resources.iter_entry_points('pytest11'):
entry_points.append(entry_point.name)
if "asdf_schema_tester" not in entry_points:
pytest_plugins += ['asdf.tests.schema_tester']
PYTEST_HEADER_MODULES['Asdf'] = 'asdf'
# Make sure we use temporary directories for the config and cache
# so that the tests are insensitive to local configuration.
<|fim▁hole|>
os.mkdir(os.path.join(os.environ['XDG_CONFIG_HOME'], 'astropy'))
os.mkdir(os.path.join(os.environ['XDG_CACHE_HOME'], 'astropy'))
# Note that we don't need to change the environment variables back or remove
# them after testing, because they are only changed for the duration of the
# Python process, and this configuration only matters if running pytest
# directly, not from e.g. an IPython session.<|fim▁end|> | os.environ['XDG_CONFIG_HOME'] = tempfile.mkdtemp('astropy_config')
os.environ['XDG_CACHE_HOME'] = tempfile.mkdtemp('astropy_cache') |
<|file_name|>test_token.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
JWT tokens (for web interface, mostly, as all peer operations function on
public key cryptography)
JWT tokens can be one of:<|fim▁hole|>* Invalid
And granting them should not take database access. They are meant to
figure out if a user is auth'd without using the database to do so.
"""
from __future__ import absolute_import
from __future__ import unicode_literals
import datetime
from ...utils.timing import TimedTestCase
from ..token import token, jwt_get, jwt_use
class test_token(TimedTestCase):
def test_good_token(self):
"""Valid JWT Token"""
self.threshold = .32
bob = token(u'bob')
example = bob.make(u'print')
bob.check(example)
def test_expired_token(self):
"""Expire a token..."""
self.threshold = .1
a = datetime.datetime.now()
assert a != None
def test_invalid_token(self):
"""Invalid Tokens"""
self.threshold = .1
fred = token(u'fred')
alice = token(u'alice')
wrong = fred.make(u'well then')
alice.check(wrong)
class test_jwt(TimedTestCase):
def test_routes(self):
self.threshold = .1
tok = jwt_get(u'ten')
res = jwt_use(tok)
print(res)<|fim▁end|> |
* Good
* Expired |
<|file_name|>fileTransform.js<|end_file_name|><|fim▁begin|>'use strict';
const path = require('path');
<|fim▁hole|> process(src, filename) {
const assetFilename = JSON.stringify(path.basename(filename));
if (filename.match(/\.svg$/)) {
return `const React = require('react');
module.exports = {
__esModule: true,
default: ${assetFilename},
ReactComponent: React.forwardRef((props, ref) => ({
$$typeof: Symbol.for('react.element'),
type: 'svg',
ref: ref,
key: null,
props: Object.assign({}, props, {
children: ${assetFilename}
})
})),
};`;
}
return `module.exports = ${assetFilename};`;
},
};<|fim▁end|> | // This is a custom Jest transformer turning file imports into filenames.
// https://facebook.github.io/jest/docs/en/webpack.html
module.exports = { |
<|file_name|>make-sim-options.py<|end_file_name|><|fim▁begin|>#!/usr/bin/python
#This script create simulation and reconstruction options
import os
import sys
import re
<|fim▁hole|>
HOME_DIR = os.environ['HOME']
JPSIKKROOT_DIR = os.environ['JPSIKKROOT']
SHARE_DIR = os.path.join(JPSIKKROOT_DIR, "share")
TEMPLATE_DIR = os.path.join(JPSIKKROOT_DIR, "share/template")
TEMPLATE_SIM_FILE = os.path.joint(TEMPLATE_DIR, "simulation.cfg")
print HOMEDIR, JPSIKKROOT_DIR, TE
DECAY_FILE = os.path.abspath(os.path.join(SHARE_DIR,sys.argv[1]))
PREFIX = sys.argv[2]
RTRAW_FILE = os.path.abspath(PREFIX+".rtraw")
DST_FILE = os.path.abspath(PREFIX+".dst")
ROOT_FILE = os.path.abspath(PREFIX+".root")<|fim▁end|> | if len(sys.argv)<4:
print "Usage: make-sim-options.py <decay_file> <output_prefix> <event_number>"
exit(1) |
<|file_name|>Game.cpp<|end_file_name|><|fim▁begin|>//--------------------------------------------------------------------------------------
// File: Game.cpp
//
// Developer unit test for DirectXTK GamePad
//
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.
//
// http://go.microsoft.com/fwlink/?LinkId=248929
//--------------------------------------------------------------------------------------
#include "pch.h"
#include "Game.h"
#ifdef GAMEINPUT
#include <GameInput.h>
#endif
#define GAMMA_CORRECT_RENDERING
#define USE_FAST_SEMANTICS
#if defined(COREWINDOW) || defined(WGI)
#include <Windows.UI.Core.h>
#endif
extern void ExitGame() noexcept;
using namespace DirectX;
using Microsoft::WRL::ComPtr;
static_assert(std::is_nothrow_move_constructible<GamePad>::value, "Move Ctor.");
static_assert(std::is_nothrow_move_assignable<GamePad>::value, "Move Assign.");
static_assert(std::is_nothrow_move_constructible<GamePad::ButtonStateTracker>::value, "Move Ctor.");
static_assert(std::is_nothrow_move_assignable<GamePad::ButtonStateTracker>::value, "Move Assign.");
// Constructor.
Game::Game() noexcept(false) :
m_state{},
m_lastStr(nullptr)
{
#ifdef GAMMA_CORRECT_RENDERING
const DXGI_FORMAT c_RenderFormat = DXGI_FORMAT_B8G8R8A8_UNORM_SRGB;
#else
const DXGI_FORMAT c_RenderFormat = DXGI_FORMAT_B8G8R8A8_UNORM;
#endif
// 2D only rendering
#ifdef XBOX
m_deviceResources = std::make_unique<DX::DeviceResources>(
c_RenderFormat, DXGI_FORMAT_UNKNOWN, 2,
DX::DeviceResources::c_Enable4K_UHD
#ifdef USE_FAST_SEMANTICS
| DX::DeviceResources::c_FastSemantics
#endif
);
#elif defined(UWP)
m_deviceResources = std::make_unique<DX::DeviceResources>(
c_RenderFormat, DXGI_FORMAT_UNKNOWN, 2, D3D_FEATURE_LEVEL_9_3,
DX::DeviceResources::c_Enable4K_Xbox
);
#else
m_deviceResources = std::make_unique<DX::DeviceResources>(c_RenderFormat, DXGI_FORMAT_UNKNOWN);
#endif
#ifdef LOSTDEVICE
m_deviceResources->RegisterDeviceNotify(this);
#endif
}
// Initialize the Direct3D resources required to run.
void Game::Initialize(
#ifdef COREWINDOW
IUnknown* window,
#else
HWND window,
#endif
int width, int height, DXGI_MODE_ROTATION rotation)
{
#ifdef XBOX
UNREFERENCED_PARAMETER(rotation);
UNREFERENCED_PARAMETER(width);
UNREFERENCED_PARAMETER(height);
m_deviceResources->SetWindow(window);
#elif defined(UWP)
m_deviceResources->SetWindow(window, width, height, rotation);
#else
UNREFERENCED_PARAMETER(rotation);
m_deviceResources->SetWindow(window, width, height);
#endif
m_gamePad = std::make_unique<GamePad>();
#ifdef PC
// Singleton test
{
bool thrown = false;
try
{
auto gamePad2 = std::make_unique<GamePad>();
}
catch (...)
{
thrown = true;
}
if (!thrown)
{
MessageBoxW(window, L"GamePad not acting like a singleton", L"GamePadTest", MB_ICONERROR);
throw std::runtime_error("GamePad not acting like a singleton");
}
}
#endif
#ifdef GAMEINPUT
m_ctrlChanged.Attach(CreateEvent(nullptr, FALSE, FALSE, nullptr));
if (!m_ctrlChanged.IsValid())
{
throw std::system_error(std::error_code(static_cast<int>(GetLastError()), std::system_category()), "CreateEvent");
}
m_gamePad->RegisterEvents(m_ctrlChanged.Get());
#elif defined(COREWINDOW)
m_ctrlChanged.Attach(CreateEvent(nullptr, FALSE, FALSE, nullptr));
m_userChanged.Attach(CreateEvent(nullptr, FALSE, FALSE, nullptr));
if (!m_ctrlChanged.IsValid() || !m_userChanged.IsValid())
{
throw std::system_error(std::error_code(static_cast<int>(GetLastError()), std::system_category()), "CreateEvent");
}
m_gamePad->RegisterEvents( m_ctrlChanged.Get(), m_userChanged.Get() );
#endif
m_found.reset(new bool[GamePad::MAX_PLAYER_COUNT] );
memset(m_found.get(), 0, sizeof(bool) * GamePad::MAX_PLAYER_COUNT);
m_deviceResources->CreateDeviceResources();
CreateDeviceDependentResources();
m_deviceResources->CreateWindowSizeDependentResources();
CreateWindowSizeDependentResources();
}
#pragma region Frame Update
// Executes the basic game loop.
void Game::Tick()
{
m_timer.Tick([&]()
{
Update(m_timer);
});
Render();
}
// Updates the world.
void Game::Update(DX::StepTimer const&)
{
m_state.connected = false;
#ifdef GAMEINPUT
if (WaitForSingleObject(m_ctrlChanged.Get(), 0) == WAIT_OBJECT_0)
{
OutputDebugStringA("EVENT: Controller changed\n");
}
#elif defined(COREWINDOW)
HANDLE events[2] = { m_ctrlChanged.Get(), m_userChanged.Get() };
switch (WaitForMultipleObjects(static_cast<DWORD>(std::size(events)), events, FALSE, 0))
{
case WAIT_OBJECT_0:
OutputDebugStringA("EVENT: Controller changed\n");
break;
case WAIT_OBJECT_0 + 1:
OutputDebugStringA("EVENT: User changed\n");
break;
}
#endif
for (int j = 0; j < GamePad::MAX_PLAYER_COUNT; ++j)
{
auto state2 = m_gamePad->GetState(j);
auto caps = m_gamePad->GetCapabilities(j);
assert(state2.IsConnected() == caps.IsConnected());
if (state2.IsConnected())
{
if (!m_found[size_t(j)])<|fim▁hole|>
if (caps.IsConnected())
{
#ifdef GAMEINPUT
char idstr[128] = {};
for (size_t l = 0; l < APP_LOCAL_DEVICE_ID_SIZE; ++l)
{
sprintf_s(idstr + l * 2, 128 - l * 2, "%02x", caps.id.value[l]);
}
char buff[128] = {};
sprintf_s(buff, "Player %d -> connected (type %u, %04X/%04X, id %s)\n", j, caps.gamepadType, caps.vid, caps.pid, idstr);
OutputDebugStringA(buff);
{
ComPtr<IGameInputDevice> idevice;
m_gamePad->GetDevice(j, idevice.GetAddressOf());
if (!idevice)
{
OutputDebugStringA(" **ERROR** GetDevice failed unexpectedly\n");
}
else
{
GameInputBatteryState battery;
idevice->GetBatteryState(&battery);
switch (battery.status)
{
case GameInputBatteryUnknown: break;
case GameInputBatteryNotPresent: OutputDebugStringA(" Battery not present\n"); break;
case GameInputBatteryDischarging: OutputDebugStringA(" Battery discharging\n"); break;
case GameInputBatteryIdle: OutputDebugStringA(" Battery idle\n"); break;
case GameInputBatteryCharging: OutputDebugStringA(" Battery charging\n"); break;
}
}
}
#elif defined(WGI)
if (!caps.id.empty())
{
using namespace Microsoft::WRL;
using namespace Microsoft::WRL::Wrappers;
using namespace ABI::Windows::Foundation;
using namespace ABI::Windows::System;
ComPtr<IUserStatics> statics;
DX::ThrowIfFailed(GetActivationFactory(HStringReference(RuntimeClass_Windows_System_User).Get(), statics.GetAddressOf()));
ComPtr<IUser> user;
HString str;
str.Set(caps.id.c_str(), static_cast<unsigned int>(caps.id.length()));
HRESULT hr = statics->GetFromId(str.Get(), user.GetAddressOf());
if (SUCCEEDED(hr))
{
UserType userType = UserType_RemoteUser;
DX::ThrowIfFailed(user->get_Type(&userType));
char buff[1024] = {};
sprintf_s(buff, "Player %d -> connected (type %u, %04X/%04X, id \"%ls\" (user found))\n", j, caps.gamepadType, caps.vid, caps.pid, caps.id.c_str());
OutputDebugStringA(buff);
}
else
{
char buff[1024] = {};
sprintf_s(buff, "Player %d -> connected (type %u, %04X/%04X, id \"%ls\" (user fail %08X))\n", j, caps.gamepadType, caps.vid, caps.pid, caps.id.c_str(), static_cast<unsigned int>(hr));
OutputDebugStringA(buff);
}
}
else
{
char buff[64] = {};
sprintf_s(buff, "Player %d -> connected (type %u, %04X/%04X, id is empty!)\n", j, caps.gamepadType, caps.vid, caps.pid);
OutputDebugStringA(buff);
}
#else
char buff[64] = {};
sprintf_s(buff, "Player %d -> connected (type %u, %04X/%04X, id %llu)\n", j, caps.gamepadType, caps.vid, caps.pid, caps.id);
OutputDebugStringA(buff);
#endif
}
}
}
else
{
if (m_found[size_t(j)])
{
m_found[size_t(j)] = false;
char buff[32];
sprintf_s(buff, "Player %d <- disconnected\n", j);
OutputDebugStringA(buff);
}
}
}
m_state = m_gamePad->GetState(GamePad::c_MostRecent);
if (m_state.IsConnected())
{
m_tracker.Update(m_state);
using ButtonState = GamePad::ButtonStateTracker::ButtonState;
if (m_tracker.a == ButtonState::PRESSED)
m_lastStr = L"Button A was pressed\n";
else if (m_tracker.a == ButtonState::RELEASED)
m_lastStr = L"Button A was released\n";
else if (m_tracker.b == ButtonState::PRESSED)
m_lastStr = L"Button B was pressed\n";
else if (m_tracker.b == ButtonState::RELEASED)
m_lastStr = L"Button B was released\n";
else if (m_tracker.x == ButtonState::PRESSED)
m_lastStr = L"Button X was pressed\n";
else if (m_tracker.x == ButtonState::RELEASED)
m_lastStr = L"Button X was released\n";
else if (m_tracker.y == ButtonState::PRESSED)
m_lastStr = L"Button Y was pressed\n";
else if (m_tracker.y == ButtonState::RELEASED)
m_lastStr = L"Button Y was released\n";
else if (m_tracker.leftStick == ButtonState::PRESSED)
m_lastStr = L"Button LeftStick was pressed\n";
else if (m_tracker.leftStick == ButtonState::RELEASED)
m_lastStr = L"Button LeftStick was released\n";
else if (m_tracker.rightStick == ButtonState::PRESSED)
m_lastStr = L"Button RightStick was pressed\n";
else if (m_tracker.rightStick == ButtonState::RELEASED)
m_lastStr = L"Button RightStick was released\n";
else if (m_tracker.leftShoulder == ButtonState::PRESSED)
m_lastStr = L"Button LeftShoulder was pressed\n";
else if (m_tracker.leftShoulder == ButtonState::RELEASED)
m_lastStr = L"Button LeftShoulder was released\n";
else if (m_tracker.rightShoulder == ButtonState::PRESSED)
m_lastStr = L"Button RightShoulder was pressed\n";
else if (m_tracker.rightShoulder == ButtonState::RELEASED)
m_lastStr = L"Button RightShoulder was released\n";
else if (m_tracker.view == ButtonState::PRESSED)
m_lastStr = L"Button BACK/VIEW was pressed\n";
else if (m_tracker.view == ButtonState::RELEASED)
m_lastStr = L"Button BACK/VIEW was released\n";
else if (m_tracker.menu == ButtonState::PRESSED)
m_lastStr = L"Button START/MENU was pressed\n";
else if (m_tracker.menu == ButtonState::RELEASED)
m_lastStr = L"Button START/MENU was released\n";
else if (m_tracker.dpadUp == ButtonState::PRESSED)
m_lastStr = L"Button DPAD UP was pressed\n";
else if (m_tracker.dpadUp == ButtonState::RELEASED)
m_lastStr = L"Button DPAD UP was released\n";
else if (m_tracker.dpadDown == ButtonState::PRESSED)
m_lastStr = L"Button DPAD DOWN was pressed\n";
else if (m_tracker.dpadDown == ButtonState::RELEASED)
m_lastStr = L"Button DPAD DOWN was released\n";
else if (m_tracker.dpadLeft == ButtonState::PRESSED)
m_lastStr = L"Button DPAD LEFT was pressed\n";
else if (m_tracker.dpadLeft == ButtonState::RELEASED)
m_lastStr = L"Button DPAD LEFT was released\n";
else if (m_tracker.dpadRight == ButtonState::PRESSED)
m_lastStr = L"Button DPAD RIGHT was pressed\n";
else if (m_tracker.dpadRight == ButtonState::RELEASED)
m_lastStr = L"Button DPAD RIGHT was released\n";
else if (m_tracker.leftStickUp == ButtonState::PRESSED)
m_lastStr = L"Button LEFT STICK was pressed UP\n";
else if (m_tracker.leftStickUp == ButtonState::RELEASED)
m_lastStr = L"Button LEFT STICK was released from UP\n";
else if (m_tracker.leftStickDown == ButtonState::PRESSED)
m_lastStr = L"Button LEFT STICK was pressed DOWN\n";
else if (m_tracker.leftStickDown == ButtonState::RELEASED)
m_lastStr = L"Button LEFT STICK was released from DOWN\n";
else if (m_tracker.leftStickLeft == ButtonState::PRESSED)
m_lastStr = L"Button LEFT STICK was pressed LEFT\n";
else if (m_tracker.leftStickLeft == ButtonState::RELEASED)
m_lastStr = L"Button LEFT STICK was released from LEFT\n";
else if (m_tracker.leftStickRight == ButtonState::PRESSED)
m_lastStr = L"Button LEFT STICK was pressed RIGHT\n";
else if (m_tracker.leftStickRight == ButtonState::RELEASED)
m_lastStr = L"Button LEFT STICK was released from RIGHT\n";
else if (m_tracker.rightStickUp == ButtonState::PRESSED)
m_lastStr = L"Button RIGHT STICK was pressed UP\n";
else if (m_tracker.rightStickUp == ButtonState::RELEASED)
m_lastStr = L"Button RIGHT STICK was released from UP\n";
else if (m_tracker.rightStickDown == ButtonState::PRESSED)
m_lastStr = L"Button RIGHT STICK was pressed DOWN\n";
else if (m_tracker.rightStickDown == ButtonState::RELEASED)
m_lastStr = L"Button RIGHT STICK was released from DOWN\n";
else if (m_tracker.rightStickLeft == ButtonState::PRESSED)
m_lastStr = L"Button RIGHT STICK was pressed LEFT\n";
else if (m_tracker.rightStickLeft == ButtonState::RELEASED)
m_lastStr = L"Button RIGHT STICK was released from LEFT\n";
else if (m_tracker.rightStickRight == ButtonState::PRESSED)
m_lastStr = L"Button RIGHT STICK was pressed RIGHT\n";
else if (m_tracker.rightStickRight == ButtonState::RELEASED)
m_lastStr = L"Button RIGHT STICK was released from RIGHT\n";
else if (m_tracker.leftTrigger == ButtonState::PRESSED)
m_lastStr = L"Button LEFT TRIGGER was pressed\n";
else if (m_tracker.leftTrigger == ButtonState::RELEASED)
m_lastStr = L"Button LEFT TRIGGER was released\n";
else if (m_tracker.rightTrigger == ButtonState::PRESSED)
m_lastStr = L"Button RIGHT TRIGGER was pressed\n";
else if (m_tracker.rightTrigger == ButtonState::RELEASED)
m_lastStr = L"Button RIGHT TRIGGER was released\n";
assert(m_tracker.back == m_tracker.view);
assert(m_tracker.start == m_tracker.menu);
m_gamePad->SetVibration(GamePad::c_MostRecent, m_state.triggers.left, m_state.triggers.right);
}
else
{
memset(&m_state, 0, sizeof(GamePad::State));
m_lastStr = nullptr;
m_tracker.Reset();
}
}
#pragma endregion
#pragma region Frame Render
// Draws the scene.
void Game::Render()
{
// Don't try to render anything before the first Update.
if (m_timer.GetFrameCount() == 0)
{
return;
}
XMVECTORF32 yellow;
#ifdef GAMMA_CORRECT_RENDERING
yellow.v = XMColorSRGBToRGB(Colors::Yellow);
#else
yellow.v = Colors::Yellow;
#endif
#ifdef XBOX
m_deviceResources->Prepare();
#endif
Clear();
m_spriteBatch->Begin();
for (int j = 0; j < std::min(GamePad::MAX_PLAYER_COUNT, 4); ++j)
{
XMVECTOR color = m_found[size_t(j)] ? Colors::White : Colors::DimGray;
m_ctrlFont->DrawString(m_spriteBatch.get(), L"$", XMFLOAT2(800.f, float(50 + j * 150)), color);
}
if (m_lastStr)
{
m_comicFont->DrawString(m_spriteBatch.get(), m_lastStr, XMFLOAT2(25.f, 650.f), yellow);
}
// X Y A B
m_ctrlFont->DrawString(m_spriteBatch.get(), L"&", XMFLOAT2(325, 150), m_state.IsXPressed() ? Colors::White : Colors::DimGray);
m_ctrlFont->DrawString(m_spriteBatch.get(), L"(", XMFLOAT2(400, 110), m_state.IsYPressed() ? Colors::White : Colors::DimGray);
m_ctrlFont->DrawString(m_spriteBatch.get(), L"'", XMFLOAT2(400, 200), m_state.IsAPressed() ? Colors::White : Colors::DimGray);
m_ctrlFont->DrawString(m_spriteBatch.get(), L")", XMFLOAT2(475, 150), m_state.IsBPressed() ? Colors::White : Colors::DimGray);
// Left/Right sticks
auto loc = XMFLOAT2(10, 110);
loc.x -= m_state.IsLeftThumbStickLeft() ? 20.f : 0.f;
loc.x += m_state.IsLeftThumbStickRight() ? 20.f : 0.f;
loc.y -= m_state.IsLeftThumbStickUp() ? 20.f : 0.f;
loc.y += m_state.IsLeftThumbStickDown() ? 20.f : 0.f;
m_ctrlFont->DrawString(m_spriteBatch.get(), L" ", loc, m_state.IsLeftStickPressed() ? Colors::White : Colors::DimGray, 0, XMFLOAT2(0, 0));
loc = XMFLOAT2(450, 300);
loc.x -= m_state.IsRightThumbStickLeft() ? 20.f : 0.f;
loc.x += m_state.IsRightThumbStickRight() ? 20.f : 0.f;
loc.y -= m_state.IsRightThumbStickUp() ? 20.f : 0.f;
loc.y += m_state.IsRightThumbStickDown() ? 20.f : 0.f;
m_ctrlFont->DrawString(m_spriteBatch.get(), L"\"", loc, m_state.IsRightStickPressed() ? Colors::White : Colors::DimGray, 0, XMFLOAT2(0, 0));
// DPad
XMVECTOR color = Colors::DimGray;
if (m_state.dpad.up || m_state.dpad.down || m_state.dpad.right || m_state.dpad.left)
color = Colors::White;
loc = XMFLOAT2(175, 300);
loc.x -= m_state.IsDPadLeftPressed() ? 20.f : 0.f;
loc.x += m_state.IsDPadRightPressed() ? 20.f : 0.f;
loc.y -= m_state.IsDPadUpPressed() ? 20.f : 0.f;
loc.y += m_state.IsDPadDownPressed() ? 20.f : 0.f;
m_ctrlFont->DrawString(m_spriteBatch.get(), L"!", loc, color);
// Back/Start (aka View/Menu)
m_ctrlFont->DrawString(m_spriteBatch.get(), L"#", XMFLOAT2(175, 75), m_state.IsViewPressed() ? Colors::White : Colors::DimGray);
assert(m_state.IsViewPressed() == m_state.IsBackPressed());
assert(m_state.buttons.back == m_state.buttons.view);
m_ctrlFont->DrawString(m_spriteBatch.get(), L"%", XMFLOAT2(300, 75), m_state.IsMenuPressed() ? Colors::White : Colors::DimGray);
assert(m_state.IsMenuPressed() == m_state.IsStartPressed());
assert(m_state.buttons.start == m_state.buttons.menu);
// Triggers/Shoulders
m_ctrlFont->DrawString(m_spriteBatch.get(), L"*", XMFLOAT2(500, 10), m_state.IsRightShoulderPressed() ? Colors::White : Colors::DimGray, 0, XMFLOAT2(0, 0), 0.5f);
loc = XMFLOAT2(450, 10);
loc.x += m_state.IsRightTriggerPressed() ? 5.f : 0.f;
color = XMVectorLerp(Colors::DimGray, Colors::White, m_state.triggers.right);
m_ctrlFont->DrawString(m_spriteBatch.get(), L"+", loc, color, 0, XMFLOAT2(0, 0), 0.5f);
loc = XMFLOAT2(130, 10);
loc.x -= m_state.IsLeftTriggerPressed() ? 5.f : 0.f;
color = XMVectorLerp(Colors::DimGray, Colors::White, m_state.triggers.left);
m_ctrlFont->DrawString(m_spriteBatch.get(), L",", loc, color, 0, XMFLOAT2(0, 0), 0.5f);
m_ctrlFont->DrawString(m_spriteBatch.get(), L"-", XMFLOAT2(10, 10), m_state.IsLeftShoulderPressed() ? Colors::White : Colors::DimGray, 0, XMFLOAT2(0, 0), 0.5f);
// Sticks
RECT src = { 0, 0, 1, 1 };
RECT rc;
rc.top = 500;
rc.left = 10;
rc.bottom = 525;
rc.right = rc.left + int(((m_state.thumbSticks.leftX + 1.f) / 2.f) * 275);
m_spriteBatch->Draw(m_defaultTex.Get(), rc, &src);
rc.top = 550;
rc.bottom = 575;
rc.right = rc.left + int(((m_state.thumbSticks.leftY + 1.f) / 2.f) * 275);
m_spriteBatch->Draw(m_defaultTex.Get(), rc, &src);
rc.top = 500;
rc.left = 325;
rc.bottom = 525;
rc.right = rc.left + int(((m_state.thumbSticks.rightX + 1.f) / 2.f) * 275);
m_spriteBatch->Draw(m_defaultTex.Get(), rc, &src);
rc.top = 550;
rc.bottom = 575;
rc.right = rc.left + int(((m_state.thumbSticks.rightY + 1.f) / 2.f) * 275);
m_spriteBatch->Draw(m_defaultTex.Get(), rc, &src);
m_spriteBatch->End();
// Show the new frame.
m_deviceResources->Present();
#ifdef XBOX
m_graphicsMemory->Commit();
#endif
}
// Helper method to clear the back buffers.
void Game::Clear()
{
// Clear the views.
auto context = m_deviceResources->GetD3DDeviceContext();
auto renderTarget = m_deviceResources->GetRenderTargetView();
XMVECTORF32 color;
#ifdef GAMMA_CORRECT_RENDERING
color.v = XMColorSRGBToRGB(Colors::CornflowerBlue);
#else
color.v = Colors::CornflowerBlue;
#endif
context->ClearRenderTargetView(renderTarget, color);
context->OMSetRenderTargets(1, &renderTarget, nullptr);
// Set the viewport.
auto viewport = m_deviceResources->GetScreenViewport();
context->RSSetViewports(1, &viewport);
}
#pragma endregion
#pragma region Message Handlers
// Message handlers
void Game::OnActivated()
{
}
void Game::OnDeactivated()
{
}
void Game::OnSuspending()
{
m_deviceResources->Suspend();
}
void Game::OnResuming()
{
m_deviceResources->Resume();
m_tracker.Reset();
m_timer.ResetElapsedTime();
}
#ifdef PC
void Game::OnWindowMoved()
{
auto r = m_deviceResources->GetOutputSize();
m_deviceResources->WindowSizeChanged(r.right, r.bottom);
}
#endif
#if defined(PC) || defined(UWP)
void Game::OnDisplayChange()
{
m_deviceResources->UpdateColorSpace();
}
#endif
#ifndef XBOX
void Game::OnWindowSizeChanged(int width, int height, DXGI_MODE_ROTATION rotation)
{
#ifdef UWP
if (!m_deviceResources->WindowSizeChanged(width, height, rotation))
return;
#else
UNREFERENCED_PARAMETER(rotation);
if (!m_deviceResources->WindowSizeChanged(width, height))
return;
#endif
CreateWindowSizeDependentResources();
}
#endif
#ifdef UWP
void Game::ValidateDevice()
{
m_deviceResources->ValidateDevice();
}
#endif
// Properties
void Game::GetDefaultSize(int& width, int& height) const
{
width = 1024;
height = 768;
}
#pragma endregion
#pragma region Direct3D Resources
// These are the resources that depend on the device.
void Game::CreateDeviceDependentResources()
{
auto device = m_deviceResources->GetD3DDevice();
auto context = m_deviceResources->GetD3DDeviceContext();
#ifdef XBOX
m_graphicsMemory = std::make_unique<GraphicsMemory>(device, m_deviceResources->GetBackBufferCount());
#endif
m_spriteBatch = std::make_unique<SpriteBatch>(context);
m_comicFont = std::make_unique<SpriteFont>(device, L"comic.spritefont");
m_ctrlFont = std::make_unique<SpriteFont>(device, L"xboxController.spritefont");
{
static const uint32_t s_pixel = 0xffffffff;
D3D11_SUBRESOURCE_DATA initData = { &s_pixel, sizeof(uint32_t), 0 };
D3D11_TEXTURE2D_DESC desc = {};
desc.Width = desc.Height = desc.MipLevels = desc.ArraySize = 1;
desc.Format = DXGI_FORMAT_R8G8B8A8_UNORM;
desc.SampleDesc.Count = 1;
desc.Usage = D3D11_USAGE_IMMUTABLE;
desc.BindFlags = D3D11_BIND_SHADER_RESOURCE;
ComPtr<ID3D11Texture2D> tex;
DX::ThrowIfFailed(device->CreateTexture2D(&desc, &initData, &tex));
D3D11_SHADER_RESOURCE_VIEW_DESC SRVDesc = {};
SRVDesc.Format = DXGI_FORMAT_R8G8B8A8_UNORM;
SRVDesc.ViewDimension = D3D11_SRV_DIMENSION_TEXTURE2D;
SRVDesc.Texture2D.MipLevels = 1;
DX::ThrowIfFailed(device->CreateShaderResourceView(tex.Get(), &SRVDesc, m_defaultTex.ReleaseAndGetAddressOf()));
}
}
// Allocate all memory resources that change on a window SizeChanged event.
void Game::CreateWindowSizeDependentResources()
{
auto viewPort = m_deviceResources->GetScreenViewport();
m_spriteBatch->SetViewport(viewPort);
#ifdef XBOX
if (m_deviceResources->GetDeviceOptions() & DX::DeviceResources::c_Enable4K_UHD)
{
// Scale sprite batch rendering when running 4k
static const D3D11_VIEWPORT s_vp1080 = { 0.f, 0.f, 1920.f, 1080.f, D3D11_MIN_DEPTH, D3D11_MAX_DEPTH };
m_spriteBatch->SetViewport(s_vp1080);
}
#elif defined(UWP)
if (m_deviceResources->GetDeviceOptions() & DX::DeviceResources::c_Enable4K_Xbox)
{
// Scale sprite batch rendering when running 4k
static const D3D11_VIEWPORT s_vp1080 = { 0.f, 0.f, 1920.f, 1080.f, D3D11_MIN_DEPTH, D3D11_MAX_DEPTH };
m_spriteBatch->SetViewport(s_vp1080);
}
m_spriteBatch->SetRotation(m_deviceResources->GetRotation());
#endif
}
#ifdef LOSTDEVICE
void Game::OnDeviceLost()
{
m_spriteBatch.reset();
m_comicFont.reset();
m_ctrlFont.reset();
m_defaultTex.Reset();
}
void Game::OnDeviceRestored()
{
CreateDeviceDependentResources();
CreateWindowSizeDependentResources();
}
#endif
#pragma endregion<|fim▁end|> | {
m_found[size_t(j)] = true; |
<|file_name|>testbindingpairiterable.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/. */
// check-tidy: no specs after this line
use dom::bindings::cell::DOMRefCell;
use dom::bindings::codegen::Bindings::TestBindingPairIterableBinding;
use dom::bindings::codegen::Bindings::TestBindingPairIterableBinding::TestBindingPairIterableMethods;
use dom::bindings::error::Fallible;
use dom::bindings::global::GlobalRef;
use dom::bindings::iterable::Iterable;
use dom::bindings::js::Root;
use dom::bindings::reflector::{Reflector, reflect_dom_object};
use dom::bindings::str::DOMString;
#[dom_struct]
pub struct TestBindingPairIterable {
reflector: Reflector,
map: DOMRefCell<Vec<(DOMString, u32)>>,
}
impl Iterable for TestBindingPairIterable {
type Key = DOMString;
type Value = u32;
fn get_iterable_length(&self) -> u32 {
self.map.borrow().len() as u32
}
fn get_value_at_index(&self, index: u32) -> u32 {
self.map.borrow().iter().nth(index as usize).map(|a| &a.1).unwrap().clone()
}
fn get_key_at_index(&self, index: u32) -> DOMString {
self.map.borrow().iter().nth(index as usize).map(|a| &a.0).unwrap().clone()
}
}
impl TestBindingPairIterable {
fn new(global: GlobalRef) -> Root<TestBindingPairIterable> {
reflect_dom_object(box TestBindingPairIterable {
reflector: Reflector::new(),
map: DOMRefCell::new(vec![]),
}, global, TestBindingPairIterableBinding::TestBindingPairIterableWrap)
}
<|fim▁hole|> }
}
impl TestBindingPairIterableMethods for TestBindingPairIterable {
fn Add(&self, key: DOMString, value: u32) {
self.map.borrow_mut().push((key, value));
}
}<|fim▁end|> | pub fn Constructor(global: GlobalRef) -> Fallible<Root<TestBindingPairIterable>> {
Ok(TestBindingPairIterable::new(global)) |
<|file_name|>KnowledgeAddController.js<|end_file_name|><|fim▁begin|>'use strict';
angular.module('wsapp')
.controller('KnowledgeAddController', function ($scope, knowledgeService, $location, $state) {
$scope.data={};
$scope.program = function(){
alertify.success("Test");
}
$scope.know = function(){
console.log($scope.data);
knowledgeService.insertKnowledge($scope.data,
function(response){
console.log(response.data);
//if(response.data.success==true){
alertify.success("SUCCESS");
$state.go('home');
//}else{
//alertify.error("ERROR");
//}
<|fim▁hole|>
console.log(response);
alertify.error("ERROR");
});
}
});<|fim▁end|> |
}
,function(response){
|
<|file_name|>objects.py<|end_file_name|><|fim▁begin|>from datetime import datetime
import uuid
class Torrent(object):
def __init__(self):
self.tracker = None
self.url = None
self.title = None
self.magnet = None
self.seeders = None
self.leechers = None
self.size = None
self.date = None
self.details = None
self.uuid = uuid.uuid4().hex<|fim▁hole|> self._remove = False
@property
def human_age(self):
if self.date:
age = datetime.now() - self.date
return "%s days" % (int(age.total_seconds()/(60*60*24)))
else:
return "Unknown"
@property
def human_size(self):
if self.size:
if self.size > 1000000000:
return "%.2f GB" % (self.size / 1000000000)
elif self.size > 1000000:
return "%.2f MB" % (self.size/1000000)
else:
return "%s KB" % (self.size/1000)
@property
def html_friendly_title(self):
return self.title.replace('.', '.​').replace('[', '​[').replace(']', ']​')
def __unicode__(self):
return "%s Size: %s Seeders: %s Age: %s %s" % (self.title.ljust(60)[0:60], str(self.human_size).ljust(12),
str(self.seeders).ljust(6), self.human_age,
self.tracker)
def __str__(self):
return self.__unicode__()<|fim▁end|> | |
<|file_name|>team-test.js<|end_file_name|><|fim▁begin|>import { moduleForModel, test } from 'ember-qunit'
moduleForModel('team', {
needs: [
'model:user'
, 'model:project'
, 'model:assignment'
, 'model:attendance'
]
})
test('it exists', function(assert) {
var model = this.subject()
// var store = this.store()
assert.ok(!!model)<|fim▁hole|><|fim▁end|> | }) |
<|file_name|>test_util.py<|end_file_name|><|fim▁begin|>import unittest
from common import TestCase
import pyuv
class UtilTest(TestCase):
def test_hrtime(self):
r = pyuv.util.hrtime()
self.assertTrue(r)
def test_freemem(self):
r = pyuv.util.get_free_memory()
self.assertTrue(r)
def test_totalmem(self):
r = pyuv.util.get_total_memory()
self.assertTrue(r)
def test_loadavg(self):
r = pyuv.util.loadavg()
self.assertTrue(r)
def test_uptime(self):
r = pyuv.util.uptime()
self.assertTrue(r)
def test_resident_set_memory(self):
r = pyuv.util.resident_set_memory()
self.assertTrue(r)
def test_interface_addresses(self):
r = pyuv.util.interface_addresses()
self.assertTrue(r)
def test_cpu_info(self):<|fim▁hole|>
if __name__ == '__main__':
unittest.main(verbosity=2)<|fim▁end|> | r = pyuv.util.cpu_info()
self.assertTrue(r)
|
<|file_name|>qm8_tf_model.py<|end_file_name|><|fim▁begin|>"""
Script that trains Tensorflow multitask models on QM8 dataset.
"""
from __future__ import print_function
from __future__ import division
from __future__ import unicode_literals
import os
import deepchem as dc
import numpy as np
from qm8_datasets import load_qm8
np.random.seed(123)
qm8_tasks, datasets, transformers = load_qm8()<|fim▁hole|>regression_metric = [
dc.metrics.Metric(dc.metrics.mean_absolute_error, mode="regression"),
dc.metrics.Metric(dc.metrics.pearson_r2_score, mode="regression")
]
model = dc.models.TensorflowMultiTaskFitTransformRegressor(
n_tasks=len(qm8_tasks),
n_features=[26, 26],
learning_rate=0.001,
momentum=.8,
batch_size=32,
weight_init_stddevs=[1 / np.sqrt(400), 1 / np.sqrt(100), 1 / np.sqrt(100)],
bias_init_consts=[0., 0., 0.],
layer_sizes=[400, 100, 100],
dropouts=[0.01, 0.01, 0.01],
fit_transformers=fit_transformers,
n_evals=10,
seed=123)
# Fit trained model
model.fit(train_dataset, nb_epoch=50)
model.save()
train_scores = model.evaluate(train_dataset, regression_metric, transformers)
print("Train scores [kcal/mol]")
print(train_scores)
valid_scores = model.evaluate(valid_dataset, regression_metric, transformers)
print("Valid scores [kcal/mol]")
print(valid_scores)
test_scores = model.evaluate(test_dataset, regression_metric, transformers)
print("Test scores [kcal/mol]")
print(test_scores)<|fim▁end|> | train_dataset, valid_dataset, test_dataset = datasets
fit_transformers = [dc.trans.CoulombFitTransformer(train_dataset)] |
<|file_name|>mpl_package.py<|end_file_name|><|fim▁begin|># Copyright (c) 2014 Mirantis, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
import os
import sys
import yaml
import murano.packages.application_package
from murano.packages import exceptions
class MuranoPlPackage(murano.packages.application_package.ApplicationPackage):
def __init__(self, source_directory, manifest, loader):
super(MuranoPlPackage, self).__init__(
source_directory, manifest, loader)
self._classes = None
self._ui = None
self._ui_cache = None
self._raw_ui_cache = None
self._classes_cache = {}
@property
def classes(self):
return tuple(self._classes.keys())
@property
def ui(self):
if not self._ui_cache:
self._load_ui(True)
return self._ui_cache
@property
def raw_ui(self):
if not self._raw_ui_cache:
self._load_ui(False)
return self._raw_ui_cache
def get_class(self, name):
if name not in self._classes_cache:
self._load_class(name)
return self._classes_cache[name]
# Private methods
def _load_ui(self, load_yaml=False):
if self._raw_ui_cache and load_yaml:
self._ui_cache = yaml.load(self._raw_ui_cache, self.yaml_loader)
else:
ui_file = self._ui
full_path = os.path.join(self._source_directory, 'UI', ui_file)
if not os.path.isfile(full_path):
self._raw_ui_cache = None
self._ui_cache = None
return
try:<|fim▁hole|> if load_yaml:
self._ui_cache = yaml.load(self._raw_ui_cache,
self.yaml_loader)
except Exception as ex:
trace = sys.exc_info()[2]
raise exceptions.PackageUILoadError(str(ex)), None, trace
def _load_class(self, name):
if name not in self._classes:
raise exceptions.PackageClassLoadError(
name, 'Class not defined in this package')
def_file = self._classes[name]
full_path = os.path.join(self._source_directory, 'Classes', def_file)
if not os.path.isfile(full_path):
raise exceptions.PackageClassLoadError(
name, 'File with class definition not found')
try:
with open(full_path) as stream:
self._classes_cache[name] = yaml.load(stream, self.yaml_loader)
except Exception as ex:
trace = sys.exc_info()[2]
msg = 'Unable to load class definition due to "{0}"'.format(
str(ex))
raise exceptions.PackageClassLoadError(name, msg), None, trace
def validate(self):
self._classes_cache.clear()
for class_name in self._classes:
self.get_class(class_name)
self._load_ui(True)
super(MuranoPlPackage, self).validate()<|fim▁end|> | with open(full_path) as stream:
self._raw_ui_cache = stream.read() |
<|file_name|>datacatalog_entry_factory.py<|end_file_name|><|fim▁begin|>#!/usr/bin/python
#
# Copyright 2020 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
<|fim▁hole|>from google.cloud import datacatalog
from google.protobuf import timestamp_pb2
from google.datacatalog_connectors.commons.prepare.base_entry_factory import \
BaseEntryFactory
from google.datacatalog_connectors.rdbms.common import constants
class DataCatalogEntryFactory(BaseEntryFactory):
NO_VALUE_SPECIFIED = 'UNDEFINED'
EMPTY_TOKEN = '?'
def __init__(self, project_id, location_id, entry_resource_url_prefix,
entry_group_id, metadata_definition):
self.__project_id = project_id
self.__location_id = location_id
self.__entry_resource_url_prefix = entry_resource_url_prefix
self.__entry_group_id = entry_group_id
self.__metadata_definition = metadata_definition
def make_entries_for_table_container(self, table_container):
"""Create Datacatalog entries from a table container dict.
:param table_container:
:return: entry_id, entry
"""
entry_id = self._format_id(table_container['name'])
entry = datacatalog.Entry()
entry.user_specified_type = self.__metadata_definition[
'table_container_def']['type']
entry.user_specified_system = self.__entry_group_id
entry.display_name = self._format_display_name(table_container['name'])
create_time, update_time = \
DataCatalogEntryFactory.__convert_source_system_timestamp_fields(
table_container.get('create_time'),
table_container.get('update_time'))
if create_time and update_time:
created_timestamp = timestamp_pb2.Timestamp()
created_timestamp.FromSeconds(create_time)
entry.source_system_timestamps.create_time = created_timestamp
updated_timestamp = timestamp_pb2.Timestamp()
updated_timestamp.FromSeconds(update_time)
entry.source_system_timestamps.update_time = updated_timestamp
desc = table_container.get('desc')
if pd.isna(desc):
desc = ''
entry.description = desc
entry.name = datacatalog.DataCatalogClient.entry_path(
self.__project_id, self.__location_id, self.__entry_group_id,
entry_id)
entry.linked_resource = '{}/{}'.format(
self.__entry_resource_url_prefix, entry_id)
return entry_id, entry
def make_entry_for_tables(self, table, table_container_name):
"""Create Datacatalog entries from a table dict.
:param table:
:param table_container_name:
:return: entry_id, entry
"""
entry_id = self._format_id('{}__{}'.format(table_container_name,
table['name']))
entry = datacatalog.Entry()
# some RDBMS' store views and tables definitions in the same
# system table, and the name is not user friendly, so we only
# keep it if it's a VIEW type.
table_type = table.get(constants.TABLE_TYPE_KEY)
if table_type and table_type.lower() == \
constants.VIEW_TYPE_VALUE:
table_type = table_type.lower()
else:
table_type = self.__metadata_definition['table_def']['type']
entry.user_specified_type = table_type
entry.user_specified_system = self.__entry_group_id
entry.display_name = self._format_display_name(table['name'])
entry.name = datacatalog.DataCatalogClient.entry_path(
self.__project_id, self.__location_id, self.__entry_group_id,
entry_id)
desc = table.get('desc')
if pd.isna(desc):
desc = ''
entry.description = desc
entry.linked_resource = '{}/{}/{}'.format(
self.__entry_resource_url_prefix, table_container_name,
self._format_id(table['name']))
create_time, update_time = \
DataCatalogEntryFactory.__convert_source_system_timestamp_fields(
table.get('create_time'),
table.get('update_time'))
if create_time and update_time:
created_timestamp = timestamp_pb2.Timestamp()
created_timestamp.FromSeconds(create_time)
entry.source_system_timestamps.create_time = created_timestamp
updated_timestamp = timestamp_pb2.Timestamp()
updated_timestamp.FromSeconds(update_time)
entry.source_system_timestamps.update_time = updated_timestamp
columns = []
for column in table['columns']:
desc = column.get('desc')
if pd.isna(desc):
desc = ''
columns.append(
datacatalog.ColumnSchema(
column=self._format_id(column['name']),
description=desc,
type=DataCatalogEntryFactory.__format_entry_column_type(
column['type'])))
entry.schema.columns.extend(columns)
return entry_id, entry
@staticmethod
def __convert_date_value_to_epoch(date_value):
if pd.notnull(date_value):
return int(date_value.timestamp())
@staticmethod
def __convert_source_system_timestamp_fields(raw_create_time,
raw_update_time):
create_time = DataCatalogEntryFactory. \
__convert_date_value_to_epoch(raw_create_time)
if not pd.isnull(raw_update_time):
update_time = DataCatalogEntryFactory. \
__convert_date_value_to_epoch(raw_update_time)
else:
update_time = create_time
return create_time, update_time
@staticmethod
def __format_entry_column_type(source_name):
if isinstance(source_name, bytes):
# We've noticed some MySQL instances use bytes-like objects
# instead of `str` to specify the column types. We are using UTF-8
# to decode such objects when it happens because UTF-8 is the
# default character set for MySQL 8.0 onwards.
#
# We didn't notice similar behavior with other RDBMS but, if so,
# we should handle encoding as a configuration option that each
# RDBMS connector would have to set up. It might be exposed as a
# CLI arg, so users could easily change that. There is also the
# option to scrape that config directly from the DB.
source_name = source_name.decode("utf-8")
formatted_name = source_name.replace('&', '_')
formatted_name = formatted_name.replace(':', '_')
formatted_name = formatted_name.replace('/', '_')
formatted_name = formatted_name.replace(' ', '_')
if formatted_name == DataCatalogEntryFactory.EMPTY_TOKEN:
formatted_name = DataCatalogEntryFactory.NO_VALUE_SPECIFIED
return formatted_name<|fim▁end|> | import pandas as pd |
<|file_name|>task.js<|end_file_name|><|fim▁begin|>"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const options_1 = require("./options");
class TslintFixTask {
constructor(configOrPath, options) {
if (options) {
this._configOrPath = configOrPath;
this._options = options;
}
else {
this._options = configOrPath;
this._configOrPath = null;
}<|fim▁hole|> toConfiguration() {
const path = typeof this._configOrPath == 'string' ? { tslintPath: this._configOrPath } : {};
const config = typeof this._configOrPath == 'object' && this._configOrPath !== null
? { tslintConfig: this._configOrPath }
: {};
const options = {
...this._options,
...path,
...config,
};
return { name: options_1.TslintFixName, options };
}
}
exports.TslintFixTask = TslintFixTask;<|fim▁end|> | } |
<|file_name|>intervalTime.js<|end_file_name|><|fim▁begin|>'use strict';
module.exports = function intervalTime(startIntervalTime){
return function(done){
var endTime = Date.now();
var runTime = endTime - startIntervalTime;
done(null,{'intervalTime': runTime});<|fim▁hole|><|fim▁end|> | };
}; |
<|file_name|>mailer.py<|end_file_name|><|fim▁begin|># coding: utf-8
import datetime
from django.core.management.base import BaseCommand
# from django.template.loader import render_to_string
from django.db.models import Count
from scheduler.models import Need
from shiftmailer.models import Mailer
from shiftmailer.excelexport import GenerateExcelSheet
DATE_FORMAT = '%d.%m.%Y'
class Command(BaseCommand):
help = 'sends emails taken from addresses (.models.mailer) with a list of shifts for this day' \
'run my cronjob'
def add_arguments(self, parser):
parser.add_argument('--date', dest='print_date', default=datetime.date.today().strftime(DATE_FORMAT),
help='The date to generate scheduler for')
def handle(self, *args, **options):
mailer = Mailer.objects.all()
t = datetime.datetime.strptime(options['print_date'], DATE_FORMAT)
for mail in mailer:
needs = Need.objects.filter(location=mail.location).filter(
ending_time__year=t.strftime("%Y"),
ending_time__month=t.strftime("%m"),
ending_time__day=t.strftime("%d")) \
.order_by('topic', 'ending_time') \
.annotate(volunteer_count=Count('registrationprofile')) \<|fim▁hole|> .select_related('topic', 'location') \
.prefetch_related('registrationprofile_set', 'registrationprofile_set__user')
# if it's not used anyway, we maybe shouldn't even render it? #
# message = render_to_string('shifts_today.html', locals())
iua = GenerateExcelSheet(shifts=needs, mailer=mail)
iua.send_file()<|fim▁end|> | |
<|file_name|>segment_allocations.py<|end_file_name|><|fim▁begin|># Copyright 2013 Openstack Foundation
# 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.
"""
Provide strategies for allocating network segments. (vlan, vxlan, etc)
"""
from quark.db import api as db_api
from quark import exceptions as quark_exceptions
from oslo_log import log as logging
from oslo_utils import timeutils
import itertools
import random
LOG = logging.getLogger(__name__)
class BaseSegmentAllocation(object):
segment_type = None
def _validate_range(self, context, sa_range):
raise NotImplementedError()
def _chunks(self, iterable, chunk_size):
"""Chunks data into chunk with size<=chunk_size."""
iterator = iter(iterable)
chunk = list(itertools.islice(iterator, 0, chunk_size))
while chunk:
yield chunk
chunk = list(itertools.islice(iterator, 0, chunk_size))
def _check_collisions(self, new_range, existing_ranges):
"""Check for overlapping ranges."""
def _contains(num, r1):
return (num >= r1[0] and
num <= r1[1])
def _is_overlap(r1, r2):
return (_contains(r1[0], r2) or
_contains(r1[1], r2) or
_contains(r2[0], r1) or
_contains(r2[1], r1))
for existing_range in existing_ranges:
if _is_overlap(new_range, existing_range):
return True
return False
def _make_segment_allocation_dict(self, id, sa_range):
return dict(
id=id,
segment_id=sa_range["segment_id"],
segment_type=sa_range["segment_type"],
segment_allocation_range_id=sa_range["id"],
deallocated=True
)
def _populate_range(self, context, sa_range):
first_id = sa_range["first_id"]
last_id = sa_range["last_id"]
id_range = xrange(first_id, last_id + 1)
LOG.info("Starting segment allocation population for "
"range:%s size:%s."
% (sa_range["id"], len(id_range)))
total_added = 0
for chunk in self._chunks(id_range, 5000):
sa_dicts = []
for segment_id in chunk:
sa_dict = self._make_segment_allocation_dict(
segment_id, sa_range)
sa_dicts.append(sa_dict)
db_api.segment_allocation_range_populate_bulk(context, sa_dicts)
context.session.flush()
total_added = total_added + len(sa_dicts)
LOG.info("Populated %s/%s segment ids for range:%s"
% (total_added, len(id_range), sa_range["id"]))
LOG.info("Finished segment allocation population for "
"range:%s size:%s."
% (sa_range["id"], len(id_range)))
def _create_range(self, context, sa_range):
with context.session.begin(subtransactions=True):
# Validate any range-specific things, like min/max ids.
self._validate_range(context, sa_range)
# Check any existing ranges for this segment for collisions
segment_id = sa_range["segment_id"]
segment_type = sa_range["segment_type"]
filters = {"segment_id": segment_id,
"segment_type": segment_type}
existing_ranges = db_api.segment_allocation_range_find(
context, lock_mode=True, scope=db_api.ALL, **filters)
collides = self._check_collisions(
(sa_range["first_id"], sa_range["last_id"]),
[(r["first_id"], r["last_id"]) for r in existing_ranges])
if collides:
raise quark_exceptions.InvalidSegmentAllocationRange(
msg=("The specified allocation collides with existing "
"range"))
return db_api.segment_allocation_range_create(
context, **sa_range)
def create_range(self, context, sa_range):
return self._create_range(context, sa_range)
def populate_range(self, context, sa_range):
return self._populate_range(context, sa_range)
def _try_allocate(self, context, segment_id, network_id):
"""Find a deallocated network segment id and reallocate it.
NOTE(morgabra) This locks the segment table, but only the rows
in use by the segment, which is pretty handy if we ever have
more than 1 segment or segment type.
"""
LOG.info("Attempting to allocate segment for network %s "
"segment_id %s segment_type %s"
% (network_id, segment_id, self.segment_type))
filter_dict = {
"segment_id": segment_id,
"segment_type": self.segment_type,
"do_not_use": False
}
available_ranges = db_api.segment_allocation_range_find(
context, scope=db_api.ALL, **filter_dict)
available_range_ids = [r["id"] for r in available_ranges]
try:
with context.session.begin(subtransactions=True):
# Search for any deallocated segment ids for the
# given segment.
filter_dict = {
"deallocated": True,
"segment_id": segment_id,
"segment_type": self.segment_type,
"segment_allocation_range_ids": available_range_ids
}
# NOTE(morgabra) We select 100 deallocated segment ids from
# the table here, and then choose 1 randomly. This is to help
# alleviate the case where an uncaught exception might leave
# an allocation active on a remote service but we do not have
# a record of it locally. If we *do* end up choosing a
# conflicted id, the caller should simply allocate another one
# and mark them all as reserved. If a single object has
# multiple reservations on the same segment, they will not be
# deallocated, and the operator must resolve the conficts
# manually.
allocations = db_api.segment_allocation_find(
context, lock_mode=True, **filter_dict).limit(100).all()
if allocations:
allocation = random.choice(allocations)
# Allocate the chosen segment.
update_dict = {
"deallocated": False,
"deallocated_at": None,
"network_id": network_id
}
allocation = db_api.segment_allocation_update(
context, allocation, **update_dict)
LOG.info("Allocated segment %s for network %s "
"segment_id %s segment_type %s"
% (allocation["id"], network_id, segment_id,
self.segment_type))
return allocation
except Exception:
LOG.exception("Error in segment reallocation.")
LOG.info("Cannot find reallocatable segment for network %s "
"segment_id %s segment_type %s"
% (network_id, segment_id, self.segment_type))
def allocate(self, context, segment_id, network_id):
allocation = self._try_allocate(
context, segment_id, network_id)
if allocation:
return allocation
raise quark_exceptions.SegmentAllocationFailure(
segment_id=segment_id, segment_type=self.segment_type)
def _try_deallocate(self, context, segment_id, network_id):
LOG.info("Attempting to deallocate segment for network %s "
"segment_id %s segment_type %s"
% (network_id, segment_id, self.segment_type))
with context.session.begin(subtransactions=True):
filter_dict = {
"deallocated": False,
"segment_id": segment_id,
"segment_type": self.segment_type,
"network_id": network_id
}
allocations = db_api.segment_allocation_find(
context, **filter_dict).all()
if not allocations:
LOG.info("Could not find allocated segment for network %s "
"segment_id %s segment_type %s for deallocate."
% (network_id, segment_id, self.segment_type))
return
if len(allocations) > 1:
LOG.error("Found multiple allocated segments for network %s "
"segment_id %s segment_type %s for deallocate. "
"Refusing to deallocate, these allocations are now "
"orphaned."
% (network_id, segment_id, self.segment_type))
return
allocation = allocations[0]
# Deallocate the found segment.
update_dict = {
"deallocated": True,
"deallocated_at": timeutils.utcnow(),
"network_id": None
}
allocation = db_api.segment_allocation_update(
context, allocation, **update_dict)
LOG.info("Deallocated %s allocated segment(s) for network %s "
"segment_id %s segment_type %s"
% (len(allocations), network_id, segment_id,
self.segment_type))
def deallocate(self, context, segment_id, network_id):
self._try_deallocate(context, segment_id, network_id)
class VXLANSegmentAllocation(BaseSegmentAllocation):
VXLAN_MIN = 1
VXLAN_MAX = (2 ** 24) - 1
segment_type = 'vxlan'
def _validate_range(self, context, sa_range):
# Validate that the range is legal and makes sense.
try:
first_id = sa_range["first_id"]
last_id = sa_range["last_id"]
first_id, last_id = (int(first_id), int(last_id))
assert first_id >= self.VXLAN_MIN
assert last_id <= self.VXLAN_MAX
assert first_id <= last_id
except Exception:
raise quark_exceptions.InvalidSegmentAllocationRange(
msg="The specified allocation range is invalid")
class SegmentAllocationRegistry(object):
def __init__(self):
self.strategies = {
VXLANSegmentAllocation.segment_type: VXLANSegmentAllocation(),<|fim▁hole|> return True
return False
def get_strategy(self, strategy_name):
if self.is_valid_strategy(strategy_name):
return self.strategies[strategy_name]
raise Exception("Segment allocation strategy %s not found."
% (strategy_name))
REGISTRY = SegmentAllocationRegistry()<|fim▁end|> | }
def is_valid_strategy(self, strategy_name):
if strategy_name in self.strategies: |
<|file_name|>ExpressRouteCircuitSku.java<|end_file_name|><|fim▁begin|>/**
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for
* license information.
*
* Code generated by Microsoft (R) AutoRest Code Generator.
*/
package com.microsoft.azure.management.network.v2020_04_01;
import com.fasterxml.jackson.annotation.JsonProperty;
/**
* Contains SKU in an ExpressRouteCircuit.
*/
public class ExpressRouteCircuitSku {
/**
* The name of the SKU.
*/
@JsonProperty(value = "name")
private String name;
/**
* The tier of the SKU. Possible values include: 'Standard', 'Premium',
* 'Basic', 'Local'.
*/
@JsonProperty(value = "tier")
private ExpressRouteCircuitSkuTier tier;
/**
* The family of the SKU. Possible values include: 'UnlimitedData',
* 'MeteredData'.
*/
@JsonProperty(value = "family")
private ExpressRouteCircuitSkuFamily family;
/**
* Get the name of the SKU.
*
* @return the name value
*/
public String name() {
return this.name;
}
/**
* Set the name of the SKU.
*
* @param name the name value to set
* @return the ExpressRouteCircuitSku object itself.
*/
public ExpressRouteCircuitSku withName(String name) {
this.name = name;
return this;
}<|fim▁hole|> /**
* Get the tier of the SKU. Possible values include: 'Standard', 'Premium', 'Basic', 'Local'.
*
* @return the tier value
*/
public ExpressRouteCircuitSkuTier tier() {
return this.tier;
}
/**
* Set the tier of the SKU. Possible values include: 'Standard', 'Premium', 'Basic', 'Local'.
*
* @param tier the tier value to set
* @return the ExpressRouteCircuitSku object itself.
*/
public ExpressRouteCircuitSku withTier(ExpressRouteCircuitSkuTier tier) {
this.tier = tier;
return this;
}
/**
* Get the family of the SKU. Possible values include: 'UnlimitedData', 'MeteredData'.
*
* @return the family value
*/
public ExpressRouteCircuitSkuFamily family() {
return this.family;
}
/**
* Set the family of the SKU. Possible values include: 'UnlimitedData', 'MeteredData'.
*
* @param family the family value to set
* @return the ExpressRouteCircuitSku object itself.
*/
public ExpressRouteCircuitSku withFamily(ExpressRouteCircuitSkuFamily family) {
this.family = family;
return this;
}
}<|fim▁end|> | |
<|file_name|>StreamTests.java<|end_file_name|><|fim▁begin|>/*
* Licensed to Elasticsearch under one or more contributor
* license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright
* ownership. Elasticsearch 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.elasticsearch.common.io.stream;
import org.apache.lucene.util.BytesRef;
import org.elasticsearch.common.CheckedBiConsumer;
import org.elasticsearch.common.CheckedFunction;
import org.elasticsearch.common.bytes.BytesArray;
import org.elasticsearch.common.bytes.BytesReference;
import org.elasticsearch.common.collect.Tuple;
import org.elasticsearch.test.ESTestCase;
import java.io.ByteArrayInputStream;
import java.io.EOFException;
import java.io.IOException;
import java.time.Instant;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.HashSet;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Objects;
import java.util.Set;
import java.util.function.Supplier;
import java.util.stream.Collectors;
import java.util.stream.IntStream;
import static org.hamcrest.Matchers.containsString;
import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.hasToString;
import static org.hamcrest.Matchers.iterableWithSize;
public class StreamTests extends ESTestCase {
public void testBooleanSerialization() throws IOException {
final BytesStreamOutput output = new BytesStreamOutput();
output.writeBoolean(false);
output.writeBoolean(true);
final BytesReference bytesReference = output.bytes();
final BytesRef bytesRef = bytesReference.toBytesRef();
assertThat(bytesRef.length, equalTo(2));
final byte[] bytes = bytesRef.bytes;
assertThat(bytes[0], equalTo((byte) 0));
assertThat(bytes[1], equalTo((byte) 1));
final StreamInput input = bytesReference.streamInput();
assertFalse(input.readBoolean());
assertTrue(input.readBoolean());
final Set<Byte> set = IntStream.range(Byte.MIN_VALUE, Byte.MAX_VALUE).mapToObj(v -> (byte) v).collect(Collectors.toSet());
set.remove((byte) 0);
set.remove((byte) 1);
final byte[] corruptBytes = new byte[]{randomFrom(set)};
final BytesReference corrupt = new BytesArray(corruptBytes);
final IllegalStateException e = expectThrows(IllegalStateException.class, () -> corrupt.streamInput().readBoolean());
final String message = String.format(Locale.ROOT, "unexpected byte [0x%02x]", corruptBytes[0]);
assertThat(e, hasToString(containsString(message)));
}
public void testOptionalBooleanSerialization() throws IOException {
final BytesStreamOutput output = new BytesStreamOutput();
output.writeOptionalBoolean(false);
output.writeOptionalBoolean(true);
output.writeOptionalBoolean(null);
final BytesReference bytesReference = output.bytes();
final BytesRef bytesRef = bytesReference.toBytesRef();
assertThat(bytesRef.length, equalTo(3));
final byte[] bytes = bytesRef.bytes;
assertThat(bytes[0], equalTo((byte) 0));
assertThat(bytes[1], equalTo((byte) 1));
assertThat(bytes[2], equalTo((byte) 2));
final StreamInput input = bytesReference.streamInput();
final Boolean maybeFalse = input.readOptionalBoolean();
assertNotNull(maybeFalse);
assertFalse(maybeFalse);
final Boolean maybeTrue = input.readOptionalBoolean();
assertNotNull(maybeTrue);
assertTrue(maybeTrue);
assertNull(input.readOptionalBoolean());
final Set<Byte> set = IntStream.range(Byte.MIN_VALUE, Byte.MAX_VALUE).mapToObj(v -> (byte) v).collect(Collectors.toSet());
set.remove((byte) 0);
set.remove((byte) 1);
set.remove((byte) 2);
final byte[] corruptBytes = new byte[]{randomFrom(set)};
final BytesReference corrupt = new BytesArray(corruptBytes);
final IllegalStateException e = expectThrows(IllegalStateException.class, () -> corrupt.streamInput().readOptionalBoolean());
final String message = String.format(Locale.ROOT, "unexpected byte [0x%02x]", corruptBytes[0]);
assertThat(e, hasToString(containsString(message)));
}
public void testRandomVLongSerialization() throws IOException {
for (int i = 0; i < 1024; i++) {
long write = randomLong();
BytesStreamOutput out = new BytesStreamOutput();
out.writeZLong(write);
long read = out.bytes().streamInput().readZLong();
assertEquals(write, read);
}
}
public void testSpecificVLongSerialization() throws IOException {
List<Tuple<Long, byte[]>> values =
Arrays.asList(
new Tuple<>(0L, new byte[]{0}),
new Tuple<>(-1L, new byte[]{1}),
new Tuple<>(1L, new byte[]{2}),
new Tuple<>(-2L, new byte[]{3}),
new Tuple<>(2L, new byte[]{4}),
new Tuple<>(Long.MIN_VALUE, new byte[]{-1, -1, -1, -1, -1, -1, -1, -1, -1, 1}),
new Tuple<>(Long.MAX_VALUE, new byte[]{-2, -1, -1, -1, -1, -1, -1, -1, -1, 1})
);
for (Tuple<Long, byte[]> value : values) {
BytesStreamOutput out = new BytesStreamOutput();
out.writeZLong(value.v1());
assertArrayEquals(Long.toString(value.v1()), value.v2(), BytesReference.toBytes(out.bytes()));
BytesReference bytes = new BytesArray(value.v2());
assertEquals(Arrays.toString(value.v2()), (long) value.v1(), bytes.streamInput().readZLong());
}
}
public void testLinkedHashMap() throws IOException {
int size = randomIntBetween(1, 1024);
boolean accessOrder = randomBoolean();
List<Tuple<String, Integer>> list = new ArrayList<>(size);
LinkedHashMap<String, Integer> write = new LinkedHashMap<>(size, 0.75f, accessOrder);
for (int i = 0; i < size; i++) {
int value = randomInt();
list.add(new Tuple<>(Integer.toString(i), value));
write.put(Integer.toString(i), value);
}
if (accessOrder) {
// randomize access order
Collections.shuffle(list, random());
for (Tuple<String, Integer> entry : list) {
// touch the entries to set the access order
write.get(entry.v1());
}
}
BytesStreamOutput out = new BytesStreamOutput();
out.writeGenericValue(write);
LinkedHashMap<String, Integer> read = (LinkedHashMap<String, Integer>) out.bytes().streamInput().readGenericValue();
assertEquals(size, read.size());
int index = 0;
for (Map.Entry<String, Integer> entry : read.entrySet()) {
assertEquals(list.get(index).v1(), entry.getKey());<|fim▁hole|> }
public void testFilterStreamInputDelegatesAvailable() throws IOException {
final int length = randomIntBetween(1, 1024);
StreamInput delegate = StreamInput.wrap(new byte[length]);
FilterStreamInput filterInputStream = new FilterStreamInput(delegate) {
};
assertEquals(filterInputStream.available(), length);
// read some bytes
final int bytesToRead = randomIntBetween(1, length);
filterInputStream.readBytes(new byte[bytesToRead], 0, bytesToRead);
assertEquals(filterInputStream.available(), length - bytesToRead);
}
public void testInputStreamStreamInputDelegatesAvailable() throws IOException {
final int length = randomIntBetween(1, 1024);
ByteArrayInputStream is = new ByteArrayInputStream(new byte[length]);
InputStreamStreamInput streamInput = new InputStreamStreamInput(is);
assertEquals(streamInput.available(), length);
// read some bytes
final int bytesToRead = randomIntBetween(1, length);
streamInput.readBytes(new byte[bytesToRead], 0, bytesToRead);
assertEquals(streamInput.available(), length - bytesToRead);
}
public void testReadArraySize() throws IOException {
BytesStreamOutput stream = new BytesStreamOutput();
byte[] array = new byte[randomIntBetween(1, 10)];
for (int i = 0; i < array.length; i++) {
array[i] = randomByte();
}
stream.writeByteArray(array);
InputStreamStreamInput streamInput = new InputStreamStreamInput(StreamInput.wrap(BytesReference.toBytes(stream.bytes())), array
.length - 1);
expectThrows(EOFException.class, streamInput::readByteArray);
streamInput = new InputStreamStreamInput(StreamInput.wrap(BytesReference.toBytes(stream.bytes())), BytesReference.toBytes(stream
.bytes()).length);
assertArrayEquals(array, streamInput.readByteArray());
}
public void testWritableArrays() throws IOException {
final String[] strings = generateRandomStringArray(10, 10, false, true);
WriteableString[] sourceArray = Arrays.stream(strings).<WriteableString>map(WriteableString::new).toArray(WriteableString[]::new);
WriteableString[] targetArray;
BytesStreamOutput out = new BytesStreamOutput();
if (randomBoolean()) {
if (randomBoolean()) {
sourceArray = null;
}
out.writeOptionalArray(sourceArray);
targetArray = out.bytes().streamInput().readOptionalArray(WriteableString::new, WriteableString[]::new);
} else {
out.writeArray(sourceArray);
targetArray = out.bytes().streamInput().readArray(WriteableString::new, WriteableString[]::new);
}
assertThat(targetArray, equalTo(sourceArray));
}
public void testArrays() throws IOException {
final String[] strings;
final String[] deserialized;
Writeable.Writer<String> writer = StreamOutput::writeString;
Writeable.Reader<String> reader = StreamInput::readString;
BytesStreamOutput out = new BytesStreamOutput();
if (randomBoolean()) {
if (randomBoolean()) {
strings = null;
} else {
strings = generateRandomStringArray(10, 10, false, true);
}
out.writeOptionalArray(writer, strings);
deserialized = out.bytes().streamInput().readOptionalArray(reader, String[]::new);
} else {
strings = generateRandomStringArray(10, 10, false, true);
out.writeArray(writer, strings);
deserialized = out.bytes().streamInput().readArray(reader, String[]::new);
}
assertThat(deserialized, equalTo(strings));
}
public void testCollection() throws IOException {
class FooBar implements Writeable {
private final int foo;
private final int bar;
private FooBar(final int foo, final int bar) {
this.foo = foo;
this.bar = bar;
}
private FooBar(final StreamInput in) throws IOException {
this.foo = in.readInt();
this.bar = in.readInt();
}
@Override
public void writeTo(final StreamOutput out) throws IOException {
out.writeInt(foo);
out.writeInt(bar);
}
@Override
public boolean equals(final Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
final FooBar that = (FooBar) o;
return foo == that.foo && bar == that.bar;
}
@Override
public int hashCode() {
return Objects.hash(foo, bar);
}
}
runWriteReadCollectionTest(
() -> new FooBar(randomInt(), randomInt()), StreamOutput::writeCollection, in -> in.readList(FooBar::new));
}
public void testStringCollection() throws IOException {
runWriteReadCollectionTest(() -> randomUnicodeOfLength(16), StreamOutput::writeStringCollection, StreamInput::readStringList);
}
private <T> void runWriteReadCollectionTest(
final Supplier<T> supplier,
final CheckedBiConsumer<StreamOutput, Collection<T>, IOException> writer,
final CheckedFunction<StreamInput, Collection<T>, IOException> reader) throws IOException {
final int length = randomIntBetween(0, 10);
final Collection<T> collection = new ArrayList<>(length);
for (int i = 0; i < length; i++) {
collection.add(supplier.get());
}
try (BytesStreamOutput out = new BytesStreamOutput()) {
writer.accept(out, collection);
try (StreamInput in = out.bytes().streamInput()) {
assertThat(collection, equalTo(reader.apply(in)));
}
}
}
public void testSetOfLongs() throws IOException {
final int size = randomIntBetween(0, 6);
final Set<Long> sourceSet = new HashSet<>(size);
for (int i = 0; i < size; i++) {
sourceSet.add(randomLongBetween(i * 1000, (i + 1) * 1000 - 1));
}
assertThat(sourceSet, iterableWithSize(size));
final BytesStreamOutput out = new BytesStreamOutput();
out.writeCollection(sourceSet, StreamOutput::writeLong);
final Set<Long> targetSet = out.bytes().streamInput().readSet(StreamInput::readLong);
assertThat(targetSet, equalTo(sourceSet));
}
public void testInstantSerialization() throws IOException {
final Instant instant = Instant.now();
try (BytesStreamOutput out = new BytesStreamOutput()) {
out.writeInstant(instant);
try (StreamInput in = out.bytes().streamInput()) {
final Instant serialized = in.readInstant();
assertEquals(instant, serialized);
}
}
}
public void testOptionalInstantSerialization() throws IOException {
final Instant instant = Instant.now();
try (BytesStreamOutput out = new BytesStreamOutput()) {
out.writeOptionalInstant(instant);
try (StreamInput in = out.bytes().streamInput()) {
final Instant serialized = in.readOptionalInstant();
assertEquals(instant, serialized);
}
}
final Instant missing = null;
try (BytesStreamOutput out = new BytesStreamOutput()) {
out.writeOptionalInstant(missing);
try (StreamInput in = out.bytes().streamInput()) {
final Instant serialized = in.readOptionalInstant();
assertEquals(missing, serialized);
}
}
}
static final class WriteableString implements Writeable {
final String string;
WriteableString(String string) {
this.string = string;
}
WriteableString(StreamInput in) throws IOException {
this(in.readString());
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
WriteableString that = (WriteableString) o;
return string.equals(that.string);
}
@Override
public int hashCode() {
return string.hashCode();
}
@Override
public void writeTo(StreamOutput out) throws IOException {
out.writeString(string);
}
}
}<|fim▁end|> | assertEquals(list.get(index).v2(), entry.getValue());
index++;
} |
<|file_name|>packr.go<|end_file_name|><|fim▁begin|><|fim▁hole|>package packr
import (
"encoding/json"
"sync"
)
var gil = &sync.Mutex{}
var data = map[string]map[string][]byte{}
// PackBytes packs bytes for a file into a box.
func PackBytes(box string, name string, bb []byte) {
gil.Lock()
defer gil.Unlock()
if _, ok := data[box]; !ok {
data[box] = map[string][]byte{}
}
data[box][name] = bb
}
// PackJSONBytes packs JSON encoded bytes for a file into a box.
func PackJSONBytes(box string, name string, jbb string) error {
bb := []byte{}
err := json.Unmarshal([]byte(jbb), &bb)
if err != nil {
return err
}
PackBytes(box, name, bb)
return nil
}<|fim▁end|> | |
<|file_name|>RDNBuilder.java<|end_file_name|><|fim▁begin|>package org.safehaus.penrose.ldap;
import java.util.Map;<|fim▁hole|> */
public class RDNBuilder {
public Map<String,Object> values = new TreeMap<String,Object>();
public RDNBuilder() {
}
public boolean isEmpty() {
return values.isEmpty();
}
public void clear() {
values.clear();
}
public void add(RDN rdn) {
values.putAll(rdn.getValues());
}
public void set(RDN rdn) {
values.clear();
values.putAll(rdn.getValues());
}
public void add(String prefix, RDN rdn) {
for (String name : rdn.getNames()) {
Object value = rdn.get(name);
values.put(prefix == null ? name : prefix + "." + name, value);
}
}
public void set(String prefix, RDN rdn) {
values.clear();
for (String name : rdn.getNames()) {
Object value = rdn.get(name);
values.put(prefix == null ? name : prefix + "." + name, value);
}
}
public void set(String name, Object value) {
this.values.put(name, value);
}
public Object remove(String name) {
return values.remove(name);
}
public void normalize() {
for (String name : values.keySet()) {
Object value = values.get(name);
if (value == null) continue;
if (value instanceof String) {
value = ((String) value).toLowerCase();
}
values.put(name, value);
}
}
public RDN toRdn() {
return new RDN(values);
}
}<|fim▁end|> | import java.util.TreeMap;
/**
* @author Endi S. Dewata |
<|file_name|>method-ufcs-2.rs<|end_file_name|><|fim▁begin|>// Copyright 2017 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.
// Unit test for the "user substitutions" that are annotated on each
// node.
#![feature(nll)]
trait Bazoom<T>: Sized {
fn method<U>(self, arg: T, arg2: U) { }
}
impl<T, U> Bazoom<U> for T {
}
fn annot_underscore() {
let a = 22;
let b = 44;
let c = 66;
<_ as Bazoom<_>>::method(a, &b, c); // OK
}
fn annot_reference_any_lifetime() {
let a = 22;
let b = 44;
let c = 66;
<_ as Bazoom<&u32>>::method(a, &b, c); // OK
}
fn annot_reference_static_lifetime() {
let a = 22;
let b = 44;
let c = 66;
let x = <&'static u32 as Bazoom<_>>::method;
x(&a, b, c); //~ ERROR
}
fn annot_reference_named_lifetime<'a>(_d: &'a u32) {
let a = 22;
let b = 44;
let c = 66;<|fim▁hole|>}
fn annot_reference_named_lifetime_ok<'a>(b: &'a u32) {
let a = 44;
let c = 66;
<_ as Bazoom<&'a u32>>::method(a, &b, c);
}
fn annot_reference_named_lifetime_in_closure<'a>(_: &'a u32) {
let a = 22;
let b = 44;
let _closure = || {
let c = 66;
<_ as Bazoom<&'a u32>>::method(a, &b, c); //~ ERROR
};
}
fn annot_reference_named_lifetime_in_closure_ok<'a>(b: &'a u32) {
let a = 44;
let c = 66;
let _closure = || {
<_ as Bazoom<&'a u32>>::method(a, &b, c);
};
}
fn main() { }<|fim▁end|> | <_ as Bazoom<&'a u32>>::method(a, &b, c); //~ ERROR |
<|file_name|>stripcomments.py<|end_file_name|><|fim▁begin|>import fileinput
for line in fileinput.input():
_line = line.strip()
# super dumb...
if _line.startswith('//') or _line.startswith('/*') or _line.startswith('*') or _line.startswith('*/'):
continue<|fim▁hole|> print line.rstrip()<|fim▁end|> | |
<|file_name|>theming.py<|end_file_name|><|fim▁begin|>from django import template
# from kilonull.conf import BlogConf
from kilonull.models import Menu, MenuItem
from kilonull.settings import SETTINGS
import re
register = template.Library()
@register.simple_tag
def blog_title():
return SETTINGS['BLOG_TITLE']
# Generate HTML for the header menu.
# Use a regex (path) to check if the current page is in the menu. If it is,
# apply the active class.
@register.simple_tag
def get_menu(menu_slug, curr_page):
html = ""
menu_items = MenuItem.objects.filter(menu__slug=menu_slug) \
.order_by("order")
path = re.compile("%s(.*)" % SETTINGS['BLOG_SITE_URL'])
for item in menu_items:
html += "<li"<|fim▁hole|> html += "><a href='%s'>%s</a></li>" % (item.link_url, item.link_text)
return html<|fim▁end|> | match = path.match(item.link_url)
if match and match.group(1) == curr_page:
html += " class='active'" |
<|file_name|>bitcoin_es.ts<|end_file_name|><|fim▁begin|><?xml version="1.0" ?><!DOCTYPE TS><TS language="es" version="2.0">
<defaultcodec>UTF-8</defaultcodec>
<context>
<name>AboutDialog</name>
<message>
<location filename="../forms/aboutdialog.ui" line="+14"/>
<source>About GoldDiggerCoin</source>
<translation>Acerca de GoldDiggerCoin</translation>
</message>
<message>
<location line="+39"/>
<source><b>GoldDiggerCoin</b> version</source>
<translation>Versión de <b>GoldDiggerCoin</b></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>
Este es un software experimental.
Distribuido bajo la licencia MIT/X11, vea el archivo adjunto
COPYING o http://www.opensource.org/licenses/mit-license.php.
Este producto incluye software desarrollado por OpenSSL Project para su uso en
el OpenSSL Toolkit (http://www.openssl.org/) y software criptográfico escrito por
Eric Young ([email protected]) y el software UPnP escrito por Thomas Bernard.</translation>
</message>
<message>
<location filename="../aboutdialog.cpp" line="+14"/>
<source>Copyright</source>
<translation>Copyright</translation>
</message>
<message>
<location line="+0"/>
<source>The GoldDiggerCoin developers</source>
<translation>Los programadores GoldDiggerCoin</translation>
</message>
</context>
<context>
<name>AddressBookPage</name>
<message>
<location filename="../forms/addressbookpage.ui" line="+14"/>
<source>Address Book</source>
<translation>Libreta de direcciones</translation>
</message>
<message>
<location line="+19"/>
<source>Double-click to edit address or label</source>
<translation>Haga doble clic para editar una dirección o etiqueta</translation>
</message>
<message>
<location line="+27"/>
<source>Create a new address</source>
<translation>Crear una nueva dirección</translation>
</message>
<message>
<location line="+14"/>
<source>Copy the currently selected address to the system clipboard</source>
<translation>Copiar la dirección seleccionada al portapapeles del sistema</translation>
</message>
<message>
<location line="-11"/>
<source>&New Address</source>
<translation>&Añadir dirección</translation>
</message>
<message>
<location filename="../addressbookpage.cpp" line="+63"/>
<source>These are your GoldDiggerCoin 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>Estas son sus direcciones GoldDiggerCoin para recibir pagos. Puede utilizar una diferente por cada persona emisora para saber quién le está pagando.</translation>
</message>
<message>
<location filename="../forms/addressbookpage.ui" line="+14"/>
<source>&Copy Address</source>
<translation>&Copiar dirección</translation>
</message>
<message>
<location line="+11"/>
<source>Show &QR Code</source>
<translation>Mostrar código &QR </translation>
</message>
<message>
<location line="+11"/>
<source>Sign a message to prove you own a GoldDiggerCoin address</source>
<translation>Firmar un mensaje para demostrar que se posee una dirección GoldDiggerCoin</translation>
</message>
<message>
<location line="+3"/>
<source>Sign &Message</source>
<translation>&Firmar mensaje</translation>
</message>
<message>
<location line="+25"/>
<source>Delete the currently selected address from the list</source>
<translation>Borrar de la lista la dirección seleccionada</translation>
</message>
<message>
<location line="+27"/>
<source>Export the data in the current tab to a file</source>
<translation>Exportar a un archivo los datos de esta pestaña</translation>
</message>
<message>
<location line="+3"/>
<source>&Export</source>
<translation>&Exportar</translation>
</message>
<message>
<location line="-44"/>
<source>Verify a message to ensure it was signed with a specified GoldDiggerCoin address</source>
<translation>Verificar un mensaje para comprobar que fue firmado con la dirección GoldDiggerCoin indicada</translation>
</message>
<message>
<location line="+3"/>
<source>&Verify Message</source>
<translation>&Verificar mensaje</translation>
</message>
<message>
<location line="+14"/>
<source>&Delete</source>
<translation>&Eliminar</translation>
</message>
<message>
<location filename="../addressbookpage.cpp" line="-5"/>
<source>These are your GoldDiggerCoin addresses for sending payments. Always check the amount and the receiving address before sending coins.</source>
<translation>Estas son sus direcciones GoldDiggerCoin para enviar pagos. Compruebe siempre la cantidad y la dirección receptora antes de transferir monedas.</translation>
</message>
<message>
<location line="+13"/>
<source>Copy &Label</source>
<translation>Copiar &etiqueta</translation>
</message>
<message>
<location line="+1"/>
<source>&Edit</source>
<translation>&Editar</translation>
</message>
<message>
<location line="+1"/>
<source>Send &Coins</source>
<translation>Enviar &monedas</translation>
</message>
<message>
<location line="+260"/>
<source>Export Address Book Data</source>
<translation>Exportar datos de la libreta de direcciones</translation>
</message>
<message>
<location line="+1"/>
<source>Comma separated file (*.csv)</source>
<translation>Archivos de columnas separadas por coma (*.csv)</translation>
</message>
<message>
<location line="+13"/>
<source>Error exporting</source>
<translation>Error al exportar</translation>
</message>
<message>
<location line="+0"/>
<source>Could not write to file %1.</source>
<translation>No se pudo escribir en el archivo %1.</translation>
</message>
</context>
<context>
<name>AddressTableModel</name>
<message>
<location filename="../addresstablemodel.cpp" line="+144"/>
<source>Label</source>
<translation>Etiqueta</translation>
</message>
<message>
<location line="+0"/>
<source>Address</source>
<translation>Dirección</translation>
</message>
<message>
<location line="+36"/>
<source>(no label)</source>
<translation>(sin etiqueta)</translation>
</message>
</context>
<context>
<name>AskPassphraseDialog</name>
<message>
<location filename="../forms/askpassphrasedialog.ui" line="+26"/>
<source>Passphrase Dialog</source>
<translation>Diálogo de contraseña</translation>
</message>
<message>
<location line="+21"/>
<source>Enter passphrase</source>
<translation>Introducir contraseña</translation>
</message>
<message>
<location line="+14"/>
<source>New passphrase</source>
<translation>Nueva contraseña</translation>
</message>
<message>
<location line="+14"/>
<source>Repeat new passphrase</source>
<translation>Repita la nueva contraseña</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>Introduzca la nueva contraseña del monedero.<br/>Por favor elija una con <b>10 o más caracteres aleatorios</b> u <b>ocho o más palabras</b>.</translation>
</message>
<message>
<location line="+1"/>
<source>Encrypt wallet</source>
<translation>Cifrar el monedero</translation>
</message>
<message>
<location line="+3"/>
<source>This operation needs your wallet passphrase to unlock the wallet.</source>
<translation>Esta operación requiere su contraseña para desbloquear el monedero.</translation>
</message>
<message>
<location line="+5"/>
<source>Unlock wallet</source>
<translation>Desbloquear monedero</translation>
</message>
<message>
<location line="+3"/>
<source>This operation needs your wallet passphrase to decrypt the wallet.</source>
<translation>Esta operación requiere su contraseña para descifrar el monedero.</translation>
</message>
<message>
<location line="+5"/>
<source>Decrypt wallet</source>
<translation>Descifrar el monedero</translation>
</message>
<message>
<location line="+3"/>
<source>Change passphrase</source>
<translation>Cambiar contraseña</translation>
</message>
<message>
<location line="+1"/>
<source>Enter the old and new passphrase to the wallet.</source>
<translation>Introduzca la contraseña anterior del monedero y la nueva. </translation>
</message>
<message>
<location line="+46"/>
<source>Confirm wallet encryption</source>
<translation>Confirmar cifrado del monedero</translation>
</message>
<message>
<location line="+1"/>
<source>Warning: If you encrypt your wallet and lose your passphrase, you will <b>LOSE ALL OF YOUR GOLDDIGGERCOINS</b>!</source>
<translation>Atencion: ¡Si cifra su monedero y pierde la contraseña perderá <b>TODOS SUS GOLDDIGGERCOINS</b>!"</translation>
</message>
<message>
<location line="+0"/>
<source>Are you sure you wish to encrypt your wallet?</source>
<translation>¿Seguro que desea cifrar su monedero?</translation>
</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>IMPORTANTE: Cualquier copia de seguridad que haya realizado previamente de su archivo de monedero debe reemplazarse con el nuevo archivo de monedero cifrado. Por razones de seguridad, las copias de seguridad previas del archivo de monedero no cifradas serán inservibles en cuanto comience a usar el nuevo monedero cifrado.</translation>
</message>
<message>
<location line="+100"/>
<location line="+24"/>
<source>Warning: The Caps Lock key is on!</source>
<translation>Aviso: ¡La tecla de bloqueo de mayúsculas está activada!</translation>
</message>
<message>
<location line="-130"/>
<location line="+58"/>
<source>Wallet encrypted</source>
<translation>Monedero cifrado</translation>
</message>
<message>
<location line="-56"/>
<source>GoldDiggerCoin will close now to finish the encryption process. Remember that encrypting your wallet cannot fully protect your golddiggercoins from being stolen by malware infecting your computer.</source>
<translation>GoldDiggerCoin se cerrará para finalizar el proceso de cifrado. Recuerde que el cifrado de su monedero no puede proteger totalmente sus golddiggercoins de robo por malware que infecte su sistema.</translation>
</message>
<message>
<location line="+13"/>
<location line="+7"/>
<location line="+42"/>
<location line="+6"/>
<source>Wallet encryption failed</source>
<translation>Ha fallado el cifrado del monedero</translation>
</message>
<message>
<location line="-54"/>
<source>Wallet encryption failed due to an internal error. Your wallet was not encrypted.</source>
<translation>Ha fallado el cifrado del monedero debido a un error interno. El monedero no ha sido cifrado.</translation>
</message>
<message>
<location line="+7"/>
<location line="+48"/>
<source>The supplied passphrases do not match.</source>
<translation>Las contraseñas no coinciden.</translation>
</message>
<message>
<location line="-37"/>
<source>Wallet unlock failed</source>
<translation>Ha fallado el desbloqueo del monedero</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 contraseña introducida para descifrar el monedero es incorrecta.</translation>
</message>
<message>
<location line="-20"/>
<source>Wallet decryption failed</source>
<translation>Ha fallado el descifrado del monedero</translation>
</message>
<message>
<location line="+14"/>
<source>Wallet passphrase was successfully changed.</source>
<translation>Se ha cambiado correctamente la contraseña del monedero.</translation>
</message>
</context>
<context>
<name>BitcoinGUI</name>
<message>
<location filename="../bitcoingui.cpp" line="+233"/>
<source>Sign &message...</source>
<translation>Firmar &mensaje...</translation>
</message>
<message>
<location line="+280"/>
<source>Synchronizing with network...</source>
<translation>Sincronizando con la red…</translation>
</message>
<message>
<location line="-349"/>
<source>&Overview</source>
<translation>&Vista general</translation>
</message>
<message>
<location line="+1"/>
<source>Show general overview of wallet</source>
<translation>Mostrar vista general del monedero</translation>
</message>
<message>
<location line="+20"/>
<source>&Transactions</source>
<translation>&Transacciones</translation>
</message>
<message>
<location line="+1"/>
<source>Browse transaction history</source>
<translation>Examinar el historial de transacciones</translation>
</message>
<message>
<location line="+7"/>
<source>Edit the list of stored addresses and labels for sending</source>
<translation>Editar la lista de las direcciones y etiquetas almacenadas</translation>
</message>
<message>
<location line="-14"/>
<source>Show the list of addresses for receiving payments</source>
<translation>Mostrar la lista de direcciones utilizadas para recibir pagos</translation>
</message>
<message>
<location line="+31"/>
<source>E&xit</source>
<translation>&Salir</translation>
</message>
<message>
<location line="+1"/>
<source>Quit application</source>
<translation>Salir de la aplicación</translation>
</message>
<message>
<location line="+4"/>
<source>Show information about GoldDiggerCoin</source>
<translation>Mostrar información acerca de GoldDiggerCoin</translation>
</message>
<message>
<location line="+2"/>
<source>About &Qt</source>
<translation>Acerca de &Qt</translation>
</message>
<message>
<location line="+1"/>
<source>Show information about Qt</source>
<translation>Mostrar información acerca de Qt</translation>
</message>
<message>
<location line="+2"/>
<source>&Options...</source>
<translation>&Opciones...</translation>
</message>
<message>
<location line="+6"/>
<source>&Encrypt Wallet...</source>
<translation>&Cifrar monedero…</translation>
</message>
<message>
<location line="+3"/>
<source>&Backup Wallet...</source>
<translation>Copia de &respaldo del monedero...</translation>
</message>
<message>
<location line="+2"/>
<source>&Change Passphrase...</source>
<translation>&Cambiar la contraseña…</translation>
</message>
<message>
<location line="+285"/>
<source>Importing blocks from disk...</source>
<translation>Importando bloques de disco...</translation>
</message>
<message>
<location line="+3"/>
<source>Reindexing blocks on disk...</source>
<translation>Reindexando bloques en disco...</translation>
</message>
<message>
<location line="-347"/>
<source>Send coins to a GoldDiggerCoin address</source>
<translation>Enviar monedas a una dirección GoldDiggerCoin</translation>
</message>
<message>
<location line="+49"/>
<source>Modify configuration options for GoldDiggerCoin</source>
<translation>Modificar las opciones de configuración de GoldDiggerCoin</translation>
</message>
<message>
<location line="+9"/>
<source>Backup wallet to another location</source>
<translation>Copia de seguridad del monedero en otra ubicación</translation>
</message>
<message>
<location line="+2"/>
<source>Change the passphrase used for wallet encryption</source>
<translation>Cambiar la contraseña utilizada para el cifrado del monedero</translation>
</message>
<message>
<location line="+6"/>
<source>&Debug window</source>
<translation>Ventana de &depuración</translation>
</message>
<message>
<location line="+1"/>
<source>Open debugging and diagnostic console</source>
<translation>Abrir la consola de depuración y diagnóstico</translation>
</message>
<message>
<location line="-4"/>
<source>&Verify message...</source>
<translation>&Verificar mensaje...</translation>
</message>
<message>
<location line="-165"/>
<location line="+530"/>
<source>GoldDiggerCoin</source>
<translation>GoldDiggerCoin</translation>
</message>
<message>
<location line="-530"/>
<source>Wallet</source>
<translation>Monedero</translation>
</message>
<message>
<location line="+101"/>
<source>&Send</source>
<translation>&Enviar</translation>
</message>
<message>
<location line="+7"/>
<source>&Receive</source>
<translation>&Recibir</translation>
</message>
<message>
<location line="+14"/>
<source>&Addresses</source>
<translation>&Direcciones</translation>
</message>
<message>
<location line="+22"/>
<source>&About GoldDiggerCoin</source>
<translation>&Acerca de GoldDiggerCoin</translation>
</message>
<message>
<location line="+9"/>
<source>&Show / Hide</source>
<translation>Mo&strar/ocultar</translation>
</message>
<message>
<location line="+1"/>
<source>Show or hide the main Window</source>
<translation>Mostrar u ocultar la ventana principal</translation>
</message>
<message>
<location line="+3"/>
<source>Encrypt the private keys that belong to your wallet</source>
<translation>Cifrar las claves privadas de su monedero</translation>
</message>
<message>
<location line="+7"/>
<source>Sign messages with your GoldDiggerCoin addresses to prove you own them</source>
<translation>Firmar mensajes con sus direcciones GoldDiggerCoin para demostrar la propiedad</translation>
</message>
<message>
<location line="+2"/>
<source>Verify messages to ensure they were signed with specified GoldDiggerCoin addresses</source>
<translation>Verificar mensajes comprobando que están firmados con direcciones GoldDiggerCoin concretas</translation>
</message>
<message>
<location line="+28"/>
<source>&File</source>
<translation>&Archivo</translation>
</message>
<message>
<location line="+7"/>
<source>&Settings</source>
<translation>&Configuración</translation>
</message>
<message>
<location line="+6"/>
<source>&Help</source>
<translation>A&yuda</translation>
</message>
<message>
<location line="+9"/>
<source>Tabs toolbar</source>
<translation>Barra de pestañas</translation>
</message>
<message>
<location line="+17"/>
<location line="+10"/>
<source>[testnet]</source>
<translation>[testnet]</translation>
</message>
<message>
<location line="+47"/>
<source>GoldDiggerCoin client</source>
<translation>Cliente GoldDiggerCoin</translation>
</message>
<message numerus="yes">
<location line="+141"/>
<source>%n active connection(s) to GoldDiggerCoin network</source>
<translation><numerusform>%n conexión activa hacia la red GoldDiggerCoin</numerusform><numerusform>%n conexiones activas hacia la red GoldDiggerCoin</numerusform></translation>
</message>
<message>
<location line="+22"/>
<source>No block source available...</source>
<translation>Ninguna fuente de bloques disponible ...</translation>
</message>
<message>
<location line="+12"/>
<source>Processed %1 of %2 (estimated) blocks of transaction history.</source>
<translation>Se han procesado %1 de %2 bloques (estimados) del historial de transacciones.</translation>
</message>
<message>
<location line="+4"/>
<source>Processed %1 blocks of transaction history.</source>
<translation>Procesados %1 bloques del historial de transacciones.</translation>
</message>
<message numerus="yes">
<location line="+20"/>
<source>%n hour(s)</source>
<translation><numerusform>%n hora</numerusform><numerusform>%n horas</numerusform></translation>
</message>
<message numerus="yes">
<location line="+4"/>
<source>%n day(s)</source>
<translation><numerusform>%n día</numerusform><numerusform>%n días</numerusform></translation>
</message>
<message numerus="yes">
<location line="+4"/>
<source>%n week(s)</source>
<translation><numerusform>%n semana</numerusform><numerusform>%n semanas</numerusform></translation>
</message>
<message>
<location line="+4"/>
<source>%1 behind</source>
<translation>%1 atrás</translation>
</message>
<message>
<location line="+14"/>
<source>Last received block was generated %1 ago.</source>
<translation>El último bloque recibido fue generado hace %1.</translation>
</message>
<message>
<location line="+2"/>
<source>Transactions after this will not yet be visible.</source>
<translation>Las transacciones posteriores a esta aún no están visibles.</translation>
</message>
<message>
<location line="+22"/>
<source>Error</source>
<translation>Error</translation>
</message>
<message>
<location line="+3"/>
<source>Warning</source>
<translation>Aviso</translation>
</message>
<message>
<location line="+3"/>
<source>Information</source>
<translation>Información</translation>
</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>Esta transacción supera el límite de tamaño. Puede enviarla con una comisión de %1, destinada a los nodos que procesen su transacción para contribuir al mantenimiento de la red. ¿Desea pagar esta comisión?</translation>
</message>
<message>
<location line="-140"/>
<source>Up to date</source>
<translation>Actualizado</translation>
</message>
<message>
<location line="+31"/>
<source>Catching up...</source>
<translation>Actualizando...</translation>
</message>
<message>
<location line="+113"/>
<source>Confirm transaction fee</source>
<translation>Confirme la tarifa de la transacción</translation>
</message>
<message>
<location line="+8"/>
<source>Sent transaction</source>
<translation>Transacción enviada</translation>
</message>
<message>
<location line="+0"/>
<source>Incoming transaction</source>
<translation>Transacción entrante</translation>
</message>
<message>
<location line="+1"/>
<source>Date: %1
Amount: %2
Type: %3
Address: %4
</source>
<translation>Fecha: %1
Cantidad: %2
Tipo: %3
Dirección: %4
</translation>
</message>
<message>
<location line="+33"/>
<location line="+23"/>
<source>URI handling</source>
<translation>Gestión de URI</translation>
</message>
<message>
<location line="-23"/>
<location line="+23"/>
<source>URI can not be parsed! This can be caused by an invalid GoldDiggerCoin address or malformed URI parameters.</source>
<translation>¡No se puede interpretar la URI! Esto puede deberse a una dirección GoldDiggerCoin inválida o a parámetros de URI mal formados.</translation>
</message>
<message>
<location line="+17"/>
<source>Wallet is <b>encrypted</b> and currently <b>unlocked</b></source>
<translation>El monedero está <b>cifrado</b> y actualmente <b>desbloqueado</b></translation>
</message>
<message>
<location line="+8"/>
<source>Wallet is <b>encrypted</b> and currently <b>locked</b></source>
<translation>El monedero está <b>cifrado</b> y actualmente <b>bloqueado</b></translation>
</message>
<message>
<location filename="../bitcoin.cpp" line="+111"/>
<source>A fatal error occurred. GoldDiggerCoin can no longer continue safely and will quit.</source>
<translation>Ha ocurrido un error crítico. GoldDiggerCoin ya no puede continuar con seguridad y se cerrará.</translation>
</message>
</context>
<context>
<name>ClientModel</name>
<message>
<location filename="../clientmodel.cpp" line="+104"/>
<source>Network Alert</source>
<translation>Alerta de red</translation>
</message>
</context>
<context>
<name>EditAddressDialog</name>
<message>
<location filename="../forms/editaddressdialog.ui" line="+14"/>
<source>Edit Address</source>
<translation>Editar Dirección</translation>
</message>
<message>
<location line="+11"/>
<source>&Label</source>
<translation>&Etiqueta</translation>
</message>
<message>
<location line="+10"/>
<source>The label associated with this address book entry</source>
<translation>La etiqueta asociada con esta entrada en la libreta</translation>
</message>
<message>
<location line="+7"/>
<source>&Address</source>
<translation>&Dirección</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>La dirección asociada con esta entrada en la guía. Solo puede ser modificada para direcciones de envío.</translation>
</message>
<message>
<location filename="../editaddressdialog.cpp" line="+21"/>
<source>New receiving address</source>
<translation>Nueva dirección para recibir</translation>
</message>
<message>
<location line="+4"/>
<source>New sending address</source>
<translation>Nueva dirección para enviar</translation>
</message>
<message>
<location line="+3"/>
<source>Edit receiving address</source>
<translation>Editar dirección de recepción</translation>
</message>
<message>
<location line="+4"/>
<source>Edit sending address</source>
<translation>Editar dirección de envío</translation>
</message>
<message>
<location line="+76"/>
<source>The entered address "%1" is already in the address book.</source>
<translation>La dirección introducida "%1" ya está presente en la libreta de direcciones.</translation>
</message>
<message>
<location line="-5"/>
<source>The entered address "%1" is not a valid GoldDiggerCoin address.</source>
<translation>La dirección introducida "%1" no es una dirección GoldDiggerCoin válida.</translation>
</message>
<message>
<location line="+10"/>
<source>Could not unlock wallet.</source>
<translation>No se pudo desbloquear el monedero.</translation>
</message>
<message>
<location line="+5"/>
<source>New key generation failed.</source>
<translation>Ha fallado la generación de la nueva clave.</translation>
</message>
</context>
<context>
<name>GUIUtil::HelpMessageBox</name>
<message>
<location filename="../guiutil.cpp" line="+424"/>
<location line="+12"/>
<source>GoldDiggerCoin-Qt</source>
<translation>GoldDiggerCoin-Qt</translation>
</message>
<message>
<location line="-12"/>
<source>version</source>
<translation>versión</translation>
</message>
<message>
<location line="+2"/>
<source>Usage:</source>
<translation>Uso:</translation>
</message>
<message>
<location line="+1"/>
<source>command-line options</source>
<translation>opciones de la línea de órdenes</translation>
</message>
<message>
<location line="+4"/>
<source>UI options</source>
<translation>Opciones GUI</translation>
</message>
<message>
<location line="+1"/>
<source>Set language, for example "de_DE" (default: system locale)</source>
<translation>Establecer el idioma, por ejemplo, "es_ES" (predeterminado: configuración regional del sistema)</translation>
</message>
<message>
<location line="+1"/>
<source>Start minimized</source>
<translation>Arrancar minimizado</translation>
</message>
<message>
<location line="+1"/>
<source>Show splash screen on startup (default: 1)</source>
<translation>Mostrar pantalla de bienvenida en el inicio (predeterminado: 1)</translation>
</message>
</context>
<context>
<name>OptionsDialog</name>
<message>
<location filename="../forms/optionsdialog.ui" line="+14"/>
<source>Options</source>
<translation>Opciones</translation>
</message>
<message>
<location line="+16"/>
<source>&Main</source>
<translation>&Principal</translation>
</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>Tarifa de transacción opcional por kB que ayuda a asegurar que sus transacciones sean procesadas rápidamente. La mayoría de transacciones son de 1kB.</translation>
</message>
<message>
<location line="+15"/>
<source>Pay transaction &fee</source>
<translation>Comisión de &transacciones</translation>
</message>
<message>
<location line="+31"/>
<source>Automatically start GoldDiggerCoin after logging in to the system.</source>
<translation>Iniciar GoldDiggerCoin automáticamente al encender el sistema.</translation>
</message>
<message>
<location line="+3"/>
<source>&Start GoldDiggerCoin on system login</source>
<translation>&Iniciar GoldDiggerCoin al iniciar el sistema</translation>
</message>
<message>
<location line="+35"/>
<source>Reset all client options to default.</source>
<translation>Restablecer todas las opciones del cliente a las predeterminadas.</translation>
</message>
<message>
<location line="+3"/>
<source>&Reset Options</source>
<translation>&Restablecer opciones</translation>
</message>
<message>
<location line="+13"/>
<source>&Network</source>
<translation>&Red</translation>
</message>
<message>
<location line="+6"/>
<source>Automatically open the GoldDiggerCoin client port on the router. This only works when your router supports UPnP and it is enabled.</source>
<translation>Abrir automáticamente el puerto del cliente GoldDiggerCoin en el router. Esta opción solo funciona si el router admite UPnP y está activado.</translation>
</message>
<message>
<location line="+3"/>
<source>Map port using &UPnP</source>
<translation>Mapear el puerto usando &UPnP</translation>
</message>
<message>
<location line="+7"/>
<source>Connect to the GoldDiggerCoin network through a SOCKS proxy (e.g. when connecting through Tor).</source>
<translation>Conectar a la red GoldDiggerCoin a través de un proxy SOCKS (ej. para conectar con la red Tor)</translation>
</message>
<message>
<location line="+3"/>
<source>&Connect through SOCKS proxy:</source>
<translation>&Conectar a través de un proxy SOCKS:</translation>
</message>
<message>
<location line="+9"/>
<source>Proxy &IP:</source>
<translation>Dirección &IP del proxy:</translation>
</message>
<message>
<location line="+19"/>
<source>IP address of the proxy (e.g. 127.0.0.1)</source>
<translation>Dirección IP del proxy (ej. 127.0.0.1)</translation>
</message>
<message>
<location line="+7"/>
<source>&Port:</source>
<translation>&Puerto:</translation>
</message>
<message>
<location line="+19"/>
<source>Port of the proxy (e.g. 9050)</source>
<translation>Puerto del servidor proxy (ej. 9050)</translation>
</message>
<message>
<location line="+7"/>
<source>SOCKS &Version:</source>
<translation>&Versión SOCKS:</translation>
</message>
<message>
<location line="+13"/>
<source>SOCKS version of the proxy (e.g. 5)</source>
<translation>Versión del proxy SOCKS (ej. 5)</translation>
</message>
<message>
<location line="+36"/>
<source>&Window</source>
<translation>&Ventana</translation>
</message>
<message>
<location line="+6"/>
<source>Show only a tray icon after minimizing the window.</source>
<translation>Minimizar la ventana a la bandeja de iconos del sistema.</translation>
</message>
<message>
<location line="+3"/>
<source>&Minimize to the tray instead of the taskbar</source>
<translation>&Minimizar a la bandeja en vez de a la barra de tareas</translation>
</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>Minimizar en lugar de salir de la aplicación al cerrar la ventana.Cuando esta opción está activa, la aplicación solo se puede cerrar seleccionando Salir desde el menú.</translation>
</message>
<message>
<location line="+3"/>
<source>M&inimize on close</source>
<translation>M&inimizar al cerrar</translation>
</message>
<message>
<location line="+21"/>
<source>&Display</source>
<translation>&Interfaz</translation>
</message>
<message>
<location line="+8"/>
<source>User Interface &language:</source>
<translation>I&dioma de la interfaz de usuario</translation>
</message>
<message>
<location line="+13"/>
<source>The user interface language can be set here. This setting will take effect after restarting GoldDiggerCoin.</source>
<translation>El idioma de la interfaz de usuario puede establecerse aquí. Este ajuste se aplicará cuando se reinicie GoldDiggerCoin.</translation>
</message>
<message>
<location line="+11"/>
<source>&Unit to show amounts in:</source>
<translation>Mostrar las cantidades en la &unidad:</translation>
</message>
<message>
<location line="+13"/>
<source>Choose the default subdivision unit to show in the interface and when sending coins.</source>
<translation>Elegir la subdivisión predeterminada para mostrar cantidades en la interfaz y cuando se envían monedas.</translation>
</message>
<message>
<location line="+9"/>
<source>Whether to show GoldDiggerCoin addresses in the transaction list or not.</source>
<translation>Mostrar o no las direcciones GoldDiggerCoin en la lista de transacciones.</translation>
</message>
<message>
<location line="+3"/>
<source>&Display addresses in transaction list</source>
<translation>&Mostrar las direcciones en la lista de transacciones</translation>
</message>
<message>
<location line="+71"/>
<source>&OK</source>
<translation>&Aceptar</translation>
</message>
<message>
<location line="+7"/>
<source>&Cancel</source>
<translation>&Cancelar</translation>
</message>
<message>
<location line="+10"/>
<source>&Apply</source>
<translation>&Aplicar</translation>
</message>
<message>
<location filename="../optionsdialog.cpp" line="+53"/>
<source>default</source>
<translation>predeterminado</translation>
</message>
<message>
<location line="+130"/>
<source>Confirm options reset</source>
<translation>Confirme el restablecimiento de las opciones</translation>
</message>
<message>
<location line="+1"/>
<source>Some settings may require a client restart to take effect.</source>
<translation>Algunas configuraciones pueden requerir un reinicio del cliente para que sean efectivas.</translation>
</message>
<message>
<location line="+0"/>
<source>Do you want to proceed?</source>
<translation>¿Quiere proceder?</translation>
</message>
<message>
<location line="+42"/>
<location line="+9"/>
<source>Warning</source>
<translation>Aviso</translation>
</message>
<message>
<location line="-9"/>
<location line="+9"/>
<source>This setting will take effect after restarting GoldDiggerCoin.</source>
<translation>Esta configuración tendrá efecto tras reiniciar GoldDiggerCoin.</translation>
</message>
<message>
<location line="+29"/>
<source>The supplied proxy address is invalid.</source>
<translation>La dirección proxy indicada es inválida.</translation>
</message>
</context>
<context>
<name>OverviewPage</name>
<message>
<location filename="../forms/overviewpage.ui" line="+14"/>
<source>Form</source>
<translation>Desde</translation>
</message>
<message>
<location line="+50"/>
<location line="+166"/>
<source>The displayed information may be out of date. Your wallet automatically synchronizes with the GoldDiggerCoin network after a connection is established, but this process has not completed yet.</source>
<translation>La información mostrada puede estar desactualizada. Su monedero se sincroniza automáticamente con la red GoldDiggerCoin después de que se haya establecido una conexión , pero este proceso aún no se ha completado.</translation>
</message>
<message>
<location line="-124"/>
<source>Balance:</source>
<translation>Saldo:</translation>
</message>
<message>
<location line="+29"/>
<source>Unconfirmed:</source>
<translation>No confirmado(s):</translation>
</message>
<message>
<location line="-78"/>
<source>Wallet</source>
<translation>Monedero</translation>
</message>
<message>
<location line="+107"/>
<source>Immature:</source>
<translation>No disponible:</translation>
</message>
<message>
<location line="+13"/>
<source>Mined balance that has not yet matured</source>
<translation>Saldo recién minado que aún no está disponible.</translation>
</message>
<message>
<location line="+46"/>
<source><b>Recent transactions</b></source>
<translation><b>Movimientos recientes</b></translation>
</message>
<message>
<location line="-101"/>
<source>Your current balance</source>
<translation>Su saldo actual</translation>
</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>Total de las transacciones que faltan por confirmar y que no contribuyen al saldo actual</translation>
</message>
<message>
<location filename="../overviewpage.cpp" line="+116"/>
<location line="+1"/>
<source>out of sync</source>
<translation>desincronizado</translation>
</message>
</context>
<context>
<name>PaymentServer</name>
<message>
<location filename="../paymentserver.cpp" line="+107"/>
<source>Cannot start golddiggercoin: click-to-pay handler</source>
<translation>No se pudo iniciar golddiggercoin: manejador de pago-al-clic</translation>
</message>
</context>
<context>
<name>QRCodeDialog</name>
<message>
<location filename="../forms/qrcodedialog.ui" line="+14"/>
<source>QR Code Dialog</source>
<translation>Diálogo de códigos QR</translation>
</message>
<message>
<location line="+59"/>
<source>Request Payment</source>
<translation>Solicitud de pago</translation>
</message>
<message>
<location line="+56"/>
<source>Amount:</source>
<translation>Cuantía:</translation>
</message>
<message>
<location line="-44"/>
<source>Label:</source>
<translation>Etiqueta:</translation>
</message>
<message>
<location line="+19"/>
<source>Message:</source>
<translation>Mensaje:</translation>
</message>
<message>
<location line="+71"/>
<source>&Save As...</source>
<translation>&Guardar como...</translation>
</message>
<message>
<location filename="../qrcodedialog.cpp" line="+62"/>
<source>Error encoding URI into QR Code.</source>
<translation>Error al codificar la URI en el código QR.</translation>
</message>
<message>
<location line="+40"/>
<source>The entered amount is invalid, please check.</source>
<translation>La cantidad introducida es inválida. Compruébela, por favor.</translation>
</message>
<message>
<location line="+23"/>
<source>Resulting URI too long, try to reduce the text for label / message.</source>
<translation>URI esultante demasiado larga. Intente reducir el texto de la etiqueta / mensaje.</translation>
</message>
<message>
<location line="+25"/>
<source>Save QR Code</source>
<translation>Guardar código QR</translation>
</message>
<message>
<location line="+0"/>
<source>PNG Images (*.png)</source>
<translation>Imágenes PNG (*.png)</translation>
</message>
</context>
<context>
<name>RPCConsole</name>
<message>
<location filename="../forms/rpcconsole.ui" line="+46"/>
<source>Client name</source>
<translation>Nombre del cliente</translation>
</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>N/D</translation>
</message>
<message>
<location line="-217"/>
<source>Client version</source>
<translation>Versión del cliente</translation>
</message>
<message>
<location line="-45"/>
<source>&Information</source>
<translation>&Información</translation>
</message>
<message>
<location line="+68"/>
<source>Using OpenSSL version</source>
<translation>Utilizando la versión OpenSSL</translation>
</message>
<message>
<location line="+49"/>
<source>Startup time</source>
<translation>Hora de inicio</translation>
</message>
<message>
<location line="+29"/>
<source>Network</source>
<translation>Red</translation>
</message>
<message>
<location line="+7"/>
<source>Number of connections</source>
<translation>Número de conexiones</translation>
</message>
<message>
<location line="+23"/>
<source>On testnet</source>
<translation>En la red de pruebas</translation>
</message>
<message>
<location line="+23"/>
<source>Block chain</source>
<translation>Cadena de bloques</translation>
</message>
<message>
<location line="+7"/>
<source>Current number of blocks</source>
<translation>Número actual de bloques</translation>
</message>
<message>
<location line="+23"/>
<source>Estimated total blocks</source>
<translation>Bloques totales estimados</translation>
</message>
<message>
<location line="+23"/>
<source>Last block time</source>
<translation>Hora del último bloque</translation>
</message>
<message>
<location line="+52"/>
<source>&Open</source>
<translation>&Abrir</translation>
</message>
<message>
<location line="+16"/>
<source>Command-line options</source>
<translation>Opciones de la línea de órdenes</translation>
</message>
<message>
<location line="+7"/>
<source>Show the GoldDiggerCoin-Qt help message to get a list with possible GoldDiggerCoin command-line options.</source>
<translation>Mostrar el mensaje de ayuda de GoldDiggerCoin-Qt que enumera las opciones disponibles de línea de órdenes para GoldDiggerCoin.</translation>
</message>
<message>
<location line="+3"/>
<source>&Show</source>
<translation>&Mostrar</translation>
</message>
<message>
<location line="+24"/>
<source>&Console</source>
<translation>&Consola</translation>
</message>
<message>
<location line="-260"/>
<source>Build date</source>
<translation>Fecha de compilación</translation>
</message>
<message>
<location line="-104"/>
<source>GoldDiggerCoin - Debug window</source>
<translation>GoldDiggerCoin - Ventana de depuración</translation>
</message>
<message>
<location line="+25"/>
<source>GoldDiggerCoin Core</source>
<translation>Núcleo de GoldDiggerCoin</translation>
</message>
<message>
<location line="+279"/>
<source>Debug log file</source>
<translation>Archivo de registro de depuración</translation>
</message>
<message>
<location line="+7"/>
<source>Open the GoldDiggerCoin debug log file from the current data directory. This can take a few seconds for large log files.</source>
<translation>Abrir el archivo de registro de depuración en el directorio actual de datos. Esto puede llevar varios segundos para archivos de registro grandes.</translation>
</message>
<message>
<location line="+102"/>
<source>Clear console</source>
<translation>Borrar consola</translation>
</message>
<message>
<location filename="../rpcconsole.cpp" line="-30"/>
<source>Welcome to the GoldDiggerCoin RPC console.</source>
<translation>Bienvenido a la consola RPC de GoldDiggerCoin</translation>
</message>
<message>
<location line="+1"/>
<source>Use up and down arrows to navigate history, and <b>Ctrl-L</b> to clear screen.</source>
<translation>Use las flechas arriba y abajo para navegar por el historial y <b>Control+L</b> para limpiar la pantalla.</translation>
</message>
<message>
<location line="+1"/>
<source>Type <b>help</b> for an overview of available commands.</source>
<translation>Escriba <b>help</b> para ver un resumen de los comandos disponibles.</translation>
</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>Enviar monedas</translation>
</message>
<message>
<location line="+50"/>
<source>Send to multiple recipients at once</source>
<translation>Enviar a multiples destinatarios de una vez</translation>
</message>
<message>
<location line="+3"/>
<source>Add &Recipient</source>
<translation>Añadir &destinatario</translation>
</message>
<message>
<location line="+20"/>
<source>Remove all transaction fields</source>
<translation>Eliminar todos los campos de las transacciones</translation>
</message>
<message>
<location line="+3"/>
<source>Clear &All</source>
<translation>Limpiar &todo</translation>
</message>
<message>
<location line="+22"/>
<source>Balance:</source>
<translation>Saldo:</translation>
</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>Confirmar el envío</translation>
</message>
<message>
<location line="+3"/>
<source>S&end</source>
<translation>&Enviar</translation>
</message>
<message>
<location filename="../sendcoinsdialog.cpp" line="-59"/>
<source><b>%1</b> to %2 (%3)</source>
<translation><b>%1</b> a %2 (%3)</translation>
</message>
<message>
<location line="+5"/>
<source>Confirm send coins</source>
<translation>Confirmar el envío de monedas</translation>
</message>
<message>
<location line="+1"/>
<source>Are you sure you want to send %1?</source>
<translation>¿Está seguro de que desea enviar %1?</translation>
</message>
<message>
<location line="+0"/>
<source> and </source>
<translation>y</translation>
</message>
<message>
<location line="+23"/>
<source>The recipient address is not valid, please recheck.</source>
<translation>La dirección de recepción no es válida, compruébela de nuevo.</translation>
</message>
<message>
<location line="+5"/>
<source>The amount to pay must be larger than 0.</source>
<translation>La cantidad por pagar tiene que ser mayor de 0.</translation>
</message>
<message>
<location line="+5"/>
<source>The amount exceeds your balance.</source>
<translation>La cantidad sobrepasa su saldo.</translation>
</message>
<message>
<location line="+5"/>
<source>The total exceeds your balance when the %1 transaction fee is included.</source>
<translation>El total sobrepasa su saldo cuando se incluye la tasa de envío de %1</translation>
</message>
<message>
<location line="+6"/>
<source>Duplicate address found, can only send to each address once per send operation.</source>
<translation>Se ha encontrado una dirección duplicada. Solo se puede enviar a cada dirección una vez por operación de envío.</translation>
</message>
<message>
<location line="+5"/>
<source>Error: Transaction creation failed!</source>
<translation>Error: ¡Ha fallado la creación de la transacción!</translation>
</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>Error: transacción rechazada. Puede haber ocurrido si alguna de las monedas ya estaba gastada o si ha usado una copia de wallet.dat y las monedas se gastaron en la copia pero no se han marcado así aquí.</translation>
</message>
</context>
<context>
<name>SendCoinsEntry</name>
<message>
<location filename="../forms/sendcoinsentry.ui" line="+14"/>
<source>Form</source>
<translation>Envío</translation>
</message>
<message>
<location line="+15"/>
<source>A&mount:</source>
<translation>Ca&ntidad:</translation>
</message>
<message>
<location line="+13"/>
<source>Pay &To:</source>
<translation>&Pagar a:</translation>
</message>
<message>
<location line="+34"/>
<source>The address to send the payment to (e.g. DJ7zB7c5BsB9UJLy1rKQtY7c6CQfGiaRLM)</source>
<translation>La dirección a la que enviar el pago (p. ej. DJ7zB7c5BsB9UJLy1rKQtY7c6CQfGiaRLM)</translation>
</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>Etiquete esta dirección para añadirla a la libreta</translation>
</message>
<message>
<location line="-78"/>
<source>&Label:</source>
<translation>&Etiqueta:</translation>
</message>
<message>
<location line="+28"/>
<source>Choose address from address book</source>
<translation>Elija una dirección de la libreta de direcciones</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>Pegar dirección desde portapapeles</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>Eliminar destinatario</translation>
</message>
<message>
<location filename="../sendcoinsentry.cpp" line="+1"/>
<source>Enter a GoldDiggerCoin address (e.g. DJ7zB7c5BsB9UJLy1rKQtY7c6CQfGiaRLM)</source>
<translation>Introduzca una dirección GoldDiggerCoin (ej. DJ7zB7c5BsB9UJLy1rKQtY7c6CQfGiaRLM)</translation>
</message>
</context>
<context>
<name>SignVerifyMessageDialog</name>
<message>
<location filename="../forms/signverifymessagedialog.ui" line="+14"/>
<source>Signatures - Sign / Verify a Message</source>
<translation>Firmas - Firmar / verificar un mensaje</translation>
</message>
<message>
<location line="+13"/>
<source>&Sign Message</source>
<translation>&Firmar mensaje</translation>
</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>Puede firmar mensajes con sus direcciones para demostrar que las posee. Tenga cuidado de no firmar cualquier cosa vaga, ya que los ataques de phishing pueden tratar de engañarle para suplantar su identidad. Firme solo declaraciones totalmente detalladas con las que usted esté de acuerdo.</translation>
</message>
<message>
<location line="+18"/>
<source>The address to sign the message with (e.g. DJ7zB7c5BsB9UJLy1rKQtY7c6CQfGiaRLM)</source>
<translation>La dirección con la que firmar el mensaje (ej. DJ7zB7c5BsB9UJLy1rKQtY7c6CQfGiaRLM)</translation>
</message>
<message>
<location line="+10"/>
<location line="+213"/>
<source>Choose an address from the address book</source>
<translation>Elija una dirección de la libreta de direcciones</translation>
</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>Pegar dirección desde portapapeles</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>Introduzca el mensaje que desea firmar aquí</translation>
</message>
<message>
<location line="+7"/>
<source>Signature</source>
<translation>Firma</translation>
</message>
<message>
<location line="+27"/>
<source>Copy the current signature to the system clipboard</source>
<translation>Copiar la firma actual al portapapeles del sistema</translation>
</message>
<message>
<location line="+21"/>
<source>Sign the message to prove you own this GoldDiggerCoin address</source>
<translation>Firmar el mensaje para demostrar que se posee esta dirección GoldDiggerCoin</translation>
</message>
<message>
<location line="+3"/>
<source>Sign &Message</source>
<translation>Firmar &mensaje</translation>
</message>
<message>
<location line="+14"/>
<source>Reset all sign message fields</source>
<translation>Limpiar todos los campos de la firma de mensaje</translation>
</message>
<message>
<location line="+3"/>
<location line="+146"/>
<source>Clear &All</source>
<translation>Limpiar &todo</translation>
</message>
<message>
<location line="-87"/>
<source>&Verify Message</source>
<translation>&Verificar mensaje</translation>
</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>Introduzca la dirección para la firma, el mensaje (asegurándose de copiar tal cual los saltos de línea, espacios, tabulaciones, etc.) y la firma a continuación para verificar el mensaje. Tenga cuidado de no asumir más información de lo que dice el propio mensaje firmado para evitar fraudes basados en ataques de tipo man-in-the-middle.</translation>
</message>
<message>
<location line="+21"/>
<source>The address the message was signed with (e.g. DJ7zB7c5BsB9UJLy1rKQtY7c6CQfGiaRLM)</source>
<translation>La dirección con la que se firmó el mensaje (ej. DJ7zB7c5BsB9UJLy1rKQtY7c6CQfGiaRLM)</translation>
</message>
<message>
<location line="+40"/>
<source>Verify the message to ensure it was signed with the specified GoldDiggerCoin address</source>
<translation>Verificar el mensaje para comprobar que fue firmado con la dirección GoldDiggerCoin indicada</translation>
</message>
<message>
<location line="+3"/>
<source>Verify &Message</source>
<translation>Verificar &mensaje</translation>
</message>
<message>
<location line="+14"/>
<source>Reset all verify message fields</source>
<translation>Limpiar todos los campos de la verificación de mensaje</translation>
</message>
<message>
<location filename="../signverifymessagedialog.cpp" line="+27"/>
<location line="+3"/>
<source>Enter a GoldDiggerCoin address (e.g. DJ7zB7c5BsB9UJLy1rKQtY7c6CQfGiaRLM)</source>
<translation>Introduzca una dirección GoldDiggerCoin (ej. DJ7zB7c5BsB9UJLy1rKQtY7c6CQfGiaRLM)</translation>
</message>
<message>
<location line="-2"/>
<source>Click "Sign Message" to generate signature</source>
<translation>Haga clic en "Firmar mensaje" para generar la firma</translation>
</message>
<message>
<location line="+3"/>
<source>Enter GoldDiggerCoin signature</source>
<translation>Introduzca una firma GoldDiggerCoin</translation>
</message>
<message>
<location line="+82"/>
<location line="+81"/>
<source>The entered address is invalid.</source>
<translation>La dirección introducida es inválida.</translation>
</message>
<message>
<location line="-81"/>
<location line="+8"/>
<location line="+73"/>
<location line="+8"/>
<source>Please check the address and try again.</source>
<translation>Verifique la dirección e inténtelo de nuevo.</translation>
</message>
<message>
<location line="-81"/>
<location line="+81"/>
<source>The entered address does not refer to a key.</source>
<translation>La dirección introducida no corresponde a una clave.</translation>
</message>
<message>
<location line="-73"/>
<source>Wallet unlock was cancelled.</source>
<translation>Se ha cancelado el desbloqueo del monedero. </translation>
</message>
<message>
<location line="+8"/>
<source>Private key for the entered address is not available.</source>
<translation>No se dispone de la clave privada para la dirección introducida.</translation>
</message>
<message>
<location line="+12"/>
<source>Message signing failed.</source>
<translation>Ha fallado la firma del mensaje.</translation>
</message>
<message>
<location line="+5"/>
<source>Message signed.</source>
<translation>Mensaje firmado.</translation>
</message>
<message>
<location line="+59"/>
<source>The signature could not be decoded.</source>
<translation>No se puede decodificar la firma.</translation>
</message>
<message>
<location line="+0"/>
<location line="+13"/>
<source>Please check the signature and try again.</source>
<translation>Compruebe la firma e inténtelo de nuevo.</translation>
</message>
<message>
<location line="+0"/>
<source>The signature did not match the message digest.</source>
<translation>La firma no coincide con el resumen del mensaje.</translation>
</message>
<message>
<location line="+7"/>
<source>Message verification failed.</source>
<translation>La verificación del mensaje ha fallado.</translation>
</message>
<message>
<location line="+5"/>
<source>Message verified.</source>
<translation>Mensaje verificado.</translation>
</message>
</context>
<context>
<name>SplashScreen</name>
<message>
<location filename="../splashscreen.cpp" line="+22"/>
<source>The GoldDiggerCoin developers</source>
<translation>Los programadores GoldDiggerCoin</translation>
</message>
<message>
<location line="+1"/>
<source>[testnet]</source>
<translation>[testnet]</translation>
</message>
</context>
<context>
<name>TransactionDesc</name>
<message>
<location filename="../transactiondesc.cpp" line="+20"/>
<source>Open until %1</source>
<translation>Abierto hasta %1</translation>
</message>
<message>
<location line="+6"/>
<source>%1/offline</source>
<translation>%1/fuera de línea</translation>
</message>
<message>
<location line="+2"/>
<source>%1/unconfirmed</source>
<translation>%1/no confirmado</translation>
</message>
<message>
<location line="+2"/>
<source>%1 confirmations</source>
<translation>%1 confirmaciones</translation>
</message>
<message>
<location line="+18"/>
<source>Status</source>
<translation>Estado</translation>
</message>
<message numerus="yes">
<location line="+7"/>
<source>, broadcast through %n node(s)</source>
<translation><numerusform>, transmitir a través de %n nodo</numerusform><numerusform>, transmitir a través de %n nodos</numerusform></translation>
</message>
<message>
<location line="+4"/>
<source>Date</source>
<translation>Fecha</translation>
</message>
<message>
<location line="+7"/>
<source>Source</source>
<translation>Fuente</translation>
</message>
<message>
<location line="+0"/>
<source>Generated</source>
<translation>Generado</translation>
</message>
<message>
<location line="+5"/>
<location line="+17"/>
<source>From</source>
<translation>De</translation>
</message>
<message>
<location line="+1"/>
<location line="+22"/>
<location line="+58"/>
<source>To</source>
<translation>Para</translation>
</message>
<message>
<location line="-77"/>
<location line="+2"/>
<source>own address</source>
<translation>dirección propia</translation>
</message>
<message>
<location line="-2"/>
<source>label</source>
<translation>etiqueta</translation>
</message>
<message>
<location line="+37"/>
<location line="+12"/>
<location line="+45"/>
<location line="+17"/>
<location line="+30"/>
<source>Credit</source>
<translation>Crédito</translation>
</message>
<message numerus="yes">
<location line="-102"/>
<source>matures in %n more block(s)</source>
<translation><numerusform>disponible en %n bloque más</numerusform><numerusform>disponible en %n bloques más</numerusform></translation>
</message>
<message>
<location line="+2"/>
<source>not accepted</source>
<translation>no aceptada</translation>
</message>
<message>
<location line="+44"/>
<location line="+8"/>
<location line="+15"/>
<location line="+30"/>
<source>Debit</source>
<translation>Débito</translation>
</message>
<message>
<location line="-39"/>
<source>Transaction fee</source>
<translation>Comisión de transacción</translation>
</message>
<message>
<location line="+16"/>
<source>Net amount</source>
<translation>Cantidad neta</translation>
</message>
<message>
<location line="+6"/>
<source>Message</source>
<translation>Mensaje</translation>
</message>
<message>
<location line="+2"/>
<source>Comment</source>
<translation>Comentario</translation>
</message>
<message>
<location line="+2"/>
<source>Transaction ID</source>
<translation>Identificador de transacción</translation>
</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>Las monedas generadas deben esperar 120 bloques antes de que se puedan gastar. Cuando se generó este bloque, se emitió a la red para ser agregado a la cadena de bloques. Si no consigue incorporarse a la cadena, su estado cambiará a "no aceptado" y las monedas no se podrán gastar. Esto puede ocurrir ocasionalmente si otro nodo genera un bloque casi al mismo tiempo que el suyo.</translation>
</message>
<message>
<location line="+7"/>
<source>Debug information</source>
<translation>Información de depuración</translation>
</message>
<message>
<location line="+8"/>
<source>Transaction</source>
<translation>Transacción</translation>
</message>
<message>
<location line="+3"/>
<source>Inputs</source>
<translation>entradas</translation>
</message>
<message>
<location line="+23"/>
<source>Amount</source>
<translation>Cantidad</translation>
</message>
<message>
<location line="+1"/>
<source>true</source>
<translation>verdadero</translation>
</message>
<message>
<location line="+0"/>
<source>false</source>
<translation>falso</translation>
</message>
<message>
<location line="-209"/>
<source>, has not been successfully broadcast yet</source>
<translation>, todavía no se ha sido difundido satisfactoriamente</translation>
</message>
<message numerus="yes">
<location line="-35"/>
<source>Open for %n more block(s)</source>
<translation><numerusform>Abrir para %n bloque más</numerusform><numerusform>Abrir para %n bloques más</numerusform></translation>
</message>
<message>
<location line="+70"/>
<source>unknown</source>
<translation>desconocido</translation>
</message>
</context>
<context>
<name>TransactionDescDialog</name>
<message>
<location filename="../forms/transactiondescdialog.ui" line="+14"/>
<source>Transaction details</source>
<translation>Detalles de transacción</translation>
</message>
<message>
<location line="+6"/>
<source>This pane shows a detailed description of the transaction</source>
<translation>Esta ventana muestra información detallada sobre la transacción</translation>
</message>
</context>
<context>
<name>TransactionTableModel</name>
<message>
<location filename="../transactiontablemodel.cpp" line="+225"/>
<source>Date</source>
<translation>Fecha</translation>
</message>
<message>
<location line="+0"/>
<source>Type</source>
<translation>Tipo</translation>
</message>
<message>
<location line="+0"/>
<source>Address</source>
<translation>Dirección</translation>
</message>
<message>
<location line="+0"/>
<source>Amount</source>
<translation>Cantidad</translation>
</message>
<message numerus="yes">
<location line="+57"/>
<source>Open for %n more block(s)</source>
<translation><numerusform>Abrir para %n bloque más</numerusform><numerusform>Abrir para %n bloques más</numerusform></translation>
</message>
<message>
<location line="+3"/>
<source>Open until %1</source>
<translation>Abierto hasta %1</translation>
</message>
<message>
<location line="+3"/>
<source>Offline (%1 confirmations)</source>
<translation>Fuera de línea (%1 confirmaciones)</translation>
</message>
<message>
<location line="+3"/>
<source>Unconfirmed (%1 of %2 confirmations)</source>
<translation>No confirmado (%1 de %2 confirmaciones)</translation>
</message>
<message>
<location line="+3"/>
<source>Confirmed (%1 confirmations)</source>
<translation>Confirmado (%1 confirmaciones)</translation>
</message>
<message numerus="yes">
<location line="+8"/>
<source>Mined balance will be available when it matures in %n more block(s)</source>
<translation><numerusform>El saldo recién minado estará disponible cuando venza el plazo en %n bloque más</numerusform><numerusform>El saldo recién minado estará disponible cuando venza el plazo en %n bloques más</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>Este bloque no ha sido recibido por otros nodos y probablemente no sea aceptado!</translation>
</message>
<message>
<location line="+3"/>
<source>Generated but not accepted</source>
<translation>Generado pero no aceptado</translation>
</message>
<message>
<location line="+43"/>
<source>Received with</source>
<translation>Recibido con</translation>
</message>
<message>
<location line="+2"/>
<source>Received from</source>
<translation>Recibidos de</translation>
</message>
<message>
<location line="+3"/>
<source>Sent to</source>
<translation>Enviado a</translation>
</message>
<message>
<location line="+2"/>
<source>Payment to yourself</source>
<translation>Pago propio</translation>
</message>
<message>
<location line="+2"/>
<source>Mined</source>
<translation>Minado</translation>
</message>
<message>
<location line="+38"/>
<source>(n/a)</source>
<translation>(nd)</translation>
</message>
<message>
<location line="+199"/>
<source>Transaction status. Hover over this field to show number of confirmations.</source>
<translation>Estado de transacción. Pasa el ratón sobre este campo para ver el número de confirmaciones.</translation>
</message>
<message>
<location line="+2"/>
<source>Date and time that the transaction was received.</source>
<translation>Fecha y hora en que se recibió la transacción.</translation>
</message>
<message>
<location line="+2"/>
<source>Type of transaction.</source>
<translation>Tipo de transacción.</translation>
</message>
<message>
<location line="+2"/>
<source>Destination address of transaction.</source>
<translation>Dirección de destino de la transacción.</translation>
</message>
<message>
<location line="+2"/>
<source>Amount removed from or added to balance.</source>
<translation>Cantidad retirada o añadida al saldo.</translation>
</message>
</context>
<context>
<name>TransactionView</name>
<message>
<location filename="../transactionview.cpp" line="+52"/>
<location line="+16"/>
<source>All</source>
<translation>Todo</translation>
</message>
<message>
<location line="-15"/>
<source>Today</source>
<translation>Hoy</translation>
</message>
<message>
<location line="+1"/>
<source>This week</source>
<translation>Esta semana</translation>
</message>
<message>
<location line="+1"/>
<source>This month</source>
<translation>Este mes</translation>
</message>
<message>
<location line="+1"/>
<source>Last month</source>
<translation>Mes pasado</translation>
</message>
<message>
<location line="+1"/>
<source>This year</source>
<translation>Este año</translation>
</message>
<message>
<location line="+1"/>
<source>Range...</source>
<translation>Rango...</translation>
</message>
<message>
<location line="+11"/>
<source>Received with</source>
<translation>Recibido con</translation>
</message>
<message>
<location line="+2"/>
<source>Sent to</source>
<translation>Enviado a</translation>
</message>
<message>
<location line="+2"/>
<source>To yourself</source>
<translation>A usted mismo</translation>
</message>
<message>
<location line="+1"/>
<source>Mined</source>
<translation>Minado</translation>
</message>
<message>
<location line="+1"/>
<source>Other</source>
<translation>Otra</translation>
</message>
<message>
<location line="+7"/>
<source>Enter address or label to search</source>
<translation>Introduzca una dirección o etiqueta que buscar</translation>
</message>
<message>
<location line="+7"/>
<source>Min amount</source>
<translation>Cantidad mínima</translation>
</message>
<message>
<location line="+34"/>
<source>Copy address</source>
<translation>Copiar dirección</translation>
</message>
<message>
<location line="+1"/>
<source>Copy label</source>
<translation>Copiar etiqueta</translation>
</message>
<message>
<location line="+1"/>
<source>Copy amount</source>
<translation>Copiar cuantía</translation>
</message>
<message>
<location line="+1"/>
<source>Copy transaction ID</source>
<translation>Copiar identificador de transacción</translation>
</message>
<message>
<location line="+1"/>
<source>Edit label</source>
<translation>Editar etiqueta</translation>
</message>
<message>
<location line="+1"/>
<source>Show transaction details</source>
<translation>Mostrar detalles de la transacción</translation>
</message>
<message>
<location line="+139"/>
<source>Export Transaction Data</source>
<translation>Exportar datos de la transacción</translation>
</message>
<message>
<location line="+1"/>
<source>Comma separated file (*.csv)</source>
<translation>Archivos de columnas separadas por coma (*.csv)</translation>
</message>
<message>
<location line="+8"/>
<source>Confirmed</source>
<translation>Confirmado</translation>
</message>
<message>
<location line="+1"/>
<source>Date</source>
<translation>Fecha</translation>
</message>
<message>
<location line="+1"/>
<source>Type</source>
<translation>Tipo</translation>
</message>
<message>
<location line="+1"/>
<source>Label</source>
<translation>Etiqueta</translation>
</message>
<message>
<location line="+1"/>
<source>Address</source>
<translation>Dirección</translation>
</message>
<message>
<location line="+1"/>
<source>Amount</source>
<translation>Cantidad</translation>
</message>
<message>
<location line="+1"/>
<source>ID</source>
<translation>ID</translation>
</message>
<message>
<location line="+4"/>
<source>Error exporting</source>
<translation>Error exportando</translation>
</message>
<message>
<location line="+0"/>
<source>Could not write to file %1.</source>
<translation>No se pudo escribir en el archivo %1.</translation>
</message>
<message>
<location line="+100"/>
<source>Range:</source>
<translation>Rango:</translation>
</message>
<message>
<location line="+8"/>
<source>to</source>
<translation>para</translation>
</message>
</context>
<context>
<name>WalletModel</name>
<message>
<location filename="../walletmodel.cpp" line="+193"/>
<source>Send Coins</source>
<translation>Enviar monedas</translation>
</message>
</context>
<context>
<name>WalletView</name>
<message>
<location filename="../walletview.cpp" line="+42"/>
<source>&Export</source>
<translation>&Exportar</translation>
</message>
<message>
<location line="+1"/>
<source>Export the data in the current tab to a file</source>
<translation>Exportar a un archivo los datos de esta pestaña</translation>
</message>
<message>
<location line="+193"/>
<source>Backup Wallet</source>
<translation>Respaldo de monedero</translation>
</message>
<message>
<location line="+0"/>
<source>Wallet Data (*.dat)</source>
<translation>Datos de monedero (*.dat)</translation>
</message>
<message>
<location line="+3"/>
<source>Backup Failed</source>
<translation>Ha fallado el respaldo</translation>
</message>
<message>
<location line="+0"/>
<source>There was an error trying to save the wallet data to the new location.</source>
<translation>Se ha producido un error al intentar guardar los datos del monedero en la nueva ubicación.</translation>
</message>
<message>
<location line="+4"/>
<source>Backup Successful</source>
<translation>Se ha completado con éxito la copia de respaldo</translation>
</message>
<message>
<location line="+0"/>
<source>The wallet data was successfully saved to the new location.</source>
<translation>Los datos del monedero se han guardado con éxito en la nueva ubicación.</translation>
</message>
</context>
<context>
<name>bitcoin-core</name>
<message>
<location filename="../bitcoinstrings.cpp" line="+94"/>
<source>GoldDiggerCoin version</source>
<translation>Versión de GoldDiggerCoin</translation>
</message>
<message>
<location line="+102"/>
<source>Usage:</source>
<translation>Uso:</translation>
</message>
<message>
<location line="-29"/>
<source>Send command to -server or golddiggercoind</source>
<translation>Envíar comando a -server o golddiggercoind</translation>
</message>
<message>
<location line="-23"/>
<source>List commands</source>
<translation>Muestra comandos
</translation>
</message>
<message>
<location line="-12"/>
<source>Get help for a command</source>
<translation>Recibir ayuda para un comando
</translation>
</message>
<message>
<location line="+24"/>
<source>Options:</source>
<translation>Opciones:
</translation>
</message>
<message>
<location line="+24"/>
<source>Specify configuration file (default: golddiggercoin.conf)</source>
<translation>Especificar archivo de configuración (predeterminado: golddiggercoin.conf)
</translation>
</message>
<message>
<location line="+3"/>
<source>Specify pid file (default: golddiggercoind.pid)</source>
<translation>Especificar archivo pid (predeterminado: golddiggercoin.pid)
</translation>
</message>
<message>
<location line="-1"/>
<source>Specify data directory</source>
<translation>Especificar directorio para los datos</translation>
</message>
<message>
<location line="-9"/>
<source>Set database cache size in megabytes (default: 25)</source>
<translation>Establecer el tamaño de caché de la base de datos en megabytes (predeterminado: 25)</translation>
</message>
<message>
<location line="-28"/>
<source>Listen for connections on <port> (default: 22556 or testnet: 44556)</source>
<translation>Escuchar conexiones en <puerto> (predeterminado: 22556 o testnet: 44556)</translation>
</message>
<message>
<location line="+5"/>
<source>Maintain at most <n> connections to peers (default: 125)</source>
<translation>Mantener como máximo <n> conexiones a pares (predeterminado: 125)</translation>
</message>
<message>
<location line="-48"/>
<source>Connect to a node to retrieve peer addresses, and disconnect</source>
<translation>Conectar a un nodo para obtener direcciones de pares y desconectar</translation>
</message>
<message>
<location line="+82"/>
<source>Specify your own public address</source>
<translation>Especifique su propia dirección pública</translation>
</message>
<message>
<location line="+3"/>
<source>Threshold for disconnecting misbehaving peers (default: 100)</source>
<translation>Umbral para la desconexión de pares con mal comportamiento (predeterminado: 100)</translation>
</message>
<message>
<location line="-134"/>
<source>Number of seconds to keep misbehaving peers from reconnecting (default: 86400)</source>
<translation>Número de segundos en que se evita la reconexión de pares con mal comportamiento (predeterminado: 86400)</translation>
</message>
<message>
<location line="-29"/>
<source>An error occurred while setting up the RPC port %u for listening on IPv4: %s</source>
<translation>Ha ocurrido un error al configurar el puerto RPC %u para escucha en IPv4: %s</translation>
</message>
<message>
<location line="+27"/>
<source>Listen for JSON-RPC connections on <port> (default: 22555 or testnet: 44555)</source>
<translation>Escuchar conexiones JSON-RPC en <puerto> (predeterminado: 22555 o testnet:44555)</translation>
</message>
<message>
<location line="+37"/>
<source>Accept command line and JSON-RPC commands</source>
<translation>Aceptar comandos consola y JSON-RPC
</translation>
</message>
<message>
<location line="+76"/>
<source>Run in the background as a daemon and accept commands</source>
<translation>Correr como demonio y aceptar comandos
</translation>
</message>
<message>
<location line="+37"/>
<source>Use the test network</source>
<translation>Usar la red de pruebas
</translation>
</message>
<message>
<location line="-112"/>
<source>Accept connections from outside (default: 1 if no -proxy or -connect)</source>
<translation>Aceptar conexiones desde el exterior (predeterminado: 1 si no -proxy o -connect)</translation>
</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=golddiggercoinrpc
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 "GoldDiggerCoin Alert" [email protected]
</source>
<translation>%s, debe establecer un valor rpcpassword en el archivo de configuración:
%s
Se recomienda utilizar la siguiente contraseña aleatoria:
rpcuser=golddiggercoinrpc
rpcpassword=%s
(no es necesario recordar esta contraseña)
El nombre de usuario y la contraseña DEBEN NO ser iguales.
Si el archivo no existe, créelo con permisos de archivo de solo lectura.
Se recomienda también establecer alertnotify para recibir notificaciones de problemas.
Por ejemplo: alertnotify=echo %%s | mail -s "GoldDiggerCoin Alert" [email protected]
</translation>
</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>Ha ocurrido un error al configurar el puerto RPC %u para escuchar mediante IPv6. Recurriendo a IPv4: %s</translation>
</message>
<message>
<location line="+3"/>
<source>Bind to given address and always listen on it. Use [host]:port notation for IPv6</source>
<translation>Vincular a la dirección dada y escuchar siempre en ella. Utilice la notación [host]:port para IPv6</translation>
</message>
<message>
<location line="+3"/>
<source>Cannot obtain a lock on data directory %s. GoldDiggerCoin is probably already running.</source>
<translation>No se puede bloquear el directorio de datos %s. Probablemente GoldDiggerCoin ya se está ejecutando.</translation>
</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>¡Error: se ha rechazado la transacción! Esto puede ocurrir si ya se han gastado algunas de las monedas del monedero, como ocurriría si hubiera hecho una copia de wallet.dat y se hubieran gastado monedas a partir de la copia, con lo que no se habrían marcado aquí como gastadas.</translation>
</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>¡Error: Esta transacción requiere una comisión de al menos %s debido a su monto, complejidad, o al uso de fondos recién recibidos!</translation>
</message>
<message>
<location line="+3"/>
<source>Execute command when a relevant alert is received (%s in cmd is replaced by message)</source>
<translation>Ejecutar orden cuando se reciba un aviso relevante (%s en cmd se reemplazará por el mensaje)</translation>
</message>
<message>
<location line="+3"/>
<source>Execute command when a wallet transaction changes (%s in cmd is replaced by TxID)</source>
<translation>Ejecutar comando cuando una transacción del monedero cambia (%s en cmd se remplazará por TxID)</translation>
</message>
<message>
<location line="+11"/>
<source>Set maximum size of high-priority/low-fee transactions in bytes (default: 27000)</source>
<translation>Establecer el tamaño máximo de las transacciones de alta prioridad/comisión baja en bytes (predeterminado:27000)</translation>
</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>Esta es una versión de pre-prueba - utilícela bajo su propio riesgo. No la utilice para usos comerciales o de minería.</translation>
</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>Aviso: ¡-paytxfee tiene un valor muy alto! Esta es la comisión que pagará si envía una transacción.</translation>
</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>Aviso: ¡Las transacciones mostradas pueden no ser correctas! Puede necesitar una actualización o bien otros nodos necesitan actualizarse.</translation>
</message>
<message>
<location line="+3"/>
<source>Warning: Please check that your computer's date and time are correct! If your clock is wrong GoldDiggerCoin will not work properly.</source>
<translation>Precaución: Por favor, ¡revise que la fecha y hora de su ordenador son correctas! Si su reloj está mal, GoldDiggerCoin no funcionará correctamente.</translation>
</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>Aviso: ¡Error al leer wallet.dat! Todas las claves se han leído correctamente, pero podrían faltar o ser incorrectos los datos de transacciones o las entradas de la libreta de direcciones.</translation>
</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>Aviso: ¡Recuperados datos de wallet.dat corrupto! El wallet.dat original se ha guardado como wallet.{timestamp}.bak en %s; si hubiera errores en su saldo o transacciones, deberá restaurar una copia de seguridad.</translation>
</message>
<message>
<location line="+14"/>
<source>Attempt to recover private keys from a corrupt wallet.dat</source>
<translation>Intento de recuperar claves privadas de un wallet.dat corrupto</translation>
</message>
<message>
<location line="+2"/>
<source>Block creation options:</source>
<translation>Opciones de creación de bloques:</translation>
</message>
<message>
<location line="+5"/>
<source>Connect only to the specified node(s)</source>
<translation>Conectar sólo a los nodos (o nodo) especificados</translation>
</message>
<message>
<location line="+3"/>
<source>Corrupted block database detected</source>
<translation>Corrupción de base de datos de bloques detectada.</translation>
</message>
<message>
<location line="+1"/>
<source>Discover own IP address (default: 1 when listening and no -externalip)</source>
<translation>Descubrir dirección IP propia (predeterminado: 1 al escuchar sin -externalip)</translation>
</message>
<message>
<location line="+1"/>
<source>Do you want to rebuild the block database now?</source>
<translation>¿Quieres reconstruir la base de datos de bloques ahora?</translation>
</message>
<message>
<location line="+2"/>
<source>Error initializing block database</source>
<translation>Error al inicializar la base de datos de bloques</translation>
</message>
<message>
<location line="+1"/>
<source>Error initializing wallet database environment %s!</source>
<translation>Error al inicializar el entorno de la base de datos del monedero %s</translation>
</message>
<message>
<location line="+1"/>
<source>Error loading block database</source>
<translation>Error cargando base de datos de bloques</translation>
</message>
<message>
<location line="+4"/>
<source>Error opening block database</source>
<translation>Error al abrir base de datos de bloques.</translation>
</message>
<message>
<location line="+2"/>
<source>Error: Disk space is low!</source>
<translation>Error: ¡Espacio en disco bajo!</translation>
</message>
<message>
<location line="+1"/>
<source>Error: Wallet locked, unable to create transaction!</source>
<translation>Error: ¡El monedero está bloqueado; no se puede crear la transacción!</translation>
</message>
<message>
<location line="+1"/>
<source>Error: system error: </source>
<translation>Error: error de sistema: </translation>
</message>
<message>
<location line="+1"/>
<source>Failed to listen on any port. Use -listen=0 if you want this.</source>
<translation>Ha fallado la escucha en todos los puertos. Use -listen=0 si desea esto.</translation>
</message>
<message>
<location line="+1"/>
<source>Failed to read block info</source>
<translation>No se ha podido leer la información de bloque</translation>
</message>
<message>
<location line="+1"/>
<source>Failed to read block</source>
<translation>No se ha podido leer el bloque</translation>
</message>
<message>
<location line="+1"/>
<source>Failed to sync block index</source>
<translation>No se ha podido sincronizar el índice de bloques</translation>
</message>
<message>
<location line="+1"/>
<source>Failed to write block index</source>
<translation>No se ha podido escribir en el índice de bloques</translation>
</message>
<message>
<location line="+1"/>
<source>Failed to write block info</source>
<translation>No se ha podido escribir la información de bloques</translation>
</message>
<message>
<location line="+1"/>
<source>Failed to write block</source>
<translation>No se ha podido escribir el bloque</translation>
</message>
<message>
<location line="+1"/>
<source>Failed to write file info</source>
<translation>No se ha podido escribir la información de archivo</translation>
</message>
<message>
<location line="+1"/>
<source>Failed to write to coin database</source>
<translation>No se ha podido escribir en la base de datos de monedas</translation>
</message>
<message>
<location line="+1"/>
<source>Failed to write transaction index</source>
<translation>No se ha podido escribir en el índice de transacciones</translation>
</message>
<message>
<location line="+1"/>
<source>Failed to write undo data</source>
<translation>No se han podido escribir los datos de deshacer</translation>
</message>
<message>
<location line="+2"/>
<source>Find peers using DNS lookup (default: 1 unless -connect)</source>
<translation>Encontrar pares mediante búsqueda de DNS (predeterminado: 1 salvo con -connect)</translation>
</message>
<message>
<location line="+1"/>
<source>Generate coins (default: 0)</source>
<translation>Generar monedas (por defecto: 0)</translation>
</message>
<message>
<location line="+2"/>
<source>How many blocks to check at startup (default: 288, 0 = all)</source>
<translation>Cuántos bloques comprobar al iniciar (predeterminado: 288, 0 = todos)</translation>
</message>
<message>
<location line="+1"/>
<source>How thorough the block verification is (0-4, default: 3)</source>
<translation>Como es de exhaustiva la verificación de bloques (0-4, por defecto 3)</translation>
</message>
<message>
<location line="+19"/>
<source>Not enough file descriptors available.</source>
<translation>No hay suficientes descriptores de archivo disponibles. </translation>
</message>
<message>
<location line="+8"/>
<source>Rebuild block chain index from current blk000??.dat files</source>
<translation>Reconstruir el índice de la cadena de bloques a partir de los archivos blk000??.dat actuales</translation>
</message>
<message>
<location line="+16"/>
<source>Set the number of threads to service RPC calls (default: 4)</source>
<translation>Establecer el número de hilos para atender las llamadas RPC (predeterminado: 4)</translation>
</message>
<message>
<location line="+26"/>
<source>Verifying blocks...</source>
<translation>Verificando bloques...</translation>
</message>
<message>
<location line="+1"/>
<source>Verifying wallet...</source>
<translation>Verificando monedero...</translation>
</message>
<message>
<location line="-69"/>
<source>Imports blocks from external blk000??.dat file</source>
<translation>Importa los bloques desde un archivo blk000??.dat externo</translation>
</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>Configura el número de hilos para el script de verificación (hasta 16, 0 = auto, <0 = leave that many cores free, por fecto: 0)</translation>
</message>
<message>
<location line="+77"/>
<source>Information</source>
<translation>Información</translation>
</message>
<message>
<location line="+3"/>
<source>Invalid -tor address: '%s'</source>
<translation>Dirección -tor inválida: '%s'</translation>
</message>
<message>
<location line="+1"/>
<source>Invalid amount for -minrelaytxfee=<amount>: '%s'</source>
<translation>Inválido por el monto -minrelaytxfee=<amount>: '%s'</translation>
</message>
<message>
<location line="+1"/>
<source>Invalid amount for -mintxfee=<amount>: '%s'</source>
<translation>Inválido por el monto -mintxfee=<amount>: '%s'</translation>
</message>
<message>
<location line="+8"/>
<source>Maintain a full transaction index (default: 0)</source>
<translation>Mantener índice de transacciones completo (predeterminado: 0)</translation>
</message>
<message>
<location line="+2"/>
<source>Maximum per-connection receive buffer, <n>*1000 bytes (default: 5000)</source>
<translation>Búfer de recepción máximo por conexión, <n>*1000 bytes (predeterminado: 5000)</translation>
</message>
<message>
<location line="+1"/>
<source>Maximum per-connection send buffer, <n>*1000 bytes (default: 1000)</source>
<translation>Búfer de recepción máximo por conexión, , <n>*1000 bytes (predeterminado: 1000)</translation>
</message>
<message>
<location line="+2"/>
<source>Only accept block chain matching built-in checkpoints (default: 1)</source>
<translation>Aceptar solamente cadena de bloques que concuerde con los puntos de control internos (predeterminado: 1)</translation>
</message>
<message>
<location line="+1"/>
<source>Only connect to nodes in network <net> (IPv4, IPv6 or Tor)</source>
<translation>Conectarse solo a nodos de la red <net> (IPv4, IPv6 o Tor)</translation>
</message>
<message>
<location line="+2"/>
<source>Output extra debugging information. Implies all other -debug* options</source>
<translation>Mostrar información de depuración adicional. Implica todos los demás opciones -debug*</translation>
</message>
<message>
<location line="+1"/>
<source>Output extra network debugging information</source>
<translation>Mostrar información de depuración adicional</translation>
</message>
<message>
<location line="+2"/>
<source>Prepend debug output with timestamp (default: 1)</source>
<translation>Anteponer marca temporal a la información de depuración</translation>
</message>
<message>
<location line="+5"/>
<source>SSL options: (see the GoldDiggerCoin Wiki for SSL setup instructions)</source>
<translation>Opciones SSL: (ver la GoldDiggerCoin Wiki para instrucciones de configuración SSL)</translation>
</message>
<message>
<location line="+1"/>
<source>Select the version of socks proxy to use (4-5, default: 5)</source>
<translation>Elija la versión del proxy socks a usar (4-5, predeterminado: 5)</translation>
</message>
<message>
<location line="+3"/>
<source>Send trace/debug info to console instead of debug.log file</source>
<translation>Enviar información de trazas/depuración a la consola en lugar de al archivo debug.log</translation>
</message>
<message>
<location line="+1"/>
<source>Send trace/debug info to debugger</source>
<translation>Enviar información de trazas/depuración al depurador</translation>
</message>
<message>
<location line="+5"/>
<source>Set maximum block size in bytes (default: 250000)</source>
<translation>Establecer tamaño máximo de bloque en bytes (predeterminado: 250000)</translation>
</message>
<message>
<location line="+1"/>
<source>Set minimum block size in bytes (default: 0)</source>
<translation>Establecer tamaño mínimo de bloque en bytes (predeterminado: 0)</translation>
</message>
<message>
<location line="+2"/>
<source>Shrink debug.log file on client startup (default: 1 when no -debug)</source>
<translation>Reducir el archivo debug.log al iniciar el cliente (predeterminado: 1 sin -debug)</translation>
</message>
<message>
<location line="+1"/>
<source>Signing transaction failed</source>
<translation>Transacción falló</translation>
</message>
<message>
<location line="+2"/>
<source>Specify connection timeout in milliseconds (default: 5000)</source>
<translation>Especificar el tiempo máximo de conexión en milisegundos (predeterminado: 5000)</translation>
</message>
<message>
<location line="+4"/>
<source>System error: </source>
<translation>Error de sistema: </translation>
</message>
<message>
<location line="+4"/>
<source>Transaction amount too small</source>
<translation>Monto de la transacción muy pequeño</translation>
</message>
<message>
<location line="+1"/>
<source>Transaction amounts must be positive</source>
<translation>Montos de transacciones deben ser positivos</translation>
</message>
<message>
<location line="+1"/>
<source>Transaction too large</source>
<translation>Transacción demasiado grande</translation>
</message>
<message>
<location line="+7"/>
<source>Use UPnP to map the listening port (default: 0)</source>
<translation>Usar UPnP para asignar el puerto de escucha (predeterminado: 0)</translation>
</message>
<message>
<location line="+1"/>
<source>Use UPnP to map the listening port (default: 1 when listening)</source>
<translation>Usar UPnP para asignar el puerto de escucha (predeterminado: 1 al escuchar)</translation>
</message>
<message>
<location line="+1"/>
<source>Use proxy to reach tor hidden services (default: same as -proxy)</source>
<translation>Utilizar proxy para conectar a Tor servicios ocultos (predeterminado: igual que -proxy)</translation>
</message>
<message>
<location line="+2"/>
<source>Username for JSON-RPC connections</source>
<translation>Nombre de usuario para las conexiones JSON-RPC
</translation>
</message>
<message>
<location line="+4"/>
<source>Warning</source>
<translation>Aviso</translation><|fim▁hole|> <message>
<location line="+1"/>
<source>Warning: This version is obsolete, upgrade required!</source>
<translation>Aviso: Esta versión es obsoleta, actualización necesaria!</translation>
</message>
<message>
<location line="+1"/>
<source>You need to rebuild the databases using -reindex to change -txindex</source>
<translation>Necesita reconstruir las bases de datos con la opción -reindex para modificar -txindex</translation>
</message>
<message>
<location line="+1"/>
<source>wallet.dat corrupt, salvage failed</source>
<translation>wallet.dat corrupto. Ha fallado la recuperación.</translation>
</message>
<message>
<location line="-50"/>
<source>Password for JSON-RPC connections</source>
<translation>Contraseña para las conexiones JSON-RPC
</translation>
</message>
<message>
<location line="-67"/>
<source>Allow JSON-RPC connections from specified IP address</source>
<translation>Permitir conexiones JSON-RPC desde la dirección IP especificada
</translation>
</message>
<message>
<location line="+76"/>
<source>Send commands to node running on <ip> (default: 127.0.0.1)</source>
<translation>Enviar comando al nodo situado en <ip> (predeterminado: 127.0.0.1)
</translation>
</message>
<message>
<location line="-120"/>
<source>Execute command when the best block changes (%s in cmd is replaced by block hash)</source>
<translation>Ejecutar un comando cuando cambia el mejor bloque (%s en cmd se sustituye por el hash de bloque)</translation>
</message>
<message>
<location line="+147"/>
<source>Upgrade wallet to latest format</source>
<translation>Actualizar el monedero al último formato</translation>
</message>
<message>
<location line="-21"/>
<source>Set key pool size to <n> (default: 100)</source>
<translation>Ajustar el número de claves en reserva <n> (predeterminado: 100)
</translation>
</message>
<message>
<location line="-12"/>
<source>Rescan the block chain for missing wallet transactions</source>
<translation>Volver a examinar la cadena de bloques en busca de transacciones del monedero perdidas</translation>
</message>
<message>
<location line="+35"/>
<source>Use OpenSSL (https) for JSON-RPC connections</source>
<translation>Usar OpenSSL (https) para las conexiones JSON-RPC
</translation>
</message>
<message>
<location line="-26"/>
<source>Server certificate file (default: server.cert)</source>
<translation>Certificado del servidor (predeterminado: server.cert)
</translation>
</message>
<message>
<location line="+1"/>
<source>Server private key (default: server.pem)</source>
<translation>Clave privada del servidor (predeterminado: server.pem)
</translation>
</message>
<message>
<location line="-151"/>
<source>Acceptable ciphers (default: TLSv1+HIGH:!SSLv2:!aNULL:!eNULL:!AH:!3DES:@STRENGTH)</source>
<translation>Cifrados aceptados (predeterminado: TLSv1+HIGH:!SSLv2:!aNULL:!eNULL:!AH:!3DES:@STRENGTH)
</translation>
</message>
<message>
<location line="+165"/>
<source>This help message</source>
<translation>Este mensaje de ayuda
</translation>
</message>
<message>
<location line="+6"/>
<source>Unable to bind to %s on this computer (bind returned error %d, %s)</source>
<translation>No es posible conectar con %s en este sistema (bind ha dado el error %d, %s)</translation>
</message>
<message>
<location line="-91"/>
<source>Connect through socks proxy</source>
<translation>Conectar mediante proxy socks</translation>
</message>
<message>
<location line="-10"/>
<source>Allow DNS lookups for -addnode, -seednode and -connect</source>
<translation>Permitir búsquedas DNS para -addnode, -seednode y -connect</translation>
</message>
<message>
<location line="+55"/>
<source>Loading addresses...</source>
<translation>Cargando direcciones...</translation>
</message>
<message>
<location line="-35"/>
<source>Error loading wallet.dat: Wallet corrupted</source>
<translation>Error al cargar wallet.dat: el monedero está dañado</translation>
</message>
<message>
<location line="+1"/>
<source>Error loading wallet.dat: Wallet requires newer version of GoldDiggerCoin</source>
<translation>Error al cargar wallet.dat: El monedero requiere una versión más reciente de GoldDiggerCoin</translation>
</message>
<message>
<location line="+93"/>
<source>Wallet needed to be rewritten: restart GoldDiggerCoin to complete</source>
<translation>El monedero ha necesitado ser reescrito. Reinicie GoldDiggerCoin para completar el proceso</translation>
</message>
<message>
<location line="-95"/>
<source>Error loading wallet.dat</source>
<translation>Error al cargar wallet.dat</translation>
</message>
<message>
<location line="+28"/>
<source>Invalid -proxy address: '%s'</source>
<translation>Dirección -proxy inválida: '%s'</translation>
</message>
<message>
<location line="+56"/>
<source>Unknown network specified in -onlynet: '%s'</source>
<translation>La red especificada en -onlynet '%s' es desconocida</translation>
</message>
<message>
<location line="-1"/>
<source>Unknown -socks proxy version requested: %i</source>
<translation>Solicitada versión de proxy -socks desconocida: %i</translation>
</message>
<message>
<location line="-96"/>
<source>Cannot resolve -bind address: '%s'</source>
<translation>No se puede resolver la dirección de -bind: '%s'</translation>
</message>
<message>
<location line="+1"/>
<source>Cannot resolve -externalip address: '%s'</source>
<translation>No se puede resolver la dirección de -externalip: '%s'</translation>
</message>
<message>
<location line="+44"/>
<source>Invalid amount for -paytxfee=<amount>: '%s'</source>
<translation>Cantidad inválida para -paytxfee=<amount>: '%s'</translation>
</message>
<message>
<location line="+1"/>
<source>Invalid amount</source>
<translation>Cuantía no válida</translation>
</message>
<message>
<location line="-6"/>
<source>Insufficient funds</source>
<translation>Fondos insuficientes</translation>
</message>
<message>
<location line="+10"/>
<source>Loading block index...</source>
<translation>Cargando el índice de bloques...</translation>
</message>
<message>
<location line="-57"/>
<source>Add a node to connect to and attempt to keep the connection open</source>
<translation>Añadir un nodo al que conectarse y tratar de mantener la conexión abierta</translation>
</message>
<message>
<location line="-25"/>
<source>Unable to bind to %s on this computer. GoldDiggerCoin is probably already running.</source>
<translation>No es posible conectar con %s en este sistema. Probablemente GoldDiggerCoin ya está ejecutándose.</translation>
</message>
<message>
<location line="+64"/>
<source>Fee per KB to add to transactions you send</source>
<translation>Tarifa por KB que añadir a las transacciones que envíe</translation>
</message>
<message>
<location line="+19"/>
<source>Loading wallet...</source>
<translation>Cargando monedero...</translation>
</message>
<message>
<location line="-52"/>
<source>Cannot downgrade wallet</source>
<translation>No se puede rebajar el monedero</translation>
</message>
<message>
<location line="+3"/>
<source>Cannot write default address</source>
<translation>No se puede escribir la dirección predeterminada</translation>
</message>
<message>
<location line="+64"/>
<source>Rescanning...</source>
<translation>Reexplorando...</translation>
</message>
<message>
<location line="-57"/>
<source>Done loading</source>
<translation>Generado pero no aceptado</translation>
</message>
<message>
<location line="+82"/>
<source>To use the %s option</source>
<translation>Para utilizar la opción %s</translation>
</message>
<message>
<location line="-74"/>
<source>Error</source>
<translation>Error</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>Tiene que establecer rpcpassword=<contraseña> en el fichero de configuración: ⏎
%s ⏎
Si el archivo no existe, créelo con permiso de lectura solamente del propietario.</translation>
</message>
</context>
</TS><|fim▁end|> | </message> |
<|file_name|>generate_unexpire_flags_unittests.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python
# Copyright 2020 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
import generate_unexpire_flags
import os
import unittest
<|fim▁hole|> TEST_MSTONE = 123
def read_golden_file(self, extension):
return file(
os.path.join(
os.path.dirname(__file__),
'unexpire_test.' + extension + '.expected')).read()
def testCcFile(self):
cc = generate_unexpire_flags.gen_features_impl('foobar', 123)
golden_cc = self.read_golden_file('cc')
self.assertEquals(golden_cc, cc)
def testHFile(self):
h = generate_unexpire_flags.gen_features_header('foobar', 123)
golden_h = self.read_golden_file('h')
self.assertEquals(golden_h, h)
def testIncFile(self):
inc = generate_unexpire_flags.gen_flags_fragment('foobar', 123)
golden_inc = self.read_golden_file('inc')
self.assertEquals(golden_inc, inc)
if __name__ == '__main__':
unittest.main()<|fim▁end|> | class TestUnexpireGenerator(unittest.TestCase): |
<|file_name|>api.js<|end_file_name|><|fim▁begin|>import apiConfig from './MovieDBConfig';
import TmdbApi from 'moviedb-api';
var api = new TmdbApi({
consume: false,
apiKey: apiConfig.apiKey
});
const makeAndList = (list) => {
return list.map(item => item.value).join();
};
export const getGenres = (input='', callback) => {
api.request('/genre/movie/list', 'GET')
.then(res => {
return res.genres.map(item => {
return {label: item.name, value: item.id};
})
})
.then(json => callback(null, {options: json, complete: false}))
.catch(err => console.log(err));
};
export const getKeywords = (input='', callback) => {
api.request('/search/keyword', 'GET', {query: input})
.then(res => {
return res.results.map(item => {
return {label: item.name, value: item.id};
});
})
.then(json => callback(null, {options: json, complete: false}))
.catch(err => console.log(err));
};
export const getActors = (input='', callback) => {
api.request('/search/person', 'GET', {query: input})
.then(res => {
return res.results.map(item => {
return {label: item.name, value: item.id};
});
})
.then(json => callback(null, {options: json, complete: false}))
.catch(err => console.log(err));
};
export const discover = (genres=null, keywords=null, actors, minYear, maxYear, page=1) => {
let g = genres ? makeAndList(genres) : null;
let k = keywords ? makeAndList(keywords) : null;
let a = actors ? makeAndList(actors) : null;
return api.request('/discover/movie', 'GET', {
with_genres: g,
with_keywords: k,
with_cast: a,<|fim▁hole|> })
.then(res => res)
};
export const getVideos = (id, language='en') => {
return api.request(`/movie/${id}/videos`, 'GET', {language})
};
export const getMovieKeywords = (id, language='en') => {
return api.request(`/movie/${id}/keywords`, 'GET', {language})
};
export const discoverWithVideo = (genres=null, keywords=null, actors, minYear, maxYear) => {
return discover(genres, keywords, actors, minYear, maxYear)
.then(res => {
return Promise.all(
res.results.map(item => getVideos(item.id)
.then(videos => videos.results[0])
)
).then(list => {
return {
...res,
results: res.results.map((item, index) => {
item.youtube = list[index];
return item;
})
}
})
})
};
export const getDetails = (id, language='en') => {
return api.request(`/movie/${id}`, 'GET', {language, append_to_response: "keywords,videos"})
};<|fim▁end|> | "release_date.gte": minYear,
"release_date.lte": maxYear,
page |
<|file_name|>models.py<|end_file_name|><|fim▁begin|>from django.db import models
from django.contrib.auth.models import User
from datetime import date
# Create your models here.
class Genre(models.Model):
"""
Model representing a book genre (e.g. Science Fiction, Non Fiction).
"""
name = models.CharField(max_length=200, help_text="Enter a book genre (e.g. Science Fiction, French Poetry etc.)")
def __str__(self):
"""
String for representing the Model object (in Admin site etc.)
"""
return self.name
from django.urls import reverse #Used to generate URLs by reversing the URL patterns
class Book(models.Model):
class Meta:
permissions = (("can_edit_book", "Edit book"),)
"""
Model representing a book (but not a specific copy of a book).
"""
title = models.CharField(max_length=200)
author = models.ForeignKey('Author', on_delete=models.SET_NULL, null=True)
# Foreign Key used because book can only have one author, but authors can have multiple books
# Author as a string rather than object because it hasn't been declared yet in the file.
summary = models.TextField(max_length=1000, help_text="Enter a brief description of the book")
isbn = models.CharField('ISBN',max_length=13, help_text='13 Character <a href="https://www.isbn-international.org/content/what-isbn">ISBN number</a>')
genre = models.ManyToManyField(Genre, help_text="Select a genre for this book")
# ManyToManyField used because genre can contain many books. Books can cover many genres.
# Genre class has already been defined so we can specify the object above.
language = models.ForeignKey('Language', on_delete=models.SET_NULL, null=True)
def __str__(self):
"""
String for representing the Model object.
"""
return self.title
def get_absolute_url(self):
"""
Returns the url to access a particular book instance.
"""
return reverse('book-detail', args=[str(self.id)])
def display_genre(self):
"""
Creates a string for the Genre. This is required to display genre in Admin.
"""
return ', '.join([ genre.name for genre in self.genre.all()[:3] ])
display_genre.short_description = 'Genre'
import uuid # Required for unique book instances
class BookInstance(models.Model):
class Meta:
permissions = (("can_mark_returned", "Set book as returned"),)
ordering = ["due_back"]
"""
Model representing a specific copy of a book (i.e. that can be borrowed from the library).
"""
id = models.UUIDField(primary_key=True, default=uuid.uuid4, help_text="Unique ID for this particular book across whole library")
book = models.ForeignKey('Book', on_delete=models.SET_NULL, null=True)
imprint = models.CharField(max_length=200)
due_back = models.DateField(null=True, blank=True)
borrower = models.ForeignKey(User, on_delete=models.SET_NULL, null=True, blank=True)
LOAN_STATUS = (
('m', 'Maintenance'),
('o', 'On loan'),
('a', 'Available'),
('r', 'Reserved'),
)
status = models.CharField(max_length=1, choices=LOAN_STATUS, blank=True, default='d', help_text='Book availability')
def __str__(self):
"""
String for representing the Model object
"""
return '%s (%s)' % (self.id,self.book.title)
@property
def is_overdue(self):
if self.due_back and date.today() > self.due_back:
return True
return False
class Author(models.Model):
"""
Model representing an author.
"""
class Meta:
permissions = (("can_edit_author", "Edit author"),)
first_name = models.CharField(max_length=100)
last_name = models.CharField(max_length=100)
date_of_birth = models.DateField(null=True, blank=True)
date_of_death = models.DateField('Died', null=True, blank=True)
def get_absolute_url(self):
"""
Returns the url to access a particular author instance.
"""
return reverse('author-detail', args=[str(self.id)])
def __str__(self):<|fim▁hole|> """
String for representing the Model object.
"""
return '%s, %s' % (self.last_name, self.first_name)
class Language(models.Model):
"""
Model representing a Language (e.g. English, French, Japanese, etc.)
"""
name = models.CharField(max_length=200, help_text="Enter a the book's natural language (e.g. English, French, Japanese etc.)")
def __str__(self):
"""
String for representing the Model object (in Admin site etc.)
"""
return self.name<|fim▁end|> | |
<|file_name|>matrix-sqrt.py<|end_file_name|><|fim▁begin|>"""
https://en.wikipedia.org/wiki/Square_root_of_a_matrix
B is the sqrt of a matrix A if B*B = A
"""
import numpy as np
from scipy.linalg import sqrtm
from scipy.stats import special_ortho_group
def denman_beaver(A, n=50):
Y = A
Z = np.eye(len(A))
for i in range(n):
Yn = 0.5*(Y + np.linalg.inv(Z))
Zn = 0.5*(Z + np.linalg.inv(Y))
Y = Yn
Z = Zn
return (Y, Z)
def babylonian(A, n=50):
X = np.eye(len(A))
for i in range(n):
X = 0.5*(X + np.dot(A, np.linalg.inv(X)))
return X
def gen_random_matrix(n):
return np.random.rand(n, n)
def gen_rotation_matrix(n):
return special_ortho_group.rvs(n)*np.random.randint(-100, 101)
def gen_symmetric_matrix(n):
A = np.random.randint(-10, 11, size=(n, n))
A = 0.5*(A + A.T)<|fim▁hole|> return A
def test(title, gen_matrix, size, iters):
print("Testing {} matrix".format(title))
for i in range(1, size):
for j in range(iters):
try:
A = gen_matrix(i)
d = np.linalg.det(A)
Y, _ = denman_beaver(A)
X = babylonian(A)
Z = sqrtm(A)
print("{}x{} matrix (det {})".format(i, i, d))
print(A)
print("Denman Beaver")
print(np.dot(Y, Y))
print("Babylonian")
print(np.dot(X, X))
print("Scipy")
print(np.dot(Z, Z))
print()
except:
pass
# iteration methods above tend to fail on random and symmetric matrices
test("random", gen_random_matrix, 5, 10)
test("symmetric", gen_symmetric_matrix, 5, 10)
# for rotation matrices, the iteration methods work
test("rotation", gen_rotation_matrix, 5, 10)<|fim▁end|> | |
<|file_name|>run_tests.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python
"""Execute the tests for the samcat program.
The golden test outputs are generated by the script generate_outputs.sh.
You have to give the root paths to the source and the binaries as arguments to
the program. These are the paths to the directory that contains the 'projects'
directory.
Usage: run_tests.py SOURCE_ROOT_PATH BINARY_ROOT_PATH
"""
import logging
import os.path
import sys
# Automagically add util/py_lib to PYTHONPATH environment variable.
path = os.path.abspath(os.path.join(os.path.dirname(__file__), '..',
'..', '..', 'util', 'py_lib'))
sys.path.insert(0, path)
import seqan.app_tests as app_tests
def main(source_base, binary_base):
"""Main entry point of the script."""
print 'Executing test for samcat'
print '========================='
print
ph = app_tests.TestPathHelper(
source_base, binary_base,
'apps/samcat/tests') # tests dir
# ============================================================
# Auto-detect the binary path.
# ============================================================
path_to_program = app_tests.autolocateBinary(
binary_base, 'apps/samcat', 'samcat')
# ============================================================
# Built TestConf list.
# ============================================================
# Build list with TestConf objects, analoguely to how the output
# was generated in generate_outputs.sh.
conf_list = []
# ============================================================
# Run on DNA (Adenoviruses).
# ============================================================
conf = app_tests.TestConf(
program=path_to_program,
args=[ph.inFile('ex1_a1.sam'),
ph.inFile('ex1_a2.sam'),
ph.inFile('ex1_a3.sam'),
'-o', ph.outFile('ex1_merged.sam')],
to_diff=[(ph.inFile('ex1_merged.sam'),
ph.outFile('ex1_merged.sam'))])
conf_list.append(conf)
conf = app_tests.TestConf(
program=path_to_program,
args=[ph.inFile('ex1_a1.sam'),
ph.inFile('ex1_a2.sam'),
ph.inFile('ex1_a3.sam'),
'-o', ph.outFile('ex1_merged.bam')],
to_diff=[(ph.inFile('ex1_merged.bam'),<|fim▁hole|>
# Execute the tests.
failures = 0
for conf in conf_list:
res = app_tests.runTest(conf)
# Output to the user.
print ' '.join(conf.commandLineArgs())
if res:
print 'OK'
else:
failures += 1
print 'FAILED'
# Cleanup.
ph.deleteTempDir()
print '=============================='
print ' total tests: %d' % len(conf_list)
print ' failed tests: %d' % failures
print 'successful tests: %d' % (len(conf_list) - failures)
print '=============================='
# Compute and return return code.
return failures != 0
if __name__ == '__main__':
sys.exit(app_tests.main(main))<|fim▁end|> | ph.outFile('ex1_merged.bam'), "gunzip")])
conf_list.append(conf) |
<|file_name|>audio_utilities.py<|end_file_name|><|fim▁begin|>import scipy.io.wavfile
from os.path import expanduser
import os
import array
from pylab import *
import scipy.signal
import scipy
import wave
import numpy as np
import time
import sys
import math
import matplotlib
import subprocess
# Author: Brian K. Vogel
# [email protected]
fft_size = 2048
iterations = 300
hopsamp = fft_size // 8
def ensure_audio():
if not os.path.exists("audio"):
print("Downloading audio dataset...")
subprocess.check_output(
"curl -SL https://storage.googleapis.com/wandb/audio.tar.gz | tar xz", shell=True)
def griffin_lim(stft, scale):
# Undo the rescaling.
stft_modified_scaled = stft / scale
stft_modified_scaled = stft_modified_scaled**0.5
# Use the Griffin&Lim algorithm to reconstruct an audio signal from the
# magnitude spectrogram.
x_reconstruct = reconstruct_signal_griffin_lim(stft_modified_scaled,
fft_size, hopsamp,
iterations)
# The output signal must be in the range [-1, 1], otherwise we need to clip or normalize.
max_sample = np.max(abs(x_reconstruct))
if max_sample > 1.0:
x_reconstruct = x_reconstruct / max_sample
return x_reconstruct
def hz_to_mel(f_hz):
"""Convert Hz to mel scale.
This uses the formula from O'Shaugnessy's book.
Args:
f_hz (float): The value in Hz.
Returns:
The value in mels.
"""
return 2595*np.log10(1.0 + f_hz/700.0)
def mel_to_hz(m_mel):
"""Convert mel scale to Hz.
This uses the formula from O'Shaugnessy's book.
Args:
m_mel (float): The value in mels
Returns:
The value in Hz
"""
return 700*(10**(m_mel/2595) - 1.0)
def fft_bin_to_hz(n_bin, sample_rate_hz, fft_size):
"""Convert FFT bin index to frequency in Hz.
Args:
n_bin (int or float): The FFT bin index.
sample_rate_hz (int or float): The sample rate in Hz.
fft_size (int or float): The FFT size.
Returns:
The value in Hz.
"""
n_bin = float(n_bin)
sample_rate_hz = float(sample_rate_hz)
fft_size = float(fft_size)
return n_bin*sample_rate_hz/(2.0*fft_size)
def hz_to_fft_bin(f_hz, sample_rate_hz, fft_size):
"""Convert frequency in Hz to FFT bin index.
Args:
f_hz (int or float): The frequency in Hz.
sample_rate_hz (int or float): The sample rate in Hz.
fft_size (int or float): The FFT size.
Returns:
The FFT bin index as an int.
"""
f_hz = float(f_hz)
sample_rate_hz = float(sample_rate_hz)
fft_size = float(fft_size)
fft_bin = int(np.round((f_hz*2.0*fft_size/sample_rate_hz)))
if fft_bin >= fft_size:
fft_bin = fft_size-1
return fft_bin
def make_mel_filterbank(min_freq_hz, max_freq_hz, mel_bin_count,
linear_bin_count, sample_rate_hz):
"""Create a mel filterbank matrix.
Create and return a mel filterbank matrix `filterbank` of shape (`mel_bin_count`,
`linear_bin_couont`). The `filterbank` matrix can be used to transform a
(linear scale) spectrum or spectrogram into a mel scale spectrum or
spectrogram as follows:
`mel_scale_spectrum` = `filterbank`*'linear_scale_spectrum'
where linear_scale_spectrum' is a shape (`linear_bin_count`, `m`) and
`mel_scale_spectrum` is shape ('mel_bin_count', `m`) where `m` is the number
of spectral time slices.
Likewise, the reverse-direction transform can be performed as:
'linear_scale_spectrum' = filterbank.T`*`mel_scale_spectrum`
Note that the process of converting to mel scale and then back to linear
scale is lossy.
This function computes the mel-spaced filters such that each filter is triangular
(in linear frequency) with response 1 at the center frequency and decreases linearly
to 0 upon reaching an adjacent filter's center frequency. Note that any two adjacent
filters will overlap having a response of 0.5 at the mean frequency of their
respective center frequencies.
Args:
min_freq_hz (float): The frequency in Hz corresponding to the lowest
mel scale bin.
max_freq_hz (flloat): The frequency in Hz corresponding to the highest
mel scale bin.
mel_bin_count (int): The number of mel scale bins.
linear_bin_count (int): The number of linear scale (fft) bins.
sample_rate_hz (float): The sample rate in Hz.
Returns:
The mel filterbank matrix as an 2-dim Numpy array.
"""
min_mels = hz_to_mel(min_freq_hz)
max_mels = hz_to_mel(max_freq_hz)
# Create mel_bin_count linearly spaced values between these extreme mel values.
mel_lin_spaced = np.linspace(min_mels, max_mels, num=mel_bin_count)
# Map each of these mel values back into linear frequency (Hz).
center_frequencies_hz = np.array([mel_to_hz(n) for n in mel_lin_spaced])
mels_per_bin = float(max_mels - min_mels)/float(mel_bin_count - 1)
mels_start = min_mels - mels_per_bin
hz_start = mel_to_hz(mels_start)
fft_bin_start = hz_to_fft_bin(hz_start, sample_rate_hz, linear_bin_count)
#print('fft_bin_start: ', fft_bin_start)
mels_end = max_mels + mels_per_bin
hz_stop = mel_to_hz(mels_end)
fft_bin_stop = hz_to_fft_bin(hz_stop, sample_rate_hz, linear_bin_count)
#print('fft_bin_stop: ', fft_bin_stop)
# Map each center frequency to the closest fft bin index.
linear_bin_indices = np.array([hz_to_fft_bin(
f_hz, sample_rate_hz, linear_bin_count) for f_hz in center_frequencies_hz])
# Create filterbank matrix.
filterbank = np.zeros((mel_bin_count, linear_bin_count))
for mel_bin in range(mel_bin_count):
center_freq_linear_bin = int(linear_bin_indices[mel_bin].item())
# Create a triangular filter having the current center freq.
# The filter will start with 0 response at left_bin (if it exists)
# and ramp up to 1.0 at center_freq_linear_bin, and then ramp
# back down to 0 response at right_bin (if it exists).
# Create the left side of the triangular filter that ramps up
# from 0 to a response of 1 at the center frequency.
if center_freq_linear_bin > 1:
# It is possible to create the left triangular filter.
if mel_bin == 0:
# Since this is the first center frequency, the left side
# must start ramping up from linear bin 0 or 1 mel bin before the center freq.
left_bin = max(0, fft_bin_start)
else:
# Start ramping up from the previous center frequency bin.
left_bin = int(linear_bin_indices[mel_bin - 1].item())
for f_bin in range(left_bin, center_freq_linear_bin+1):
if (center_freq_linear_bin - left_bin) > 0:
response = float(f_bin - left_bin) / \
float(center_freq_linear_bin - left_bin)
filterbank[mel_bin, f_bin] = response
# Create the right side of the triangular filter that ramps down
# from 1 to 0.
if center_freq_linear_bin < linear_bin_count-2:
# It is possible to create the right triangular filter.
if mel_bin == mel_bin_count - 1:
# Since this is the last mel bin, we must ramp down to response of 0
# at the last linear freq bin.
right_bin = min(linear_bin_count - 1, fft_bin_stop)
else:
right_bin = int(linear_bin_indices[mel_bin + 1].item())
for f_bin in range(center_freq_linear_bin, right_bin+1):
if (right_bin - center_freq_linear_bin) > 0:
response = float(right_bin - f_bin) / \
float(right_bin - center_freq_linear_bin)
filterbank[mel_bin, f_bin] = response
filterbank[mel_bin, center_freq_linear_bin] = 1.0
return filterbank
def stft_for_reconstruction(x, fft_size, hopsamp):
"""Compute and return the STFT of the supplied time domain signal x.
Args:
x (1-dim Numpy array): A time domain signal.
fft_size (int): FFT size. Should be a power of 2, otherwise DFT will be used.
hopsamp (int):<|fim▁hole|> window = np.hanning(fft_size)
fft_size = int(fft_size)
hopsamp = int(hopsamp)
return np.array([np.fft.rfft(window*x[i:i+fft_size])
for i in range(0, len(x)-fft_size, hopsamp)])
def istft_for_reconstruction(X, fft_size, hopsamp):
"""Invert a STFT into a time domain signal.
Args:
X (2-dim Numpy array): Input spectrogram. The rows are the time slices and columns are the frequency bins.
fft_size (int):
hopsamp (int): The hop size, in samples.
Returns:
The inverse STFT.
"""
fft_size = int(fft_size)
hopsamp = int(hopsamp)
window = np.hanning(fft_size)
time_slices = X.shape[0]
len_samples = int(time_slices*hopsamp + fft_size)
x = np.zeros(len_samples)
for n, i in enumerate(range(0, len(x)-fft_size, hopsamp)):
x[i:i+fft_size] += window*np.real(np.fft.irfft(X[n]))
return x
def get_signal(in_file, expected_fs=44100):
"""Load a wav file.
If the file contains more than one channel, return a mono file by taking
the mean of all channels.
If the sample rate differs from the expected sample rate (default is 44100 Hz),
raise an exception.
Args:
in_file: The input wav file, which should have a sample rate of `expected_fs`.
expected_fs (int): The expected sample rate of the input wav file.
Returns:
The audio siganl as a 1-dim Numpy array. The values will be in the range [-1.0, 1.0]. fixme ( not yet)
"""
fs, y = scipy.io.wavfile.read(in_file)
num_type = y[0].dtype
if num_type == 'int16':
y = y*(1.0/32768)
elif num_type == 'int32':
y = y*(1.0/2147483648)
elif num_type == 'float32':
# Nothing to do
pass
elif num_type == 'uint8':
raise Exception('8-bit PCM is not supported.')
else:
raise Exception('Unknown format.')
if fs != expected_fs:
raise Exception('Invalid sample rate.')
if y.ndim == 1:
return y
else:
return y.mean(axis=1)
def reconstruct_signal_griffin_lim(magnitude_spectrogram, fft_size, hopsamp, iterations):
"""Reconstruct an audio signal from a magnitude spectrogram.
Given a magnitude spectrogram as input, reconstruct
the audio signal and return it using the Griffin-Lim algorithm from the paper:
"Signal estimation from modified short-time fourier transform" by Griffin and Lim,
in IEEE transactions on Acoustics, Speech, and Signal Processing. Vol ASSP-32, No. 2, April 1984.
Args:
magnitude_spectrogram (2-dim Numpy array): The magnitude spectrogram. The rows correspond to the time slices
and the columns correspond to frequency bins.
fft_size (int): The FFT size, which should be a power of 2.
hopsamp (int): The hope size in samples.
iterations (int): Number of iterations for the Griffin-Lim algorithm. Typically a few hundred
is sufficient.
Returns:
The reconstructed time domain signal as a 1-dim Numpy array.
"""
time_slices = magnitude_spectrogram.shape[0]
len_samples = int(time_slices*hopsamp + fft_size)
# Initialize the reconstructed signal to noise.
x_reconstruct = np.random.randn(len_samples)
n = iterations # number of iterations of Griffin-Lim algorithm.
while n > 0:
n -= 1
reconstruction_spectrogram = stft_for_reconstruction(
x_reconstruct, fft_size, hopsamp)
reconstruction_angle = np.angle(reconstruction_spectrogram)
# Discard magnitude part of the reconstruction and use the supplied magnitude spectrogram instead.
proposal_spectrogram = magnitude_spectrogram * \
np.exp(1.0j*reconstruction_angle)
prev_x = x_reconstruct
x_reconstruct = istft_for_reconstruction(
proposal_spectrogram, fft_size, hopsamp)
diff = sqrt(sum((x_reconstruct - prev_x)**2)/x_reconstruct.size)
#print('Reconstruction iteration: {}/{} RMSE: {} '.format(iterations - n, iterations, diff))
return x_reconstruct
def save_audio_to_file(x, sample_rate, outfile='out.wav'):
"""Save a mono signal to a file.
Args:
x (1-dim Numpy array): The audio signal to save. The signal values should be in the range [-1.0, 1.0].
sample_rate (int): The sample rate of the signal, in Hz.
outfile: Name of the file to save.
"""
x_max = np.max(abs(x))
assert x_max <= 1.0, 'Input audio value is out of range. Should be in the range [-1.0, 1.0].'
x = x*32767.0
data = array.array('h')
for i in range(len(x)):
cur_samp = int(round(x[i]))
data.append(cur_samp)
f = wave.open(outfile, 'w')
f.setparams((1, 2, sample_rate, 0, "NONE", "Uncompressed"))
f.writeframes(data.tostring())
f.close()<|fim▁end|> |
Returns:
The STFT. The rows are the time slices and columns are the frequency bins.
""" |
<|file_name|>defaultfilters.py<|end_file_name|><|fim▁begin|>"""Default variable filters."""
import re
from decimal import Decimal, InvalidOperation, ROUND_HALF_UP
import random as random_module
try:
from functools import wraps
except ImportError:
from django.utils.functional import wraps # Python 2.4 fallback.
from django.template import Variable, Library
from django.conf import settings
from django.utils import formats
from django.utils.translation import ugettext, ungettext
from django.utils.encoding import force_unicode, iri_to_uri
from django.utils.safestring import mark_safe, SafeData
register = Library()
#######################
# STRING DECORATOR #
#######################
def stringfilter(func):
"""
Decorator for filters which should only receive unicode objects. The object
passed as the first positional argument will be converted to a unicode
object.
"""
def _dec(*args, **kwargs):
if args:
args = list(args)
args[0] = force_unicode(args[0])
if isinstance(args[0], SafeData) and getattr(func, 'is_safe', False):
return mark_safe(func(*args, **kwargs))
return func(*args, **kwargs)
# Include a reference to the real function (used to check original
# arguments by the template parser).
_dec._decorated_function = getattr(func, '_decorated_function', func)
for attr in ('is_safe', 'needs_autoescape'):
if hasattr(func, attr):
setattr(_dec, attr, getattr(func, attr))
return wraps(func)(_dec)
###################
# STRINGS #
###################
def addslashes(value):
"""
Adds slashes before quotes. Useful for escaping strings in CSV, for
example. Less useful for escaping JavaScript; use the ``escapejs``
filter instead.
"""
return value.replace('\\', '\\\\').replace('"', '\\"').replace("'", "\\'")
addslashes.is_safe = True
addslashes = stringfilter(addslashes)
def capfirst(value):
"""Capitalizes the first character of the value."""
return value and value[0].upper() + value[1:]
capfirst.is_safe=True
capfirst = stringfilter(capfirst)
_base_js_escapes = (
('\\', r'\u005C'),
('\'', r'\u0027'),
('"', r'\u0022'),
('>', r'\u003E'),
('<', r'\u003C'),
('&', r'\u0026'),
('=', r'\u003D'),
('-', r'\u002D'),
(';', r'\u003B'),
(u'\u2028', r'\u2028'),
(u'\u2029', r'\u2029')
)
# Escape every ASCII character with a value less than 32.
_js_escapes = (_base_js_escapes +
tuple([('%c' % z, '\\u%04X' % z) for z in range(32)]))
def escapejs(value):
"""Hex encodes characters for use in JavaScript strings."""
for bad, good in _js_escapes:
value = value.replace(bad, good)
return value
escapejs = stringfilter(escapejs)
def fix_ampersands(value):
"""Replaces ampersands with ``&`` entities."""
from django.utils.html import fix_ampersands
return fix_ampersands(value)
fix_ampersands.is_safe=True
fix_ampersands = stringfilter(fix_ampersands)
# Values for testing floatformat input against infinity and NaN representations,
# which differ across platforms and Python versions. Some (i.e. old Windows
# ones) are not recognized by Decimal but we want to return them unchanged vs.
# returning an empty string as we do for completley invalid input. Note these
# need to be built up from values that are not inf/nan, since inf/nan values do
# not reload properly from .pyc files on Windows prior to some level of Python 2.5
# (see Python Issue757815 and Issue1080440).
pos_inf = 1e200 * 1e200
neg_inf = -1e200 * 1e200
nan = (1e200 * 1e200) / (1e200 * 1e200)
special_floats = [str(pos_inf), str(neg_inf), str(nan)]
def floatformat(text, arg=-1):
"""
Displays a float to a specified number of decimal places.
If called without an argument, it displays the floating point number with
one decimal place -- but only if there's a decimal place to be displayed:
* num1 = 34.23234
* num2 = 34.00000
* num3 = 34.26000
* {{ num1|floatformat }} displays "34.2"
* {{ num2|floatformat }} displays "34"
* {{ num3|floatformat }} displays "34.3"
If arg is positive, it will always display exactly arg number of decimal
places:
* {{ num1|floatformat:3 }} displays "34.232"
* {{ num2|floatformat:3 }} displays "34.000"
* {{ num3|floatformat:3 }} displays "34.260"
If arg is negative, it will display arg number of decimal places -- but
only if there are places to be displayed:
* {{ num1|floatformat:"-3" }} displays "34.232"
* {{ num2|floatformat:"-3" }} displays "34"
* {{ num3|floatformat:"-3" }} displays "34.260"
If the input float is infinity or NaN, the (platform-dependent) string
representation of that value will be displayed.
"""
try:
input_val = force_unicode(text)
d = Decimal(input_val)
except UnicodeEncodeError:
return u''
except InvalidOperation:
if input_val in special_floats:
return input_val
try:
d = Decimal(force_unicode(float(text)))
except (ValueError, InvalidOperation, TypeError, UnicodeEncodeError):
return u''
try:
p = int(arg)
except ValueError:
return input_val
try:
m = int(d) - d
except (ValueError, OverflowError, InvalidOperation):
return input_val
if not m and p < 0:
return mark_safe(formats.number_format(u'%d' % (int(d)), 0))
if p == 0:
exp = Decimal(1)
else:
exp = Decimal('1.0') / (Decimal(10) ** abs(p))
try:
return mark_safe(formats.number_format(u'%s' % str(d.quantize(exp, ROUND_HALF_UP)), abs(p)))
except InvalidOperation:
return input_val
floatformat.is_safe = True
def iriencode(value):
"""Escapes an IRI value for use in a URL."""
return force_unicode(iri_to_uri(value))
iriencode.is_safe = True
iriencode = stringfilter(iriencode)
def linenumbers(value, autoescape=None):
"""Displays text with line numbers."""
from django.utils.html import escape
lines = value.split(u'\n')
# Find the maximum width of the line count, for use with zero padding
# string format command
width = unicode(len(unicode(len(lines))))
if not autoescape or isinstance(value, SafeData):
for i, line in enumerate(lines):
lines[i] = (u"%0" + width + u"d. %s") % (i + 1, line)
else:
for i, line in enumerate(lines):
lines[i] = (u"%0" + width + u"d. %s") % (i + 1, escape(line))
return mark_safe(u'\n'.join(lines))
linenumbers.is_safe = True
linenumbers.needs_autoescape = True
linenumbers = stringfilter(linenumbers)
def lower(value):
"""Converts a string into all lowercase."""
return value.lower()
lower.is_safe = True
lower = stringfilter(lower)
def make_list(value):
"""
Returns the value turned into a list.
For an integer, it's a list of digits.
For a string, it's a list of characters.
"""
return list(value)
make_list.is_safe = False
make_list = stringfilter(make_list)
def slugify(value):
"""
Normalizes string, converts to lowercase, removes non-alpha characters,
and converts spaces to hyphens.
"""
import unicodedata<|fim▁hole|> value = unicode(re.sub('[^\w\s-]', '', value).strip().lower())
return mark_safe(re.sub('[-\s]+', '-', value))
slugify.is_safe = True
slugify = stringfilter(slugify)
def stringformat(value, arg):
"""
Formats the variable according to the arg, a string formatting specifier.
This specifier uses Python string formating syntax, with the exception that
the leading "%" is dropped.
See http://docs.python.org/lib/typesseq-strings.html for documentation
of Python string formatting
"""
try:
return (u"%" + unicode(arg)) % value
except (ValueError, TypeError):
return u""
stringformat.is_safe = True
def title(value):
"""Converts a string into titlecase."""
t = re.sub("([a-z])'([A-Z])", lambda m: m.group(0).lower(), value.title())
return re.sub("\d([A-Z])", lambda m: m.group(0).lower(), t)
title.is_safe = True
title = stringfilter(title)
def truncatewords(value, arg):
"""
Truncates a string after a certain number of words.
Argument: Number of words to truncate after.
"""
from django.utils.text import truncate_words
try:
length = int(arg)
except ValueError: # Invalid literal for int().
return value # Fail silently.
return truncate_words(value, length)
truncatewords.is_safe = True
truncatewords = stringfilter(truncatewords)
def truncatewords_html(value, arg):
"""
Truncates HTML after a certain number of words.
Argument: Number of words to truncate after.
"""
from django.utils.text import truncate_html_words
try:
length = int(arg)
except ValueError: # invalid literal for int()
return value # Fail silently.
return truncate_html_words(value, length)
truncatewords_html.is_safe = True
truncatewords_html = stringfilter(truncatewords_html)
def upper(value):
"""Converts a string into all uppercase."""
return value.upper()
upper.is_safe = False
upper = stringfilter(upper)
def urlencode(value):
"""Escapes a value for use in a URL."""
from django.utils.http import urlquote
return urlquote(value)
urlencode.is_safe = False
urlencode = stringfilter(urlencode)
def urlize(value, autoescape=None):
"""Converts URLs in plain text into clickable links."""
from django.utils.html import urlize
return mark_safe(urlize(value, nofollow=True, autoescape=autoescape))
urlize.is_safe=True
urlize.needs_autoescape = True
urlize = stringfilter(urlize)
def urlizetrunc(value, limit, autoescape=None):
"""
Converts URLs into clickable links, truncating URLs to the given character
limit, and adding 'rel=nofollow' attribute to discourage spamming.
Argument: Length to truncate URLs to.
"""
from django.utils.html import urlize
return mark_safe(urlize(value, trim_url_limit=int(limit), nofollow=True,
autoescape=autoescape))
urlizetrunc.is_safe = True
urlizetrunc.needs_autoescape = True
urlizetrunc = stringfilter(urlizetrunc)
def wordcount(value):
"""Returns the number of words."""
return len(value.split())
wordcount.is_safe = False
wordcount = stringfilter(wordcount)
def wordwrap(value, arg):
"""
Wraps words at specified line length.
Argument: number of characters to wrap the text at.
"""
from django.utils.text import wrap
return wrap(value, int(arg))
wordwrap.is_safe = True
wordwrap = stringfilter(wordwrap)
def ljust(value, arg):
"""
Left-aligns the value in a field of a given width.
Argument: field size.
"""
return value.ljust(int(arg))
ljust.is_safe = True
ljust = stringfilter(ljust)
def rjust(value, arg):
"""
Right-aligns the value in a field of a given width.
Argument: field size.
"""
return value.rjust(int(arg))
rjust.is_safe = True
rjust = stringfilter(rjust)
def center(value, arg):
"""Centers the value in a field of a given width."""
return value.center(int(arg))
center.is_safe = True
center = stringfilter(center)
def cut(value, arg):
"""
Removes all values of arg from the given string.
"""
safe = isinstance(value, SafeData)
value = value.replace(arg, u'')
if safe and arg != ';':
return mark_safe(value)
return value
cut = stringfilter(cut)
###################
# HTML STRINGS #
###################
def escape(value):
"""
Marks the value as a string that should not be auto-escaped.
"""
from django.utils.safestring import mark_for_escaping
return mark_for_escaping(value)
escape.is_safe = True
escape = stringfilter(escape)
def force_escape(value):
"""
Escapes a string's HTML. This returns a new string containing the escaped
characters (as opposed to "escape", which marks the content for later
possible escaping).
"""
from django.utils.html import escape
return mark_safe(escape(value))
force_escape = stringfilter(force_escape)
force_escape.is_safe = True
def linebreaks(value, autoescape=None):
"""
Replaces line breaks in plain text with appropriate HTML; a single
newline becomes an HTML line break (``<br />``) and a new line
followed by a blank line becomes a paragraph break (``</p>``).
"""
from django.utils.html import linebreaks
autoescape = autoescape and not isinstance(value, SafeData)
return mark_safe(linebreaks(value, autoescape))
linebreaks.is_safe = True
linebreaks.needs_autoescape = True
linebreaks = stringfilter(linebreaks)
def linebreaksbr(value, autoescape=None):
"""
Converts all newlines in a piece of plain text to HTML line breaks
(``<br />``).
"""
if autoescape and not isinstance(value, SafeData):
from django.utils.html import escape
value = escape(value)
return mark_safe(value.replace('\n', '<br />'))
linebreaksbr.is_safe = True
linebreaksbr.needs_autoescape = True
linebreaksbr = stringfilter(linebreaksbr)
def safe(value):
"""
Marks the value as a string that should not be auto-escaped.
"""
return mark_safe(value)
safe.is_safe = True
safe = stringfilter(safe)
def safeseq(value):
"""
A "safe" filter for sequences. Marks each element in the sequence,
individually, as safe, after converting them to unicode. Returns a list
with the results.
"""
return [mark_safe(force_unicode(obj)) for obj in value]
safeseq.is_safe = True
def removetags(value, tags):
"""Removes a space separated list of [X]HTML tags from the output."""
tags = [re.escape(tag) for tag in tags.split()]
tags_re = u'(%s)' % u'|'.join(tags)
starttag_re = re.compile(ur'<%s(/?>|(\s+[^>]*>))' % tags_re, re.U)
endtag_re = re.compile(u'</%s>' % tags_re)
value = starttag_re.sub(u'', value)
value = endtag_re.sub(u'', value)
return value
removetags.is_safe = True
removetags = stringfilter(removetags)
def striptags(value):
"""Strips all [X]HTML tags."""
from django.utils.html import strip_tags
return strip_tags(value)
striptags.is_safe = True
striptags = stringfilter(striptags)
###################
# LISTS #
###################
def dictsort(value, arg):
"""
Takes a list of dicts, returns that list sorted by the property given in
the argument.
"""
var_resolve = Variable(arg).resolve
decorated = [(var_resolve(item), item) for item in value]
decorated.sort()
return [item[1] for item in decorated]
dictsort.is_safe = False
def dictsortreversed(value, arg):
"""
Takes a list of dicts, returns that list sorted in reverse order by the
property given in the argument.
"""
var_resolve = Variable(arg).resolve
decorated = [(var_resolve(item), item) for item in value]
decorated.sort()
decorated.reverse()
return [item[1] for item in decorated]
dictsortreversed.is_safe = False
def first(value):
"""Returns the first item in a list."""
try:
return value[0]
except IndexError:
return u''
first.is_safe = False
def join(value, arg, autoescape=None):
"""
Joins a list with a string, like Python's ``str.join(list)``.
"""
value = map(force_unicode, value)
if autoescape:
from django.utils.html import conditional_escape
value = [conditional_escape(v) for v in value]
try:
data = arg.join(value)
except AttributeError: # fail silently but nicely
return value
return mark_safe(data)
join.is_safe = True
join.needs_autoescape = True
def last(value):
"Returns the last item in a list"
try:
return value[-1]
except IndexError:
return u''
last.is_safe = True
def length(value):
"""Returns the length of the value - useful for lists."""
try:
return len(value)
except (ValueError, TypeError):
return ''
length.is_safe = True
def length_is(value, arg):
"""Returns a boolean of whether the value's length is the argument."""
try:
return len(value) == int(arg)
except (ValueError, TypeError):
return ''
length_is.is_safe = False
def random(value):
"""Returns a random item from the list."""
return random_module.choice(value)
random.is_safe = True
def slice_(value, arg):
"""
Returns a slice of the list.
Uses the same syntax as Python's list slicing; see
http://diveintopython.org/native_data_types/lists.html#odbchelper.list.slice
for an introduction.
"""
try:
bits = []
for x in arg.split(u':'):
if len(x) == 0:
bits.append(None)
else:
bits.append(int(x))
return value[slice(*bits)]
except (ValueError, TypeError):
return value # Fail silently.
slice_.is_safe = True
def unordered_list(value, autoescape=None):
"""
Recursively takes a self-nested list and returns an HTML unordered list --
WITHOUT opening and closing <ul> tags.
The list is assumed to be in the proper format. For example, if ``var``
contains: ``['States', ['Kansas', ['Lawrence', 'Topeka'], 'Illinois']]``,
then ``{{ var|unordered_list }}`` would return::
<li>States
<ul>
<li>Kansas
<ul>
<li>Lawrence</li>
<li>Topeka</li>
</ul>
</li>
<li>Illinois</li>
</ul>
</li>
"""
if autoescape:
from django.utils.html import conditional_escape
escaper = conditional_escape
else:
escaper = lambda x: x
def convert_old_style_list(list_):
"""
Converts old style lists to the new easier to understand format.
The old list format looked like:
['Item 1', [['Item 1.1', []], ['Item 1.2', []]]
And it is converted to:
['Item 1', ['Item 1.1', 'Item 1.2]]
"""
if not isinstance(list_, (tuple, list)) or len(list_) != 2:
return list_, False
first_item, second_item = list_
if second_item == []:
return [first_item], True
old_style_list = True
new_second_item = []
for sublist in second_item:
item, old_style_list = convert_old_style_list(sublist)
if not old_style_list:
break
new_second_item.extend(item)
if old_style_list:
second_item = new_second_item
return [first_item, second_item], old_style_list
def _helper(list_, tabs=1):
indent = u'\t' * tabs
output = []
list_length = len(list_)
i = 0
while i < list_length:
title = list_[i]
sublist = ''
sublist_item = None
if isinstance(title, (list, tuple)):
sublist_item = title
title = ''
elif i < list_length - 1:
next_item = list_[i+1]
if next_item and isinstance(next_item, (list, tuple)):
# The next item is a sub-list.
sublist_item = next_item
# We've processed the next item now too.
i += 1
if sublist_item:
sublist = _helper(sublist_item, tabs+1)
sublist = '\n%s<ul>\n%s\n%s</ul>\n%s' % (indent, sublist,
indent, indent)
output.append('%s<li>%s%s</li>' % (indent,
escaper(force_unicode(title)), sublist))
i += 1
return '\n'.join(output)
value, converted = convert_old_style_list(value)
return mark_safe(_helper(value))
unordered_list.is_safe = True
unordered_list.needs_autoescape = True
###################
# INTEGERS #
###################
def add(value, arg):
"""Adds the arg to the value."""
try:
return int(value) + int(arg)
except (ValueError, TypeError):
try:
return value + arg
except:
return value
add.is_safe = False
def get_digit(value, arg):
"""
Given a whole number, returns the requested digit of it, where 1 is the
right-most digit, 2 is the second-right-most digit, etc. Returns the
original value for invalid input (if input or argument is not an integer,
or if argument is less than 1). Otherwise, output is always an integer.
"""
try:
arg = int(arg)
value = int(value)
except ValueError:
return value # Fail silently for an invalid argument
if arg < 1:
return value
try:
return int(str(value)[-arg])
except IndexError:
return 0
get_digit.is_safe = False
###################
# DATES #
###################
def date(value, arg=None):
"""Formats a date according to the given format."""
from django.utils.dateformat import format
if not value:
return u''
if arg is None:
arg = settings.DATE_FORMAT
try:
return formats.date_format(value, arg)
except AttributeError:
try:
return format(value, arg)
except AttributeError:
return ''
date.is_safe = False
def time(value, arg=None):
"""Formats a time according to the given format."""
from django.utils import dateformat
if value in (None, u''):
return u''
if arg is None:
arg = settings.TIME_FORMAT
try:
return formats.time_format(value, arg)
except AttributeError:
try:
return dateformat.time_format(value, arg)
except AttributeError:
return ''
time.is_safe = False
def timesince(value, arg=None):
"""Formats a date as the time since that date (i.e. "4 days, 6 hours")."""
from django.utils.timesince import timesince
if not value:
return u''
try:
if arg:
return timesince(value, arg)
return timesince(value)
except (ValueError, TypeError):
return u''
timesince.is_safe = False
def timeuntil(value, arg=None):
"""Formats a date as the time until that date (i.e. "4 days, 6 hours")."""
from django.utils.timesince import timeuntil
from datetime import datetime
if not value:
return u''
try:
return timeuntil(value, arg)
except (ValueError, TypeError):
return u''
timeuntil.is_safe = False
###################
# LOGIC #
###################
def default(value, arg):
"""If value is unavailable, use given default."""
return value or arg
default.is_safe = False
def default_if_none(value, arg):
"""If value is None, use given default."""
if value is None:
return arg
return value
default_if_none.is_safe = False
def divisibleby(value, arg):
"""Returns True if the value is devisible by the argument."""
return int(value) % int(arg) == 0
divisibleby.is_safe = False
def yesno(value, arg=None):
"""
Given a string mapping values for true, false and (optionally) None,
returns one of those strings accoding to the value:
========== ====================== ==================================
Value Argument Outputs
========== ====================== ==================================
``True`` ``"yeah,no,maybe"`` ``yeah``
``False`` ``"yeah,no,maybe"`` ``no``
``None`` ``"yeah,no,maybe"`` ``maybe``
``None`` ``"yeah,no"`` ``"no"`` (converts None to False
if no mapping for None is given.
========== ====================== ==================================
"""
if arg is None:
arg = ugettext('yes,no,maybe')
bits = arg.split(u',')
if len(bits) < 2:
return value # Invalid arg.
try:
yes, no, maybe = bits
except ValueError:
# Unpack list of wrong size (no "maybe" value provided).
yes, no, maybe = bits[0], bits[1], bits[1]
if value is None:
return maybe
if value:
return yes
return no
yesno.is_safe = False
###################
# MISC #
###################
def filesizeformat(bytes):
"""
Formats the value like a 'human-readable' file size (i.e. 13 KB, 4.1 MB,
102 bytes, etc).
"""
try:
bytes = float(bytes)
except (TypeError,ValueError,UnicodeDecodeError):
return u"0 bytes"
if bytes < 1024:
return ungettext("%(size)d byte", "%(size)d bytes", bytes) % {'size': bytes}
if bytes < 1024 * 1024:
return ugettext("%.1f KB") % (bytes / 1024)
if bytes < 1024 * 1024 * 1024:
return ugettext("%.1f MB") % (bytes / (1024 * 1024))
return ugettext("%.1f GB") % (bytes / (1024 * 1024 * 1024))
filesizeformat.is_safe = True
def pluralize(value, arg=u's'):
"""
Returns a plural suffix if the value is not 1. By default, 's' is used as
the suffix:
* If value is 0, vote{{ value|pluralize }} displays "0 votes".
* If value is 1, vote{{ value|pluralize }} displays "1 vote".
* If value is 2, vote{{ value|pluralize }} displays "2 votes".
If an argument is provided, that string is used instead:
* If value is 0, class{{ value|pluralize:"es" }} displays "0 classes".
* If value is 1, class{{ value|pluralize:"es" }} displays "1 class".
* If value is 2, class{{ value|pluralize:"es" }} displays "2 classes".
If the provided argument contains a comma, the text before the comma is
used for the singular case and the text after the comma is used for the
plural case:
* If value is 0, cand{{ value|pluralize:"y,ies" }} displays "0 candies".
* If value is 1, cand{{ value|pluralize:"y,ies" }} displays "1 candy".
* If value is 2, cand{{ value|pluralize:"y,ies" }} displays "2 candies".
"""
if not u',' in arg:
arg = u',' + arg
bits = arg.split(u',')
if len(bits) > 2:
return u''
singular_suffix, plural_suffix = bits[:2]
try:
if int(value) != 1:
return plural_suffix
except ValueError: # Invalid string that's not a number.
pass
except TypeError: # Value isn't a string or a number; maybe it's a list?
try:
if len(value) != 1:
return plural_suffix
except TypeError: # len() of unsized object.
pass
return singular_suffix
pluralize.is_safe = False
def phone2numeric(value):
"""Takes a phone number and converts it in to its numerical equivalent."""
from django.utils.text import phone2numeric
return phone2numeric(value)
phone2numeric.is_safe = True
def pprint(value):
"""A wrapper around pprint.pprint -- for debugging, really."""
from pprint import pformat
try:
return pformat(value)
except Exception, e:
return u"Error in formatting: %s" % force_unicode(e, errors="replace")
pprint.is_safe = True
# Syntax: register.filter(name of filter, callback)
register.filter(add)
register.filter(addslashes)
register.filter(capfirst)
register.filter(center)
register.filter(cut)
register.filter(date)
register.filter(default)
register.filter(default_if_none)
register.filter(dictsort)
register.filter(dictsortreversed)
register.filter(divisibleby)
register.filter(escape)
register.filter(escapejs)
register.filter(filesizeformat)
register.filter(first)
register.filter(fix_ampersands)
register.filter(floatformat)
register.filter(force_escape)
register.filter(get_digit)
register.filter(iriencode)
register.filter(join)
register.filter(last)
register.filter(length)
register.filter(length_is)
register.filter(linebreaks)
register.filter(linebreaksbr)
register.filter(linenumbers)
register.filter(ljust)
register.filter(lower)
register.filter(make_list)
register.filter(phone2numeric)
register.filter(pluralize)
register.filter(pprint)
register.filter(removetags)
register.filter(random)
register.filter(rjust)
register.filter(safe)
register.filter(safeseq)
register.filter('slice', slice_)
register.filter(slugify)
register.filter(stringformat)
register.filter(striptags)
register.filter(time)
register.filter(timesince)
register.filter(timeuntil)
register.filter(title)
register.filter(truncatewords)
register.filter(truncatewords_html)
register.filter(unordered_list)
register.filter(upper)
register.filter(urlencode)
register.filter(urlize)
register.filter(urlizetrunc)
register.filter(wordcount)
register.filter(wordwrap)
register.filter(yesno)<|fim▁end|> | value = unicodedata.normalize('NFKD', value).encode('ascii', 'ignore') |
<|file_name|>root.rs<|end_file_name|><|fim▁begin|>// check-pass
#![feature(register_tool)]<|fim▁hole|>mod submodule;
fn main() {
submodule::foo();
}<|fim▁end|> | #![register_tool(tool)]
|
<|file_name|>Sections.js<|end_file_name|><|fim▁begin|>import SectionUtilities from '../../transform/SectionUtilities'
/**
* Hide or unhide a section.
* @param {!string} sectionId
* @param {?boolean} hidden
* @return {void}
*/
const setHidden = (sectionId, hidden) => {
if (!document) {
return
}
SectionUtilities.setHidden(document, sectionId, hidden)
}
export default {
getOffsets: SectionUtilities.getSectionOffsets,<|fim▁hole|><|fim▁end|> | setHidden
} |
<|file_name|>db.js<|end_file_name|><|fim▁begin|>// Compiled by ClojureScript 1.9.946 {}
goog.provide('eckersdorf.window.db');
goog.require('cljs.core');
goog.require('re_frame.core');
eckersdorf.window.db.window_state = new cljs.core.PersistentArrayMap(null, 2, [new cljs.core.Keyword("window","height","window/height",1310154766),(0),new cljs.core.Keyword("window","width","window/width",-1138776901),(0)], null);
<|fim▁hole|><|fim▁end|> | //# sourceMappingURL=db.js.map?rel=1510703504091 |
<|file_name|>sb-1.3.0.js<|end_file_name|><|fim▁begin|>/**
*
* Spacebrew Library for Javascript
* --------------------------------
*
* This library was designed to work on front-end (browser) envrionments, and back-end (server)
* environments. Please refer to the readme file, the documentation and examples to learn how to
* use this library.
*
* Spacebrew is an open, dynamically re-routable software toolkit for choreographing interactive
* spaces. Or, in other words, a simple way to connect interactive things to one another. Learn
* more about Spacebrew here: http://docs.spacebrew.cc/
*
* To import into your web apps, we recommend using the minimized version of this library.
*
* Latest Updates:
* - added blank "options" attribute to config message - for future use
* - caps number of messages sent to 60 per second
* - reconnect to spacebrew if connection lost
* - enable client apps to extend libs with admin functionality.
* - added close method to close Spacebrew connection.
*
* @author Brett Renfer and Julio Terra from LAB @ Rockwell Group
* @filename sb-1.3.0.js
* @version 1.3.0
* @date May 7, 2013
*
*/
/**
* Check if Bind method exists in current enviroment. If not, it creates an implementation of
* this useful method.
*/
if (!Function.prototype.bind) {
Function.prototype.bind = function (oThis) {
if (typeof this !== "function") {
// closest thing possible to the ECMAScript 5 internal IsCallable function
throw new TypeError("Function.prototype.bind - what is trying to be bound is not callable");
}
var aArgs = Array.prototype.slice.call(arguments, 1),
fToBind = this,
fNOP = function () {},
fBound = function () {
return fToBind.apply(this instanceof fNOP
? this
: oThis || window,
aArgs.concat(Array.prototype.slice.call(arguments)));
};
fNOP.prototype = this.prototype;
fBound.prototype = new fNOP();
return fBound;
};
}
/**
* @namespace for Spacebrew library
*/
var Spacebrew = Spacebrew || {};
/**
* create placeholder var for WebSocket object, if it does not already exist
*/
var WebSocket = WebSocket || {};
/**
* Check if Running in Browser or Server (Node) Environment *
*/
// check if window object already exists to determine if running browswer
var window = window || undefined;
// check if module object already exists to determine if this is a node application
var module = module || undefined;
// if app is running in a browser, then define the getQueryString method
if (window) {
if (!window['getQueryString']){
/**
* Get parameters from a query string
* @param {String} name Name of query string to parse (w/o '?' or '&')
* @return {String} value of parameter (or empty string if not found)
*/
window.getQueryString = function( name ) {
if (!window.location) return;
name = name.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");
var regexS = "[\\?&]"+name+"=([^&#]*)";
var regex = new RegExp( regexS );
var results = regex.exec( window.location.href );
if( results == null ) return "";
else return results[1];
}
}
}
// if app is running in a node server environment then package Spacebrew library as a module.
// WebSocket module (ws) needs to be saved in a node_modules so that it can be imported.
if (!window && module) {
WebSocket = require("ws");
module.exports = {
Spacebrew: Spacebrew
}
}
/**
* Define the Spacebrew Library *
*/
/**
* Spacebrew client!
* @constructor
* @param {String} server (Optional) Base address of Spacebrew server. This server address is overwritten if server defined in query string; defaults to localhost.
* @param {String} name (Optional) Base name of app. Base name is overwritten if "name" is defined in query string; defaults to window.location.href.
* @param {String} description (Optional) Base description of app. Description name is overwritten if "description" is defined in query string;
* @param {Object} options (Optional) An object that holds the optional parameters described below
* port (Optional) Port number for the Spacebrew server
* admin (Optional) Flag that identifies when app should register for admin privileges with server
* debug (Optional) Debug flag that turns on info and debug messaging (limited use)
*/
Spacebrew.Client = function( server, name, description, options ){
var options = options || {};
// check if the server variable is an object that holds all config values
if (server != undefined) {
if (toString.call(server) !== '[object String]') {
options.port = server.port || undefined;
options.debug = server.debug || false;<|fim▁hole|> description = server.description || undefined;
name = server.name || undefined;
server = server.server || undefined;
}
}
this.debug = (window.getQueryString('debug') === "true" ? true : (options.debug || false));
this.reconnect = options.reconnect || true;
this.reconnect_timer = undefined;
this.send_interval = 16;
this.send_blocked = false;
this.msg = {};
/**
* Name of app
* @type {String}
*/
this._name = name || "javascript client #";
if (window) {
this._name = (window.getQueryString('name') !== "" ? unescape(window.getQueryString('name')) : this._name);
}
/**
* Description of your app
* @type {String}
*/
this._description = description || "spacebrew javascript client";
if (window) {
this._description = (window.getQueryString('description') !== "" ? unescape(window.getQueryString('description')) : this._description);
}
/**
* Spacebrew server to which the app will connect
* @type {String}
*/
this.server = server || "sandbox.spacebrew.cc";
if (window) {
this.server = (window.getQueryString('server') !== "" ? unescape(window.getQueryString('server')) : this.server);
}
/**
* Port number on which Spacebrew server is running
* @type {Integer}
*/
this.port = options.port || 9000;
if (window) {
port = window.getQueryString('port');
if (port !== "" && !isNaN(port)) {
this.port = port;
}
}
/**
* Reference to WebSocket
* @type {WebSocket}
*/
this.socket = null;
/**
* Configuration file for Spacebrew
* @type {Object}
*/
this.client_config = {
name: this._name,
description: this._description,
publish:{
messages:[]
},
subscribe:{
messages:[]
},
options:{}
};
this.admin = {}
/**
* Are we connected to a Spacebrew server?
* @type {Boolean}
*/
this._isConnected = false;
}
/**
* Connect to Spacebrew
* @memberOf Spacebrew.Client
*/
Spacebrew.Client.prototype.connect = function(){
try {
this.socket = new WebSocket("ws://" + this.server + ":" + this.port);
this.socket.onopen = this._onOpen.bind(this);
this.socket.onmessage = this._onMessage.bind(this);
this.socket.onclose = this._onClose.bind(this);
} catch(e){
this._isConnected = false;
console.log("[connect:Spacebrew] connection attempt failed")
}
}
/**
* Close Spacebrew connection
* @memberOf Spacebrew.Client
*/
Spacebrew.Client.prototype.close = function(){
try {
if (this._isConnected) {
this.socket.close();
this._isConnected = false;
console.log("[close:Spacebrew] closing websocket connection")
}
} catch (e) {
this._isConnected = false;
}
}
/**
* Override in your app to receive on open event for connection
* @memberOf Spacebrew.Client
* @public
*/
Spacebrew.Client.prototype.onOpen = function( name, value ){}
/**
* Override in your app to receive on close event for connection
* @memberOf Spacebrew.Client
* @public
*/
Spacebrew.Client.prototype.onClose = function( name, value ){}
/**
* Override in your app to receive "range" messages, e.g. sb.onRangeMessage = yourRangeFunction
* @param {String} name Name of incoming route
* @param {String} value [description]
* @memberOf Spacebrew.Client
* @public
*/
Spacebrew.Client.prototype.onRangeMessage = function( name, value ){}
/**
* Override in your app to receive "boolean" messages, e.g. sb.onBooleanMessage = yourBoolFunction
* @param {String} name Name of incoming route
* @param {String} value [description]
* @memberOf Spacebrew.Client
* @public
*/
Spacebrew.Client.prototype.onBooleanMessage = function( name, value ){}
/**
* Override in your app to receive "string" messages, e.g. sb.onStringMessage = yourStringFunction
* @param {String} name Name of incoming route
* @param {String} value [description]
* @memberOf Spacebrew.Client
* @public
*/
Spacebrew.Client.prototype.onStringMessage = function( name, value ){}
/**
* Override in your app to receive "custom" messages, e.g. sb.onCustomMessage = yourStringFunction
* @param {String} name Name of incoming route
* @param {String} value [description]
* @memberOf Spacebrew.Client
* @public
*/
Spacebrew.Client.prototype.onCustomMessage = function( name, value, type ){}
/**
* Add a route you are publishing on
* @param {String} name Name of incoming route
* @param {String} type "boolean", "range", or "string"
* @param {String} def default value
* @memberOf Spacebrew.Client
* @public
*/
Spacebrew.Client.prototype.addPublish = function( name, type, def ){
this.client_config.publish.messages.push({"name":name, "type":type, "default":def});
this.updatePubSub();
}
/**
* [addSubscriber description]
* @param {String} name Name of outgoing route
* @param {String} type "boolean", "range", or "string"
* @memberOf Spacebrew.Client
* @public
*/
Spacebrew.Client.prototype.addSubscribe = function( name, type ){
this.client_config.subscribe.messages.push({"name":name, "type":type });
this.updatePubSub();
}
/**
* Update publishers and subscribers
* @memberOf Spacebrew.Client
* @private
*/
Spacebrew.Client.prototype.updatePubSub = function(){
if (this._isConnected) {
this.socket.send(JSON.stringify({"config": this.client_config}));
}
}
/**
* Send a route to Spacebrew
* @param {String} name Name of outgoing route (must match something in addPublish)
* @param {String} type "boolean", "range", or "string"
* @param {String} value Value to send
* @memberOf Spacebrew.Client
* @public
*/
Spacebrew.Client.prototype.send = function( name, type, value ){
var self = this;
this.msg = {
"message": {
"clientName":this._name,
"name": name,
"type": type,
"value": value
}
}
// if send block is not active then send message
if (!this.send_blocked) {
this.socket.send(JSON.stringify(this.msg));
this.send_blocked = true;
this.msg = undefined;
// set the timer to unblock message sending
setTimeout(function() {
self.send_blocked = false; // remove send block
if (self.msg != undefined) { // if message exists then sent it
self.send(self.msg.message.name, self.msg.message.type, self.msg.message.value);
}
}, self.send_interval);
}
}
/**
* Called on WebSocket open
* @private
* @memberOf Spacebrew.Client
*/
Spacebrew.Client.prototype._onOpen = function() {
console.log("[_onOpen:Spacebrew] Spacebrew connection opened, client name is: " + this._name);
this._isConnected = true;
if (this.admin.active) this.connectAdmin();
// if reconnect functionality is activated then clear interval timer when connection succeeds
if (this.reconnect_timer) {
console.log("[_onOpen:Spacebrew] tearing down reconnect timer")
this.reconnect_timer = clearInterval(this.reconnect_timer);
this.reconnect_timer = undefined;
}
// send my config
this.updatePubSub();
this.onOpen();
}
/**
* Called on WebSocket message
* @private
* @param {Object} e
* @memberOf Spacebrew.Client
*/
Spacebrew.Client.prototype._onMessage = function( e ){
var data = JSON.parse(e.data)
, name
, type
, value
;
// handle client messages
if (data["message"]) {
// check to make sure that this is not an admin message
if (!data.message["clientName"]) {
name = data.message.name;
type = data.message.type;
value = data.message.value;
switch( type ){
case "boolean":
this.onBooleanMessage( name, value == "true" );
break;
case "string":
this.onStringMessage( name, value );
break;
case "range":
this.onRangeMessage( name, Number(value) );
break;
default:
this.onCustomMessage( name, value, type );
}
}
}
// handle admin messages
else {
if (this.admin.active) {
this._handleAdminMessages( data );
}
}
}
/**
* Called on WebSocket close
* @private
* @memberOf Spacebrew.Client
*/
Spacebrew.Client.prototype._onClose = function() {
var self = this;
console.log("[_onClose:Spacebrew] Spacebrew connection closed");
this._isConnected = false;
if (this.admin.active) this.admin.remoteAddress = undefined;
// if reconnect functionality is activated set interval timer if connection dies
if (this.reconnect && !this.reconnect_timer) {
console.log("[_onClose:Spacebrew] setting up reconnect timer");
this.reconnect_timer = setInterval(function () {
if (self.isConnected != false) {
self.connect();
console.log("[reconnect:Spacebrew] attempting to reconnect to spacebrew");
}
}, 5000);
}
this.onClose();
};
/**
* name Method that sets or gets the spacebrew app name. If parameter is provided then it sets the name, otherwise
* it just returns the current app name.
* @param {String} newName New name of the spacebrew app
* @return {String} Returns the name of the spacebrew app if called as a getter function. If called as a
* setter function it will return false if the method is called after connecting to spacebrew,
* because the name must be configured before connection is made.
*/
Spacebrew.Client.prototype.name = function (newName){
if (newName) { // if a name has been passed in then update it
if (this._isConnected) return false; // if already connected we can't update name
this._name = newName;
if (window) {
this._name = (window.getQueryString('name') !== "" ? unescape(window.getQueryString('name')) : this._name);
}
this.client_config.name = this._name; // update spacebrew config file
}
return this._name;
};
/**
* name Method that sets or gets the spacebrew app description. If parameter is provided then it sets the description,
* otherwise it just returns the current app description.
* @param {String} newDesc New description of the spacebrew app
* @return {String} Returns the description of the spacebrew app if called as a getter function. If called as a
* setter function it will return false if the method is called after connecting to spacebrew,
* because the description must be configured before connection is made.
*/
Spacebrew.Client.prototype.description = function (newDesc){
if (newDesc) { // if a description has been passed in then update it
if (this._isConnected) return false; // if already connected we can't update description
this._description = newDesc || "spacebrew javascript client";
if (window) {
this._description = (window.getQueryString('description') !== "" ? unescape(window.getQueryString('description')) : this._description);
}
this.client_config.description = this._description; // update spacebrew config file
}
return this._description;
};
/**
* isConnected Method that returns current connection state of the spacebrew client.
* @return {Boolean} Returns true if currently connected to Spacebrew
*/
Spacebrew.Client.prototype.isConnected = function (){
return this._isConnected;
};
Spacebrew.Client.prototype.extend = function ( mixin ) {
for (var prop in mixin) {
if (mixin.hasOwnProperty(prop)) {
this[prop] = mixin[prop];
}
}
};<|fim▁end|> | options.reconnect = server.reconnect || false; |
<|file_name|>jsonschema.d.ts<|end_file_name|><|fim▁begin|>interface jsonschema {
id?: string
$schema?: string
type?: string
title?: string<|fim▁hole|> default?: any
format?: string | Object
enum?: any[]
definitions?: { [index: string]: jsonschema }
allOf?: jsonschema[]
anyOf?: jsonschema[]
oneOf?: jsonschema[]
not?: jsonschema[]
multipleOf?: number
maximum?: number
minimum?: number
exclusiveMaximum?: boolean
exclusiveMinimum?: boolean
maxLength?: number
minLength?: number
pattern?: string
additionalItems?: boolean | jsonschema
items?: jsonschema | jsonschema[]
maxItems?: number
minItems?: number
uniqueItems?: boolean
maxProperties?: number
minProperties?: number
required?: string[]
additionalProperties?: boolean | jsonschema
properties?: { [index: string]: jsonschema }
patternProperties?: { [index: string]: jsonschema }
dependencies?: { [index: string]: jsonschema }
}<|fim▁end|> | description?: string |
<|file_name|>sync_users.py<|end_file_name|><|fim▁begin|>import logging
from django.core.management.base import BaseCommand
from waldur_rancher.utils import SyncUser
logger = logging.getLogger(__name__)
class Command(BaseCommand):
help = """Sync users from Waldur to Rancher."""
<|fim▁hole|> def handle(self, *args, **options):
def print_message(count, action, name='user'):
if count == 1:
self.stdout.write(
self.style.SUCCESS('%s %s has been %s.' % (count, name, action))
)
else:
self.stdout.write(
self.style.SUCCESS('%s %ss have been %s.' % (count, name, action))
)
result = SyncUser.run()
for action in ['blocked', 'created', 'activated', 'updated']:
print_message(result.get(action, 0), action)
print_message(result.get('project roles deleted', 0), 'deleted', 'project role')
print_message(result('project roles created', 0), 'created', 'project role')<|fim▁end|> | |
<|file_name|>test.py<|end_file_name|><|fim▁begin|>#Ensure there is an exceptional edge from the following case
def f2():
b, d = Base, Derived
try:
class MyNewClass(b, d):
pass
except:
e2
def f3():
sequence_of_four = a_global
try:
a, b, c = sequence_of_four
except:
e3
#Always treat locals as non-raising to keep DB size down.
def f4():
if cond:
local = 1
try:
local
except:
e4
def f5():
try:
a_global
except:
e5
def f6():
local = a_global
try:<|fim▁hole|> except:
e6
#Literals can't raise
def f7():
try:
4
except:
e7
def f8():
try:
a + b
except:
e8
#OK assignments
def f9():
try:
a, b = 1, 2
except:
e9
def fa():
seq = a_global
try:
a = seq
except:
ea
def fb():
a, b, c = a_global
try:
seq = a, b, c
except:
eb
#Ensure that a.b and c[d] can raise
def fc():
a, b = a_global
try:
return a[b]
except:
ec
def fd():
a = a_global
try:
return a.b
except:
ed
def fe():
try:
call()
except:
ee
else:
ef<|fim▁end|> | local() |
<|file_name|>profiles.py<|end_file_name|><|fim▁begin|># vim:fileencoding=UTF-8:ts=4:sw=4:sta:et:sts=4:ai
from __future__ import with_statement
__license__ = 'GPL 3'
__copyright__ = '2009, Kovid Goyal <[email protected]>'
__docformat__ = 'restructuredtext en'
from itertools import izip
from calibre.customize import Plugin as _Plugin
FONT_SIZES = [('xx-small', 1),
('x-small', None),
('small', 2),
('medium', 3),
('large', 4),
('x-large', 5),
('xx-large', 6),
(None, 7)]
class Plugin(_Plugin):
fbase = 12
fsizes = [5, 7, 9, 12, 13.5, 17, 20, 22, 24]
screen_size = (1600, 1200)
dpi = 100
def __init__(self, *args, **kwargs):
_Plugin.__init__(self, *args, **kwargs)
self.width, self.height = self.screen_size
fsizes = list(self.fsizes)
self.fkey = list(self.fsizes)
self.fsizes = []
for (name, num), size in izip(FONT_SIZES, fsizes):
self.fsizes.append((name, num, float(size)))
self.fnames = dict((name, sz) for name, _, sz in self.fsizes if name)
self.fnums = dict((num, sz) for _, num, sz in self.fsizes if num)
self.width_pts = self.width * 72./self.dpi
self.height_pts = self.height * 72./self.dpi
# Input profiles {{{
class InputProfile(Plugin):
author = 'Kovid Goyal'
supported_platforms = set(['windows', 'osx', 'linux'])
can_be_disabled = False
type = _('Input profile')
name = 'Default Input Profile'
short_name = 'default' # Used in the CLI so dont use spaces etc. in it
description = _('This profile tries to provide sane defaults and is useful '
'if you know nothing about the input document.')
class SonyReaderInput(InputProfile):
name = 'Sony Reader'
short_name = 'sony'
description = _('This profile is intended for the SONY PRS line. '
'The 500/505/600/700 etc.')
screen_size = (584, 754)
dpi = 168.451
fbase = 12
fsizes = [7.5, 9, 10, 12, 15.5, 20, 22, 24]
class SonyReader300Input(SonyReaderInput):
name = 'Sony Reader 300'
short_name = 'sony300'
description = _('This profile is intended for the SONY PRS 300.')
dpi = 200
class SonyReader900Input(SonyReaderInput):
author = 'John Schember'
name = 'Sony Reader 900'
short_name = 'sony900'
description = _('This profile is intended for the SONY PRS-900.')
screen_size = (584, 978)
class MSReaderInput(InputProfile):
name = 'Microsoft Reader'
short_name = 'msreader'
description = _('This profile is intended for the Microsoft Reader.')
screen_size = (480, 652)
dpi = 96
fbase = 13
fsizes = [10, 11, 13, 16, 18, 20, 22, 26]
class MobipocketInput(InputProfile):
name = 'Mobipocket Books'
short_name = 'mobipocket'
description = _('This profile is intended for the Mobipocket books.')
# Unfortunately MOBI books are not narrowly targeted, so this information is
# quite likely to be spurious
screen_size = (600, 800)
dpi = 96
fbase = 18
fsizes = [14, 14, 16, 18, 20, 22, 24, 26]
class HanlinV3Input(InputProfile):
name = 'Hanlin V3'
short_name = 'hanlinv3'
description = _('This profile is intended for the Hanlin V3 and its clones.')
# Screen size is a best guess
screen_size = (584, 754)
dpi = 168.451
fbase = 16
fsizes = [12, 12, 14, 16, 18, 20, 22, 24]
class HanlinV5Input(HanlinV3Input):
name = 'Hanlin V5'
short_name = 'hanlinv5'
description = _('This profile is intended for the Hanlin V5 and its clones.')
# Screen size is a best guess
screen_size = (584, 754)
dpi = 200
class CybookG3Input(InputProfile):
name = 'Cybook G3'
short_name = 'cybookg3'
description = _('This profile is intended for the Cybook G3.')
# Screen size is a best guess
screen_size = (600, 800)
dpi = 168.451
fbase = 16
fsizes = [12, 12, 14, 16, 18, 20, 22, 24]
class CybookOpusInput(InputProfile):
author = 'John Schember'
name = 'Cybook Opus'
short_name = 'cybook_opus'
description = _('This profile is intended for the Cybook Opus.')
# Screen size is a best guess
screen_size = (600, 800)
dpi = 200
fbase = 16
fsizes = [12, 12, 14, 16, 18, 20, 22, 24]
class KindleInput(InputProfile):
name = 'Kindle'
short_name = 'kindle'
description = _('This profile is intended for the Amazon Kindle.')
# Screen size is a best guess
screen_size = (525, 640)
dpi = 168.451
fbase = 16
fsizes = [12, 12, 14, 16, 18, 20, 22, 24]
class IlliadInput(InputProfile):
name = 'Illiad'
short_name = 'illiad'
description = _('This profile is intended for the Irex Illiad.')
screen_size = (760, 925)
dpi = 160.0
fbase = 12
fsizes = [7.5, 9, 10, 12, 15.5, 20, 22, 24]
class IRexDR1000Input(InputProfile):
author = 'John Schember'
name = 'IRex Digital Reader 1000'
short_name = 'irexdr1000'
description = _('This profile is intended for the IRex Digital Reader 1000.')
# Screen size is a best guess
screen_size = (1024, 1280)
dpi = 160
fbase = 16
fsizes = [12, 14, 16, 18, 20, 22, 24]
class IRexDR800Input(InputProfile):
author = 'Eric Cronin'
name = 'IRex Digital Reader 800'
short_name = 'irexdr800'
description = _('This profile is intended for the IRex Digital Reader 800.')
screen_size = (768, 1024)
dpi = 160
fbase = 16
fsizes = [12, 14, 16, 18, 20, 22, 24]
class NookInput(InputProfile):
author = 'John Schember'
name = 'Nook'
short_name = 'nook'
description = _('This profile is intended for the B&N Nook.')
# Screen size is a best guess
screen_size = (600, 800)
dpi = 167
fbase = 16
fsizes = [12, 12, 14, 16, 18, 20, 22, 24]
input_profiles = [InputProfile, SonyReaderInput, SonyReader300Input,
SonyReader900Input, MSReaderInput, MobipocketInput, HanlinV3Input,
HanlinV5Input, CybookG3Input, CybookOpusInput, KindleInput, IlliadInput,
IRexDR1000Input, IRexDR800Input, NookInput]
input_profiles.sort(cmp=lambda x,y:cmp(x.name.lower(), y.name.lower()))
# }}}
class OutputProfile(Plugin):
author = 'Kovid Goyal'
supported_platforms = set(['windows', 'osx', 'linux'])
can_be_disabled = False
type = _('Output profile')
name = 'Default Output Profile'
short_name = 'default' # Used in the CLI so dont use spaces etc. in it
description = _('This profile tries to provide sane defaults and is useful '
'if you want to produce a document intended to be read at a '
'computer or on a range of devices.')
#: The image size for comics
comic_screen_size = (584, 754)
#: If True the MOBI renderer on the device supports MOBI indexing
supports_mobi_indexing = False
#: If True output should be optimized for a touchscreen interface
touchscreen = False
touchscreen_news_css = ''
#: A list of extra (beyond CSS 2.1) modules supported by the device
#: Format is a cssutils profile dictionary (see iPad for example)
extra_css_modules = []
#: If True, the date is appended to the title of downloaded news
periodical_date_in_title = True
#: Characters used in jackets and catalogs
ratings_char = u'*'
empty_ratings_char = u' '
#: Unsupported unicode characters to be replaced during preprocessing
unsupported_unicode_chars = []
#: Number of ems that the left margin of a blockquote is rendered as
mobi_ems_per_blockquote = 1.0
#: Special periodical formatting needed in EPUB
epub_periodical_format = None
class iPadOutput(OutputProfile):
name = 'iPad'
short_name = 'ipad'
description = _('Intended for the iPad and similar devices with a '
'resolution of 768x1024')
screen_size = (768, 1024)
comic_screen_size = (768, 1024)
dpi = 132.0
extra_css_modules = [
{
'name':'webkit',
'props': {'-webkit-border-bottom-left-radius':'{length}',
'-webkit-border-bottom-right-radius':'{length}',
'-webkit-border-top-left-radius':'{length}',
'-webkit-border-top-right-radius':'{length}',
'-webkit-border-radius': r'{border-width}(\s+{border-width}){0,3}|inherit',
},
'macros': {'border-width': '{length}|medium|thick|thin'}
}
]
ratings_char = u'\u2605' # filled star
empty_ratings_char = u'\u2606' # hollow star
touchscreen = True
# touchscreen_news_css {{{
touchscreen_news_css = u'''
/* hr used in articles */
.article_articles_list {
width:18%;
}
.article_link {
color: #593f29;
font-style: italic;
}
.article_next {
-webkit-border-top-right-radius:4px;
-webkit-border-bottom-right-radius:4px;
font-style: italic;
width:32%;
}
.article_prev {
-webkit-border-top-left-radius:4px;
-webkit-border-bottom-left-radius:4px;
font-style: italic;
width:32%;
}
.article_sections_list {
width:18%;
}
.articles_link {
font-weight: bold;
}
.sections_link {
font-weight: bold;
}
.caption_divider {
border:#ccc 1px solid;
}
.touchscreen_navbar {
background:#c3bab2;
border:#ccc 0px solid;
border-collapse:separate;
border-spacing:1px;
margin-left: 5%;
margin-right: 5%;
page-break-inside:avoid;
width: 90%;
-webkit-border-radius:4px;
}
.touchscreen_navbar td {
background:#fff;
font-family:Helvetica;
font-size:80%;
/* UI touchboxes use 8px padding */
padding: 6px;
text-align:center;
}
.touchscreen_navbar td a:link {
color: #593f29;
text-decoration: none;
}
/* Index formatting */
.publish_date {
text-align:center;
}
.divider {
border-bottom:1em solid white;
border-top:1px solid gray;
}
hr.caption_divider {
border-color:black;
border-style:solid;
border-width:1px;
}
/* Feed summary formatting */
.article_summary {
display:inline-block;
padding-bottom:0.5em;
}
.feed {
font-family:sans-serif;
font-weight:bold;
font-size:larger;
}
.feed_link {
font-style: italic;
}
.feed_next {
-webkit-border-top-right-radius:4px;
-webkit-border-bottom-right-radius:4px;
font-style: italic;
width:40%;
}
.feed_prev {
-webkit-border-top-left-radius:4px;
-webkit-border-bottom-left-radius:4px;
font-style: italic;
width:40%;
}
.feed_title {
text-align: center;
font-size: 160%;
}
.feed_up {
font-weight: bold;
width:20%;
}
.summary_headline {
font-weight:bold;
text-align:left;
}
.summary_byline {
text-align:left;
font-family:monospace;
}
.summary_text {
text-align:left;
}
'''
# }}}
class iPad3Output(iPadOutput):
screen_size = comic_screen_size = (2048, 1536)
dpi = 264.0
name = 'iPad 3'
short_name = 'ipad3'
description = _('Intended for the iPad 3 and similar devices with a '
'resolution of 1536x2048')
class TabletOutput(iPadOutput):
name = 'Tablet'
short_name = 'tablet'
description = _('Intended for generic tablet devices, does no resizing of images')
screen_size = (10000, 10000)
comic_screen_size = (10000, 10000)
class SamsungGalaxy(TabletOutput):
name = 'Samsung Galaxy'
short_name = 'galaxy'
description = _('Intended for the Samsung Galaxy and similar tablet devices with '
'a resolution of 600x1280')
screen_size = comic_screen_size = (600, 1280)
class NookHD(TabletOutput):
name = 'Nook HD+'
short_name = 'nook_hd_plus'
description = _('Intended for the Nook HD+ and similar tablet devices with '
'a resolution of 1280x1920')
screen_size = comic_screen_size = (1280, 1920)
class SonyReaderOutput(OutputProfile):
name = 'Sony Reader'
short_name = 'sony'
description = _('This profile is intended for the SONY PRS line. '
'The 500/505/600/700 etc.')
screen_size = (590, 775)
dpi = 168.451<|fim▁hole|>
epub_periodical_format = 'sony'
# periodical_date_in_title = False
class KoboReaderOutput(OutputProfile):
name = 'Kobo Reader'
short_name = 'kobo'
description = _('This profile is intended for the Kobo Reader.')
screen_size = (536, 710)
comic_screen_size = (536, 710)
dpi = 168.451
fbase = 12
fsizes = [7.5, 9, 10, 12, 15.5, 20, 22, 24]
class SonyReader300Output(SonyReaderOutput):
author = 'John Schember'
name = 'Sony Reader 300'
short_name = 'sony300'
description = _('This profile is intended for the SONY PRS-300.')
dpi = 200
class SonyReader900Output(SonyReaderOutput):
author = 'John Schember'
name = 'Sony Reader 900'
short_name = 'sony900'
description = _('This profile is intended for the SONY PRS-900.')
screen_size = (600, 999)
comic_screen_size = screen_size
class SonyReaderT3Output(SonyReaderOutput):
author = 'Kovid Goyal'
name = 'Sony Reader T3'
short_name = 'sonyt3'
description = _('This profile is intended for the SONY PRS-T3.')
screen_size = (758, 934)
comic_screen_size = screen_size
class GenericEink(SonyReaderOutput):
name = 'Generic e-ink'
short_name = 'generic_eink'
description = _('Suitable for use with any e-ink device')
epub_periodical_format = None
class GenericEinkLarge(GenericEink):
name = 'Generic e-ink large'
short_name = 'generic_eink_large'
description = _('Suitable for use with any large screen e-ink device')
screen_size = (600, 999)
comic_screen_size = screen_size
class GenericEinkHD(GenericEink):
name = 'Generic e-ink HD'
short_name = 'generic_eink_hd'
description = _('Suitable for use with any modern high resolution e-ink device')
screen_size = (10000, 10000)
comic_screen_size = (10000, 10000)
class JetBook5Output(OutputProfile):
name = 'JetBook 5-inch'
short_name = 'jetbook5'
description = _('This profile is intended for the 5-inch JetBook.')
screen_size = (480, 640)
dpi = 168.451
class SonyReaderLandscapeOutput(SonyReaderOutput):
name = 'Sony Reader Landscape'
short_name = 'sony-landscape'
description = _('This profile is intended for the SONY PRS line. '
'The 500/505/700 etc, in landscape mode. Mainly useful '
'for comics.')
screen_size = (784, 1012)
comic_screen_size = (784, 1012)
class MSReaderOutput(OutputProfile):
name = 'Microsoft Reader'
short_name = 'msreader'
description = _('This profile is intended for the Microsoft Reader.')
screen_size = (480, 652)
dpi = 96
fbase = 13
fsizes = [10, 11, 13, 16, 18, 20, 22, 26]
class MobipocketOutput(OutputProfile):
name = 'Mobipocket Books'
short_name = 'mobipocket'
description = _('This profile is intended for the Mobipocket books.')
# Unfortunately MOBI books are not narrowly targeted, so this information is
# quite likely to be spurious
screen_size = (600, 800)
dpi = 96
fbase = 18
fsizes = [14, 14, 16, 18, 20, 22, 24, 26]
class HanlinV3Output(OutputProfile):
name = 'Hanlin V3'
short_name = 'hanlinv3'
description = _('This profile is intended for the Hanlin V3 and its clones.')
# Screen size is a best guess
screen_size = (584, 754)
dpi = 168.451
fbase = 16
fsizes = [12, 12, 14, 16, 18, 20, 22, 24]
class HanlinV5Output(HanlinV3Output):
name = 'Hanlin V5'
short_name = 'hanlinv5'
description = _('This profile is intended for the Hanlin V5 and its clones.')
dpi = 200
class CybookG3Output(OutputProfile):
name = 'Cybook G3'
short_name = 'cybookg3'
description = _('This profile is intended for the Cybook G3.')
# Screen size is a best guess
screen_size = (600, 800)
comic_screen_size = (600, 757)
dpi = 168.451
fbase = 16
fsizes = [12, 12, 14, 16, 18, 20, 22, 24]
class CybookOpusOutput(SonyReaderOutput):
author = 'John Schember'
name = 'Cybook Opus'
short_name = 'cybook_opus'
description = _('This profile is intended for the Cybook Opus.')
# Screen size is a best guess
dpi = 200
fbase = 16
fsizes = [12, 12, 14, 16, 18, 20, 22, 24]
epub_periodical_format = None
class KindleOutput(OutputProfile):
name = 'Kindle'
short_name = 'kindle'
description = _('This profile is intended for the Amazon Kindle.')
# Screen size is a best guess
screen_size = (525, 640)
dpi = 168.451
fbase = 16
fsizes = [12, 12, 14, 16, 18, 20, 22, 24]
supports_mobi_indexing = True
periodical_date_in_title = False
empty_ratings_char = u'\u2606'
ratings_char = u'\u2605'
mobi_ems_per_blockquote = 2.0
class KindleDXOutput(OutputProfile):
name = 'Kindle DX'
short_name = 'kindle_dx'
description = _('This profile is intended for the Amazon Kindle DX.')
# Screen size is a best guess
screen_size = (744, 1022)
dpi = 150.0
comic_screen_size = (771, 1116)
# comic_screen_size = (741, 1022)
supports_mobi_indexing = True
periodical_date_in_title = False
empty_ratings_char = u'\u2606'
ratings_char = u'\u2605'
mobi_ems_per_blockquote = 2.0
class KindlePaperWhiteOutput(KindleOutput):
name = 'Kindle PaperWhite'
short_name = 'kindle_pw'
description = _('This profile is intended for the Amazon Kindle PaperWhite 1 and 2')
# Screen size is a best guess
screen_size = (658, 940)
dpi = 212.0
comic_screen_size = screen_size
class KindleVoyageOutput(KindleOutput):
name = 'Kindle Voyage'
short_name = 'kindle_voyage'
description = _('This profile is intended for the Amazon Kindle Voyage')
# Screen size is currently just the spec size, actual renderable area will
# depend on someone with the device doing tests.
screen_size = (1080, 1430)
dpi = 300.0
comic_screen_size = screen_size
class KindlePaperWhite3Output(KindleVoyageOutput):
name = 'Kindle PaperWhite 3'
short_name = 'kindle_pw3'
description = _('This profile is intended for the Amazon Kindle PaperWhite 3 and above')
# Screen size is currently just the spec size, actual renderable area will
# depend on someone with the device doing tests.
screen_size = (1072, 1430)
dpi = 300.0
comic_screen_size = screen_size
class KindleFireOutput(KindleDXOutput):
name = 'Kindle Fire'
short_name = 'kindle_fire'
description = _('This profile is intended for the Amazon Kindle Fire.')
screen_size = (570, 1016)
dpi = 169.0
comic_screen_size = (570, 1016)
class IlliadOutput(OutputProfile):
name = 'Illiad'
short_name = 'illiad'
description = _('This profile is intended for the Irex Illiad.')
screen_size = (760, 925)
comic_screen_size = (760, 925)
dpi = 160.0
fbase = 12
fsizes = [7.5, 9, 10, 12, 15.5, 20, 22, 24]
class IRexDR1000Output(OutputProfile):
author = 'John Schember'
name = 'IRex Digital Reader 1000'
short_name = 'irexdr1000'
description = _('This profile is intended for the IRex Digital Reader 1000.')
# Screen size is a best guess
screen_size = (1024, 1280)
comic_screen_size = (996, 1241)
dpi = 160
fbase = 16
fsizes = [12, 14, 16, 18, 20, 22, 24]
class IRexDR800Output(OutputProfile):
author = 'Eric Cronin'
name = 'IRex Digital Reader 800'
short_name = 'irexdr800'
description = _('This profile is intended for the IRex Digital Reader 800.')
# Screen size is a best guess
screen_size = (768, 1024)
comic_screen_size = (768, 1024)
dpi = 160
fbase = 16
fsizes = [12, 14, 16, 18, 20, 22, 24]
class NookOutput(OutputProfile):
author = 'John Schember'
name = 'Nook'
short_name = 'nook'
description = _('This profile is intended for the B&N Nook.')
# Screen size is a best guess
screen_size = (600, 730)
comic_screen_size = (584, 730)
dpi = 167
fbase = 16
fsizes = [12, 12, 14, 16, 18, 20, 22, 24]
class NookColorOutput(NookOutput):
name = 'Nook Color'
short_name = 'nook_color'
description = _('This profile is intended for the B&N Nook Color.')
screen_size = (600, 900)
comic_screen_size = (594, 900)
dpi = 169
class PocketBook900Output(OutputProfile):
author = 'Chris Lockfort'
name = 'PocketBook Pro 900'
short_name = 'pocketbook_900'
description = _('This profile is intended for the PocketBook Pro 900 series of devices.')
screen_size = (810, 1180)
dpi = 150.0
comic_screen_size = screen_size
class PocketBookPro912Output(OutputProfile):
author = 'Daniele Pizzolli'
name = 'PocketBook Pro 912'
short_name = 'pocketbook_pro_912'
description = _('This profile is intended for the PocketBook Pro 912 series of devices.')
# According to http://download.pocketbook-int.com/user-guides/E_Ink/912/User_Guide_PocketBook_912(EN).pdf
screen_size = (825, 1200)
dpi = 155.0
comic_screen_size = screen_size
output_profiles = [
OutputProfile, SonyReaderOutput, SonyReader300Output, SonyReader900Output,
SonyReaderT3Output, MSReaderOutput, MobipocketOutput, HanlinV3Output,
HanlinV5Output, CybookG3Output, CybookOpusOutput, KindleOutput, iPadOutput,
iPad3Output, KoboReaderOutput, TabletOutput, SamsungGalaxy,
SonyReaderLandscapeOutput, KindleDXOutput, IlliadOutput, NookHD,
IRexDR1000Output, IRexDR800Output, JetBook5Output, NookOutput,
NookColorOutput, PocketBook900Output,
PocketBookPro912Output, GenericEink, GenericEinkLarge, GenericEinkHD,
KindleFireOutput, KindlePaperWhiteOutput, KindleVoyageOutput,
KindlePaperWhite3Output
]
output_profiles.sort(cmp=lambda x,y:cmp(x.name.lower(), y.name.lower()))<|fim▁end|> | fbase = 12
fsizes = [7.5, 9, 10, 12, 15.5, 20, 22, 24]
unsupported_unicode_chars = [u'\u201f', u'\u201b'] |
<|file_name|>node.hpp<|end_file_name|><|fim▁begin|>// -*- C++ -*-
// Copyright (C) 2005, 2006 Free Software Foundation, Inc.
//
// This file is part of the GNU ISO C++ Library. This library 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, or (at your option) any later
// version.
// This library is distributed in the hope that it will be useful, but
// WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// General Public License for more details.
// You should have received a copy of the GNU General Public License
// along with this library; see the file COPYING. If not, write to
// the Free Software Foundation, 59 Temple Place - Suite 330, Boston,
// MA 02111-1307, USA.<|fim▁hole|>
// As a special exception, you may use this file as part of a free
// software library without restriction. Specifically, if other files
// instantiate templates or use macros or inline functions from this
// file, or you compile this file and link it with other files to
// produce an executable, this file does not by itself cause the
// resulting executable to be covered by the GNU General Public
// License. This exception does not however invalidate any other
// reasons why the executable file might be covered by the GNU General
// Public License.
// Copyright (C) 2004 Ami Tavory and Vladimir Dreizin, IBM-HRL.
// Permission to use, copy, modify, sell, and distribute this software
// is hereby granted without fee, provided that the above copyright
// notice appears in all copies, and that both that copyright notice
// and this permission notice appear in supporting documentation. None
// of the above authors, nor IBM Haifa Research Laboratories, make any
// representation about the suitability of this software for any
// purpose. It is provided "as is" without express or implied
// warranty.
/**
* @file node.hpp
* Contains an implementation struct for splay_tree_'s node.
*/
#ifndef PB_DS_SPLAY_TREE_NODE_HPP
#define PB_DS_SPLAY_TREE_NODE_HPP
namespace __gnu_pbds
{
namespace detail
{
template<typename Value_Type, class Metadata, class Allocator>
struct splay_tree_node_
{
public:
typedef Value_Type value_type;
typedef Metadata metadata_type;
typedef
typename Allocator::template rebind<
splay_tree_node_<Value_Type, Metadata, Allocator> >::other::pointer
node_pointer;
typedef
typename Allocator::template rebind<metadata_type>::other::reference
metadata_reference;
typedef
typename Allocator::template rebind<metadata_type>::other::const_reference
const_metadata_reference;
#ifdef PB_DS_BIN_SEARCH_TREE_TRACE_
void
trace() const
{ std::cout << PB_DS_V2F(m_value) << "(" << m_metadata << ")"; }
#endif
inline bool
special() const
{ return m_special; }
inline const_metadata_reference
get_metadata() const
{ return m_metadata; }
inline metadata_reference
get_metadata()
{ return m_metadata; }
value_type m_value;
bool m_special;
node_pointer m_p_left;
node_pointer m_p_right;
node_pointer m_p_parent;
metadata_type m_metadata;
};
template<typename Value_Type, typename Allocator>
struct splay_tree_node_<Value_Type, null_node_metadata, Allocator>
{
public:
typedef Value_Type value_type;
typedef null_node_metadata metadata_type;
typedef
typename Allocator::template rebind<
splay_tree_node_<Value_Type, null_node_metadata, Allocator> >::other::pointer
node_pointer;
inline bool
special() const
{ return m_special; }
#ifdef PB_DS_BIN_SEARCH_TREE_TRACE_
void
trace() const
{ std::cout << PB_DS_V2F(m_value); }
#endif
node_pointer m_p_left;
node_pointer m_p_right;
node_pointer m_p_parent;
value_type m_value;
bool m_special;
};
} // namespace detail
} // namespace __gnu_pbds
#endif<|fim▁end|> | |
<|file_name|>search-context.service.ts<|end_file_name|><|fim▁begin|>import { Injectable } from '@angular/core';
import { Router} from '@angular/router';
import { Store, ActionReducer, Action} from '@ngrx/store';
import { Observable } from 'rxjs/Rx';
const initSearchContext: any = {
q: null,
i: 1,<|fim▁hole|> sortId: 0
};
export const searchContext: ActionReducer<any> = (state: any = initSearchContext, action: Action) => {
switch (action.type) {
case 'SEARCHCONTEXT.CREATE':
return Object.assign({}, action.payload);
case 'SEARCHCONTEXT.UDPATE':
return Object.assign({}, state, action.payload);
case 'SEARCHCONTEXT.RESET':
return Object.assign({}, initSearchContext);
case 'SEARCHCONTEXT.REMOVE':
return Object.assign({}, Object.keys(state).reduce((result: any, key: any) => {
if (key !== action.payload) result[key] = state[key];
return result;
}, {}));
default:
return state;
}
};
@Injectable()
export class SearchContext {
public data: Observable<any>;
constructor(public router: Router, public store: Store<any>) {
this.data = this.store.select('searchContext');
}
public new(params: Object): void {
this.create = params;
this.go();
}
public get state(): any {
let s: any;
this.data.take(1).subscribe(state => s = state);
return s;
}
public set remove(param: any) {
this.store.dispatch({ type: 'SEARCHCONTEXT.REMOVE', payload: param });
}
public set update(params: any) {
this.store.dispatch({ type: 'SEARCHCONTEXT.UDPATE', payload: this.decodeParams(params) });
}
public set create(params: any) {
this.store.dispatch({ type: 'SEARCHCONTEXT.CREATE', payload: this.decodeParams(params) });
}
public go(): void {
this.router.navigate(['/search', this.state]);
}
private decodeParams(params: any) {
let decodedParams: any = {};
let d: any = JSON.parse(JSON.stringify(params));
for (let param in d) {
if (d[param] === '' || params[param] === 'true') {
delete d[param];
return d;
}
decodedParams[param] = decodeURIComponent(params[param]);
}
return decodedParams;
}
}<|fim▁end|> | n: 100, |
<|file_name|>provider.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python2.5
"""A test provider for the stress testing."""
# change registry this often [msec]
registryChangeTimeout = 2017
from ContextKit.flexiprovider import *
import gobject
import time<|fim▁hole|> t = time.time()
dt = int(1000*(t - round(t)))
gobject.timeout_add(1000 - dt, update)
v = int(round(t))
fp.set('test.int', v)
fp.set('test.int2', v)
print t
return False
pcnt = 0
def chgRegistry():
global pcnt
pcnt += 1
if pcnt % 2:
print "1 provider"
os.system('cp 1provider.cdb tmp.cdb; mv tmp.cdb cache.cdb')
else:
print "2 providers"
os.system('cp 2providers.cdb tmp.cdb; mv tmp.cdb cache.cdb')
return True
gobject.timeout_add(1000, update)
# uncoment this to see the "Bus error" XXX
gobject.timeout_add(registryChangeTimeout, chgRegistry)
fp = Flexiprovider([INT('test.int'), INT('test.int2')], 'my.test.provider', 'session')
fp.run()<|fim▁end|> | import os
def update(): |
<|file_name|>BaselineSelection.cc<|end_file_name|><|fim▁begin|>//# BaselineSelection.cc: Class to handle the baseline selection
//# Copyright (C) 2012
//# ASTRON (Netherlands Institute for Radio Astronomy)
//# P.O.Box 2, 7990 AA Dwingeloo, The Netherlands
//#
//# This file is part of the LOFAR software suite.
//# The LOFAR software suite 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.
//#
//# The LOFAR software suite 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 the LOFAR software suite. If not, see <http://www.gnu.org/licenses/>.
//#
//# $Id$
//#
//# @author Ger van Diepen
#include <lofar_config.h>
#include <DPPP/BaselineSelection.h>
#include <DPPP/DPLogger.h>
#include <MS/BaselineSelect.h>
#include <Common/ParameterSet.h>
#include <Common/ParameterValue.h>
#include <Common/LofarLogger.h>
#include <Common/StreamUtil.h>
using namespace casa;
using namespace std;
namespace LOFAR {
namespace DPPP {
BaselineSelection::BaselineSelection()
{}
BaselineSelection::BaselineSelection (const ParameterSet& parset,
const string& prefix,
bool minmax,
const string& defaultCorrType,
const string& defaultBaseline)
: itsStrBL (parset.getString (prefix + "baseline", defaultBaseline)),
itsCorrType (parset.getString (prefix + "corrtype", defaultCorrType)),
itsRangeBL (parset.getDoubleVector (prefix + "blrange",
vector<double>()))
{
if (minmax) {
double minbl = parset.getDouble (prefix + "blmin", -1);
double maxbl = parset.getDouble (prefix + "blmax", -1);
if (minbl > 0) {
itsRangeBL.push_back (0.);
itsRangeBL.push_back (minbl);
}
if (maxbl > 0) {
itsRangeBL.push_back (maxbl);
itsRangeBL.push_back (1e30);
}
}
ASSERTSTR (itsRangeBL.size()%2 == 0,
"NDPPP error: uneven number of lengths in baseline range");
}
bool BaselineSelection::hasSelection() const
{
return !((itsStrBL.empty() || itsStrBL == "[]") &&
itsCorrType.empty() && itsRangeBL.empty());
}
void BaselineSelection::show (ostream& os, const string& blanks) const
{
os << " Baseline selection:" << std::endl;
os << " baseline: " << blanks << itsStrBL << std::endl;
os << " corrtype: " << blanks << itsCorrType << std::endl;
os << " blrange: " << blanks << itsRangeBL << std::endl;
}
Matrix<bool> BaselineSelection::apply (const DPInfo& info) const
{
// Size and initialize the selection matrix.
int nant = info.antennaNames().size();
Matrix<bool> selectBL(nant, nant, true);
// Apply the various parts if given.
if (! itsStrBL.empty() && itsStrBL != "[]") {
handleBL (selectBL, info);
}
if (! itsCorrType.empty()) {<|fim▁hole|> handleLength (selectBL, info);
}
return selectBL;
}
Vector<bool> BaselineSelection::applyVec (const DPInfo& info) const
{
Matrix<bool> sel = apply(info);
Vector<bool> vec;
vec.resize (info.nbaselines());
for (uint i=0; i<info.nbaselines(); ++i) {
vec[i] = sel(info.getAnt1()[i], info.getAnt2()[i]);
}
return vec;
}
void BaselineSelection::handleBL (Matrix<bool>& selectBL,
const DPInfo& info) const
{
// Handle the value(s) in the baseline selection string.
ParameterValue pvBL(itsStrBL);
// The value can be a vector or an MSSelection string.
// Alas the ParameterValue vector test cannot be used, because
// the first character of a MSSelection string can also be [.
// So if the first is [ and a ] is found before the end and before
// another [, it must be a MSSelection string.
bool mssel = true;
if (itsStrBL[0] == '[') {
String::size_type rb = itsStrBL.find (']');
ASSERTSTR (rb != string::npos,
"Baseline selection " + itsStrBL +
" has no ending ]");
if (rb == itsStrBL.size()-1) {
mssel = false;
} else {
String::size_type lb = itsStrBL.find ('[', 1);
mssel = (lb == string::npos || lb > rb);
}
}
if (!mssel) {
// Specified as a vector of antenna name patterns.
selectBL = selectBL && handleBLVector (pvBL, info.antennaNames());
} else {
// Specified in casacore's MSSelection format.
string msName = info.msName();
ASSERT (! msName.empty());
Matrix<bool> sel(BaselineSelect::convert (msName, itsStrBL));
// The resulting matrix can be smaller because new stations might have
// been added that are not present in the MS's ANTENNA table.
if (sel.nrow() == selectBL.nrow()) {
selectBL = selectBL && sel;
} else {
// Only and the subset.
Matrix<bool> selBL = selectBL(IPosition(2,0),
IPosition(2,sel.nrow()-1));
selBL = selBL && sel;
}
}
}
Matrix<bool> BaselineSelection::handleBLVector (const ParameterValue& pvBL,
const Vector<String>& antNames) const
{
Matrix<Bool> sel(antNames.size(), antNames.size());
sel = false;
vector<ParameterValue> pairs = pvBL.getVector();
// Each ParameterValue can be a single value (antenna) or a pair of
// values (a baseline).
// Note that [ant1,ant2] is somewhat ambiguous; it means two antennae,
// but one might think it means a baseline [[ant1,ant2]].
if (pairs.size() == 2 &&
!(pairs[0].isVector() || pairs[1].isVector())) {
LOG_WARN_STR ("PreFlagger baseline " << pvBL.get()
<< " means two antennae, but is somewhat ambigious; "
<< "it's more clear to use [[ant1],[ant2]]");
}
for (uint i=0; i<pairs.size(); ++i) {
vector<string> bl = pairs[i].getStringVector();
if (bl.size() == 1) {
// Turn the given antenna name pattern into a regex.
Regex regex(Regex::fromPattern (bl[0]));
int nmatch = 0;
// Loop through all antenna names and set matrix for matching ones.
for (uint i2=0; i2<antNames.size(); ++i2) {
if (antNames[i2].matches (regex)) {
nmatch++;
// Antenna matches, so set all corresponding flags.
for (uint j=0; j<antNames.size(); ++j) {
sel(i2,j) = true;
sel(j,i2) = true;
}
}
}
if (nmatch == 0) {
DPLOG_WARN_STR ("PreFlagger: no matches for antenna name pattern ["
<< bl[0] << "]");
}
} else {
ASSERTSTR (bl.size() == 2, "PreFlagger baseline " << bl <<
" should contain 1 or 2 antenna name patterns");
// Turn the given antenna name pattern into a regex.
Regex regex1(Regex::fromPattern (bl[0]));
Regex regex2(Regex::fromPattern (bl[1]));
int nmatch = 0;
// Loop through all antenna names and set matrix for matching ones.
for (uint i2=0; i2<antNames.size(); ++i2) {
if (antNames[i2].matches (regex2)) {
// Antenna2 matches, now try Antenna1.
for (uint i1=0; i1<antNames.size(); ++i1) {
if (antNames[i1].matches (regex1)) {
nmatch++;
sel(i1,i2) = true;
sel(i2,i1) = true;
}
}
}
}
if (nmatch == 0) {
DPLOG_WARN_STR ("PreFlagger: no matches for baseline name pattern ["
<< bl[0] << ',' << bl[1] << "]");
}
}
}
return sel;
}
void BaselineSelection::handleCorrType (Matrix<bool>& selectBL) const
{
// Process corrtype if given.
string corrType = toLower(itsCorrType);
ASSERTSTR (corrType == "auto" || corrType == "cross",
"NDPPP corrType " << corrType
<< " is invalid; must be auto, cross, or empty string");
if (corrType == "auto") {
Vector<bool> diag = selectBL.diagonal().copy();
selectBL = false;
selectBL.diagonal() = diag;
} else {
selectBL.diagonal() = false;
}
}
void BaselineSelection::handleLength (Matrix<bool>& selectBL,
const DPInfo& info) const
{
// Get baseline lengths.
const vector<double>& blength = info.getBaselineLengths();
const Vector<Int>& ant1 = info.getAnt1();
const Vector<Int>& ant2 = info.getAnt2();
for (uint i=0; i<ant1.size(); ++i) {
// Clear selection if no range matches.
bool match = false;
for (uint j=0; j<itsRangeBL.size(); j+=2) {
if (blength[i] >= itsRangeBL[j] && blength[i] <= itsRangeBL[j+1]) {
match = true;
break;
}
}
if (!match) {
int a1 = ant1[i];
int a2 = ant2[i];
selectBL(a1,a2) = false;
selectBL(a2,a1) = false;
}
}
}
} //# end namespace
}<|fim▁end|> | handleCorrType (selectBL);
}
if (! itsRangeBL.empty()) { |
<|file_name|>raw.py<|end_file_name|><|fim▁begin|>"""
Export to RAW/RPL file format
Based on:
http://www.nist.gov/lispix/doc/image-file-formats/raw-file-format.htm
"""
# Standard library modules.
import os
# Third party modules.
# Local modules.
from pyhmsa.fileformat.exporter.exporter import _Exporter, _ExporterThread
from pyhmsa.spec.datum.analysislist import AnalysisList2D
from pyhmsa.spec.datum.imageraster import ImageRaster2D, ImageRaster2DSpectral
# Globals and constants variables.
class _ExporterRAWThread(_ExporterThread):
def _run(self, datafile, dirpath, *args, **kwargs):
basefilename = datafile.header.title or 'Untitled'
keys = set(datafile.data.findkeys(AnalysisList2D)) | \
set(datafile.data.findkeys(ImageRaster2D)) | \
set(datafile.data.findkeys(ImageRaster2DSpectral))
length = len(keys)
filepaths = []
for i, identifier in enumerate(keys):
datum = datafile.data[identifier]
self._update_status(i / length, 'Exporting %s' % identifier)
filename = basefilename + '_' + identifier
lines = self._create_rpl_lines(identifier, datum)
rpl_filepath = os.path.join(dirpath, filename + '.rpl')
with open(rpl_filepath, 'w') as fp:
fp.write('\n'.join(lines))
raw_filepath = os.path.join(dirpath, filename + '.raw')
with open(raw_filepath, 'wb') as fp:
datum = datum.copy()
datum.dtype.newbyteorder('<')
fp.write(datum.tobytes())
filepaths.append(raw_filepath)
return filepaths
def _create_rpl_lines(self, identifier, datum):
lines = []
lines.append('key\t%s' % identifier)
lines.append('offset\t0')
if isinstance(datum, ImageRaster2D):
width, height = datum.shape
depth = 1
record_by = 'dont-care'
elif isinstance(datum, ImageRaster2DSpectral):
width, height, depth = datum.shape
record_by = 'vector'
elif isinstance(datum, AnalysisList2D):
depth, width, height = datum.shape
record_by = 'image'
else:
raise IOError('Unkmown datum type')
lines.append('width\t%i' % width)
lines.append('height\t%i' % height)
lines.append('depth\t%i' % depth)
lines.append('record-by\t%s' % record_by)
dtype = datum.dtype
lines.append('data-length\t%i' % dtype.itemsize)
byteorder = 'little-endian' if dtype.itemsize > 1 else 'dont-care'
lines.append('byte-order\t%s' % byteorder)
if dtype.kind == 'f':
data_type = 'float'
elif dtype.kind == 'u':
data_type = 'unsigned'
else:
data_type = 'signed'
lines.append('data-type\t%s' % data_type)
return lines
class ExporterRAW(_Exporter):
def _create_thread(self, datafile, dirpath, *args, **kwargs):
return _ExporterRAWThread(datafile, dirpath)
def validate(self, datafile):
super().validate(datafile)
identifiers = set(datafile.data.findkeys(AnalysisList2D)) | \
set(datafile.data.findkeys(ImageRaster2D)) | \
set(datafile.data.findkeys(ImageRaster2DSpectral))
if not identifiers:<|fim▁hole|><|fim▁end|> | raise ValueError('Datafile must contain at least one ' + \
'AnalysisList2D, ImageRaster2D or ' + \
'ImageRaster2DSpectral datum') |
<|file_name|>HostOperationFailureException.ts<|end_file_name|><|fim▁begin|>/// <reference path="../../../node.d.ts" />
<|fim▁hole|>
import HttpServiceUnavailableException = require('../../errors/HttpServiceUnavailableException');
'use strict';
/**
* サービスが利用できません。サーバの操作に失敗しました。このエラーが繰り返し発生する場合は、メンテナンス情報、サポートサイトをご確認ください。
*/
class HostOperationFailureException extends HttpServiceUnavailableException {
/**
* @constructor
* @public
* @param {number} status
* @param {string} code=null
* @param {string} message=""
*/
constructor(status:number, code:string=null, message:string="") {
super(status, code, message == null || message == "" ? "サービスが利用できません。サーバの操作に失敗しました。このエラーが繰り返し発生する場合は、メンテナンス情報、サポートサイトをご確認ください。" : message);
}
}<|fim▁end|> | export = HostOperationFailureException; |
<|file_name|>configuration.rs<|end_file_name|><|fim▁begin|>use clingo::*;
use std::env;
fn print_prefix(depth: u8) {
println!();
for _ in 0..depth {
print!(" ");
}
}
// recursively print the configuartion object
fn print_configuration(conf: &Configuration, key: Id, depth: u8) {
// get the type of an entry and switch over its various values
let configuration_type = conf.configuration_type(key).unwrap();
match configuration_type {
// print values
ConfigurationType::VALUE => {
let value = conf
.value_get(key)
.expect("Failed to retrieve statistics value.");
println!("{}", value);
}
// print arrays
ConfigurationType::ARRAY => {
// loop over array elements
let size = conf
.array_size(key)
.expect("Failed to retrieve statistics array size.");
for i in 0..size {
// print array offset (with prefix for readability)
let subkey = conf
.array_at(key, i)
.expect("Failed to retrieve statistics array.");
print_prefix(depth);
print!("{}:", i);
// recursively print subentry
print_configuration(conf, subkey, depth + 1);<|fim▁hole|>
// print maps
ConfigurationType::MAP => {
// loop over map elements
let size = conf.map_size(key).unwrap();
for i in 0..size {
// get and print map name (with prefix for readability)
let name = conf.map_subkey_name(key, i).unwrap();
let subkey = conf.map_at(key, name).unwrap();
print_prefix(depth);
print!("{}:", name);
// recursively print subentry
print_configuration(conf, subkey, depth + 1);
}
}
// this case won't occur if the configuration are traversed like this
_ => {
let bla = conf.value_get(key).unwrap();
print!(" {}", bla);
// println!("Unknown ConfigurationType");
}
}
}
fn print_model(model: &Model) {
// retrieve the symbols in the model
let atoms = model
.symbols(ShowType::SHOWN)
.expect("Failed to retrieve symbols in the model.");
print!("Model:");
for atom in atoms {
// retrieve and print the symbol's string
print!(" {}", atom.to_string().unwrap());
}
println!();
}
fn solve(ctl: &mut Control) {
// get a solve handle
let mut handle = ctl
.solve(SolveMode::YIELD, &[])
.expect("Failed retrieving solve handle.");
// loop over all models
loop {
handle.resume().expect("Failed resume on solve handle.");
match handle.model() {
// print the model
Ok(Some(model)) => print_model(model),
// stop if there are no more models
Ok(None) => break,
Err(e) => panic!("Error: {}", e),
}
}
// close the solve handle
handle
.get()
.expect("Failed to get result from solve handle.");
handle.close().expect("Failed to close solve handle.");
}
fn main() {
// collect clingo options from the command line
let options = env::args().skip(1).collect();
// create a control object and pass command line arguments
let mut ctl = Control::new(options).expect("Failed creating Control.");
{
// get the configuration object and its root key
let conf = ctl.configuration_mut().unwrap();
let root_key = conf.root().unwrap();
print_configuration(conf, root_key, 0);
let mut sub_key;
// configure to enumerate all models
sub_key = conf.map_at(root_key, "solve.models").unwrap();
conf.value_set(sub_key, "0")
.expect("Failed to set solve.models to 0.");
// configure the first solver to use the berkmin heuristic
sub_key = conf.map_at(root_key, "solver").unwrap();
sub_key = conf.array_at(sub_key, 0).unwrap();
sub_key = conf.map_at(sub_key, "heuristic").unwrap();
conf.value_set(sub_key, "berkmin")
.expect("Failed to set heuristic to berkmin.");
}
// note that the solver entry can be used both as an array and a map
// if used as a map, this simply sets the configuration of the first solver and
// is equivalent to the code above
// add a logic program to the base part
ctl.add("base", &[], "a :- not b. b :- not a.")
.expect("Failed to add a logic program.");
// ground the base part
let part = Part::new("base", &[]).unwrap();
let parts = vec![part];
ctl.ground(&parts)
.expect("Failed to ground a logic program.");
// solve
solve(&mut ctl);
}<|fim▁end|> | }
} |
<|file_name|>test06.java<|end_file_name|><|fim▁begin|>package com.fqc.jdk8;
import java.util.ArrayList;
import java.util.Arrays;<|fim▁hole|>import java.util.Set;
import java.util.stream.Collectors;
public class test06 {
public static void main(String[] args) {
int[] arr = {1, 2, 3, 4, 5};
ArrayList<Integer> list = Arrays.stream(arr).collect(ArrayList::new, ArrayList::add, ArrayList::addAll);
Set<Integer> set = list.stream().collect(Collectors.toSet());
System.out.println(set.contains(33));
ArrayList<User> users = new ArrayList<>();
for (int i = 0; i < 10; i++) {
users.add(new User("name:" + i));
}
Map<String, User> map = users.stream().collect(Collectors.toMap(u -> u.username, u -> u));
map.forEach((s, user) -> System.out.println(user.username));
}
}
class User {
String username;
public User(String username) {
this.username = username;
}
}<|fim▁end|> | import java.util.Map; |
<|file_name|>Frame-onPop-generators-01.js<|end_file_name|><|fim▁begin|>// |jit-test| error: StopIteration
// Returning {throw:} from an onPop handler when yielding works and
// does closes the generator-iterator.<|fim▁hole|>var dbg = new Debugger;
var gw = dbg.addDebuggee(g);
dbg.onDebuggerStatement = function handleDebugger(frame) {
frame.onPop = function (c) {
return {throw: "fit"};
};
};
g.eval("function g() { for (var i = 0; i < 10; i++) { debugger; yield i; } }");
g.eval("var it = g();");
var rv = gw.executeInGlobal("it.next();");
assertEq(rv.throw, "fit");
dbg.enabled = false;
g.it.next();<|fim▁end|> |
load(libdir + "asserts.js");
var g = newGlobal(); |
<|file_name|>placement_rule_test.go<|end_file_name|><|fim▁begin|>// Copyright 2020 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 (
"encoding/hex"
"encoding/json"
. "github.com/pingcap/check"
"github.com/pingcap/parser/ast"
"github.com/pingcap/tidb/ddl/placement"
"github.com/pingcap/tidb/tablecodec"
"github.com/pingcap/tidb/util/codec"
)
var _ = Suite(&testPlacementSuite{})
type testPlacementSuite struct {
}
func (s *testPlacementSuite) TestPlacementBuild(c *C) {
tests := []struct {
input []*ast.PlacementSpec
bundle *placement.Bundle
output []*placement.Rule
err string
}{
{
input: []*ast.PlacementSpec{},
output: []*placement.Rule{},
},
{
input: []*ast.PlacementSpec{{
Role: ast.PlacementRoleVoter,
Tp: ast.PlacementAdd,
Replicas: 3,
Constraints: `["+ zone=sh", "-zone = bj"]`,
}},
output: []*placement.Rule{
{
Role: placement.Voter,
Count: 3,
LabelConstraints: []placement.LabelConstraint{
{Key: "zone", Op: "in", Values: []string{"sh"}},
{Key: "zone", Op: "notIn", Values: []string{"bj"}},
},
},
},
},
{
input: []*ast.PlacementSpec{
{
Role: ast.PlacementRoleVoter,
Tp: ast.PlacementAdd,
Replicas: 3,
Constraints: `["+ zone=sh", "-zone = bj"]`,
},
{
Role: ast.PlacementRoleFollower,
Tp: ast.PlacementAdd,
Replicas: 2,
Constraints: `["- zone=sh", "+zone = bj"]`,
},<|fim▁hole|> Role: placement.Voter,
Count: 3,
LabelConstraints: []placement.LabelConstraint{
{Key: "zone", Op: "in", Values: []string{"sh"}},
{Key: "zone", Op: "notIn", Values: []string{"bj"}},
},
},
{
Role: placement.Follower,
Count: 2,
LabelConstraints: []placement.LabelConstraint{
{Key: "zone", Op: "notIn", Values: []string{"sh"}},
{Key: "zone", Op: "in", Values: []string{"bj"}},
},
},
},
},
{
input: []*ast.PlacementSpec{
{
Role: ast.PlacementRoleVoter,
Tp: ast.PlacementAdd,
Replicas: 3,
Constraints: `["+ zone=sh", "-zone = bj"]`,
},
{
Role: ast.PlacementRoleVoter,
Tp: ast.PlacementAlter,
Replicas: 2,
Constraints: `["- zone=sh", "+zone = bj"]`,
},
},
output: []*placement.Rule{
{
Role: placement.Voter,
Count: 2,
LabelConstraints: []placement.LabelConstraint{
{Key: "zone", Op: "notIn", Values: []string{"sh"}},
{Key: "zone", Op: "in", Values: []string{"bj"}},
},
},
},
},
{
input: []*ast.PlacementSpec{
{
Role: ast.PlacementRoleVoter,
Tp: ast.PlacementAdd,
Replicas: 3,
Constraints: `["+ zone=sh", "-zone = bj"]`,
},
{
Role: ast.PlacementRoleVoter,
Tp: ast.PlacementAlter,
Replicas: 3,
Constraints: `{"- zone=sh":1, "+zone = bj":1}`,
},
},
output: []*placement.Rule{
{
Role: placement.Voter,
Count: 1,
LabelConstraints: []placement.LabelConstraint{{Key: "zone", Op: "notIn", Values: []string{"sh"}}},
},
{
Role: placement.Voter,
Count: 1,
LabelConstraints: []placement.LabelConstraint{{Key: "zone", Op: "in", Values: []string{"bj"}}},
},
{
Role: placement.Voter,
Count: 1,
},
},
},
{
input: []*ast.PlacementSpec{
{
Role: ast.PlacementRoleVoter,
Tp: ast.PlacementAdd,
Replicas: 3,
Constraints: `["+ zone=sh", "-zone = bj"]`,
},
{
Role: ast.PlacementRoleVoter,
Tp: ast.PlacementDrop,
},
},
output: []*placement.Rule{},
},
{
input: []*ast.PlacementSpec{
{
Role: ast.PlacementRoleLearner,
Tp: ast.PlacementDrop,
},
{
Role: ast.PlacementRoleVoter,
Tp: ast.PlacementDrop,
},
},
bundle: &placement.Bundle{Rules: []*placement.Rule{
{Role: placement.Learner},
{Role: placement.Voter},
{Role: placement.Learner},
{Role: placement.Voter},
}},
output: []*placement.Rule{},
},
{
input: []*ast.PlacementSpec{
{
Role: ast.PlacementRoleLearner,
Tp: ast.PlacementAdd,
Replicas: 3,
Constraints: `["+ zone=sh", "-zone = bj"]`,
},
{
Role: ast.PlacementRoleVoter,
Tp: ast.PlacementDrop,
},
},
output: []*placement.Rule{
{
Role: placement.Learner,
Count: 3,
LabelConstraints: []placement.LabelConstraint{
{Key: "zone", Op: "in", Values: []string{"sh"}},
{Key: "zone", Op: "notIn", Values: []string{"bj"}},
},
},
},
},
}
for i, t := range tests {
var bundle *placement.Bundle
if t.bundle == nil {
bundle = &placement.Bundle{Rules: []*placement.Rule{}}
} else {
bundle = t.bundle
}
out, err := buildPlacementSpecs(bundle, t.input)
if err == nil {
expected, err := json.Marshal(t.output)
c.Assert(err, IsNil)
got, err := json.Marshal(out.Rules)
c.Assert(err, IsNil)
c.Assert(len(t.output), Equals, len(out.Rules))
for _, r1 := range t.output {
found := false
for _, r2 := range out.Rules {
if ok, _ := DeepEquals.Check([]interface{}{r1, r2}, nil); ok {
found = true
break
}
}
c.Assert(found, IsTrue, Commentf("%d test\nexpected %s\nbut got %s", i, expected, got))
}
} else {
c.Assert(err.Error(), ErrorMatches, t.err)
}
}
}
func (s *testPlacementSuite) TestPlacementBuildDrop(c *C) {
tests := []struct {
input int64
output *placement.Bundle
}{
{
input: 2,
output: &placement.Bundle{ID: placement.GroupID(2)},
},
{
input: 1,
output: &placement.Bundle{ID: placement.GroupID(1)},
},
}
for _, t := range tests {
out := placement.BuildPlacementDropBundle(t.input)
c.Assert(t.output, DeepEquals, out)
}
}
func (s *testPlacementSuite) TestPlacementBuildTruncate(c *C) {
bundle := &placement.Bundle{
ID: placement.GroupID(-1),
Rules: []*placement.Rule{{GroupID: placement.GroupID(-1)}},
}
tests := []struct {
input int64
output *placement.Bundle
}{
{
input: 1,
output: &placement.Bundle{
ID: placement.GroupID(1),
Rules: []*placement.Rule{{
GroupID: placement.GroupID(1),
StartKeyHex: hex.EncodeToString(codec.EncodeBytes(nil, tablecodec.GenTablePrefix(1))),
EndKeyHex: hex.EncodeToString(codec.EncodeBytes(nil, tablecodec.GenTablePrefix(2))),
}},
},
},
{
input: 2,
output: &placement.Bundle{
ID: placement.GroupID(2),
Rules: []*placement.Rule{{
GroupID: placement.GroupID(2),
StartKeyHex: hex.EncodeToString(codec.EncodeBytes(nil, tablecodec.GenTablePrefix(2))),
EndKeyHex: hex.EncodeToString(codec.EncodeBytes(nil, tablecodec.GenTablePrefix(3))),
}},
},
},
}
for _, t := range tests {
out := placement.BuildPlacementCopyBundle(bundle, t.input)
c.Assert(t.output, DeepEquals, out)
c.Assert(bundle.ID, Equals, placement.GroupID(-1))
c.Assert(bundle.Rules, HasLen, 1)
c.Assert(bundle.Rules[0].GroupID, Equals, placement.GroupID(-1))
}
}<|fim▁end|> | },
output: []*placement.Rule{
{ |
<|file_name|>Client.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python
# **********************************************************************
#
# Copyright (c) 2003-2011 ZeroC, Inc. All rights reserved.
#<|fim▁hole|># ICE_LICENSE file included in this distribution.
#
# **********************************************************************
import os, sys, traceback
import Ice, AllTests
def test(b):
if not b:
raise RuntimeError('test assertion failed')
def usage(n):
sys.stderr.write("Usage: " + n + " port...\n")
def run(args, communicator):
ports = []
for arg in args[1:]:
if arg[0] == '-':
sys.stderr.write(args[0] + ": unknown option `" + arg + "'\n")
usage(args[0])
return False
ports.append(int(arg))
if len(ports) == 0:
sys.stderr.write(args[0] + ": no ports specified\n")
usage(args[0])
return False
try:
AllTests.allTests(communicator, ports)
except:
traceback.print_exc()
test(False)
return True
try:
initData = Ice.InitializationData()
initData.properties = Ice.createProperties(sys.argv)
#
# This test aborts servers, so we don't want warnings.
#
initData.properties.setProperty('Ice.Warn.Connections', '0')
communicator = Ice.initialize(sys.argv, initData)
status = run(sys.argv, communicator)
except:
traceback.print_exc()
status = False
if communicator:
try:
communicator.destroy()
except:
traceback.print_exc()
status = False
sys.exit(not status)<|fim▁end|> | # This copy of Ice is licensed to you under the terms described in the |
<|file_name|>dashboard_apis.go<|end_file_name|><|fim▁begin|>// Copyright 2014 Wandoujia Inc. All Rights Reserved.
// Licensed under the MIT (MIT-LICENSE.txt) license.
package main
import (
"encoding/json"
"fmt"
"net/http"
"strconv"
"time"
"github.com/go-martini/martini"
"github.com/wandoulabs/go-zookeeper/zk"
"github.com/wandoulabs/zkhelper"
"github.com/wandoulabs/codis/pkg/models"
"github.com/wandoulabs/codis/pkg/utils"
"github.com/wandoulabs/codis/pkg/utils/log"
)
var globalMigrateManager *MigrateManager
type RangeSetTask struct {
FromSlot int `json:"from"`
ToSlot int `json:"to"`
NewGroupId int `json:"new_group"`
Status string `json:"status"`
}
func apiGetProxyDebugVars() (int, string) {
m := getAllProxyDebugVars()
if m == nil {
return 500, "Error getting proxy debug vars"
}
b, err := json.MarshalIndent(m, " ", " ")
if err != nil {
log.WarnErrorf(err, "to json failed")
return 500, err.Error()
}
return 200, string(b)
}
func apiOverview() (int, string) {
// get all server groups
groups, err := models.ServerGroups(unsafeZkConn, globalEnv.ProductName())
if err != nil && !zkhelper.ZkErrorEqual(err, zk.ErrNoNode) {
return 500, err.Error()
}
var instances []string
for _, group := range groups {
for _, srv := range group.Servers {
if srv.Type == "master" {
instances = append(instances, srv.Addr)
}
}
}
info := make(map[string]interface{})
info["product"] = globalEnv.ProductName()
info["ops"] = proxiesSpeed
redisInfos := make([]map[string]string, 0)
if len(instances) > 0 {
for _, instance := range instances {
info, err := utils.GetRedisStat(instance, globalEnv.Password())
if err != nil {
log.ErrorErrorf(err, "get redis stat failed")
}
redisInfos = append(redisInfos, info)
}
}
info["redis_infos"] = redisInfos
b, err := json.MarshalIndent(info, " ", " ")
return 200, string(b)
}
func apiGetServerGroupList() (int, string) {
groups, err := models.ServerGroups(safeZkConn, globalEnv.ProductName())
if err != nil {
log.ErrorErrorf(err, "get server groups failed")
return 500, err.Error()
}
b, err := json.MarshalIndent(groups, " ", " ")
return 200, string(b)
}
func apiInitSlots(r *http.Request) (int, string) {
r.ParseForm()
isForce := false
val := r.FormValue("is_force")
if len(val) > 0 && (val == "1" || val == "true") {
isForce = true
}
if !isForce {
s, _ := models.Slots(safeZkConn, globalEnv.ProductName())
if len(s) > 0 {
return 500, "slots already initialized, you may use 'is_force' flag and try again."
}
}
if err := models.InitSlotSet(safeZkConn, globalEnv.ProductName(), models.DEFAULT_SLOT_NUM); err != nil {
log.ErrorErrorf(err, "init slot set failed")
return 500, err.Error()
}
return jsonRetSucc()
}
func apiRedisStat(param martini.Params) (int, string) {
addr := param["addr"]
info, err := utils.GetRedisStat(addr, globalEnv.Password())
if err != nil {
return 500, err.Error()
}
b, _ := json.MarshalIndent(info, " ", " ")
return 200, string(b)
}
type migrateTaskForm struct {
From int `json:"from"`
To int `json:"to"`
Group int `json:"new_group"`
Delay int `json:"delay"`
}
func apiDoMigrate(form migrateTaskForm) (int, string) {
for i := form.From; i <= form.To; i++ {
task := MigrateTaskInfo{
SlotId: i,
Delay: form.Delay,
NewGroupId: form.Group,
Status: MIGRATE_TASK_PENDING,
CreateAt: strconv.FormatInt(time.Now().Unix(), 10),
}
globalMigrateManager.PostTask(&task)
}
// do migrate async
return jsonRetSucc()
}
func apiRebalance(param martini.Params) (int, string) {
if len(globalMigrateManager.Tasks()) > 0 {
return 500, "there are migration tasks running, you should wait them done"
}
if err := Rebalance(); err != nil {
log.ErrorErrorf(err, "rebalance failed")
return 500, err.Error()
}
return jsonRetSucc()
}
func apiGetMigrateTasks() (int, string) {
tasks := globalMigrateManager.Tasks()
b, _ := json.MarshalIndent(tasks, " ", " ")
return 200, string(b)
}
func apiGetServerGroup(param martini.Params) (int, string) {
id := param["id"]
groupId, err := strconv.Atoi(id)
if err != nil {
log.ErrorErrorf(err, "parse groupid failed")
return 500, err.Error()
}
group, err := models.GetGroup(safeZkConn, globalEnv.ProductName(), groupId)
if err != nil {
log.ErrorErrorf(err, "get group %d failed", groupId)
return 500, err.Error()
}
b, err := json.MarshalIndent(group, " ", " ")
return 200, string(b)
}
func apiMigrateStatus() (int, string) {
migrateSlots, err := models.GetMigratingSlots(safeZkConn, globalEnv.ProductName())
if err != nil && !zkhelper.ZkErrorEqual(err, zk.ErrNoNode) {
return 500, err.Error()
}
b, err := json.MarshalIndent(map[string]interface{}{
"migrate_slots": migrateSlots,
"migrate_task": globalMigrateManager.runningTask,
}, " ", " ")
return 200, string(b)
}
func apiGetRedisSlotInfo(param martini.Params) (int, string) {
addr := param["addr"]
slotId, err := strconv.Atoi(param["id"])
if err != nil {
log.ErrorErrorf(err, "parse slotid failed")
return 500, err.Error()
}
slotInfo, err := utils.SlotsInfo(addr, globalEnv.Password(), slotId, slotId)
if err != nil {
log.ErrorErrorf(err, "get slot info %d failed", slotId)
return 500, err.Error()
}
out, _ := json.MarshalIndent(map[string]interface{}{
"keys": slotInfo[slotId],
"slot_id": slotId,
}, " ", " ")
return 200, string(out)
}
func apiGetRedisSlotInfoFromGroupId(param martini.Params) (int, string) {
groupId, err := strconv.Atoi(param["group_id"])
if err != nil {
log.ErrorErrorf(err, "parse groupid failed")
return 500, err.Error()
}
slotId, err := strconv.Atoi(param["slot_id"])
if err != nil {
log.ErrorErrorf(err, "parse slotid failed")
return 500, err.Error()
}
g, err := models.GetGroup(safeZkConn, globalEnv.ProductName(), groupId)
if err != nil {
log.ErrorErrorf(err, "get group %d failed", groupId)
return 500, err.Error()
}
s, err := g.Master(safeZkConn)
if err != nil {
log.ErrorErrorf(err, "get master of group %d failed", groupId)
return 500, err.Error()
}
if s == nil {
return 500, "master not found"
}
slotInfo, err := utils.SlotsInfo(s.Addr, globalEnv.Password(), slotId, slotId)
if err != nil {
log.ErrorErrorf(err, "get slot info %d failed", slotId)
return 500, err.Error()
}
out, _ := json.MarshalIndent(map[string]interface{}{
"keys": slotInfo[slotId],
"slot_id": slotId,
"group_id": groupId,
"addr": s.Addr,
}, " ", " ")
return 200, string(out)
}
func apiRemoveServerGroup(param martini.Params) (int, string) {
lock := utils.GetZkLock(safeZkConn, globalEnv.ProductName())
lock.Lock(fmt.Sprintf("removing group %s", param["id"]))
defer func() {
err := lock.Unlock()
if err != nil {
log.ErrorErrorf(err, "unlock node failed")
}
}()
groupId, _ := strconv.Atoi(param["id"])
serverGroup := models.NewServerGroup(globalEnv.ProductName(), groupId)
if err := serverGroup.Remove(safeZkConn); err != nil {
log.ErrorErrorf(err, "remove server group failed")
return 500, err.Error()
}
return jsonRetSucc()
}
// create new server group
func apiAddServerGroup(newGroup models.ServerGroup) (int, string) {
lock := utils.GetZkLock(safeZkConn, globalEnv.ProductName())
lock.Lock(fmt.Sprintf("add group %+v", newGroup))
defer func() {
err := lock.Unlock()
if err != nil {
log.ErrorErrorf(err, "unlock node failed")
}
}()
newGroup.ProductName = globalEnv.ProductName()
exists, err := newGroup.Exists(safeZkConn)
if err != nil {
log.ErrorErrorf(err, "check group exits failed")
return 500, err.Error()
}
if exists {
return 500, "group already exists"
}
err = newGroup.Create(safeZkConn)
if err != nil {
log.ErrorErrorf(err, "create node for new group failed")
return 500, err.Error()
}
return jsonRetSucc()
}
// add redis server to exist server group
func apiAddServerToGroup(server models.Server, param martini.Params) (int, string) {
groupId, _ := strconv.Atoi(param["id"])
lock := utils.GetZkLock(safeZkConn, globalEnv.ProductName())
lock.Lock(fmt.Sprintf("add server to group, %+v", server))
defer func() {
err := lock.Unlock()
if err != nil {
log.ErrorErrorf(err, "unlock node failed")
}
}()
// check group exists first
serverGroup := models.NewServerGroup(globalEnv.ProductName(), groupId)
exists, err := serverGroup.Exists(safeZkConn)
if err != nil {
log.ErrorErrorf(err, "check group exits failed")
return 500, err.Error()
}
// create new group if not exists
if !exists {
if err := serverGroup.Create(safeZkConn); err != nil {
return 500, err.Error()
}
}
if err := serverGroup.AddServer(safeZkConn, &server, globalEnv.Password()); err != nil {
log.ErrorErrorf(err, "add server to group failed")
return 500, err.Error()
}
return jsonRetSucc()
}
func apiPromoteServer(server models.Server, param martini.Params) (int, string) {
lock := utils.GetZkLock(safeZkConn, globalEnv.ProductName())
lock.Lock(fmt.Sprintf("promote server %+v", server))
defer func() {
err := lock.Unlock()
if err != nil {
log.ErrorErrorf(err, "unlock node failed")
}
}()
group, err := models.GetGroup(safeZkConn, globalEnv.ProductName(), server.GroupId)
if err != nil {
log.ErrorErrorf(err, "get group %d failed", server.GroupId)
return 500, err.Error()
}
err = group.Promote(safeZkConn, server.Addr, globalEnv.Password())
if err != nil {
log.ErrorErrorf(err, "promote group %d failed", server.GroupId)
return 500, err.Error()
}
return jsonRetSucc()
}<|fim▁hole|> lock.Lock(fmt.Sprintf("removing server from group, %+v", server))
defer func() {
err := lock.Unlock()
if err != nil {
log.ErrorErrorf(err, "unlock node failed")
}
}()
serverGroup := models.NewServerGroup(globalEnv.ProductName(), groupId)
err := serverGroup.RemoveServer(safeZkConn, server.Addr)
if err != nil {
log.ErrorErrorf(err, "remove group %d failed", groupId)
return 500, err.Error()
}
return jsonRetSucc()
}
func apiSetProxyStatus(proxy models.ProxyInfo, param martini.Params) (int, string) {
err := models.SetProxyStatus(safeZkConn, globalEnv.ProductName(), proxy.Id, proxy.State)
if err != nil {
// if this proxy is not online, just return success
if proxy.State == models.PROXY_STATE_MARK_OFFLINE && zkhelper.ZkErrorEqual(err, zk.ErrNoNode) {
return jsonRetSucc()
}
log.ErrorErrorf(err, "set proxy states failed: %+v", proxy)
return 500, err.Error()
}
return jsonRetSucc()
}
func apiGetProxyList(param martini.Params) (int, string) {
proxies, err := models.ProxyList(safeZkConn, globalEnv.ProductName(), nil)
if err != nil {
log.ErrorErrorf(err, "get proxy list failed")
return 500, err.Error()
}
b, err := json.MarshalIndent(proxies, " ", " ")
return 200, string(b)
}
func apiGetSingleSlot(param martini.Params) (int, string) {
id, err := strconv.Atoi(param["id"])
if err != nil {
return 500, err.Error()
}
slot, err := models.GetSlot(safeZkConn, globalEnv.ProductName(), id)
if err != nil {
log.ErrorErrorf(err, "get slot %d failed", id)
return 500, err.Error()
}
b, err := json.MarshalIndent(slot, " ", " ")
return 200, string(b)
}
func apiGetSlots() (int, string) {
slots, err := models.Slots(safeZkConn, globalEnv.ProductName())
if err != nil {
log.ErrorErrorf(err, "Error getting slot info, try init slots first?")
return 500, err.Error()
}
b, err := json.MarshalIndent(slots, " ", " ")
return 200, string(b)
}
func apiSlotRangeSet(task RangeSetTask) (int, string) {
lock := utils.GetZkLock(safeZkConn, globalEnv.ProductName())
lock.Lock(fmt.Sprintf("set slot range, %+v", task))
defer func() {
err := lock.Unlock()
if err != nil {
log.ErrorErrorf(err, "unlock node failed")
}
}()
// default set online
if len(task.Status) == 0 {
task.Status = string(models.SLOT_STATUS_ONLINE)
}
err := models.SetSlotRange(safeZkConn, globalEnv.ProductName(), task.FromSlot, task.ToSlot, task.NewGroupId, models.SlotStatus(task.Status))
if err != nil {
log.ErrorErrorf(err, "set slot range [%d,%d] failed", task.FromSlot, task.ToSlot)
return 500, err.Error()
}
return jsonRetSucc()
}
// actions
func apiActionGC(r *http.Request) (int, string) {
r.ParseForm()
keep, _ := strconv.Atoi(r.FormValue("keep"))
secs, _ := strconv.Atoi(r.FormValue("secs"))
lock := utils.GetZkLock(safeZkConn, globalEnv.ProductName())
lock.Lock(fmt.Sprintf("action gc"))
defer func() {
err := lock.Unlock()
if err != nil {
log.ErrorErrorf(err, "unlock node failed")
}
}()
var err error
if keep >= 0 {
err = models.ActionGC(safeZkConn, globalEnv.ProductName(), models.GC_TYPE_N, keep)
} else if secs > 0 {
err = models.ActionGC(safeZkConn, globalEnv.ProductName(), models.GC_TYPE_SEC, secs)
}
if err != nil {
return 500, err.Error()
}
return jsonRetSucc()
}
func apiForceRemoveLocks() (int, string) {
err := models.ForceRemoveLock(safeZkConn, globalEnv.ProductName())
if err != nil {
log.ErrorErrorf(err, "force remove lock failed")
return 500, err.Error()
}
return jsonRetSucc()
}
func apiRemoveFence() (int, string) {
err := models.ForceRemoveDeadFence(safeZkConn, globalEnv.ProductName())
if err != nil {
log.ErrorErrorf(err, "force remove fence failed")
return 500, err.Error()
}
return jsonRetSucc()
}<|fim▁end|> |
func apiRemoveServerFromGroup(server models.Server, param martini.Params) (int, string) {
groupId, _ := strconv.Atoi(param["id"])
lock := utils.GetZkLock(safeZkConn, globalEnv.ProductName()) |
<|file_name|>MarcaVO.java<|end_file_name|><|fim▁begin|>package br.com.dlp.jazzav.produto;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import br.com.dlp.jazzav.AbstractLogEntityVO;
/**
*
* @author darcio
*
*/
@Entity
public class MarcaVO extends AbstractLogEntityVO<Long> {
private static final long serialVersionUID = 6715916803586893459L;<|fim▁hole|>
private String nome;
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Override
public Long getPK() {
return this.pk;
}
public String getNome() {
return nome;
}
public void setNome(String nome) {
this.nome = nome;
}
}<|fim▁end|> | |
<|file_name|>Cache.js<|end_file_name|><|fim▁begin|>/**
* An ES6 screeps game engine.
*
* An attempt to conquer screeps, the first MMO strategy sandbox
* game for programmers!
*
* @author Geert Hauwaerts <[email protected]>
* @copyright Copyright (c) Geert Hauwaerts
* @license MIT License
*/
/**
* Cache for static function results.
*/
export default class Cache {
/**
* Cache for static function results.
*
* @returns {void}
*/
constructor() {
this.cache = {};
}
/**
* Store or retrieve an entry from cache.
*
* @param {string} table The cache table.
* @param {string} key The entry to store or retrieve.
* @param {*} value The callback function.
* @param {*} ...args The callback function arguments.
* @returns {*}
*/
remember(table, key, callback, ...args) {
if (this.cache[table] === undefined) {
this.cache[table] = {};
}
let value = this.cache[table][key];
if (value === undefined) {
value = callback(args);<|fim▁hole|>
return value;
}
/**
* Remove an entry from cache.
*
* @param {string} table The cache table.
* @param {string} key The entry to remove.
* @returns {void}
*/
forget(table, key) {
delete this.cache[table][key];
}
}<|fim▁end|> | this.cache[table][key] = value;
} |
<|file_name|>interface.py<|end_file_name|><|fim▁begin|>import random
import json
from django.db import connection
from django.conf import settings
from sitemodel.interface import SiteInterface, SiteModel, random_str
from django.core.files import File
from server.models import Site, TextUpload, BinaryUpload
from sitemodel.frp.model import FRP_Category, FRP_Contact, FRP_Property, FRP_PropertyImage, FRP_SubProperty, FRP_SubPropertyImage
SITE_NAME = 'FisherRoelandProperty'
SITE_TOKEN = 'frp'
USER_EDITABLE_MODEL_NAMES = [ 'frp_contact', 'frp_property', 'frp_propertyimage', 'frp_subproperty', 'frp_subpropertyimage' ]
SITE_USER_NAMES = [ 'frpjenny', 'frpmelissa' ]
IMPORT_ROOT_LOCATION = settings.SITE_DATA_IMPORT_ROOT_FOLDER + SITE_TOKEN + '/'
def load_as_json(file_name):
path = IMPORT_ROOT_LOCATION + file_name
d = None
json_str = None
try:
with open(path, 'rt') as source_file:
json_str = source_file.read()
d = json.loads(json_str)
except Exception as e:
print('error loading JSON file @ {0}'.format(path))
print(e)
print(json_str)
raise e
return d
def populate_model_constants():
if len(FRP_Category.objects.all()) > 0:
return
# categories
categories = load_as_json('categories.json')
for category_name in categories['categories']:
if FRP_Category.objects.filter(name=category_name).exists():
continue
db_category = FRP_Category(name=category_name)
db_category.save()
def populate_datamodel():
import_root_location = settings.SITE_DATA_IMPORT_ROOT_FOLDER + SITE_TOKEN + '/'
# CONTACTS
#
if len(FRP_Contact.objects.all()) == 0:
contacts = load_as_json('contacts.json')
for i in range(len(contacts['contacts'])):
contact = contacts['contacts'][i]
print(contact)
db_contact = FRP_Contact(name=contact['name'],
email=contact['email'],
phone=contact['phone'],
isprimary=contact['isprimary'],
iscc=contact['iscc']
)
db_contact.save()
for category in contact['categories']:
db_category = FRP_Category.objects.get(name=category)
db_contact.categories.add(db_category)
db_contact.save()
# PROPERTIES BY CATEGORY
#
for category in FRP_Category.objects.all():
# PROPERTIES
try:
to_import = load_as_json(category.name + '.json')
except IOError as e:
continue
for prop in to_import['properties']:
db_property = FRP_Property(category=category, sold=False, name=prop['name'], areaSQM=prop['areaSQM'], description=prop['description'], shortLocation=prop['shortLocation'],longLocation=prop['longLocation'], latitude=prop['latitude'], longitude=prop['longitude'])
db_property.save()
for i in range(len(prop['images'])):
prop_image_file_name = prop['images'][i]<|fim▁hole|>
image_source_location = import_root_location + category.name + '/' + prop_image_file_name
db_property_image = FRP_PropertyImage(property=db_property)
image_source_django_file = None
with open(image_source_location) as image_source_python_file:
image_source_django_file = File(image_source_python_file)
db_property_image.file.save(prop_image_file_name, image_source_django_file)
if i == 0:
db_property_image.isprimary = True
db_property_image.save()
for j in range(len(prop['subproperties'])):
sub_prop = prop['subproperties'][j]
db_subproperty = FRP_SubProperty(property=db_property, name=sub_prop['name'], areaSQM=sub_prop['areaSQM'], description=sub_prop['description'])
db_subproperty.save()
if ('images' in sub_prop.keys()):
for k in range(len(sub_prop['images'])):
sub_prop_image_file_name = sub_prop['images'][k]
image_source_location = import_root_location + category.name + '/' + sub_prop_image_file_name
db_sub_property_image = FRP_SubPropertyImage(subproperty=db_subproperty)
image_source_django_file = None
with open(image_source_location) as image_source_python_file:
image_source_django_file = File(image_source_python_file)
db_sub_property_image.file.save(sub_prop_image_file_name, image_source_django_file)
if k == 0:
db_sub_property_image.isprimary = True
db_sub_property_image.save()
def render_site_model(site_token):
data_model = {}
db_text_uploads = []
db_binary_uploads = []
db_site = Site.objects.get(token=site_token)
# CONTACTS
#
data_model['contacts'] = []
for db_contact in FRP_Contact.objects.all():
contact = { 'name' : db_contact.name,
'phone' : db_contact.phone,
'email' : db_contact.email,
'categories' : [],
'isprimary' : db_contact.isprimary,
'iscc' : db_contact.iscc
}
for db_category in db_contact.categories.all():
contact['categories'].append(db_category.name)
data_model['contacts'].append(contact)
# PROPERTIES
#
data_model['properties'] = []
for db_prop in FRP_Property.objects.all():
property = { 'category' : db_prop.category.name,
'sold' : db_prop.sold,
'name': db_prop.name,
'areaSQM': db_prop.areaSQM,
'description': [],
'shortLocation': db_prop.shortLocation,
'longLocation': db_prop.longLocation,
'latitude': float(str(db_prop.latitude)) if db_prop.latitude is not None else None,
'longitude': float(str(db_prop.longitude)) if db_prop.longitude is not None else None,
'images' : [],
'subproperties' : []
}
# description
#
if db_prop.description is not None:
property['description'] = db_prop.description.split('\n')
db_images = FRP_PropertyImage.objects.filter(property=db_prop)
primary_db_images = [x for x in db_images if x.isprimary == True]
secondary_db_images = [x for x in db_images if x.isprimary == False]
ordered_db_images = []
ordered_db_images.extend(primary_db_images)
ordered_db_images.extend(secondary_db_images)
for db_image in ordered_db_images:
if (db_image.file.name is None) or (len(db_image.file.name) == 0):
continue
source = None
dest_path = None
source = settings.MEDIA_ROOT + '/' + db_image.file.name
dest_path = '/'.join(db_image.file.name.split('/')[1:])
db_binary_upload = BinaryUpload(source_path=source, destination_path=dest_path, site=db_site)
db_binary_uploads.append(db_binary_upload)
property['images'].append(dest_path)
# sub property
#
for db_sub_property in FRP_SubProperty.objects.filter(property=db_prop):
sub_property = { 'name' : db_sub_property.name,
'areaSQM' : db_sub_property.areaSQM,
'description' : [],
'sold' : db_sub_property.sold,
'images' : []
}
# description
#
if db_sub_property.description is not None:
sub_property['description'] = db_sub_property.description.split('\n')
db_images = FRP_SubPropertyImage.objects.filter(subproperty=db_sub_property)
primary_db_images = [x for x in db_images if x.isprimary == True]
secondary_db_images = [x for x in db_images if x.isprimary == False]
ordered_db_images = []
ordered_db_images.extend(primary_db_images)
ordered_db_images.extend(secondary_db_images)
for db_image in ordered_db_images:
if (db_image.file.name is None) or (len(db_image.file.name) == 0):
continue
source = None
dest_path = None
source = settings.MEDIA_ROOT + '/' + db_image.file.name
dest_path = '/'.join(db_image.file.name.split('/')[1:])
db_binary_upload = BinaryUpload(source_path=source, destination_path=dest_path, site=db_site)
db_binary_uploads.append(db_binary_upload)
# append sub-property images to main property image list
property['images'].append(dest_path)
sub_property['images'].append(dest_path)
property['subproperties'].append(sub_property)
data_model['properties'].append(property)
return SiteModel(data_model,
db_text_uploads=db_text_uploads,
db_binary_uploads=db_binary_uploads)
SiteInterface.register(
SITE_NAME,
SITE_TOKEN,
SITE_USER_NAMES,
USER_EDITABLE_MODEL_NAMES,
populate_model_constants,
render_site_model,
populate_datamodel
)<|fim▁end|> | |
<|file_name|>length.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/. */
//! [Length values][length].
//!
//! [length]: https://drafts.csswg.org/css-values/#lengths
use super::{AllowQuirks, Number, Percentage, ToComputedValue};
use crate::computed_value_flags::ComputedValueFlags;
use crate::font_metrics::{FontMetrics, FontMetricsOrientation};
use crate::parser::{Parse, ParserContext};
use crate::values::computed::{self, CSSPixelLength, Context};
use crate::values::generics::length as generics;
use crate::values::generics::length::{
GenericLengthOrNumber, GenericLengthPercentageOrNormal, GenericMaxSize, GenericSize,
};
use crate::values::generics::NonNegative;
use crate::values::specified::calc::CalcNode;
use crate::values::specified::NonNegativeNumber;
use crate::values::CSSFloat;
use crate::Zero;
use app_units::Au;
use cssparser::{Parser, Token};
use euclid::default::Size2D;
use std::cmp;
use std::ops::{Add, Mul};
use style_traits::values::specified::AllowedNumericType;
use style_traits::{ParseError, SpecifiedValueInfo, StyleParseErrorKind};
pub use super::image::{ColorStop, EndingShape as GradientEndingShape, Gradient};
pub use super::image::{GradientKind, Image};
pub use crate::values::specified::calc::CalcLengthPercentage;
/// Number of app units per pixel
pub const AU_PER_PX: CSSFloat = 60.;
/// Number of app units per inch
pub const AU_PER_IN: CSSFloat = AU_PER_PX * 96.;
/// Number of app units per centimeter
pub const AU_PER_CM: CSSFloat = AU_PER_IN / 2.54;
/// Number of app units per millimeter
pub const AU_PER_MM: CSSFloat = AU_PER_IN / 25.4;
/// Number of app units per quarter
pub const AU_PER_Q: CSSFloat = AU_PER_MM / 4.;
/// Number of app units per point
pub const AU_PER_PT: CSSFloat = AU_PER_IN / 72.;
/// Number of app units per pica
pub const AU_PER_PC: CSSFloat = AU_PER_PT * 12.;
/// A font relative length.
#[derive(Clone, Copy, Debug, MallocSizeOf, PartialEq, ToCss, ToShmem)]
pub enum FontRelativeLength {
/// A "em" value: https://drafts.csswg.org/css-values/#em
#[css(dimension)]
Em(CSSFloat),
/// A "ex" value: https://drafts.csswg.org/css-values/#ex
#[css(dimension)]
Ex(CSSFloat),
/// A "ch" value: https://drafts.csswg.org/css-values/#ch
#[css(dimension)]
Ch(CSSFloat),
/// A "rem" value: https://drafts.csswg.org/css-values/#rem
#[css(dimension)]
Rem(CSSFloat),
}
/// A source to resolve font-relative units against<|fim▁hole|>#[derive(Clone, Copy, Debug, PartialEq)]
pub enum FontBaseSize {
/// Use the font-size of the current element.
CurrentStyle,
/// Use the inherited font-size.
InheritedStyle,
}
impl FontBaseSize {
/// Calculate the actual size for a given context
pub fn resolve(&self, context: &Context) -> computed::Length {
match *self {
FontBaseSize::CurrentStyle => context.style().get_font().clone_font_size().size(),
FontBaseSize::InheritedStyle => {
context.style().get_parent_font().clone_font_size().size()
},
}
}
}
impl FontRelativeLength {
/// Return true if this is a zero value.
fn is_zero(&self) -> bool {
match *self {
FontRelativeLength::Em(v) |
FontRelativeLength::Ex(v) |
FontRelativeLength::Ch(v) |
FontRelativeLength::Rem(v) => v == 0.0,
}
}
fn try_sum(&self, other: &Self) -> Result<Self, ()> {
use self::FontRelativeLength::*;
if std::mem::discriminant(self) != std::mem::discriminant(other) {
return Err(());
}
Ok(match (self, other) {
(&Em(one), &Em(other)) => Em(one + other),
(&Ex(one), &Ex(other)) => Ex(one + other),
(&Ch(one), &Ch(other)) => Ch(one + other),
(&Rem(one), &Rem(other)) => Rem(one + other),
// See https://github.com/rust-lang/rust/issues/68867. rustc isn't
// able to figure it own on its own so we help.
_ => unsafe {
match *self {
Em(..) | Ex(..) | Ch(..) | Rem(..) => {},
}
debug_unreachable!("Forgot to handle unit in try_sum()")
},
})
}
/// Computes the font-relative length.
pub fn to_computed_value(
&self,
context: &Context,
base_size: FontBaseSize,
) -> computed::Length {
let (reference_size, length) = self.reference_font_size_and_length(context, base_size);
reference_size * length
}
/// Return reference font size.
///
/// We use the base_size flag to pass a different size for computing
/// font-size and unconstrained font-size.
///
/// This returns a pair, the first one is the reference font size, and the
/// second one is the unpacked relative length.
fn reference_font_size_and_length(
&self,
context: &Context,
base_size: FontBaseSize,
) -> (computed::Length, CSSFloat) {
fn query_font_metrics(
context: &Context,
base_size: FontBaseSize,
orientation: FontMetricsOrientation,
) -> FontMetrics {
context
.font_metrics_provider
.query(context, base_size, orientation)
}
let reference_font_size = base_size.resolve(context);
match *self {
FontRelativeLength::Em(length) => {
if context.for_non_inherited_property.is_some() {
if base_size == FontBaseSize::CurrentStyle {
context
.rule_cache_conditions
.borrow_mut()
.set_font_size_dependency(reference_font_size.into());
}
}
(reference_font_size, length)
},
FontRelativeLength::Ex(length) => {
if context.for_non_inherited_property.is_some() {
context.rule_cache_conditions.borrow_mut().set_uncacheable();
}
context
.builder
.add_flags(ComputedValueFlags::DEPENDS_ON_FONT_METRICS);
// The x-height is an intrinsically horizontal metric.
let metrics =
query_font_metrics(context, base_size, FontMetricsOrientation::Horizontal);
let reference_size = metrics.x_height.unwrap_or_else(|| {
// https://drafts.csswg.org/css-values/#ex
//
// In the cases where it is impossible or impractical to
// determine the x-height, a value of 0.5em must be
// assumed.
//
reference_font_size * 0.5
});
(reference_size, length)
},
FontRelativeLength::Ch(length) => {
if context.for_non_inherited_property.is_some() {
context.rule_cache_conditions.borrow_mut().set_uncacheable();
}
context
.builder
.add_flags(ComputedValueFlags::DEPENDS_ON_FONT_METRICS);
// https://drafts.csswg.org/css-values/#ch:
//
// Equal to the used advance measure of the “0” (ZERO,
// U+0030) glyph in the font used to render it. (The advance
// measure of a glyph is its advance width or height,
// whichever is in the inline axis of the element.)
//
let metrics =
query_font_metrics(context, base_size, FontMetricsOrientation::MatchContext);
let reference_size = metrics.zero_advance_measure.unwrap_or_else(|| {
// https://drafts.csswg.org/css-values/#ch
//
// In the cases where it is impossible or impractical to
// determine the measure of the “0” glyph, it must be
// assumed to be 0.5em wide by 1em tall. Thus, the ch
// unit falls back to 0.5em in the general case, and to
// 1em when it would be typeset upright (i.e.
// writing-mode is vertical-rl or vertical-lr and
// text-orientation is upright).
//
let wm = context.style().writing_mode;
if wm.is_vertical() && wm.is_upright() {
reference_font_size
} else {
reference_font_size * 0.5
}
});
(reference_size, length)
},
FontRelativeLength::Rem(length) => {
// https://drafts.csswg.org/css-values/#rem:
//
// When specified on the font-size property of the root
// element, the rem units refer to the property's initial
// value.
//
let reference_size = if context.builder.is_root_element || context.in_media_query {
reference_font_size
} else {
computed::Length::new(context.device().root_font_size().to_f32_px())
};
(reference_size, length)
},
}
}
}
/// A viewport-relative length.
///
/// <https://drafts.csswg.org/css-values/#viewport-relative-lengths>
#[derive(Clone, Copy, Debug, MallocSizeOf, PartialEq, ToCss, ToShmem)]
pub enum ViewportPercentageLength {
/// A vw unit: https://drafts.csswg.org/css-values/#vw
#[css(dimension)]
Vw(CSSFloat),
/// A vh unit: https://drafts.csswg.org/css-values/#vh
#[css(dimension)]
Vh(CSSFloat),
/// <https://drafts.csswg.org/css-values/#vmin>
#[css(dimension)]
Vmin(CSSFloat),
/// <https://drafts.csswg.org/css-values/#vmax>
#[css(dimension)]
Vmax(CSSFloat),
}
impl ViewportPercentageLength {
/// Return true if this is a zero value.
fn is_zero(&self) -> bool {
match *self {
ViewportPercentageLength::Vw(v) |
ViewportPercentageLength::Vh(v) |
ViewportPercentageLength::Vmin(v) |
ViewportPercentageLength::Vmax(v) => v == 0.0,
}
}
fn try_sum(&self, other: &Self) -> Result<Self, ()> {
use self::ViewportPercentageLength::*;
if std::mem::discriminant(self) != std::mem::discriminant(other) {
return Err(());
}
Ok(match (self, other) {
(&Vw(one), &Vw(other)) => Vw(one + other),
(&Vh(one), &Vh(other)) => Vh(one + other),
(&Vmin(one), &Vmin(other)) => Vmin(one + other),
(&Vmax(one), &Vmax(other)) => Vmax(one + other),
// See https://github.com/rust-lang/rust/issues/68867. rustc isn't
// able to figure it own on its own so we help.
_ => unsafe {
match *self {
Vw(..) | Vh(..) | Vmin(..) | Vmax(..) => {},
}
debug_unreachable!("Forgot to handle unit in try_sum()")
},
})
}
/// Computes the given viewport-relative length for the given viewport size.
pub fn to_computed_value(&self, viewport_size: Size2D<Au>) -> CSSPixelLength {
let (factor, length) = match *self {
ViewportPercentageLength::Vw(length) => (length, viewport_size.width),
ViewportPercentageLength::Vh(length) => (length, viewport_size.height),
ViewportPercentageLength::Vmin(length) => {
(length, cmp::min(viewport_size.width, viewport_size.height))
},
ViewportPercentageLength::Vmax(length) => {
(length, cmp::max(viewport_size.width, viewport_size.height))
},
};
// FIXME: Bug 1396535, we need to fix the extremely small viewport length for transform.
// See bug 989802. We truncate so that adding multiple viewport units
// that add up to 100 does not overflow due to rounding differences
let trunc_scaled = ((length.0 as f64) * factor as f64 / 100.).trunc();
Au::from_f64_au(trunc_scaled).into()
}
}
/// HTML5 "character width", as defined in HTML5 § 14.5.4.
#[derive(Clone, Copy, Debug, MallocSizeOf, PartialEq, ToCss, ToShmem)]
pub struct CharacterWidth(pub i32);
impl CharacterWidth {
/// Computes the given character width.
pub fn to_computed_value(&self, reference_font_size: computed::Length) -> computed::Length {
// This applies the *converting a character width to pixels* algorithm
// as specified in HTML5 § 14.5.4.
//
// TODO(pcwalton): Find these from the font.
let average_advance = reference_font_size * 0.5;
let max_advance = reference_font_size;
average_advance * (self.0 as CSSFloat - 1.0) + max_advance
}
}
/// Represents an absolute length with its unit
#[derive(Clone, Copy, Debug, MallocSizeOf, PartialEq, ToCss, ToShmem)]
pub enum AbsoluteLength {
/// An absolute length in pixels (px)
#[css(dimension)]
Px(CSSFloat),
/// An absolute length in inches (in)
#[css(dimension)]
In(CSSFloat),
/// An absolute length in centimeters (cm)
#[css(dimension)]
Cm(CSSFloat),
/// An absolute length in millimeters (mm)
#[css(dimension)]
Mm(CSSFloat),
/// An absolute length in quarter-millimeters (q)
#[css(dimension)]
Q(CSSFloat),
/// An absolute length in points (pt)
#[css(dimension)]
Pt(CSSFloat),
/// An absolute length in pica (pc)
#[css(dimension)]
Pc(CSSFloat),
}
impl AbsoluteLength {
fn is_zero(&self) -> bool {
match *self {
AbsoluteLength::Px(v) |
AbsoluteLength::In(v) |
AbsoluteLength::Cm(v) |
AbsoluteLength::Mm(v) |
AbsoluteLength::Q(v) |
AbsoluteLength::Pt(v) |
AbsoluteLength::Pc(v) => v == 0.,
}
}
/// Convert this into a pixel value.
#[inline]
pub fn to_px(&self) -> CSSFloat {
use std::f32;
let pixel = match *self {
AbsoluteLength::Px(value) => value,
AbsoluteLength::In(value) => value * (AU_PER_IN / AU_PER_PX),
AbsoluteLength::Cm(value) => value * (AU_PER_CM / AU_PER_PX),
AbsoluteLength::Mm(value) => value * (AU_PER_MM / AU_PER_PX),
AbsoluteLength::Q(value) => value * (AU_PER_Q / AU_PER_PX),
AbsoluteLength::Pt(value) => value * (AU_PER_PT / AU_PER_PX),
AbsoluteLength::Pc(value) => value * (AU_PER_PC / AU_PER_PX),
};
pixel.min(f32::MAX).max(f32::MIN)
}
}
impl ToComputedValue for AbsoluteLength {
type ComputedValue = CSSPixelLength;
fn to_computed_value(&self, _: &Context) -> Self::ComputedValue {
CSSPixelLength::new(self.to_px())
}
fn from_computed_value(computed: &Self::ComputedValue) -> Self {
AbsoluteLength::Px(computed.px())
}
}
impl PartialOrd for AbsoluteLength {
fn partial_cmp(&self, other: &Self) -> Option<cmp::Ordering> {
self.to_px().partial_cmp(&other.to_px())
}
}
impl Mul<CSSFloat> for AbsoluteLength {
type Output = AbsoluteLength;
#[inline]
fn mul(self, scalar: CSSFloat) -> AbsoluteLength {
match self {
AbsoluteLength::Px(v) => AbsoluteLength::Px(v * scalar),
AbsoluteLength::In(v) => AbsoluteLength::In(v * scalar),
AbsoluteLength::Cm(v) => AbsoluteLength::Cm(v * scalar),
AbsoluteLength::Mm(v) => AbsoluteLength::Mm(v * scalar),
AbsoluteLength::Q(v) => AbsoluteLength::Q(v * scalar),
AbsoluteLength::Pt(v) => AbsoluteLength::Pt(v * scalar),
AbsoluteLength::Pc(v) => AbsoluteLength::Pc(v * scalar),
}
}
}
impl Add<AbsoluteLength> for AbsoluteLength {
type Output = Self;
#[inline]
fn add(self, rhs: Self) -> Self {
match (self, rhs) {
(AbsoluteLength::Px(x), AbsoluteLength::Px(y)) => AbsoluteLength::Px(x + y),
(AbsoluteLength::In(x), AbsoluteLength::In(y)) => AbsoluteLength::In(x + y),
(AbsoluteLength::Cm(x), AbsoluteLength::Cm(y)) => AbsoluteLength::Cm(x + y),
(AbsoluteLength::Mm(x), AbsoluteLength::Mm(y)) => AbsoluteLength::Mm(x + y),
(AbsoluteLength::Q(x), AbsoluteLength::Q(y)) => AbsoluteLength::Q(x + y),
(AbsoluteLength::Pt(x), AbsoluteLength::Pt(y)) => AbsoluteLength::Pt(x + y),
(AbsoluteLength::Pc(x), AbsoluteLength::Pc(y)) => AbsoluteLength::Pc(x + y),
_ => AbsoluteLength::Px(self.to_px() + rhs.to_px()),
}
}
}
/// A `<length>` without taking `calc` expressions into account
///
/// <https://drafts.csswg.org/css-values/#lengths>
#[derive(Clone, Copy, Debug, MallocSizeOf, PartialEq, ToCss, ToShmem)]
pub enum NoCalcLength {
/// An absolute length
///
/// <https://drafts.csswg.org/css-values/#absolute-length>
Absolute(AbsoluteLength),
/// A font-relative length:
///
/// <https://drafts.csswg.org/css-values/#font-relative-lengths>
FontRelative(FontRelativeLength),
/// A viewport-relative length.
///
/// <https://drafts.csswg.org/css-values/#viewport-relative-lengths>
ViewportPercentage(ViewportPercentageLength),
/// HTML5 "character width", as defined in HTML5 § 14.5.4.
///
/// This cannot be specified by the user directly and is only generated by
/// `Stylist::synthesize_rules_for_legacy_attributes()`.
#[css(function)]
ServoCharacterWidth(CharacterWidth),
}
impl Mul<CSSFloat> for NoCalcLength {
type Output = NoCalcLength;
#[inline]
fn mul(self, scalar: CSSFloat) -> NoCalcLength {
match self {
NoCalcLength::Absolute(v) => NoCalcLength::Absolute(v * scalar),
NoCalcLength::FontRelative(v) => NoCalcLength::FontRelative(v * scalar),
NoCalcLength::ViewportPercentage(v) => NoCalcLength::ViewportPercentage(v * scalar),
NoCalcLength::ServoCharacterWidth(_) => panic!("Can't multiply ServoCharacterWidth!"),
}
}
}
impl NoCalcLength {
/// Parse a given absolute or relative dimension.
pub fn parse_dimension(
context: &ParserContext,
value: CSSFloat,
unit: &str,
) -> Result<Self, ()> {
Ok(match_ignore_ascii_case! { unit,
"px" => NoCalcLength::Absolute(AbsoluteLength::Px(value)),
"in" => NoCalcLength::Absolute(AbsoluteLength::In(value)),
"cm" => NoCalcLength::Absolute(AbsoluteLength::Cm(value)),
"mm" => NoCalcLength::Absolute(AbsoluteLength::Mm(value)),
"q" => NoCalcLength::Absolute(AbsoluteLength::Q(value)),
"pt" => NoCalcLength::Absolute(AbsoluteLength::Pt(value)),
"pc" => NoCalcLength::Absolute(AbsoluteLength::Pc(value)),
// font-relative
"em" => NoCalcLength::FontRelative(FontRelativeLength::Em(value)),
"ex" => NoCalcLength::FontRelative(FontRelativeLength::Ex(value)),
"ch" => NoCalcLength::FontRelative(FontRelativeLength::Ch(value)),
"rem" => NoCalcLength::FontRelative(FontRelativeLength::Rem(value)),
// viewport percentages
"vw" if !context.in_page_rule() => {
NoCalcLength::ViewportPercentage(ViewportPercentageLength::Vw(value))
},
"vh" if !context.in_page_rule() => {
NoCalcLength::ViewportPercentage(ViewportPercentageLength::Vh(value))
},
"vmin" if !context.in_page_rule() => {
NoCalcLength::ViewportPercentage(ViewportPercentageLength::Vmin(value))
},
"vmax" if !context.in_page_rule() => {
NoCalcLength::ViewportPercentage(ViewportPercentageLength::Vmax(value))
},
_ => return Err(()),
})
}
/// Try to sume two lengths if compatible into the left hand side.
pub(crate) fn try_sum(&self, other: &Self) -> Result<Self, ()> {
use self::NoCalcLength::*;
if std::mem::discriminant(self) != std::mem::discriminant(other) {
return Err(());
}
Ok(match (self, other) {
(&Absolute(ref one), &Absolute(ref other)) => Absolute(*one + *other),
(&FontRelative(ref one), &FontRelative(ref other)) => FontRelative(one.try_sum(other)?),
(&ViewportPercentage(ref one), &ViewportPercentage(ref other)) => {
ViewportPercentage(one.try_sum(other)?)
},
(&ServoCharacterWidth(ref one), &ServoCharacterWidth(ref other)) => {
ServoCharacterWidth(CharacterWidth(one.0 + other.0))
},
// See https://github.com/rust-lang/rust/issues/68867. rustc isn't
// able to figure it own on its own so we help.
_ => unsafe {
match *self {
Absolute(..) |
FontRelative(..) |
ViewportPercentage(..) |
ServoCharacterWidth(..) => {},
}
debug_unreachable!("Forgot to handle unit in try_sum()")
},
})
}
/// Get a px value without context.
#[inline]
pub fn to_computed_pixel_length_without_context(&self) -> Result<CSSFloat, ()> {
match *self {
NoCalcLength::Absolute(len) => Ok(len.to_px()),
_ => Err(()),
}
}
/// Get an absolute length from a px value.
#[inline]
pub fn from_px(px_value: CSSFloat) -> NoCalcLength {
NoCalcLength::Absolute(AbsoluteLength::Px(px_value))
}
}
impl SpecifiedValueInfo for NoCalcLength {}
impl PartialOrd for NoCalcLength {
fn partial_cmp(&self, other: &Self) -> Option<cmp::Ordering> {
use self::NoCalcLength::*;
if std::mem::discriminant(self) != std::mem::discriminant(other) {
return None;
}
match (self, other) {
(&Absolute(ref one), &Absolute(ref other)) => one.to_px().partial_cmp(&other.to_px()),
(&FontRelative(ref one), &FontRelative(ref other)) => one.partial_cmp(other),
(&ViewportPercentage(ref one), &ViewportPercentage(ref other)) => {
one.partial_cmp(other)
},
(&ServoCharacterWidth(ref one), &ServoCharacterWidth(ref other)) => {
one.0.partial_cmp(&other.0)
},
// See https://github.com/rust-lang/rust/issues/68867. rustc isn't
// able to figure it own on its own so we help.
_ => unsafe {
match *self {
Absolute(..) |
FontRelative(..) |
ViewportPercentage(..) |
ServoCharacterWidth(..) => {},
}
debug_unreachable!("Forgot an arm in partial_cmp?")
},
}
}
}
impl Zero for NoCalcLength {
fn zero() -> Self {
NoCalcLength::Absolute(AbsoluteLength::Px(0.))
}
fn is_zero(&self) -> bool {
match *self {
NoCalcLength::Absolute(v) => v.is_zero(),
NoCalcLength::FontRelative(v) => v.is_zero(),
NoCalcLength::ViewportPercentage(v) => v.is_zero(),
NoCalcLength::ServoCharacterWidth(v) => v.0 == 0,
}
}
}
/// An extension to `NoCalcLength` to parse `calc` expressions.
/// This is commonly used for the `<length>` values.
///
/// <https://drafts.csswg.org/css-values/#lengths>
#[derive(Clone, Debug, MallocSizeOf, PartialEq, SpecifiedValueInfo, ToCss, ToShmem)]
pub enum Length {
/// The internal length type that cannot parse `calc`
NoCalc(NoCalcLength),
/// A calc expression.
///
/// <https://drafts.csswg.org/css-values/#calc-notation>
Calc(Box<CalcLengthPercentage>),
}
impl From<NoCalcLength> for Length {
#[inline]
fn from(len: NoCalcLength) -> Self {
Length::NoCalc(len)
}
}
impl Mul<CSSFloat> for Length {
type Output = Length;
#[inline]
fn mul(self, scalar: CSSFloat) -> Length {
match self {
Length::NoCalc(inner) => Length::NoCalc(inner * scalar),
Length::Calc(..) => panic!("Can't multiply Calc!"),
}
}
}
impl PartialOrd for FontRelativeLength {
fn partial_cmp(&self, other: &Self) -> Option<cmp::Ordering> {
use self::FontRelativeLength::*;
if std::mem::discriminant(self) != std::mem::discriminant(other) {
return None;
}
match (self, other) {
(&Em(ref one), &Em(ref other)) => one.partial_cmp(other),
(&Ex(ref one), &Ex(ref other)) => one.partial_cmp(other),
(&Ch(ref one), &Ch(ref other)) => one.partial_cmp(other),
(&Rem(ref one), &Rem(ref other)) => one.partial_cmp(other),
// See https://github.com/rust-lang/rust/issues/68867. rustc isn't
// able to figure it own on its own so we help.
_ => unsafe {
match *self {
Em(..) | Ex(..) | Ch(..) | Rem(..) => {},
}
debug_unreachable!("Forgot an arm in partial_cmp?")
},
}
}
}
impl Mul<CSSFloat> for FontRelativeLength {
type Output = FontRelativeLength;
#[inline]
fn mul(self, scalar: CSSFloat) -> FontRelativeLength {
match self {
FontRelativeLength::Em(v) => FontRelativeLength::Em(v * scalar),
FontRelativeLength::Ex(v) => FontRelativeLength::Ex(v * scalar),
FontRelativeLength::Ch(v) => FontRelativeLength::Ch(v * scalar),
FontRelativeLength::Rem(v) => FontRelativeLength::Rem(v * scalar),
}
}
}
impl Mul<CSSFloat> for ViewportPercentageLength {
type Output = ViewportPercentageLength;
#[inline]
fn mul(self, scalar: CSSFloat) -> ViewportPercentageLength {
match self {
ViewportPercentageLength::Vw(v) => ViewportPercentageLength::Vw(v * scalar),
ViewportPercentageLength::Vh(v) => ViewportPercentageLength::Vh(v * scalar),
ViewportPercentageLength::Vmin(v) => ViewportPercentageLength::Vmin(v * scalar),
ViewportPercentageLength::Vmax(v) => ViewportPercentageLength::Vmax(v * scalar),
}
}
}
impl PartialOrd for ViewportPercentageLength {
fn partial_cmp(&self, other: &Self) -> Option<cmp::Ordering> {
use self::ViewportPercentageLength::*;
if std::mem::discriminant(self) != std::mem::discriminant(other) {
return None;
}
match (self, other) {
(&Vw(ref one), &Vw(ref other)) => one.partial_cmp(other),
(&Vh(ref one), &Vh(ref other)) => one.partial_cmp(other),
(&Vmin(ref one), &Vmin(ref other)) => one.partial_cmp(other),
(&Vmax(ref one), &Vmax(ref other)) => one.partial_cmp(other),
// See https://github.com/rust-lang/rust/issues/68867. rustc isn't
// able to figure it own on its own so we help.
_ => unsafe {
match *self {
Vw(..) | Vh(..) | Vmin(..) | Vmax(..) => {},
}
debug_unreachable!("Forgot an arm in partial_cmp?")
},
}
}
}
impl Length {
#[inline]
fn parse_internal<'i, 't>(
context: &ParserContext,
input: &mut Parser<'i, 't>,
num_context: AllowedNumericType,
allow_quirks: AllowQuirks,
) -> Result<Self, ParseError<'i>> {
let location = input.current_source_location();
let token = input.next()?;
match *token {
Token::Dimension {
value, ref unit, ..
} if num_context.is_ok(context.parsing_mode, value) => {
NoCalcLength::parse_dimension(context, value, unit)
.map(Length::NoCalc)
.map_err(|()| location.new_unexpected_token_error(token.clone()))
},
Token::Number { value, .. } if num_context.is_ok(context.parsing_mode, value) => {
if value != 0. &&
!context.parsing_mode.allows_unitless_lengths() &&
!allow_quirks.allowed(context.quirks_mode)
{
return Err(location.new_custom_error(StyleParseErrorKind::UnspecifiedError));
}
Ok(Length::NoCalc(NoCalcLength::Absolute(AbsoluteLength::Px(
value,
))))
},
Token::Function(ref name) => {
let function = CalcNode::math_function(name, location)?;
let calc = CalcNode::parse_length(context, input, num_context, function)?;
Ok(Length::Calc(Box::new(calc)))
},
ref token => return Err(location.new_unexpected_token_error(token.clone())),
}
}
/// Parse a non-negative length
#[inline]
pub fn parse_non_negative<'i, 't>(
context: &ParserContext,
input: &mut Parser<'i, 't>,
) -> Result<Self, ParseError<'i>> {
Self::parse_non_negative_quirky(context, input, AllowQuirks::No)
}
/// Parse a non-negative length, allowing quirks.
#[inline]
pub fn parse_non_negative_quirky<'i, 't>(
context: &ParserContext,
input: &mut Parser<'i, 't>,
allow_quirks: AllowQuirks,
) -> Result<Self, ParseError<'i>> {
Self::parse_internal(
context,
input,
AllowedNumericType::NonNegative,
allow_quirks,
)
}
/// Get an absolute length from a px value.
#[inline]
pub fn from_px(px_value: CSSFloat) -> Length {
Length::NoCalc(NoCalcLength::from_px(px_value))
}
}
impl Parse for Length {
fn parse<'i, 't>(
context: &ParserContext,
input: &mut Parser<'i, 't>,
) -> Result<Self, ParseError<'i>> {
Self::parse_quirky(context, input, AllowQuirks::No)
}
}
impl Zero for Length {
fn zero() -> Self {
Length::NoCalc(NoCalcLength::zero())
}
fn is_zero(&self) -> bool {
// FIXME(emilio): Seems a bit weird to treat calc() unconditionally as
// non-zero here?
match *self {
Length::NoCalc(ref l) => l.is_zero(),
Length::Calc(..) => false,
}
}
}
impl Length {
/// Parses a length, with quirks.
pub fn parse_quirky<'i, 't>(
context: &ParserContext,
input: &mut Parser<'i, 't>,
allow_quirks: AllowQuirks,
) -> Result<Self, ParseError<'i>> {
Self::parse_internal(context, input, AllowedNumericType::All, allow_quirks)
}
}
/// A wrapper of Length, whose value must be >= 0.
pub type NonNegativeLength = NonNegative<Length>;
impl Parse for NonNegativeLength {
#[inline]
fn parse<'i, 't>(
context: &ParserContext,
input: &mut Parser<'i, 't>,
) -> Result<Self, ParseError<'i>> {
Ok(NonNegative(Length::parse_non_negative(context, input)?))
}
}
impl From<NoCalcLength> for NonNegativeLength {
#[inline]
fn from(len: NoCalcLength) -> Self {
NonNegative(Length::NoCalc(len))
}
}
impl From<Length> for NonNegativeLength {
#[inline]
fn from(len: Length) -> Self {
NonNegative(len)
}
}
impl NonNegativeLength {
/// Get an absolute length from a px value.
#[inline]
pub fn from_px(px_value: CSSFloat) -> Self {
Length::from_px(px_value.max(0.)).into()
}
/// Parses a non-negative length, optionally with quirks.
#[inline]
pub fn parse_quirky<'i, 't>(
context: &ParserContext,
input: &mut Parser<'i, 't>,
allow_quirks: AllowQuirks,
) -> Result<Self, ParseError<'i>> {
Ok(NonNegative(Length::parse_non_negative_quirky(
context,
input,
allow_quirks,
)?))
}
}
/// A `<length-percentage>` value. This can be either a `<length>`, a
/// `<percentage>`, or a combination of both via `calc()`.
///
/// https://drafts.csswg.org/css-values-4/#typedef-length-percentage
#[allow(missing_docs)]
#[derive(Clone, Debug, MallocSizeOf, PartialEq, SpecifiedValueInfo, ToCss, ToShmem)]
pub enum LengthPercentage {
Length(NoCalcLength),
Percentage(computed::Percentage),
Calc(Box<CalcLengthPercentage>),
}
impl From<Length> for LengthPercentage {
fn from(len: Length) -> LengthPercentage {
match len {
Length::NoCalc(l) => LengthPercentage::Length(l),
Length::Calc(l) => LengthPercentage::Calc(l),
}
}
}
impl From<NoCalcLength> for LengthPercentage {
#[inline]
fn from(len: NoCalcLength) -> Self {
LengthPercentage::Length(len)
}
}
impl From<Percentage> for LengthPercentage {
#[inline]
fn from(pc: Percentage) -> Self {
if pc.is_calc() {
LengthPercentage::Calc(Box::new(CalcLengthPercentage {
percentage: Some(computed::Percentage(pc.get())),
..Default::default()
}))
} else {
LengthPercentage::Percentage(computed::Percentage(pc.get()))
}
}
}
impl From<computed::Percentage> for LengthPercentage {
#[inline]
fn from(pc: computed::Percentage) -> Self {
LengthPercentage::Percentage(pc)
}
}
impl Parse for LengthPercentage {
#[inline]
fn parse<'i, 't>(
context: &ParserContext,
input: &mut Parser<'i, 't>,
) -> Result<Self, ParseError<'i>> {
Self::parse_quirky(context, input, AllowQuirks::No)
}
}
impl LengthPercentage {
#[inline]
/// Returns a `0%` value.
pub fn zero_percent() -> LengthPercentage {
LengthPercentage::Percentage(computed::Percentage::zero())
}
fn parse_internal<'i, 't>(
context: &ParserContext,
input: &mut Parser<'i, 't>,
num_context: AllowedNumericType,
allow_quirks: AllowQuirks,
) -> Result<Self, ParseError<'i>> {
let location = input.current_source_location();
let token = input.next()?;
match *token {
Token::Dimension {
value, ref unit, ..
} if num_context.is_ok(context.parsing_mode, value) => {
return NoCalcLength::parse_dimension(context, value, unit)
.map(LengthPercentage::Length)
.map_err(|()| location.new_unexpected_token_error(token.clone()));
},
Token::Percentage { unit_value, .. }
if num_context.is_ok(context.parsing_mode, unit_value) =>
{
return Ok(LengthPercentage::Percentage(computed::Percentage(
unit_value,
)));
}
Token::Number { value, .. } if num_context.is_ok(context.parsing_mode, value) => {
if value != 0. &&
!context.parsing_mode.allows_unitless_lengths() &&
!allow_quirks.allowed(context.quirks_mode)
{
return Err(location.new_unexpected_token_error(token.clone()));
} else {
return Ok(LengthPercentage::Length(NoCalcLength::from_px(value)));
}
},
Token::Function(ref name) => {
let function = CalcNode::math_function(name, location)?;
let calc =
CalcNode::parse_length_or_percentage(context, input, num_context, function)?;
Ok(LengthPercentage::Calc(Box::new(calc)))
},
_ => return Err(location.new_unexpected_token_error(token.clone())),
}
}
/// Parses allowing the unitless length quirk.
/// <https://quirks.spec.whatwg.org/#the-unitless-length-quirk>
#[inline]
pub fn parse_quirky<'i, 't>(
context: &ParserContext,
input: &mut Parser<'i, 't>,
allow_quirks: AllowQuirks,
) -> Result<Self, ParseError<'i>> {
Self::parse_internal(context, input, AllowedNumericType::All, allow_quirks)
}
/// Parse a non-negative length.
///
/// FIXME(emilio): This should be not public and we should use
/// NonNegativeLengthPercentage instead.
#[inline]
pub fn parse_non_negative<'i, 't>(
context: &ParserContext,
input: &mut Parser<'i, 't>,
) -> Result<Self, ParseError<'i>> {
Self::parse_non_negative_quirky(context, input, AllowQuirks::No)
}
/// Parse a non-negative length, with quirks.
#[inline]
pub fn parse_non_negative_quirky<'i, 't>(
context: &ParserContext,
input: &mut Parser<'i, 't>,
allow_quirks: AllowQuirks,
) -> Result<Self, ParseError<'i>> {
Self::parse_internal(
context,
input,
AllowedNumericType::NonNegative,
allow_quirks,
)
}
}
impl Zero for LengthPercentage {
fn zero() -> Self {
LengthPercentage::Length(NoCalcLength::zero())
}
fn is_zero(&self) -> bool {
match *self {
LengthPercentage::Length(l) => l.is_zero(),
LengthPercentage::Percentage(p) => p.0 == 0.0,
LengthPercentage::Calc(_) => false,
}
}
}
/// A specified type for `<length-percentage> | auto`.
pub type LengthPercentageOrAuto = generics::LengthPercentageOrAuto<LengthPercentage>;
impl LengthPercentageOrAuto {
/// Returns a value representing `0%`.
#[inline]
pub fn zero_percent() -> Self {
generics::LengthPercentageOrAuto::LengthPercentage(LengthPercentage::zero_percent())
}
/// Parses a length or a percentage, allowing the unitless length quirk.
/// <https://quirks.spec.whatwg.org/#the-unitless-length-quirk>
#[inline]
pub fn parse_quirky<'i, 't>(
context: &ParserContext,
input: &mut Parser<'i, 't>,
allow_quirks: AllowQuirks,
) -> Result<Self, ParseError<'i>> {
Self::parse_with(context, input, |context, input| {
LengthPercentage::parse_quirky(context, input, allow_quirks)
})
}
}
/// A wrapper of LengthPercentageOrAuto, whose value must be >= 0.
pub type NonNegativeLengthPercentageOrAuto =
generics::LengthPercentageOrAuto<NonNegativeLengthPercentage>;
impl NonNegativeLengthPercentageOrAuto {
/// Returns a value representing `0%`.
#[inline]
pub fn zero_percent() -> Self {
generics::LengthPercentageOrAuto::LengthPercentage(
NonNegativeLengthPercentage::zero_percent(),
)
}
/// Parses a non-negative length-percentage, allowing the unitless length
/// quirk.
#[inline]
pub fn parse_quirky<'i, 't>(
context: &ParserContext,
input: &mut Parser<'i, 't>,
allow_quirks: AllowQuirks,
) -> Result<Self, ParseError<'i>> {
Self::parse_with(context, input, |context, input| {
NonNegativeLengthPercentage::parse_quirky(context, input, allow_quirks)
})
}
}
/// A wrapper of LengthPercentage, whose value must be >= 0.
pub type NonNegativeLengthPercentage = NonNegative<LengthPercentage>;
/// Either a NonNegativeLengthPercentage or the `normal` keyword.
pub type NonNegativeLengthPercentageOrNormal =
GenericLengthPercentageOrNormal<NonNegativeLengthPercentage>;
impl From<NoCalcLength> for NonNegativeLengthPercentage {
#[inline]
fn from(len: NoCalcLength) -> Self {
NonNegative(LengthPercentage::from(len))
}
}
impl Parse for NonNegativeLengthPercentage {
#[inline]
fn parse<'i, 't>(
context: &ParserContext,
input: &mut Parser<'i, 't>,
) -> Result<Self, ParseError<'i>> {
Self::parse_quirky(context, input, AllowQuirks::No)
}
}
impl NonNegativeLengthPercentage {
#[inline]
/// Returns a `0%` value.
pub fn zero_percent() -> Self {
NonNegative(LengthPercentage::zero_percent())
}
/// Parses a length or a percentage, allowing the unitless length quirk.
/// <https://quirks.spec.whatwg.org/#the-unitless-length-quirk>
#[inline]
pub fn parse_quirky<'i, 't>(
context: &ParserContext,
input: &mut Parser<'i, 't>,
allow_quirks: AllowQuirks,
) -> Result<Self, ParseError<'i>> {
LengthPercentage::parse_non_negative_quirky(context, input, allow_quirks).map(NonNegative)
}
}
/// Either a `<length>` or the `auto` keyword.
///
/// Note that we use LengthPercentage just for convenience, since it pretty much
/// is everything we care about, but we could just add a similar LengthOrAuto
/// instead if we think getting rid of this weirdness is worth it.
pub type LengthOrAuto = generics::LengthPercentageOrAuto<Length>;
impl LengthOrAuto {
/// Parses a length, allowing the unitless length quirk.
/// <https://quirks.spec.whatwg.org/#the-unitless-length-quirk>
#[inline]
pub fn parse_quirky<'i, 't>(
context: &ParserContext,
input: &mut Parser<'i, 't>,
allow_quirks: AllowQuirks,
) -> Result<Self, ParseError<'i>> {
Self::parse_with(context, input, |context, input| {
Length::parse_quirky(context, input, allow_quirks)
})
}
}
/// Either a non-negative `<length>` or the `auto` keyword.
pub type NonNegativeLengthOrAuto = generics::LengthPercentageOrAuto<NonNegativeLength>;
/// Either a `<length>` or a `<number>`.
pub type LengthOrNumber = GenericLengthOrNumber<Length, Number>;
/// A specified value for `min-width`, `min-height`, `width` or `height` property.
pub type Size = GenericSize<NonNegativeLengthPercentage>;
impl Parse for Size {
fn parse<'i, 't>(
context: &ParserContext,
input: &mut Parser<'i, 't>,
) -> Result<Self, ParseError<'i>> {
Size::parse_quirky(context, input, AllowQuirks::No)
}
}
impl Size {
/// Parses, with quirks.
pub fn parse_quirky<'i, 't>(
context: &ParserContext,
input: &mut Parser<'i, 't>,
allow_quirks: AllowQuirks,
) -> Result<Self, ParseError<'i>> {
#[cfg(feature = "gecko")]
{
if let Ok(l) = input.try(computed::ExtremumLength::parse) {
return Ok(GenericSize::ExtremumLength(l));
}
}
if input.try(|i| i.expect_ident_matching("auto")).is_ok() {
return Ok(GenericSize::Auto);
}
let length = NonNegativeLengthPercentage::parse_quirky(context, input, allow_quirks)?;
Ok(GenericSize::LengthPercentage(length))
}
/// Returns `0%`.
#[inline]
pub fn zero_percent() -> Self {
GenericSize::LengthPercentage(NonNegativeLengthPercentage::zero_percent())
}
}
/// A specified value for `max-width` or `max-height` property.
pub type MaxSize = GenericMaxSize<NonNegativeLengthPercentage>;
impl Parse for MaxSize {
fn parse<'i, 't>(
context: &ParserContext,
input: &mut Parser<'i, 't>,
) -> Result<Self, ParseError<'i>> {
MaxSize::parse_quirky(context, input, AllowQuirks::No)
}
}
impl MaxSize {
/// Parses, with quirks.
pub fn parse_quirky<'i, 't>(
context: &ParserContext,
input: &mut Parser<'i, 't>,
allow_quirks: AllowQuirks,
) -> Result<Self, ParseError<'i>> {
#[cfg(feature = "gecko")]
{
if let Ok(l) = input.try(computed::ExtremumLength::parse) {
return Ok(GenericMaxSize::ExtremumLength(l));
}
}
if input.try(|i| i.expect_ident_matching("none")).is_ok() {
return Ok(GenericMaxSize::None);
}
let length = NonNegativeLengthPercentage::parse_quirky(context, input, allow_quirks)?;
Ok(GenericMaxSize::LengthPercentage(length))
}
}
/// A specified non-negative `<length>` | `<number>`.
pub type NonNegativeLengthOrNumber = GenericLengthOrNumber<NonNegativeLength, NonNegativeNumber>;<|fim▁end|> | |
<|file_name|>AdMob.java<|end_file_name|><|fim▁begin|>package com.agamemnus.cordova.plugin;
import com.google.android.gms.ads.AdListener;
import com.google.android.gms.ads.AdRequest;
import com.google.android.gms.ads.AdSize;
import com.google.android.gms.ads.AdView;
import com.google.android.gms.ads.InterstitialAd;
import com.google.android.gms.ads.mediation.admob.AdMobExtras;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.GooglePlayServicesUtil;
import org.apache.cordova.CallbackContext;
import org.apache.cordova.CordovaInterface;
import org.apache.cordova.CordovaPlugin;
import org.apache.cordova.CordovaWebView;
import org.apache.cordova.PluginResult;
import org.apache.cordova.PluginResult.Status;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.os.Bundle;
import java.util.Iterator;
import java.util.Random;
import android.provider.Settings;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import android.util.Log;
public class AdMob extends CordovaPlugin {
// Common tag used for logging statements.
private static final String LOGTAG = "AdMob";
private static final boolean CORDOVA_4 = Integer.valueOf(CordovaWebView.CORDOVA_VERSION.split("\\.")[0]) >= 4;
// Cordova Actions.
private static final String ACTION_SET_OPTIONS = "setOptions";
private static final String ACTION_CREATE_BANNER_VIEW = "createBannerView";
private static final String ACTION_DESTROY_BANNER_VIEW = "destroyBannerView";
private static final String ACTION_REQUEST_AD = "requestAd";
private static final String ACTION_SHOW_AD = "showAd";
private static final String ACTION_CREATE_INTERSTITIAL_VIEW = "createInterstitialView";
private static final String ACTION_REQUEST_INTERSTITIAL_AD = "requestInterstitialAd";
private static final String ACTION_SHOW_INTERSTITIAL_AD = "showInterstitialAd";
// Options.
private static final String OPT_AD_ID = "adId";
private static final String OPT_AD_SIZE = "adSize";
private static final String OPT_BANNER_AT_TOP = "bannerAtTop";
private static final String OPT_OVERLAP = "overlap";
private static final String OPT_OFFSET_TOPBAR = "offsetTopBar";
private static final String OPT_IS_TESTING = "isTesting";
private static final String OPT_AD_EXTRAS = "adExtras";
private static final String OPT_AUTO_SHOW = "autoShow";
// The adView to display to the user.
private ViewGroup parentView;
private AdView adView;
// If the user wants banner view overlap webview, we will need this layout.
private RelativeLayout adViewLayout = null;
// The interstitial ad to display to the user.
private InterstitialAd interstitialAd;
private AdSize adSize = AdSize.SMART_BANNER;
private String adId = "";
private boolean bannerAtTop = false;
private boolean bannerOverlap = false;
private boolean offsetTopBar = false;
private boolean isTesting = false;
private boolean bannerShow = true;
private boolean autoShow = true;
private boolean autoShowBanner = true;
private boolean autoShowInterstitial = true;
private boolean bannerVisible = false;
private boolean isGpsAvailable = false;
private JSONObject adExtras = null;
@Override public void initialize (CordovaInterface cordova, CordovaWebView webView) {
super.initialize (cordova, webView);
isGpsAvailable = (GooglePlayServicesUtil.isGooglePlayServicesAvailable(cordova.getActivity()) == ConnectionResult.SUCCESS);
Log.w (LOGTAG, String.format("isGooglePlayServicesAvailable: %s", isGpsAvailable ? "true" : "false"));
}
// This is the main method for the AdMob plugin. All API calls go through here.
// This method determines the action, and executes the appropriate call.
//
// @param action The action that the plugin should execute.
// @param inputs The input parameters for the action.
// @param callbackContext The callback context.
// @return A PluginResult representing the result of the provided action.
// A status of INVALID_ACTION is returned if the action is not recognized.
@Override public boolean execute (String action, JSONArray inputs, CallbackContext callbackContext) throws JSONException {
PluginResult result = null;
if (ACTION_SET_OPTIONS.equals(action)) {
JSONObject options = inputs.optJSONObject(0);
result = executeSetOptions(options, callbackContext);
} else if (ACTION_CREATE_BANNER_VIEW.equals(action)) {
JSONObject options = inputs.optJSONObject(0);
result = executeCreateBannerView(options, callbackContext);
} else if (ACTION_CREATE_INTERSTITIAL_VIEW.equals(action)) {
JSONObject options = inputs.optJSONObject(0);
result = executeCreateInterstitialView(options, callbackContext);
} else if (ACTION_DESTROY_BANNER_VIEW.equals(action)) {
result = executeDestroyBannerView(callbackContext);
} else if (ACTION_REQUEST_INTERSTITIAL_AD.equals(action)) {
JSONObject options = inputs.optJSONObject(0);
result = executeRequestInterstitialAd(options, callbackContext);
} else if (ACTION_REQUEST_AD.equals(action)) {
JSONObject options = inputs.optJSONObject(0);
result = executeRequestAd(options, callbackContext);
} else if (ACTION_SHOW_AD.equals(action)) {
boolean show = inputs.optBoolean(0);
result = executeShowAd(show, callbackContext);
} else if (ACTION_SHOW_INTERSTITIAL_AD.equals(action)) {
boolean show = inputs.optBoolean(0);
result = executeShowInterstitialAd(show, callbackContext);
} else {
Log.d (LOGTAG, String.format("Invalid action passed: %s", action));
result = new PluginResult(Status.INVALID_ACTION);
}
if (result != null) callbackContext.sendPluginResult (result);
return true;
}
private PluginResult executeSetOptions (JSONObject options, CallbackContext callbackContext) {
Log.w (LOGTAG, "executeSetOptions");
this.setOptions (options);
callbackContext.success ();
return null;
}
private void setOptions (JSONObject options) {
if (options == null) return;
if (options.has(OPT_AD_ID)) this.adId = options.optString (OPT_AD_ID);
if (options.has(OPT_AD_SIZE)) this.adSize = adSizeFromString (options.optString(OPT_AD_SIZE));
if (options.has(OPT_BANNER_AT_TOP)) this.bannerAtTop = options.optBoolean (OPT_BANNER_AT_TOP);
if (options.has(OPT_OVERLAP)) this.bannerOverlap = options.optBoolean (OPT_OVERLAP);
if (options.has(OPT_OFFSET_TOPBAR)) this.offsetTopBar = options.optBoolean (OPT_OFFSET_TOPBAR);
if (options.has(OPT_IS_TESTING)) this.isTesting = options.optBoolean (OPT_IS_TESTING);
if (options.has(OPT_AD_EXTRAS)) this.adExtras = options.optJSONObject (OPT_AD_EXTRAS);
if (options.has(OPT_AUTO_SHOW)) this.autoShow = options.optBoolean (OPT_AUTO_SHOW);
}
// Parses the create banner view input parameters and runs the create banner
// view action on the UI thread. If this request is successful, the developer
// should make the requestAd call to request an ad for the banner.
//
// @param inputs The JSONArray representing input parameters. This function
// expects the first object in the array to be a JSONObject with the input parameters.
// @return A PluginResult representing whether or not the banner was created successfully.
private PluginResult executeCreateBannerView (JSONObject options, final CallbackContext callbackContext) {
this.setOptions (options);
autoShowBanner = autoShow;
cordova.getActivity().runOnUiThread (new Runnable() {
@Override public void run () {
boolean adViewWasNull = (adView == null);
if (adView == null) {
adView = new AdView (cordova.getActivity());
adView.setAdUnitId (adId);
adView.setAdSize (adSize);
}
if (adView.getParent() != null) ((ViewGroup)adView.getParent()).removeView(adView);
if (adViewLayout == null) {
adViewLayout = new RelativeLayout(cordova.getActivity());
RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.MATCH_PARENT, RelativeLayout.LayoutParams.MATCH_PARENT);
if (CORDOVA_4) {
((ViewGroup) webView.getView().getParent()).addView(adViewLayout, params);
} else {
((ViewGroup) webView).addView(adViewLayout, params);
}
}
bannerVisible = false;
adView.loadAd (buildAdRequest());
if (adViewWasNull) adView.setAdListener (new BannerListener());
if (autoShowBanner) executeShowAd (true, null);
callbackContext.success ();
}
});
return null;
}
private PluginResult executeDestroyBannerView (CallbackContext callbackContext) {
Log.w (LOGTAG, "executeDestroyBannerView");
final CallbackContext delayCallback = callbackContext;
cordova.getActivity().runOnUiThread (new Runnable() {
@Override public void run () {
if (adView != null) {
ViewGroup parentView = (ViewGroup)adView.getParent();
if (parentView != null) parentView.removeView(adView);
adView.destroy ();
adView = null;
}
bannerVisible = false;
delayCallback.success ();
}
});
return null;
}
// Parses the create interstitial view input parameters and runs the create interstitial
// view action on the UI thread. If this request is successful, the developer should make the requestAd call to request an ad for the banner.
//
// @param inputs The JSONArray representing input parameters. This function expects the first object in the array to be a JSONObject with the input parameters.
// @return A PluginResult representing whether or not the banner was created successfully.
private PluginResult executeCreateInterstitialView (JSONObject options, CallbackContext callbackContext) {
this.setOptions (options);
autoShowInterstitial = autoShow;
final CallbackContext delayCallback = callbackContext;
cordova.getActivity().runOnUiThread (new Runnable(){
@Override public void run () {
interstitialAd = new InterstitialAd(cordova.getActivity());
interstitialAd.setAdUnitId (adId);
interstitialAd.loadAd (buildAdRequest());<|fim▁hole|> }
});
return null;
}
private AdRequest buildAdRequest () {
AdRequest.Builder request_builder = new AdRequest.Builder();
if (isTesting) {
// This will request test ads on the emulator and deviceby passing this hashed device ID.
String ANDROID_ID = Settings.Secure.getString(cordova.getActivity().getContentResolver(), android.provider.Settings.Secure.ANDROID_ID);
String deviceId = md5(ANDROID_ID).toUpperCase();
request_builder = request_builder.addTestDevice(deviceId).addTestDevice(AdRequest.DEVICE_ID_EMULATOR);
}
Bundle bundle = new Bundle();
bundle.putInt("cordova", 1);
if (adExtras != null) {
Iterator<String> it = adExtras.keys();
while (it.hasNext()) {
String key = it.next();
try {
bundle.putString(key, adExtras.get(key).toString());
} catch (JSONException exception) {
Log.w (LOGTAG, String.format("Caught JSON Exception: %s", exception.getMessage()));
}
}
}
AdMobExtras adextras = new AdMobExtras (bundle);
request_builder = request_builder.addNetworkExtras (adextras);
AdRequest request = request_builder.build ();
return request;
}
// Parses the request ad input parameters and runs the request ad action on
// the UI thread.
//
// @param inputs The JSONArray representing input parameters. This function expects the first object in the array to be a JSONObject with the input parameters.
// @return A PluginResult representing whether or not an ad was requested succcessfully.
// Listen for onReceiveAd() and onFailedToReceiveAd() callbacks to see if an ad was successfully retrieved.
private PluginResult executeRequestAd (JSONObject options, CallbackContext callbackContext) {
this.setOptions (options);
if (adView == null) {
callbackContext.error ("adView is null, call createBannerView first");
return null;
}
final CallbackContext delayCallback = callbackContext;
cordova.getActivity().runOnUiThread (new Runnable() {
@Override public void run () {
adView.loadAd (buildAdRequest());
delayCallback.success ();
}
});
return null;
}
private PluginResult executeRequestInterstitialAd (JSONObject options, CallbackContext callbackContext) {
this.setOptions (options);
if (adView == null) {
callbackContext.error ("interstitialAd is null: call createInterstitialView first.");
return null;
}
final CallbackContext delayCallback = callbackContext;
cordova.getActivity().runOnUiThread (new Runnable() {
@Override public void run () {
interstitialAd.loadAd (buildAdRequest());
delayCallback.success ();
}
});
return null;
}
// Parses the show ad input parameters and runs the show ad action on the UI thread.
//
// @param inputs The JSONArray representing input parameters. This function
// expects the first object in the array to be a JSONObject with the
// input parameters.
// @return A PluginResult representing whether or not an ad was requested
// succcessfully. Listen for onReceiveAd() and onFailedToReceiveAd()
// callbacks to see if an ad was successfully retrieved.
private PluginResult executeShowAd (final boolean show, final CallbackContext callbackContext) {
bannerShow = show;
if (adView == null) return new PluginResult (Status.ERROR, "adView is null: call createBannerView first.");
cordova.getActivity().runOnUiThread (new Runnable(){
@Override public void run () {
if(bannerVisible == bannerShow) { // No change.
} else if (bannerShow) {
if (adView.getParent() != null) {
((ViewGroup)adView.getParent()).removeView(adView);
}
if (bannerOverlap) {
RelativeLayout.LayoutParams params2 = new RelativeLayout.LayoutParams(
RelativeLayout.LayoutParams.MATCH_PARENT,
RelativeLayout.LayoutParams.WRAP_CONTENT);
params2.addRule(bannerAtTop ? RelativeLayout.ALIGN_PARENT_TOP : RelativeLayout.ALIGN_PARENT_BOTTOM);
adViewLayout.addView(adView, params2);
adViewLayout.bringToFront();
} else {
if (CORDOVA_4) {
ViewGroup wvParentView = (ViewGroup) webView.getView().getParent();
if (parentView == null) {
parentView = new LinearLayout(webView.getContext());
}
if (wvParentView != null && wvParentView != parentView) {
wvParentView.removeView(webView.getView());
((LinearLayout) parentView).setOrientation(LinearLayout.VERTICAL);
parentView.setLayoutParams(new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT, 0.0F));
webView.getView().setLayoutParams(new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT, 1.0F));
parentView.addView(webView.getView());
cordova.getActivity().setContentView(parentView);
}
} else {
parentView = (ViewGroup) ((ViewGroup) webView).getParent();
}
if (bannerAtTop) {
parentView.addView (adView, 0);
} else {
parentView.addView (adView);
}
parentView.bringToFront ();
parentView.requestLayout();
}
adView.setVisibility (View.VISIBLE);
bannerVisible = true;
} else {
adView.setVisibility (View.GONE);
bannerVisible = false;
}
if (callbackContext != null) callbackContext.success ();
}
});
return null;
}
private PluginResult executeShowInterstitialAd (final boolean show, final CallbackContext callbackContext) {
if (interstitialAd == null) return new PluginResult(Status.ERROR, "interstitialAd is null: call createInterstitialView first.");
cordova.getActivity().runOnUiThread (new Runnable () {
@Override public void run () {
if (interstitialAd.isLoaded()) interstitialAd.show ();
if (callbackContext != null) callbackContext.success ();
}
});
return null;
}
// This class implements the AdMob ad listener events. It forwards the events to the JavaScript layer. To listen for these events, use:
// document.addEventListener ('onReceiveAd' , function());
// document.addEventListener ('onFailedToReceiveAd', function(data){});
// document.addEventListener ('onPresentAd' , function());
// document.addEventListener ('onDismissAd' , function());
// document.addEventListener ('onLeaveToAd' , function());
public class BasicListener extends AdListener {
@Override public void onAdFailedToLoad (int errorCode) {
webView.loadUrl (String.format(
"javascript:cordova.fireDocumentEvent('onFailedToReceiveAd', { 'error': %d, 'reason':'%s' });",
errorCode, getErrorReason(errorCode))
);
}
}
private class BannerListener extends BasicListener {
@Override public void onAdLoaded () {webView.loadUrl ("javascript:cordova.fireDocumentEvent('onReceiveAd');");}
@Override public void onAdOpened () {webView.loadUrl ("javascript:cordova.fireDocumentEvent('onPresentAd');");}
@Override public void onAdClosed () {webView.loadUrl ("javascript:cordova.fireDocumentEvent('onDismissAd');");}
@Override public void onAdLeftApplication () {webView.loadUrl ("javascript:cordova.fireDocumentEvent('onLeaveToAd');");}
}
private class InterstitialListener extends BasicListener {
@Override public void onAdLoaded () {
Log.w ("AdMob", "InterstitialAdLoaded");
webView.loadUrl ("javascript:cordova.fireDocumentEvent('onReceiveInterstitialAd');");
if (autoShowInterstitial) executeShowInterstitialAd (true, null);
}
@Override public void onAdOpened () {
webView.loadUrl ("javascript:cordova.fireDocumentEvent('onPresentInterstitialAd');");
}
@Override public void onAdClosed () {
webView.loadUrl ("javascript:cordova.fireDocumentEvent('onDismissInterstitialAd');");
interstitialAd = null;
}
@Override public void onAdLeftApplication () {
webView.loadUrl ("javascript:cordova.fireDocumentEvent('onLeaveToInterstitialAd');");
interstitialAd = null;
}
}
@Override public void onPause (boolean multitasking) {
if (adView != null) adView.pause ();
super.onPause (multitasking);
}
@Override public void onResume (boolean multitasking) {
super.onResume (multitasking);
isGpsAvailable = (GooglePlayServicesUtil.isGooglePlayServicesAvailable(cordova.getActivity()) == ConnectionResult.SUCCESS);
if (adView != null) adView.resume ();
}
@Override public void onDestroy () {
if (adView != null) {
adView.destroy ();
adView = null;
}
if (adViewLayout != null) {
ViewGroup parentView = (ViewGroup)adViewLayout.getParent();
if(parentView != null) {
parentView.removeView(adViewLayout);
}
adViewLayout = null;
}
super.onDestroy ();
}
/**
* Gets an AdSize object from the string size passed in from JavaScript.
* Returns null if an improper string is provided.
*
* @param size The string size representing an ad format constant.
* @return An AdSize object used to create a banner.
*/
public static AdSize adSizeFromString (String size) {
if ("BANNER".equals(size)) {
return AdSize.BANNER;
} else if ("IAB_MRECT".equals(size)) {
return AdSize.MEDIUM_RECTANGLE;
} else if ("IAB_BANNER".equals(size)) {
return AdSize.FULL_BANNER;
} else if ("IAB_LEADERBOARD".equals(size)) {
return AdSize.LEADERBOARD;
} else if ("SMART_BANNER".equals(size)) {
return AdSize.SMART_BANNER;
} else {
return null;
}
}
/** Gets a string error reason from an error code. */
public String getErrorReason (int errorCode) {
String errorReason = "";
switch(errorCode) {
case AdRequest.ERROR_CODE_INTERNAL_ERROR:
errorReason = "Internal error";
break;
case AdRequest.ERROR_CODE_INVALID_REQUEST:
errorReason = "Invalid request";
break;
case AdRequest.ERROR_CODE_NETWORK_ERROR:
errorReason = "Network Error";
break;
case AdRequest.ERROR_CODE_NO_FILL:
errorReason = "No fill";
break;
}
return errorReason;
}
public static final String md5 (final String s) {
try {
MessageDigest digest = java.security.MessageDigest.getInstance ("MD5");
digest.update (s.getBytes());
byte messageDigest[] = digest.digest ();
StringBuffer hexString = new StringBuffer();
for (int i = 0; i < messageDigest.length; i++) {
String h = Integer.toHexString(0xFF & messageDigest[i]);
while (h.length() < 2) h = "0" + h;
hexString.append (h);
}
return hexString.toString();
} catch (NoSuchAlgorithmException e) {
}
return "";
}
}<|fim▁end|> | interstitialAd.setAdListener (new InterstitialListener());
delayCallback.success (); |
<|file_name|>interval_relu.py<|end_file_name|><|fim▁begin|>"""
relu where each channel has a different leak rate
"""<|fim▁hole|>import theano
import theano.tensor as T
import treeano
import treeano.nodes as tn
fX = theano.config.floatX
@treeano.register_node("interval_relu")
class IntervalReLUNode(treeano.NodeImpl):
hyperparameter_names = ("leak_min",
"leak_max")
def compute_output(self, network, in_vw):
leak_min = network.find_hyperparameter(["leak_min"], 0)
leak_max = network.find_hyperparameter(["leak_max"], 1)
num_channels = in_vw.shape[1]
alpha = np.linspace(leak_min, leak_max, num_channels).astype(fX)
pattern = ["x" if i != 1 else 0 for i in range(in_vw.ndim)]
alpha_var = T.constant(alpha).dimshuffle(*pattern)
out_var = treeano.utils.rectify(in_vw.variable,
negative_coefficient=alpha_var)
network.create_vw(
"default",
variable=out_var,
shape=in_vw.shape,
tags={"output"},
)<|fim▁end|> |
import numpy as np |
<|file_name|>UI.py<|end_file_name|><|fim▁begin|>from tkinter import *
from tkinter import ttk
from tkinter import filedialog
from tkinter import messagebox
from PDFManager.PDFMangerFacade import PDFMangerFacade
class PDFManager_UI:
def __init__(self):
self.i= -1;
self.files=[]
self.root = Tk()
self.root.title('PDFManager')
self.root.wm_iconbitmap("ico.ico") #icona
self.frame = Frame(self.root,height=2,bd=2,relief=SUNKEN,bg='black',)
self.root.resizable(False, False) #settaggio redimensione
#centrare nello schermo
larghezza = self.root.winfo_screenwidth() # larghezza schermo in pixel
altezza = self.root.winfo_screenheight() # altezza schermo in pixel
WIDTH = self.root.winfo_reqwidth()
HEIGHT = self.root.winfo_reqheight()
x = larghezza//2 - WIDTH
y = altezza//2 - HEIGHT
self.root.geometry("%dx%d+%d+%d" % (421,342 , x, y))
self.button_merge = Button(self.root, text = 'Unisci', command=self.__unisci__)
self.button_stitching = Button(self.root,text = 'Dividi',command=self.dividi)
self.button_split = Button(self.root, text = 'Fusione', command=self.__fusione__)
self.button_watermark = Button(self.root, text = 'Filigrana', command=self.__filigrana__)
self.button_encript = Button(self.root, text = 'Cripta', command=self.__cripta__)
self.button_rotate = Button(self.root, text='Ruota', command=self.__ruota__)
self.button_clear =Button(self.root, text='Rimuovi tutto', command=self.__svuota__)
self.password = Entry(self.root)
self.combo_rotate = ttk.Combobox(self.root,state='readonly')
self.combo_rotate['values'] = (0,90,180,270)
lblPass = Label(self.root,text='Password :',anchor=E)
lblGradi = Label(self.root,text='Gradi :',anchor=E)
self.button_add = Button(self.root, text='Aggiungi PDF', command=self.__aggiungi__)
self.button_delete = Button(self.root, text='Rimuovi selezionato', command=self.__rimuovi__)
self.list_file = ttk.Treeview(self.root)
self.list_file['columns'] =('NumeroPagine')
self.list_file.heading("#0",text='NomeFile')
self.list_file.column('#0',anchor=W)
self.list_file.heading('NumeroPagine',text = 'Numero pagine')
self.list_file.column('NumeroPagine',anchor='center',width=100)
self.button_add.grid(row=0, column= 0,columnspan=2,sticky=(W,E))
self.button_delete.grid(row=1,column=0,columnspan=2,sticky=(W,E))
self.button_clear.grid(row = 2,column=0,columnspan=2,sticky=(W,E))
self.list_file.grid(row=0,column=2,columnspan=3,rowspan=3)
self.frame.grid(row=3,column=0,columnspan=5,sticky=(W,E),pady=5)
self.button_merge.grid(row=4,column=0,columnspan=2,sticky=(W,E))
self.button_stitching.grid(row=4,column=3,columnspan=2,sticky=(W,E))
self.button_split.grid(row=5,column=0,columnspan=2,sticky=(W,E))
self.button_watermark.grid(row=5,column=3,columnspan=2,sticky=(W,E))
self.button_encript.grid(row=6,column=0,columnspan=2,sticky=(W,E))
lblPass.grid(row=6,column=2)
self.password.grid(row=6,column=3,columnspan=2,sticky=(W,E))
self.button_rotate.grid(row=7,column=0,columnspan=2,sticky=(W,E))
lblGradi.grid(row=7,column=2)
self.combo_rotate.grid(row=7,column=3,columnspan=2,sticky=(W,E))
self.button_stitching.config(state=DISABLED)
self.button_encript.config(state=DISABLED)
self.button_watermark.config(state=DISABLED)
self.button_merge.config(state=DISABLED)
self.button_split.config(state=DISABLED)
self.button_rotate.config(state=DISABLED)
def __aggiungi__(self):
filelist = filedialog.askopenfilenames(filetypes=[("PDF file",".pdf")])
for file in filelist:
if(file in self.files):
continue
self.i = self.i+1<|fim▁hole|> self.__controlla__()
def __rimuovi__(self):
try:
pos = self.list_file.selection()[0]
posizione = self.list_file.index(pos)
del(self.files[posizione])
self.list_file.delete(pos)
self.i= self.i-1
print(self.files)
except IndexError:
messagebox.showwarning("Attenzione","Nessun elemento selezionato")
self.__controlla__()
def __unisci__(self):
try:
name = filedialog.asksaveasfilename(filetypes=[("PDF file",".pdf")])
if(name.endswith('.pdf') == False):
name = name+'.pdf'
PDFMangerFacade.merge(*self.files, filenameOut=name)
except Exception as e:
messagebox.showwarning("Attenzione",e)
def __svuota__(self):
self.files = []
self.list_file.delete(*self.list_file.get_children())
def dividi(self):
try:
pos = self.list_file.selection()[0]
posizione = self.list_file.index(pos)
phat = filedialog.askdirectory()
prefisso = (self.files[posizione].split("/").pop()).split('.')[0]
PDFMangerFacade.stitching(self.files[posizione], phat + '/' + prefisso)
except IndexError:
messagebox.showwarning("Attenzione","Elemento non selezionato")
def __fusione__(self):
try:
name = filedialog.asksaveasfilename(filetypes=[("PDF file",".pdf")])
PDFMangerFacade.splitting(*self.files,filenameOut = name)
except IndexError as e:
messagebox.showwarning("Attenzione",e)
def __filigrana__(self):
try:
pos = self.list_file.selection()[0]
posizione = self.list_file.index(pos)
print(self.files[posizione])
name_filigrana = filedialog.askopenfilename(filetypes=[("PDF file",".pdf")])
name = filedialog.asksaveasfilename(filetypes=[("PDF file",".pdf")])
PDFMangerFacade.watermark(self.files[posizione], name_filigrana, name)
except IndexError:
messagebox.showwarning("Attenzione","Elemento non selezionato.")
def __cripta__(self):
try:
pos = self.list_file.selection()[0]
posizione = self.list_file.index(pos)
password = self.password.get()
if(password == ""):
messagebox.showwarning("Attenzione","Inserire una password.")
return
name = filedialog.asksaveasfilename(filetypes=[("PDF file",".pdf")])
PDFMangerFacade.encrypt(self.files[posizione], password, name);
self.password.delete(0,'end')
except IndexError:
messagebox.showwarning("Attenzione","Elemento non selezionato.")
def __ruota__(self):
try:
pos = self.list_file.selection()[0]
posizione = self.list_file.index(pos)
gradi = int(self.combo_rotate.get())
name = filedialog.asksaveasfilename(filetypes=[("PDF file",".pdf")])
PDFMangerFacade.rotatePage(self.files[posizione],name,gradi);
except IndexError:
messagebox.showwarning("Attenzione","Elemento non selezionato.")
except ValueError:
messagebox.showwarning("Attenzione","Selezionare il grado di rotazione.")
def start(self):
self.root.mainloop()
def __controlla__(self):
if((self.i+1) == 0):
self.button_stitching.config(state=DISABLED)
self.button_encript.config(state=DISABLED)
self.button_watermark.config(state=DISABLED)
self.button_merge.config(state=DISABLED)
self.button_split.config(state=DISABLED)
self.button_rotate.config(state=DISABLED)
if((self.i+1) ==1):
self.button_stitching.config(state=NORMAL)
self.button_encript.config(state=NORMAL)
self.button_watermark.config(state=NORMAL)
self.button_merge.config(state=DISABLED)
self.button_split.config(state=DISABLED)
self.button_rotate.config(state=NORMAL)
if((self.i+1) >1):
self.button_stitching.config(state=NORMAL)
self.button_encript.config(state=NORMAL)
self.button_watermark.config(state=NORMAL)
self.button_merge.config(state=NORMAL)
self.button_split.config(state=NORMAL)
self.button_rotate.config(state=NORMAL)<|fim▁end|> | self.files.append(file)
split = file.split("/").pop()
self.list_file.insert("",self.i,text=split,values=(PDFMangerFacade.pagescount(file)))
|
<|file_name|>step4.rs<|end_file_name|><|fim▁begin|>println!("14. Issuer (Trust Anchor) is creating a Credential Offer for Prover");
let cred_offer_json = anoncreds::issuer_create_credential_offer(wallet_handle, &cred_def_id).wait().unwrap();
println!("15. Prover creates Credential Request");
let (cred_req_json, cred_req_metadata_json) = anoncreds::prover_create_credential_req(prover_wallet_handle, prover_did, &cred_offer_json, &cred_def_json, &master_secret_name).wait().unwrap();
println!("16. Issuer (Trust Anchor) creates Credential for Credential Request");
let cred_values_json = json!({
"sex": { "raw": "male", "encoded": "5944657099558967239210949258394887428692050081607692519917050011144233115103" },
"name": { "raw": "Alex", "encoded": "99262857098057710338306967609588410025648622308394250666849665532448612202874" },
"height": { "raw": "175", "encoded": "175" },
"age": { "raw": "28", "encoded": "28" },
});
println!("cred_values_json = '{}'", &cred_values_json.to_string());
let (cred_json, _cred_revoc_id, _revoc_reg_delta_json) =
anoncreds::issuer_create_credential(wallet_handle, &cred_offer_json, &cred_req_json, &cred_values_json.to_string(), None, -1).wait().unwrap();
println!("17. Prover processes and stores Credential");
let out_cred_id = anoncreds::prover_store_credential(prover_wallet_handle, None, &cred_req_metadata_json, &cred_json, &cred_def_json, None).wait().unwrap();
println!("Stored Credential ID is {}", &out_cred_id);
// Clean UP
println!("17. Close and delete two wallets");
wallet::close_wallet(prover_wallet_handle).wait().unwrap();
wallet::delete_wallet(&prover_wallet_config, USEFUL_CREDENTIALS).wait().unwrap();
wallet::close_wallet(wallet_handle).wait().unwrap();
wallet::delete_wallet(&config, USEFUL_CREDENTIALS).wait().unwrap();<|fim▁hole|>pool::delete_pool_ledger(&pool_name).wait().unwrap();<|fim▁end|> |
println!("18. Close pool and delete pool ledger config");
pool::close_pool_ledger(pool_handle).wait().unwrap(); |
<|file_name|>JsonConfigReader.ts<|end_file_name|><|fim▁begin|>let fs = require('fs');
import { ConfigParams } from './ConfigParams';
import { IConfigurable } from './IConfigurable';
import { FileConfigReader } from './FileConfigReader';
import { ConfigException } from '../errors/ConfigException'
import { FileException } from '../errors/FileException'
import { JsonConverter } from '../convert/JsonConverter'
/**
* Provides methods for reading configuration parameters from a JSON file.
*
* @see FileConfigReader
*/
export class JsonConfigReader extends FileConfigReader {
/**
* @param path (optional) path to the target file containing configuration parameters in JSON format.
* If 'path' is omitted in the constructor, then it must be set otherwise
* (for example, using "setPath()") before using the new object.
*
* @see FileConfigReader
* @see FileConfigReader#setPath
*/
public constructor(path: string = null) {
super(path);
}
/**
* Reads the JSON data from the file and returns it as a parameterized {@link NullableMap} object.
* Reader's path must be set.
*
<|fim▁hole|> * @returns NullableMap with data from the JSON file.
*
* @see ConfigReader#parameterize
* @see NullableMap
*/
public readObject(correlationId: string, parameters: ConfigParams): any {
if (super.getPath() == null)
throw new ConfigException(correlationId, "NO_PATH", "Missing config file path");
try {
// Todo: make this async?
let data: string = fs.readFileSync(super.getPath(), "utf8");
data = this.parameterize(data, parameters);
return JsonConverter.toNullableMap(data);
} catch (e) {
throw new FileException(
correlationId,
"READ_FAILED",
"Failed reading configuration " + super.getPath() + ": " + e
)
.withDetails("path", super.getPath())
.withCause(e);
}
}
/**
* Reads the JSON data from the file and returns it as a parameterized {@link ConfigParams} object.
* Reader's path must be set.
*
* @param correlationId unique business transaction id to trace calls across components.
* @param parameters used to parameterize the reader.
* @param callback callback function that will be called with an error or with the
* ConfigParams that were read.
* @see #readObject(correlationId: string, parameters: ConfigParams)
*/
public readConfig(correlationId: string, parameters: ConfigParams,
callback: (err: any, config: ConfigParams) => void): void {
try {
let value: any = this.readObject(correlationId, parameters);
let config = ConfigParams.fromValue(value);
callback(null, config);
} catch (ex) {
callback(ex, null);
}
}
/**
* Static implementation of JsonConfigReader's non-static {@link #readObject}.
*
* @param correlationId unique business transaction id to trace calls across components.
* @param path location of the target JSON file.
* @param parameters used to parameterize the reader.
*
* @see #readObject(correlationId: string, parameters: ConfigParams)
*/
public static readObject(correlationId: string, path: string, parameters: ConfigParams): void {
return new JsonConfigReader(path).readObject(correlationId, parameters);
}
/**
* Static implementation of JsonConfigReader's non-static {@link #readConfig}.
*
* @param correlationId unique business transaction id to trace calls across components.
* @param path location of the target JSON file.
* @param parameters used to parameterize the reader.
*
* @see #readConfig(correlationId: string, parameters: ConfigParams, callback: (err: any, config: ConfigParams) => void)
*/
public static readConfig(correlationId: string, path: string, parameters: ConfigParams): ConfigParams {
let value: any = new JsonConfigReader(path).readObject(correlationId, parameters);
let config = ConfigParams.fromValue(value);
return config;
}
}<|fim▁end|> | * @param correlationId unique business transaction id to trace calls across components.
* @param parameters used to parameterize the reader.
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.