prompt
large_stringlengths 70
991k
| completion
large_stringlengths 0
1.02k
|
---|---|
<|file_name|>posix.rs<|end_file_name|><|fim▁begin|>#![allow(dead_code)]
// New rule: only posix.rs gets to use libc.
extern crate libc;
use std::process::exit;
use std::mem;
use std::ops::Drop;
use std::io;
use std::io::Result;
use std::io::Read;
use std::io::Write;
use std::io::Error;
use std::io::ErrorKind;
use std::fmt;
use std::os::unix::io::AsRawFd;
use std::fs::File;
extern "C" {
fn tcsetpgrp(fd: libc::c_int, prgp: libc::pid_t) -> libc::c_int;
}
// eek!
#[repr(C)]
struct Repr<T> {
data: *const T,
len: usize,
}
macro_rules! etry {
($e:expr) => {{
let res = $e;
if res < 0 {
return Err(Error::last_os_error());
}
res
}}
}
// Note that we can't derive Clone/Copy on FileDesc: since we use drop
// to close the file, making copies will give us unexpected fd closure.
/// Struct representing a file descriptor.
pub struct FileDesc(i32);
/// Struct representing the readable side of a pipe.
pub struct ReadPipe(FileDesc);
/// Struct representing the writable side of a pipe.
pub struct WritePipe(FileDesc);
/// Struct representing a process' pgid
#[derive(Clone, Copy)]
pub struct Pgid(i32);
/// Struct representing a process' pid
#[derive(Clone, Copy, Debug)]
pub struct Pid(i32);
/// Struct representing a process' status
#[derive(Clone, Copy)]
pub struct Status(i32);
impl Status {
pub fn to_int(&self) -> i32 {
self.0
}
pub fn to_string(&self) -> String {
self.0.to_string()
}
}
impl Pid {
pub fn current() -> i32 {
unsafe { libc::getpid() }
}
pub fn to_pgid(&self) -> Pgid {
Pgid(self.0)
}
}
impl fmt::Display for FileDesc {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "{}", self.0)
}
}
impl Read for FileDesc {
fn read(&mut self, buf: &mut [u8]) -> Result<usize> {
let ret = etry!(unsafe {
libc::read(self.0,
buf.as_mut_ptr() as *mut libc::c_void,
buf.len() as libc::size_t)
});
Ok(ret as usize)
}
fn read_to_end(&mut self, buf: &mut Vec<u8>) -> io::Result<usize> {
// this is essentially a copy of read_to_end_uninitialized from std::io
let start_len = buf.len();
buf.reserve(16);
loop {
if buf.len() == buf.capacity() {
buf.reserve(1);
}
// from_raw_parts_mut from libcore
unsafe {
let buf_slice = mem::transmute(Repr {
data: buf.as_mut_ptr().offset(buf.len() as isize),
len: buf.capacity() - buf.len(),
});
match self.read(buf_slice) {
Ok(0) => {
return Ok(buf.len() - start_len);
}
Ok(n) => {
let len = buf.len() + n;
buf.set_len(len);
}
Err(ref e) if e.kind() == ErrorKind::Interrupted => {}
Err(e) => {
return Err(e);
}
}
}
}
}
}
impl Write for FileDesc {
fn write(&mut self, buf: &[u8]) -> Result<usize> {
let ret = etry!(unsafe {
libc::write(self.0,
buf.as_ptr() as *const libc::c_void,
buf.len() as libc::size_t)
});
Ok(ret as usize)
}
fn flush(&mut self) -> Result<()> {
// given we are only using FileDesc structs for pipes,
// flush isn't important (TODO: confirm this?)
Ok(())
}
}
impl FileDesc {
pub fn new(n: i32) -> Self {
FileDesc(n)
}
pub fn into_raw(self) -> i32 {
let fd = self.0;
mem::forget(self);
fd
}
}
impl Drop for FileDesc {
fn drop(&mut self) {
let _ = unsafe { libc::close(self.0) };
}
}
impl From<File> for FileDesc {
fn from(f: File) -> Self {
let fd = f.as_raw_fd();
mem::forget(f);
FileDesc(fd)
}
}
impl ReadPipe {
pub fn into_raw(self) -> i32 {
self.0.into_raw()
}
pub fn close(self) {
drop(self)
}
}
impl WritePipe {
pub fn into_raw(self) -> i32 {
self.0.into_raw()
}
pub fn close(self) {
drop(self)
}
}
impl Read for ReadPipe {
fn read(&mut self, buf: &mut [u8]) -> Result<usize> {
self.0.read(buf)
}
}
impl Write for WritePipe {
fn write(&mut self, buf: &[u8]) -> Result<usize> {
self.0.write(buf)
}
fn flush(&mut self) -> Result<()> {
self.0.flush()
}
}
/// Initialize the shell in a POSIX-pleasing way
pub fn init() {
// wait until we are in the fg
unsafe {
let pgid = libc::getpgrp();
while libc::tcgetpgrp(libc::STDIN_FILENO) != pgid {
libc::kill(-libc::STDIN_FILENO, libc::SIGTTIN);
}
}
// ignore interactive signals && job control signals
if let Err(e) = set_signal_ignore(true) {
println!("Could not set signals as ignored: {}", e);
}
// guarantee we are in charge of the terminal/we are process group leader
unsafe {
let pgid = libc::getpid();
if pgid != libc::getpgrp() {
if libc::setpgid(pgid, pgid) < 0 {
err!("Couldn't put shell in its own process group: {}",
Error::last_os_error());
}
}
}
if let Err(e) = take_terminal() {
err!("Couldn't take the terminal: {}", e);
}
}
/// Returns true iff stdin is a TTY; or, equivalently, if the
/// shell is to be interactive.
pub fn is_interactive() -> bool {
unsafe {
// since stdin is always a valid fd, will only return 0
// if stdin is in fact not a TTY
libc::isatty(libc::STDIN_FILENO) != 0
}
}
/// (Attempts to) create a pipe.
pub fn pipe() -> io::Result<(ReadPipe, WritePipe)> {
unsafe {
let mut fds = [0; 2];
etry!(libc::pipe(fds.as_mut_ptr()));
Ok((ReadPipe(FileDesc(fds[0])), WritePipe(FileDesc(fds[1]))))
}
}
/// Waits for any child process to finish.
pub fn wait_any() -> Result<(Pid, Option<Status>)> {
unimplemented!();
}
/// Waits for any child from the given process group to finish.
pub fn wait_pgid(_group: &Pgid) -> Result<(Pid, Option<Status>)> {
unimplemented!();
}
/// Waits for a child process to finish.
pub fn wait_pid(child: &Pid) -> Result<Option<Status>> {
unsafe {
let mut st: i32 = 0;
if libc::waitpid(child.0, &mut st, 0) < 0 {
if Error::last_os_error().kind() == ErrorKind::Interrupted {
Ok(None)
} else {
Err(Error::last_os_error())
}
} else {
let st = st >> 8;
Ok(Some(Status(st)))
}
}
}
/// Set stdin to be the current pipe.
pub fn set_stdin(pipe: ReadPipe) -> Result<()> {
unsafe {
let fd = pipe.into_raw();
etry!(libc::dup2(fd, libc::STDIN_FILENO));
};
Ok(())
}
/// Set stdout to be the current pipe.
pub fn set_stdout(pipe: WritePipe) -> Result<()> {
unsafe {
let fd = pipe.into_raw();
etry!(libc::dup2(fd, libc::STDOUT_FILENO));
};
Ok(())
}
pub fn dup_fd(src: i32) -> Result<i32> {
let res = unsafe { etry!(libc::dup(src)) };
Ok(res)
}
pub fn dup_stdin() -> Result<ReadPipe> {
let n_fd = try!(dup_fd(0));
Ok(ReadPipe(FileDesc(n_fd)))
}
pub fn dup_stdout() -> Result<WritePipe> {
let n_fd = try!(dup_fd(1));
Ok(WritePipe(FileDesc(n_fd)))
}
pub fn dup_fds(src: i32, dest: i32) -> Result<()> {
unsafe {
etry!(libc::dup2(dest, src));
}
Ok(())
}
pub fn set_signal_ignore(ignore: bool) -> Result<()> {
macro_rules! stry {
($e:expr) => {{
let res = $e;
if res == libc::SIG_ERR {
return Err(Error::last_os_error());
}
res
}}
}
let action = if ignore {
libc::SIG_IGN
} else {
libc::SIG_DFL
};
unsafe {
stry!(libc::signal(libc::SIGINT, action));
stry!(libc::signal(libc::SIGQUIT, action));
stry!(libc::signal(libc::SIGTSTP, action));
stry!(libc::signal(libc::SIGTTIN, action));
stry!(libc::signal(libc::SIGTTOU, action));
}
Ok(())
}
pub fn fork(inter: bool, pgid: Option<Pgid>) -> Result<Option<Pid>> {
let c_pid = unsafe { etry!(libc::fork()) };
if c_pid == 0 {
if inter {
if let Err(e) = set_signal_ignore(false) {
warn!("Child could not listen to signals: {}", e);
exit(2);
}
}
Ok(None)
} else {
let pid = Some(Pid(c_pid));
if inter {
try!(put_into_pgrp(pid, pgid));
try!(set_signal_ignore(false));
}
Ok(pid)
}
}
/// Puts a process into a process group.
/// If pid is None, puts the calling process into the process group.
/// If pgid is None, creates a new process group with pgid = pid.
///
/// Returns, upon success, the Pgid into which this process was put.
///
/// (Even if both pid and pgid is None, returns a nonzero Pgid value which
/// can be used to put other processes into the same process group.)
pub fn put_into_pgrp(pid: Option<Pid>, pgid: Option<Pgid>) -> Result<Pgid> {
let pid = unsafe {
if let Some(pid) = pid {
pid.0
} else {<|fim▁hole|> }
};
if let Some(pgid) = pgid {
unsafe {
etry!(libc::setpgid(pid, pgid.0));
}
Ok(pgid)
} else {
unsafe {
etry!(libc::setpgid(pid, pid));
}
Ok(Pgid(pid))
}
}
pub fn give_terminal(pgid: Pgid) -> Result<()> {
unsafe {
if etry!(libc::tcgetpgrp(libc::STDIN_FILENO)) != pgid.0 {
etry!(tcsetpgrp(libc::STDIN_FILENO, pgid.0));
}
}
Ok(())
}
pub fn take_terminal() -> Result<()> {
unsafe {
let my_pgid = Pgid(libc::getpgrp());
give_terminal(my_pgid)
}
}
// This shouldn't probably do much, since we want BuiltinProcesses to work correctly
// in the interactive case, and those won't be calling this function at all.
pub fn execv(cmd: *const i8, argv: *const *const i8) -> Error {
unsafe {
libc::execv(cmd, argv);
}
Error::last_os_error()
}<|fim▁end|> | libc::getpid() |
<|file_name|>TreeWidget.py<|end_file_name|><|fim▁begin|># XXX TO DO:
# - popup menu
# - support partial or total redisplay
# - key bindings (instead of quick-n-dirty bindings on Canvas):
# - up/down arrow keys to move focus around
# - ditto for page up/down, home/end
# - left/right arrows to expand/collapse & move out/in
# - more doc strings
# - add icons for "file", "module", "class", "method"; better "python" icon
# - callback for selection???
# - multiple-item selection
# - tooltips
# - redo geometry without magic numbers
# - keep track of object ids to allow more careful cleaning
# - optimize tree redraw after expand of subnode
import os
from Tkinter import *
import imp
from idlelib import ZoomHeight
from idlelib.configHandler import idleConf
ICONDIR = "Icons"
# Look for Icons subdirectory in the same directory as this module
try:
_icondir = os.path.join(os.path.dirname(__file__), ICONDIR)
except NameError:
_icondir = ICONDIR
if os.path.isdir(_icondir):
ICONDIR = _icondir
elif not os.path.isdir(ICONDIR):
raise RuntimeError, "can't find icon directory (%r)" % (ICONDIR,)
def listicons(icondir=ICONDIR):
"""Utility to display the available icons."""
root = Tk()
import glob
list = glob.glob(os.path.join(icondir, "*.gif"))
list.sort()
images = []
row = column = 0
for file in list:
name = os.path.splitext(os.path.basename(file))[0]
image = PhotoImage(file=file, master=root)
images.append(image)
label = Label(root, image=image, bd=1, relief="raised")
label.grid(row=row, column=column)
label = Label(root, text=name)
label.grid(row=row+1, column=column)
column = column + 1
if column >= 10:
row = row+2
column = 0
root.images = images
class TreeNode:
def __init__(self, canvas, parent, item):
self.canvas = canvas
self.parent = parent
self.item = item
self.state = 'collapsed'
self.selected = False
self.children = []
self.x = self.y = None
self.iconimages = {} # cache of PhotoImage instances for icons
def destroy(self):
for c in self.children[:]:
self.children.remove(c)
c.destroy()
self.parent = None
def geticonimage(self, name):
try:
return self.iconimages[name]
except KeyError:
pass
file, ext = os.path.splitext(name)
ext = ext or ".gif"
fullname = os.path.join(ICONDIR, file + ext)
image = PhotoImage(master=self.canvas, file=fullname)
self.iconimages[name] = image
return image
def select(self, event=None):
if self.selected:
return
self.deselectall()
self.selected = True
self.canvas.delete(self.image_id)
self.drawicon()
self.drawtext()
def deselect(self, event=None):
if not self.selected:
return
self.selected = False
self.canvas.delete(self.image_id)
self.drawicon()
self.drawtext()
def deselectall(self):
if self.parent:
self.parent.deselectall()
else:
self.deselecttree()
def deselecttree(self):
if self.selected:
self.deselect()
for child in self.children:
child.deselecttree()
def flip(self, event=None):
if self.state == 'expanded':
self.collapse()
else:
self.expand()
self.item.OnDoubleClick()
return "break"
def expand(self, event=None):
if not self.item._IsExpandable():
return
if self.state != 'expanded':
self.state = 'expanded'
self.update()
self.view()
def collapse(self, event=None):
if self.state != 'collapsed':
self.state = 'collapsed'
self.update()
def view(self):
top = self.y - 2
bottom = self.lastvisiblechild().y + 17
height = bottom - top
visible_top = self.canvas.canvasy(0)
visible_height = self.canvas.winfo_height()
visible_bottom = self.canvas.canvasy(visible_height)
if visible_top <= top and bottom <= visible_bottom:
return
x0, y0, x1, y1 = self.canvas._getints(self.canvas['scrollregion'])
if top >= visible_top and height <= visible_height:
fraction = top + height - visible_height
else:
fraction = top
fraction = float(fraction) / y1
self.canvas.yview_moveto(fraction)
def lastvisiblechild(self):
if self.children and self.state == 'expanded':
return self.children[-1].lastvisiblechild()
else:
return self
def update(self):
if self.parent:
self.parent.update()
else:
oldcursor = self.canvas['cursor']
self.canvas['cursor'] = "watch"
self.canvas.update()
self.canvas.delete(ALL) # XXX could be more subtle
self.draw(7, 2)
x0, y0, x1, y1 = self.canvas.bbox(ALL)
self.canvas.configure(scrollregion=(0, 0, x1, y1))
self.canvas['cursor'] = oldcursor
def draw(self, x, y):
# XXX This hard-codes too many geometry constants!
self.x, self.y = x, y
self.drawicon()
self.drawtext()
if self.state != 'expanded':
return y+17
# draw children
if not self.children:
sublist = self.item._GetSubList()
if not sublist:
# _IsExpandable() was mistaken; that's allowed
return y+17
for item in sublist:
child = self.__class__(self.canvas, self, item)
self.children.append(child)
cx = x+20
cy = y+17
cylast = 0
for child in self.children:
cylast = cy
self.canvas.create_line(x+9, cy+7, cx, cy+7, fill="gray50")
cy = child.draw(cx, cy)
if child.item._IsExpandable():
if child.state == 'expanded':
iconname = "minusnode"
callback = child.collapse
else:
iconname = "plusnode"
callback = child.expand
image = self.geticonimage(iconname)
id = self.canvas.create_image(x+9, cylast+7, image=image)
# XXX This leaks bindings until canvas is deleted:
self.canvas.tag_bind(id, "<1>", callback)
self.canvas.tag_bind(id, "<Double-1>", lambda x: None)
id = self.canvas.create_line(x+9, y+10, x+9, cylast+7,
##stipple="gray50", # XXX Seems broken in Tk 8.0.x
fill="gray50")
self.canvas.tag_lower(id) # XXX .lower(id) before Python 1.5.2
return cy
def drawicon(self):
if self.selected:
imagename = (self.item.GetSelectedIconName() or
self.item.GetIconName() or
"openfolder")
else:
imagename = self.item.GetIconName() or "folder"
image = self.geticonimage(imagename)
id = self.canvas.create_image(self.x, self.y, anchor="nw", image=image)
self.image_id = id
self.canvas.tag_bind(id, "<1>", self.select)
self.canvas.tag_bind(id, "<Double-1>", self.flip)
def drawtext(self):
textx = self.x+20-1
texty = self.y-1
labeltext = self.item.GetLabelText()
if labeltext:
id = self.canvas.create_text(textx, texty, anchor="nw",
text=labeltext)
self.canvas.tag_bind(id, "<1>", self.select)
self.canvas.tag_bind(id, "<Double-1>", self.flip)
x0, y0, x1, y1 = self.canvas.bbox(id)
textx = max(x1, 200) + 10
text = self.item.GetText() or "<no text>"
try:
self.entry
except AttributeError:
pass
else:
self.edit_finish()
try:
label = self.label
except AttributeError:
# padding carefully selected (on Windows) to match Entry widget:
self.label = Label(self.canvas, text=text, bd=0, padx=2, pady=2)
theme = idleConf.GetOption('main','Theme','name')
if self.selected:
self.label.configure(idleConf.GetHighlight(theme, 'hilite'))
else:
self.label.configure(idleConf.GetHighlight(theme, 'normal'))
id = self.canvas.create_window(textx, texty,
anchor="nw", window=self.label)
self.label.bind("<1>", self.select_or_edit)
self.label.bind("<Double-1>", self.flip)
self.text_id = id
def select_or_edit(self, event=None):
if self.selected and self.item.IsEditable():
self.edit(event)
else:
self.select(event)
def edit(self, event=None):
self.entry = Entry(self.label, bd=0, highlightthickness=1, width=0)
self.entry.insert(0, self.label['text'])
self.entry.selection_range(0, END)
self.entry.pack(ipadx=5)
self.entry.focus_set()
self.entry.bind("<Return>", self.edit_finish)
self.entry.bind("<Escape>", self.edit_cancel)
def edit_finish(self, event=None):
try:
entry = self.entry
del self.entry
except AttributeError:
return
text = entry.get()
entry.destroy()
if text and text != self.item.GetText():
self.item.SetText(text)
text = self.item.GetText()
self.label['text'] = text
self.drawtext()
self.canvas.focus_set()
def edit_cancel(self, event=None):
try:
entry = self.entry
del self.entry
except AttributeError:
return
entry.destroy()
self.drawtext()
self.canvas.focus_set()
class TreeItem:
"""Abstract class representing tree items.
Methods should typically be overridden, otherwise a default action
is used.
"""
def __init__(self):
"""Constructor. Do whatever you need to do."""
def GetText(self):
"""Return text string to display."""
def GetLabelText(self):
"""Return label text string to display in front of text (if any)."""
expandable = None
def _IsExpandable(self):
"""Do not override! Called by TreeNode."""
if self.expandable is None:
self.expandable = self.IsExpandable()
return self.expandable
def IsExpandable(self):
"""Return whether there are subitems."""
return 1
def _GetSubList(self):
"""Do not override! Called by TreeNode."""
if not self.IsExpandable():
return []
sublist = self.GetSubList()
if not sublist:
self.expandable = 0
return sublist
def IsEditable(self):
"""Return whether the item's text may be edited."""
def SetText(self, text):
"""Change the item's text (if it is editable)."""
def GetIconName(self):
"""Return name of icon to be displayed normally."""
def GetSelectedIconName(self):
"""Return name of icon to be displayed when selected."""
def GetSubList(self):
"""Return list of items forming sublist."""
def OnDoubleClick(self):
"""Called on a double-click on the item."""
# Example application
class FileTreeItem(TreeItem):
"""Example TreeItem subclass -- browse the file system."""
def __init__(self, path):
self.path = path
def GetText(self):
return os.path.basename(self.path) or self.path
def IsEditable(self):
return os.path.basename(self.path) != ""
def SetText(self, text):
newpath = os.path.dirname(self.path)
newpath = os.path.join(newpath, text)
if os.path.dirname(newpath) != os.path.dirname(self.path):
return
try:
os.rename(self.path, newpath)
self.path = newpath
except os.error:
pass
def GetIconName(self):
if not self.IsExpandable():
return "python" # XXX wish there was a "file" icon
def IsExpandable(self):
return os.path.isdir(self.path)
def GetSubList(self):
try:
names = os.listdir(self.path)
except os.error:
return []
names.sort(key = os.path.normcase)
sublist = []
for name in names:
item = FileTreeItem(os.path.join(self.path, name))
sublist.append(item)
return sublist
# A canvas widget with scroll bars and some useful bindings
class ScrolledCanvas:
def __init__(self, master, **opts):
if 'yscrollincrement' not in opts:
opts['yscrollincrement'] = 17
self.master = master
self.frame = Frame(master)
self.frame.rowconfigure(0, weight=1)
self.frame.columnconfigure(0, weight=1)
self.canvas = Canvas(self.frame, **opts)
self.canvas.grid(row=0, column=0, sticky="nsew")
<|fim▁hole|> self.vbar = Scrollbar(self.frame, name="vbar")
self.vbar.grid(row=0, column=1, sticky="nse")
self.hbar = Scrollbar(self.frame, name="hbar", orient="horizontal")
self.hbar.grid(row=1, column=0, sticky="ews")
self.canvas['yscrollcommand'] = self.vbar.set
self.vbar['command'] = self.canvas.yview
self.canvas['xscrollcommand'] = self.hbar.set
self.hbar['command'] = self.canvas.xview
self.canvas.bind("<Key-Prior>", self.page_up)
self.canvas.bind("<Key-Next>", self.page_down)
self.canvas.bind("<Key-Up>", self.unit_up)
self.canvas.bind("<Key-Down>", self.unit_down)
#if isinstance(master, Toplevel) or isinstance(master, Tk):
self.canvas.bind("<Alt-Key-2>", self.zoom_height)
self.canvas.focus_set()
def page_up(self, event):
self.canvas.yview_scroll(-1, "page")
return "break"
def page_down(self, event):
self.canvas.yview_scroll(1, "page")
return "break"
def unit_up(self, event):
self.canvas.yview_scroll(-1, "unit")
return "break"
def unit_down(self, event):
self.canvas.yview_scroll(1, "unit")
return "break"
def zoom_height(self, event):
ZoomHeight.zoom_height(self.master)
return "break"
# Testing functions
def test():
from idlelib import PyShell
root = Toplevel(PyShell.root)
root.configure(bd=0, bg="yellow")
root.focus_set()
sc = ScrolledCanvas(root, bg="white", highlightthickness=0, takefocus=1)
sc.frame.pack(expand=1, fill="both")
item = FileTreeItem("C:/windows/desktop")
node = TreeNode(sc.canvas, None, item)
node.expand()
def test2():
# test w/o scrolling canvas
root = Tk()
root.configure(bd=0)
canvas = Canvas(root, bg="white", highlightthickness=0)
canvas.pack(expand=1, fill="both")
item = FileTreeItem(os.curdir)
node = TreeNode(canvas, None, item)
node.update()
canvas.focus_set()
if __name__ == '__main__':
test()<|fim▁end|> | |
<|file_name|>network.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*-
import socket
from paramiko import SSHClient, AutoAddPolicy, AuthenticationException
from bssh.utils import env
from bssh.auth import get_pkey
from bssh.logger import logger
def connect(
hostname=None,
port=22,
username=None,
password=None,
pkey=None,
pkey_pwd=None,
sock=None,
timeout=env.timeout,
**kwargs
):
"""Connect the remote ssh server"""
passauth = True if password else False
pkey = pkey if passauth else get_pkey(pkey, pkey_pwd)
client = SSHClient()
client.set_missing_host_key_policy(AutoAddPolicy())
try:
client.connect(hostname=hostname,
port=int(port),
username=username,
password=password,
pkey=pkey,
sock=sock,
timeout=timeout)
logger.login.debug('%s connect successfully.' % hostname)
return client
except AuthenticationException:
logger.login.error('%s Validation failed.' % hostname)<|fim▁hole|><|fim▁end|> | except socket.error:
logger.login.error('%s Network Error' % hostname)
except Exception as e:
logger.login.error('%s %s' % (hostname, str(e))) |
<|file_name|>NodeProperty.rs<|end_file_name|><|fim▁begin|>GUI.NodeProperty$4
GUI.NodeProperty
GUI.NodeProperty$5
GUI.NodeProperty$2
GUI.NodeProperty$3
GUI.NodeProperty$8
GUI.NodeProperty$9
GUI.NodeProperty$6
GUI.NodeProperty$7
GUI.NodeProperty$11
GUI.NodeProperty$12
GUI.NodeProperty$10<|fim▁hole|><|fim▁end|> | GUI.NodeProperty$1
GUI.NodeProperty$13
GUI.NodeProperty$14 |
<|file_name|>test_import_command.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*-
from __future__ import absolute_import, unicode_literals
import datetime
from collections import namedtuple
import mock
import six
from django.conf import settings
from django.test import TestCase
from django.utils import timezone
from wagtail.wagtailcore.models import Page
from articles.models import ArticleCategory, ArticlePage
from images.models import AttributedImage
from people.models import ContributorPage
from wordpress_importer.management.commands import import_from_wordpress
from wordpress_importer.models import (ImageImport, ImportDownloadError,
PostImport)
class ImageCleanUp(object):
def delete_images(self):
# clean up any image files that were created.
images = AttributedImage.objects.all()
for image in images:
storage, path = image.file.storage, image.file.path
image.delete()
storage.delete(path)
FakeResponse = namedtuple('FakeResponse', 'status_code, content')
def local_get_successful(url):
"Fetch a stream from local files."
p_url = six.moves.urllib.parse.urlparse(url)
if p_url.scheme != 'file':
raise ValueError("Expected file scheme")
filename = six.moves.urllib.request.url2pathname(p_url.path)
response = FakeResponse(200, open(filename, 'rb').read())
return response
def local_get_404(url):
"Fetch a stream from local files."
response = FakeResponse(404, None)
return response
test_image_url = 'file:///{}/wordpress_importer/tests/files/testcat.jpg'.format(
settings.PROJECT_ROOT)
test_image_url_with_unicode = 'file:///{}/wordpress_importer/tests/files/testcat♥.jpg'.format(
settings.PROJECT_ROOT)
class TestCommandImportFromWordPressLoadContributors(TestCase, ImageCleanUp):
def setUp(self):
import_from_wordpress.Command.get_contributor_data = self.get_test_contributor_data
def tearDown(self):
self.delete_images()
@mock.patch('requests.get', local_get_successful)
def testLoadContributorsCreatesContributor(self):
command = import_from_wordpress.Command()
command.load_contributors()
contributors = ContributorPage.objects.filter(email='[email protected]')
self.assertEqual(1, contributors.count())
@mock.patch('requests.get', local_get_successful)
def testLoadContributorsSetsFirstName(self):
command = import_from_wordpress.Command()
command.load_contributors()
contributors = ContributorPage.objects.filter(email='[email protected]')
self.assertEqual('Bob', contributors.first().first_name)
@mock.patch('requests.get', local_get_successful)
def testLoadContributorsSetsLastName(self):
command = import_from_wordpress.Command()
command.load_contributors()
contributors = ContributorPage.objects.filter(email='[email protected]')
self.assertEqual('Smith', contributors.first().last_name)
@mock.patch('requests.get', local_get_successful)
def testLoadContributorsSetsNickname(self):
command = import_from_wordpress.Command()
command.load_contributors()
contributors = ContributorPage.objects.filter(email='[email protected]')
self.assertEqual('Bobby Smith', contributors.first().nickname)
@mock.patch('requests.get', local_get_successful)
def testLoadContributorsSetsTwitterHandle(self):
command = import_from_wordpress.Command()
command.load_contributors()
contributors = ContributorPage.objects.filter(email='[email protected]')
self.assertEqual('@bobsmith', contributors.first().twitter_handle)
@mock.patch('requests.get', local_get_successful)
def testLoadContributorsSetsTwitterHandleFromUrl(self):
import_from_wordpress.Command.get_contributor_data = self.get_test_contributor_data_twitter_url
command = import_from_wordpress.Command()
command.load_contributors()
contributors = ContributorPage.objects.filter(email='[email protected]')
self.assertEqual('@bobsmith', contributors.first().twitter_handle)
@mock.patch('requests.get', local_get_successful)
def testLoadContributorsSetsLongBio(self):
command = import_from_wordpress.Command()
command.load_contributors()
contributors = ContributorPage.objects.filter(email='[email protected]')
self.assertEqual('Bob Smith is a person who does stuff.',
contributors.first().long_bio)
@mock.patch('requests.get', local_get_successful)
def testLoadContributorsSetsShortBio(self):
command = import_from_wordpress.Command()
command.load_contributors()
contributors = ContributorPage.objects.filter(email='[email protected]')
self.assertEqual('He does stuff.',
contributors.first().short_bio)
# @mock.patch('requests.get', local_get_successful)
# def testLoadContributorsSetsImageFile(self):
# command = import_from_wordpress.Command()
# command.load_contributors()
# contributors = ContributorPage.objects.filter(email='[email protected]')
#
# images = AttributedImage.objects.filter(title='testcat.jpg')
# self.assertEqual(1, images.count())
# self.assertEqual(images.first(), contributors.first().headshot)
#
# @mock.patch('requests.get', local_get_404)
# def testDownloadErrorLoggedWhenErrorGettingImage(self):
# command = import_from_wordpress.Command()
# command.load_contributors()
#
# errors = ImportDownloadError.objects.all()
# self.assertEqual(1, errors.count())
# self.assertEqual(404, errors.first().status_code)
# self.assertEqual(settings.WP_IMPORTER_USER_PHOTO_URL_PATTERN.format("testcat.jpg"), errors.first().url)
def get_test_contributor_data(self):
data = [
('[email protected]', 'first_name', 'Bob'),
('[email protected]', 'last_name', 'Smith'),
('[email protected]', 'nickname', 'Bobby Smith'),
('[email protected]', 'twitter', '@bobsmith'),
('[email protected]', 'description',
'Bob Smith is a person who does stuff.'),
('[email protected]', 'SHORT_BIO',
'He does stuff.'),
('[email protected]', 'userphoto_image_file', 'testcat.jpg'),
]
return data
def get_test_contributor_data_twitter_url(self):
data = [
('[email protected]', 'first_name', 'Bob'),
('[email protected]', 'last_name', 'Smith'),
('[email protected]', 'nickname', 'Bobby Smith'),
('[email protected]', 'TWITTER', 'https://twitter.com/bobsmith'),
('[email protected]', 'description',
'Bob Smith is a person who does stuff.'),
('[email protected]', 'SHORT_BIO',
'He does stuff.'),
('[email protected]', 'userphoto_image_file', 'testcat.jpg'),
]
return data
@mock.patch('requests.get', local_get_successful)
class TestCommandImportFromWordPressUnicodeSlug(TestCase, ImageCleanUp):
def setUp(self):
import_from_wordpress.Command.get_post_data = self.get_test_post_data
import_from_wordpress.Command.get_post_image_data = self.get_test_post_image_data
import_from_wordpress.Command.get_data_for_topics = self.get_test_data_for_topics
def tearDown(self):
self.delete_images()
def testCreatesPageWithAsciiSlug(self):
command = import_from_wordpress.Command()
command.load_posts()
pages = ArticlePage.objects.filter(
slug='crisis-at-home-for-canadas-armed-forces')
self.assertEqual(1, pages.count())
def get_test_post_data(self, post_type):
data = [
(1,
'Crisis At Home',
'Test?',
'Body.',
"crisis-at-home-for-canadas-armed-forces%e2%80%a8",
'[email protected]',
datetime.datetime(2011, 2, 22, 5, 48, 31),
),
]
return data
def get_test_post_image_data(self, post_id):
return None
def get_test_data_for_topics(self, post_id, primary_topic=False):
return (
('Topic 1', 'topic-1'),
)
class TestCommandImportFromWordPressLoadPosts(TestCase, ImageCleanUp):
fixtures = ['test.json']
def setUp(self):
import_from_wordpress.Command.get_post_data = self.get_test_post_data
import_from_wordpress.Command.get_post_image_data = self.get_test_post_image_data
import_from_wordpress.Command.get_data_for_topics = self.get_test_data_for_topics
import_from_wordpress.Command.get_category_data = self.get_test_category_data
def tearDown(self):
self.delete_images()
@mock.patch('requests.get', local_get_successful)
def testCreatesPageWithSlug(self):
command = import_from_wordpress.Command()
command.load_posts()
pages = ArticlePage.objects.filter(
slug='is-nato-ready-for-putin')
self.assertEqual(1, pages.count())
@mock.patch('requests.get', local_get_successful)
def testPageIsChildOfFeatures(self):
command = import_from_wordpress.Command()
command.load_posts()
pages = ArticlePage.objects.filter(
slug='is-nato-ready-for-putin')
features_page = Page.objects.get(slug='features')
self.assertTrue(pages.first().is_descendant_of(features_page))
@mock.patch('requests.get', local_get_successful)
def testPageSetsTitle(self):
command = import_from_wordpress.Command()
command.load_posts()
pages = ArticlePage.objects.filter(
slug='is-nato-ready-for-putin')
self.assertEqual('Is NATO Ready for Putin?', pages.first().title)
@mock.patch('requests.get', local_get_successful)
def testPageSetsBody(self):
command = import_from_wordpress.Command()
command.load_posts()
pages = ArticlePage.objects.filter(
slug='is-nato-ready-for-putin')
self.assertEqual(
[{'type': "Paragraph", 'value': {"text": "<p>Vladimir Putin has challenged</p>", "use_dropcap": False}}, ],
pages.first().body.stream_data)
@mock.patch('requests.get', local_get_successful)
def testPageSetsExcerptContainingUnicode(self):
command = import_from_wordpress.Command()
command.load_posts()
pages = ArticlePage.objects.filter(
slug='is-nato-ready-for-putin')
self.assertEqual(
'Political hurdles hold NATO back — how convenient for Russian tactics.',
pages.first().excerpt)
@mock.patch('requests.get', local_get_successful)
def testPageImportsHTML(self):
command = import_from_wordpress.Command()
command.load_posts()
pages = ArticlePage.objects.filter(slug='html-post')
self.assertEqual('The excerpt also has some <strong>HTML</strong>.',
pages.first().excerpt)
self.assertEqual(
[{"type": "Paragraph", "value": {'text': '<p>This <strong>is</strong></p>', 'use_dropcap': False}},
{"type": "Paragraph",
"value": {'text': '<p><img src="http://www.example.com/test.jpg"/></p>', 'use_dropcap': False}},
{"type": "Paragraph",
"value": {'text': '<p>a <a href="http://www.example.com">post</a><span class="special">that has html</span></p>', 'use_dropcap': False}},
{"type": "Paragraph", "value": {'text': '<p>Yay!</p>', 'use_dropcap': False}}, ],
pages.first().body.stream_data)
@mock.patch('requests.get', local_get_successful)
def testPageUpdatesLocalImageUrls(self):
command = import_from_wordpress.Command()
command.load_posts()
pages = ArticlePage.objects.filter(slug='html-local-image-post')
images = AttributedImage.objects.filter(title='testcat.jpg')
self.assertEqual(
[{'type': 'Image', 'value': {'image': images.first().id, 'placement': 'full', 'expandable': False, 'label': None}},
{'type': "Paragraph", 'value': {"text": "<p>a cat</p>", 'use_dropcap': False}},
],
pages.first().body.stream_data)
@mock.patch('requests.get', local_get_404)
def testDownloadErrorLoggedWhenErrorGettingImage(self):
command = import_from_wordpress.Command()
command.load_posts()
errors = ImportDownloadError.objects.filter(url=test_image_url)
self.assertEqual(404, errors.first().status_code)
@mock.patch('requests.get', local_get_successful)
def testPageNullFields(self):
command = import_from_wordpress.Command()
command.load_posts()
pages = ArticlePage.objects.filter(slug='null-fields')
self.assertEqual('', pages.first().excerpt)
self.assertEqual([], pages.first().body.stream_data)
self.assertEqual('', pages.first().title)
@mock.patch('requests.get', local_get_successful)
def testPageBlankFields(self):
command = import_from_wordpress.Command()
command.load_posts()
pages = ArticlePage.objects.filter(slug='blank-fields')
self.assertEqual('', pages.first().excerpt)
self.assertEqual([], pages.first().body.stream_data)
self.assertEqual('', pages.first().title)
@mock.patch('requests.get', local_get_successful)
def testPageHasAuthor(self):
command = import_from_wordpress.Command()
command.load_posts()
pages = ArticlePage.objects.filter(
slug='is-nato-ready-for-putin')
contributors = ContributorPage.objects.filter(email='[email protected]')
self.assertEqual(pages.first().author_links.count(), 1)
self.assertEqual(pages.first().author_links.first().author, contributors.first())
@mock.patch('requests.get', local_get_successful)
def testPageAuthorNotSet(self):
command = import_from_wordpress.Command()
command.load_posts()
pages = ArticlePage.objects.filter(slug='null-author')
self.assertEqual(pages.first().author_links.count(), 0)
@mock.patch('requests.get', local_get_successful)
def testPageEmptyAuthor(self):
command = import_from_wordpress.Command()
command.load_posts()
pages = ArticlePage.objects.filter(slug='empty-author')
self.assertEqual(pages.first().author_links.count(), 0)
@mock.patch('requests.get', local_get_successful)
def testPageNonExistantAuthor(self):
# TODO: should this cause an error
command = import_from_wordpress.Command()
command.load_posts()
pages = ArticlePage.objects.filter(slug='nonexistant-author')
self.assertEqual(pages.first().author_links.count(), 0)
@mock.patch('requests.get', local_get_successful)
def testUpdatesDuplicateSlug(self):
command = import_from_wordpress.Command()
command.load_posts()
pages = ArticlePage.objects.filter(slug='duplicate')
self.assertEqual(pages.count(), 1)
self.assertEqual(pages.first().title, "title 2")
@mock.patch('requests.get', local_get_successful)
def testImportTrackingCreated(self):
command = import_from_wordpress.Command()
command.load_posts()
imports = PostImport.objects.filter(post_id=5)
self.assertEqual(imports.count(), 1)
@mock.patch('requests.get', local_get_successful)
def testSetsDate(self):
command = import_from_wordpress.Command()
command.load_posts()
pages = ArticlePage.objects.filter(
slug='is-nato-ready-for-putin')
self.assertEqual(
timezone.datetime(2011, 2, 22, 5, 48, 31, tzinfo=timezone.pytz.timezone('GMT')),
pages.first().first_published_at)
@mock.patch('requests.get', local_get_successful)
def testDefaultCategorySet(self):
command = import_from_wordpress.Command()
command.load_posts()
page = ArticlePage.objects.filter(
slug='is-nato-ready-for-putin').first()
default_category = ArticleCategory.objects.get(slug="feature")
self.assertEqual(default_category, page.category)
@mock.patch('requests.get', local_get_successful)
def testSetsPrimaryTopic(self):
command = import_from_wordpress.Command()
command.load_posts()
page = ArticlePage.objects.filter(
slug='is-nato-ready-for-putin').first()
self.assertEqual("Primary Topic 1", page.primary_topic.name)
@mock.patch('requests.get', local_get_successful)
def testSetsSecondaryTopics(self):
command = import_from_wordpress.Command()
command.load_posts()
page = ArticlePage.objects.filter(
slug='is-nato-ready-for-putin').first()
self.assertEqual(1, page.topic_links.count())
self.assertEqual("Secondary Topic 1", page.topic_links.first().topic.name)
def get_test_post_image_data(self, post_id):
return None
def get_test_category_data(self):
return (
("Features", 1, "features", 0),
("Essays", 3, "essays", 0),
("101s", 4, "101", 0),
("Roundtable", 5, "roundtable", 0),
("Dispatch", 6, "roundtable", 0),
("Comments", 7, "roundtable", 0),
("Essays", 6, "roundtable", 0),
("Visualizations", 9, "roundtable", 0),
("Interviews", 10, "roundtable", 0),
("Rapid Response Group", 11, "roundtable", 0),
("Graphics", 2, "graphics", 1),
)
def get_test_data_for_topics(self, post_id, primary_topic=False):
if primary_topic:
return (
('Primary Topic 1', 'primary-topic-1'),
)
else:
return (
('Secondary Topic 1', 'secondary-topic-1'),
)
def get_test_post_data(self, post_type):
if post_type == "Features":
data = [
(1,
'Vladimir Putin has challenged',
'Is NATO Ready for Putin?',
'Political hurdles hold NATO back — how convenient for Russian tactics.',
'is-nato-ready-for-putin',
'[email protected]',
datetime.datetime(2011, 2, 22, 5, 48, 31),
),
(2,
'<p>This <strong>is</strong> <img src="http://www.example.com/test.jpg" /> a <a href="http://www.example.com">post</a><span class="special">that has html</span></p><div>Yay!</div>',
'HTML Works?',
'The excerpt also has some <strong>HTML</strong>.',
'html-post',
'[email protected]',
datetime.datetime(2011, 2, 22, 5, 48, 31),
),
(3,
None,
None,
None,
'null-fields',
'[email protected]',
datetime.datetime(2011, 2, 22, 5, 48, 31),
),
(5,
'',
'',
'',
'blank-fields',
'[email protected]',
datetime.datetime(2011, 2, 22, 5, 48, 31),
),
(6,
'body',
'title',
'excerpt',
'null-author',
None,
datetime.datetime(2011, 2, 22, 5, 48, 31),
),
(7,
'body',
'title',
'excerpt',
'empty-author',
'',
datetime.datetime(2011, 2, 22, 5, 48, 31),
),
(8,
'body',
'title',
'excerpt',
'nonexistant-author',
'[email protected]',
datetime.datetime(2011, 2, 22, 5, 48, 31),
),
(9,
'body',
'title',
'excerpt',
'duplicate',
'[email protected]',
datetime.datetime(2011, 2, 22, 5, 48, 31),
),
(10,
'body',
'title 2',
'excerpt',
'duplicate',
'[email protected]',
datetime.datetime(2011, 2, 22, 5, 48, 31),
),
(11,
'<div><img src="{}" />a cat</div>'.format(test_image_url),
'title',
'excerpt',
'html-local-image-post',
'[email protected]',
datetime.datetime(2011, 2, 22, 5, 48, 31),
),
]
else:
data = []
return data
class TestCommandImportProcessHTMLForImages(TestCase, ImageCleanUp):
def tearDown(self):
self.delete_images()
@mock.patch('requests.get', local_get_successful)
def testHTMLHasImageImageCreatedWhenDownloaded(self):
command = import_from_wordpress.Command()
html = "<img src='{}'/>".format(test_image_url)
command.process_html_for_images(html)
images = AttributedImage.objects.filter(title='testcat.jpg')
self.assertEqual(1, images.count())
@mock.patch('requests.get', local_get_successful)
def testHTMLImageSourceUpdatedWhenDownloaded(self):
command = import_from_wordpress.Command()
html = "<img src='{}'/>".format(test_image_url)
html = command.process_html_for_images(html)
images = AttributedImage.objects.filter(title='testcat.jpg')
self.assertEqual(html, "<img src='{}'/>".format(
images.first().get_rendition('width-100').url))
@mock.patch('requests.get', local_get_successful)
def testImageNotDownloadedForRemote(self):
command = import_from_wordpress.Command()
html = "<img src='http://upload.wikimedia.org/wikipedia/en/b/bd/Test.jpg'/>"
command.process_html_for_images(html)
images = AttributedImage.objects.filter(title='Test.jpg')
self.assertEqual(0, images.count())
@mock.patch('requests.get', local_get_successful)
def testHTMLNotUpdatedForRemote(self):
command = import_from_wordpress.Command()
html = "<img src='http://upload.wikimedia.org/wikipedia/en/b/bd/Test.jpg'/>"
html = command.process_html_for_images(html)
self.assertEqual(html,
"<img src='http://upload.wikimedia.org/wikipedia/en/b/bd/Test.jpg'/>")
@mock.patch('requests.get', local_get_successful)
def testHTMLWithUnicodeNoUpload(self):
command = import_from_wordpress.Command()
html = "<p>€</p><img src='http://upload.wikimedia.org/wikipedia/en/b/bd/Test€.jpg'/>"
html = command.process_html_for_images(html)
self.assertEqual(html,
"<p>€</p><img src='http://upload.wikimedia.org/wikipedia/en/b/bd/Test€.jpg'/>")
@mock.patch('requests.get', local_get_successful)
def testHTMLWithUnicodeImageSourceUpdatedWhenDownloaded(self):
command = import_from_wordpress.Command()
html = "<img src='{}' />".format(test_image_url_with_unicode)
html = command.process_html_for_images(html)
images = AttributedImage.objects.filter(title='testcat♥.jpg')
self.assertEqual(1, images.count())
self.assertEqual(html, "<img src='{}' />".format(
images.first().get_rendition('width-100').url))
@mock.patch('requests.get', local_get_404)
def testDownloadErrorLoggedWhenError(self):
command = import_from_wordpress.Command()
html = "<img src='{}' />".format(test_image_url_with_unicode)
html = command.process_html_for_images(html)
errors = ImportDownloadError.objects.filter(url=test_image_url_with_unicode)
self.assertEqual(1, errors.count())
self.assertEqual(404, errors.first().status_code)
class TestCommandImportDownloadImage(TestCase, ImageCleanUp):
def tearDown(self):
self.delete_images()
@mock.patch('requests.get', local_get_successful)
def testImageCreatedWhenDownloaded(self):
command = import_from_wordpress.Command()
command.download_image(test_image_url, 'testcat.jpg')
images = AttributedImage.objects.filter(title='testcat.jpg')
self.assertEqual(1, images.count())
@mock.patch('requests.get', local_get_404)
def testDownloadExceptionWhenError(self):
command = import_from_wordpress.Command()
with self.assertRaises(import_from_wordpress.DownloadException):
command.download_image(
'file:///{}/wordpress_importer/tests/files/purple.jpg'.format(
settings.PROJECT_ROOT),
'purple.jpg'
)
@mock.patch('requests.get', local_get_404)
def testDownloadExceptionHasDetails(self):
command = import_from_wordpress.Command()
try:
command.download_image(
'file:///{}/wordpress_importer/tests/files/purple.jpg'.format(
settings.PROJECT_ROOT),
'purple.jpg'
)
except import_from_wordpress.DownloadException as e:
self.assertEqual(
'file:///{}/wordpress_importer/tests/files/purple.jpg'.format(
settings.PROJECT_ROOT), e.url)
self.assertEqual(e.response.status_code, 404)
@mock.patch('requests.get', local_get_successful)
def testImageImportRecordCreatedWhenDownloaded(self):
command = import_from_wordpress.Command()
command.download_image(test_image_url, 'testcat.jpg')
image_records = ImageImport.objects.filter(name='testcat.jpg')
self.assertEqual(1, image_records.count())
@mock.patch('requests.get', local_get_successful)
class TestCommandProcessHTLMForStreamField(TestCase, ImageCleanUp):
def tearDown(self):
self.delete_images()
def testSimpleParagraph(self):
command = import_from_wordpress.Command()
html = "<p>This is a simple paragraph.</p>"
processed = command.process_html_for_stream_field(html)
self.assertEqual(
[{"type": "Paragraph",
"value": {"text": "<p>This is a simple paragraph.</p>", 'use_dropcap': False}}],
processed
)
def testImageUploadedLocally(self):
command = import_from_wordpress.Command()
html = "<img src='{}' />".format(test_image_url)
processed = command.process_html_for_stream_field(html)
images = AttributedImage.objects.filter(title='testcat.jpg')
self.assertEqual(1, images.count())
self.assertEqual(processed, [{"type": "Image",
"value": {'image': 1, 'placement': 'full'}}, ])
def testImageWithParagraphs(self):
command = import_from_wordpress.Command()
html = "<p>This is a simple paragraph.</p><img src='{}' /><p>This is a second paragraph.</p>".format(
test_image_url)
processed = command.process_html_for_stream_field(html)
self.assertEqual(
[{"type": "Paragraph",
"value": {"text": "<p>This is a simple paragraph.</p>", 'use_dropcap': False}},
{"type": "Image",
"value": {'image': 1, 'placement': 'full'}},
{"type": "Paragraph",
"value": {"text": "<p>This is a second paragraph.</p>", 'use_dropcap': False}},
],
processed
)
def testImageInParagraph(self):
command = import_from_wordpress.Command()
html = "<p>This is a paragraph. <img src='{}' /> This is a second paragraph.</p>".format(
test_image_url)
processed = command.process_html_for_stream_field(html)
self.assertEqual(
[{"type": "Paragraph",
"value": {"text": "<p>This is a paragraph.</p>", 'use_dropcap': False}},
{"type": "Image",
"value": {'image': 1, 'placement': 'full'}},
{"type": "Paragraph",
"value": {"text": "<p>This is a second paragraph.</p>", 'use_dropcap': False}},
],
processed
)
def testExternalImage(self):
command = import_from_wordpress.Command()
html = "<p>This is a simple paragraph.</p><img src='http://upload.wikimedia.org/wikipedia/en/b/bd/Test.jpg' /><p>This is a second paragraph.</p>"
processed = command.process_html_for_stream_field(html)
self.assertEqual(
[{"type": "Paragraph",
"value": {"text": "<p>This is a simple paragraph.</p>", 'use_dropcap': False}},
{"type": "Paragraph",
"value": {"text": '<p><img src="http://upload.wikimedia.org/wikipedia/en/b/bd/Test.jpg"/></p>', 'use_dropcap': False}},
{"type": "Paragraph",
"value": {"text": "<p>This is a second paragraph.</p>", 'use_dropcap': False}},
],
processed
)
def testDivs(self):
command = import_from_wordpress.Command()
html = "<div><div>This is a simple paragraph.</div><img src='{}' /><div>This is a second paragraph.<img src='{}' /></div></div>".format(
test_image_url, test_image_url)
processed = command.process_html_for_stream_field(html)
self.assertEqual(
[{"type": "Paragraph",
"value": {"text": "<p>This is a simple paragraph.</p>", 'use_dropcap': False}},
{"type": "Image",
"value": {'image': 1, 'placement': 'full'}},
{"type": "Paragraph",
"value": {"text": "<p>This is a second paragraph.</p>", 'use_dropcap': False}},
{"type": "Image",
"value": {'image': 1, 'placement': 'full'}},
],
processed
)
def testHeaders(self):
command = import_from_wordpress.Command()
html = "<h1>This is a header 1</h1><h2>This is a header 2</h2>" \
"<h3>This is a header 3</h3><h4>This is a header 4</h4>" \
"<h5>This is a header 5</h5><h6>This is a header 6</h6>"
processed = command.process_html_for_stream_field(html)
self.assertEqual(
[{"type": "Heading",
"value": {'text': "This is a header 1", 'heading_level': 2}},
{"type": "Heading",
"value": {'text': "This is a header 2", 'heading_level': 2}},
{"type": "Heading",
"value": {'text': "This is a header 3", 'heading_level': 2}},
{"type": "Heading",
"value": {'text': "This is a header 4", 'heading_level': 2}},
{"type": "Heading",
"value": {'text': "This is a header 5", 'heading_level': 2}},
{"type": "Heading",
"value": {'text': "This is a header 6", 'heading_level': 2}},
],
processed
)
def testImagesInHeaders(self):
command = import_from_wordpress.Command()
html = "<h2><img src='{}' />This is the heading</h2>".format(
test_image_url)
processed = command.process_html_for_stream_field(html)
self.assertEqual(
[{"type": "Image",
"value": {'image': 1, 'placement': 'full'}},
{"type": "Heading",
"value": {'text': "This is the heading", 'heading_level': 2}},
],
processed
)
def testImagesInHeadersFollowingText(self):
command = import_from_wordpress.Command()
html = "<h2>This is the heading<img src='{}' /></h2>".format(
test_image_url)
processed = command.process_html_for_stream_field(html)
self.assertEqual(
[
{"type": "Heading",
"value": {'text': "This is the heading", 'heading_level': 2}},
{"type": "Image",
"value": {'image': 1, 'placement': 'full'}},
],
processed
)
def testImagesInHeadersWrappedInText(self):
command = import_from_wordpress.Command()
html = "<h2>This is the heading<img src='{0}' />This is more heading<img src='{0}' />This is even more heading</h2>".format(
test_image_url)
processed = command.process_html_for_stream_field(html)
self.assertEqual(
[
{"type": "Heading",
"value": {'text': "This is the heading", 'heading_level': 2}},
{"type": "Image",
"value": {'image': 1, 'placement': 'full'}},
{"type": "Heading",
"value": {'text': "This is more heading", 'heading_level': 2}},
{"type": "Image",
"value": {'image': 1, 'placement': 'full'}},
{"type": "Heading",
"value": {'text': "This is even more heading", 'heading_level': 2}},
],
processed
)
def testNonBlockTagStrong(self):
command = import_from_wordpress.Command()
html = "<p>This is a <strong>simple paragraph.</strong></p>"
processed = command.process_html_for_stream_field(html)
self.assertEqual(
[{"type": "Paragraph",
"value": {"text": "<p>This is a <strong>simple paragraph.</strong></p>", 'use_dropcap': False}},
],
processed
)
def testNonAndBlockSubTags(self):
command = import_from_wordpress.Command()
html = '<p>This <strong>is</strong> <img src="http://www.example.com/test.jpg" /></p>'
processed = command.process_html_for_stream_field(html)
self.assertEqual(
[{"type": "Paragraph", "value": {"text": '<p>This <strong>is</strong></p>', 'use_dropcap': False}},
{"type": "Paragraph",
"value": {"text": '<p><img src="http://www.example.com/test.jpg"/></p>', 'use_dropcap': False}},
],
processed)
def testExtraWhiteSpaceIsRemoved(self):
command = import_from_wordpress.Command()
html = " <p>Test</p> <div>Second</div> <p>Third</p>"
processed = command.process_html_for_stream_field(html)
self.assertEqual(
[{'type': 'Paragraph', 'value': {"text": '<p>Test</p>', 'use_dropcap': False}},
{'type': 'Paragraph', 'value': {"text": '<p>Second</p>', 'use_dropcap': False}},
{'type': 'Paragraph', 'value': {"text": '<p>Third</p>', 'use_dropcap': False}},
],
processed
)
def testCommentsOutsideStructureAreRemoved(self):
command = import_from_wordpress.Command()
html = ' <!--more--> <p>This has a <!--more--> comment</p>'
processed = command.process_html_for_stream_field(html)
self.assertEqual(
[{'type': 'Paragraph', 'value': {'text': '<p>This has a comment</p>', 'use_dropcap': False}}],
processed
)
def testSimpleCommentsAreRemoved(self):
command = import_from_wordpress.Command()
html = '<p>This has a <!--more--> comment</p>'
processed = command.process_html_for_stream_field(html)
self.assertEqual(
[{'type': 'Paragraph', 'value': {"text": '<p>This has a comment</p>', 'use_dropcap': False}}],
processed
)
def testStringsWithNoTagsWithRNBreaks(self):
command = import_from_wordpress.Command()
html = "This is text.\r\n\r\nThat should be in paragraphs."
processed = command.process_html_for_stream_field(html)
self.assertEqual(
[{'type': 'Paragraph', 'value': {"text": '<p>This is text.</p>', 'use_dropcap': False}},
{'type': 'Paragraph',
'value': {"text": '<p>That should be in paragraphs.</p>', 'use_dropcap': False}}],
processed
)
def testStringsWithNoTagsWithNNBreaks(self):
command = import_from_wordpress.Command()
html = "This is text.\n\nThat should be in paragraphs."
processed = command.process_html_for_stream_field(html)
self.assertEqual(
[{'type': 'Paragraph', 'value': {"text": '<p>This is text.</p>', 'use_dropcap': False}},
{'type': 'Paragraph',
'value': {"text": '<p>That should be in paragraphs.</p>', 'use_dropcap': False}}],
processed
)
def testStringsWithNoTagsWithNBreaks(self):
command = import_from_wordpress.Command()
html = """This is text.\nThat should be in paragraphs."""
processed = command.process_html_for_stream_field(html)
self.assertEqual(
[{'type': 'Paragraph',
'value': {"text": '<p>This is text.<br/>That should be in paragraphs.</p>', 'use_dropcap': False}}],
processed
)
def testNoExtraLineBreakks(self):
command = import_from_wordpress.Command()
html = """As one of Canada's principal security and intelligence agencies.
<h4>What is CSE?</h4>
Little is known about CSE because of secrecy."""
processed = command.process_html_for_stream_field(html)
self.assertEqual(
[{'type': 'Paragraph',
'value': {"text": "<p>As one of Canada's principal security and intelligence agencies.</p>", 'use_dropcap': False}},
{'type': 'Heading',
'value': {"text": 'What is CSE?', 'heading_level': 2}},
{'type': 'Paragraph',
'value': {"text": '<p>Little is known about CSE because of secrecy.</p>', 'use_dropcap': False}}
],
processed
)
class TestProcessForLineBreaks(TestCase):
def testStringNoTags(self):
command = import_from_wordpress.Command()
html = "This is a string."
processed = command.process_for_line_breaks(html)
self.assertEqual("<p>This is a string.</p>", processed)
def testStringsWithNoTagsWithRNBreaks(self):
command = import_from_wordpress.Command()
html = "This is text.\r\n\r\nThat should be in paragraphs."
processed = command.process_for_line_breaks(html)
self.assertEqual(
"<p>This is text.</p><p>That should be in paragraphs.</p>",
processed
)
def testStringsWithNoTagsWithNNBreaks(self):
command = import_from_wordpress.Command()
html = "This is text.\n\nThat should be in paragraphs."
processed = command.process_for_line_breaks(html)
self.assertEqual(
"<p>This is text.</p><p>That should be in paragraphs.</p>",
processed
)
def testStringsWithNoTagsWithNBreaks(self):
command = import_from_wordpress.Command()
html = "This is text.\nThat has a line break."
processed = command.process_for_line_breaks(html)
self.assertEqual(
"<p>This is text.<br/>That has a line break.</p>",
processed
)
class TestGetDownloadPathAndFilename(TestCase):
def testNoSubFolderReturnsFilenameAndUrl(self):
command = import_from_wordpress.Command()
url, filename = command.get_download_path_and_filename(
"http://example.com/uploads/my_image.jpg",
"http://newdomain.com/images/{}"
)
self.assertEqual("http://newdomain.com/images/my_image.jpg", url)
self.assertEqual("my_image.jpg", filename)
def testSubFolderReturnsFilenameAndUrlWithSubfolders(self):
command = import_from_wordpress.Command()
url, filename = command.get_download_path_and_filename(
"http://example.com/uploads/2011/04/my_image.jpg",
"http://newdomain.com/images/{}"<|fim▁hole|>
class TestParseEmbed(TestCase):
def testParagraphWithStreamDataReturnsURL(self):
command = import_from_wordpress.Command()
pre, url, post = command.parse_string_for_embed('[stream provider=youtube flv=http%3A//www.youtube.com/watch%3Fv%3DdiTubVRKdz0 embed=false share=false width=646 height=390 dock=true controlbar=over bandwidth=high autostart=false /]')
self.assertEqual('http://www.youtube.com/watch?v=diTubVRKdz0', url)
self.assertEqual('', pre)
self.assertEqual('', post)
def testEmbedWithPreAndPost(self):
command = import_from_wordpress.Command()
pre, url, post = command.parse_string_for_embed('Stuff before the embed. [stream provider=youtube flv=http%3A//www.youtube.com/watch%3Fv%3DdiTubVRKdz0 embed=false share=false width=646 height=390 dock=true controlbar=over bandwidth=high autostart=false /] Stuff after the embed.')
self.assertEqual('http://www.youtube.com/watch?v=diTubVRKdz0', url)
self.assertEqual('Stuff before the embed.', pre)
self.assertEqual('Stuff after the embed.', post)
def testNoEmbed(self):
command = import_from_wordpress.Command()
pre, url, post = command.parse_string_for_embed('Just a regular paragraph.')
self.assertEqual('', url)
self.assertEqual('Just a regular paragraph.', pre)
self.assertEqual('', post)<|fim▁end|> | )
self.assertEqual("http://newdomain.com/images/2011/04/my_image.jpg", url)
self.assertEqual("2011_04_my_image.jpg", filename) |
<|file_name|>setup.py<|end_file_name|><|fim▁begin|>import setuptools<|fim▁hole|>
with open("README.md", "r") as fh:
long_description = fh.read()
setuptools.setup(
name="gabriel-server",
version="2.0.2",
author="Roger Iyengar",
author_email="[email protected]",
description="Server for Wearable Cognitive Assistance Applications",
long_description=long_description,
long_description_content_type="text/markdown",
url="http://gabriel.cs.cmu.edu",
packages=setuptools.find_packages("src"),
package_dir={"": "src"},
license="Apache",
classifiers=[
"Programming Language :: Python :: 3.6",
"Programming Language :: Python :: 3.7",
"Programming Language :: Python :: 3.8",
"Programming Language :: Python :: 3.9",
"License :: OSI Approved :: Apache Software License",
"Operating System :: OS Independent",
],
python_requires=">=3.6",
install_requires=[
"gabriel-protocol==2.0.1",
"websockets==8.1",
"pyzmq==18.1",
],
)<|fim▁end|> | |
<|file_name|>test_image_meta.py<|end_file_name|><|fim▁begin|># Copyright 2014 Red Hat, 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 datetime
from nova import exception
from nova import objects
from nova import test
class TestImageMeta(test.NoDBTestCase):
def test_basic_attrs(self):
image = {'status': 'active',
'container_format': 'bare',
'min_ram': 0,
'updated_at': '2014-12-12T11:16:36.000000',
# Testing string -> int conversion
'min_disk': '0',
'owner': '2d8b9502858c406ebee60f0849486222',
# Testing string -> bool conversion
'protected': 'yes',
'properties': {
'os_type': 'Linux',
'hw_video_model': 'vga',
'hw_video_ram': '512',
'hw_qemu_guest_agent': 'yes',
'hw_scsi_model': 'virtio-scsi',
},
'size': 213581824,
'name': 'f16-x86_64-openstack-sda',
'checksum': '755122332caeb9f661d5c978adb8b45f',
'created_at': '2014-12-10T16:23:14.000000',
'disk_format': 'qcow2',
'id': 'c8b1790e-a07d-4971-b137-44f2432936cd'
}
image_meta = objects.ImageMeta.from_dict(image)
self.assertEqual('active', image_meta.status)
self.assertEqual('bare', image_meta.container_format)
self.assertEqual(0, image_meta.min_ram)
self.assertIsInstance(image_meta.updated_at, datetime.datetime)
self.assertEqual(0, image_meta.min_disk)
self.assertEqual('2d8b9502858c406ebee60f0849486222', image_meta.owner)
self.assertTrue(image_meta.protected)
self.assertEqual(213581824, image_meta.size)
self.assertEqual('f16-x86_64-openstack-sda', image_meta.name)
self.assertEqual('755122332caeb9f661d5c978adb8b45f',
image_meta.checksum)
self.assertIsInstance(image_meta.created_at, datetime.datetime)
self.assertEqual('qcow2', image_meta.disk_format)
self.assertEqual('c8b1790e-a07d-4971-b137-44f2432936cd', image_meta.id)
self.assertIsInstance(image_meta.properties, objects.ImageMetaProps)
def test_no_props(self):
image_meta = objects.ImageMeta.from_dict({})
self.assertIsInstance(image_meta.properties, objects.ImageMetaProps)
def test_volume_backed_image(self):
image = {'container_format': None,
'size': 0,
'checksum': None,
'disk_format': None,
}
image_meta = objects.ImageMeta.from_dict(image)
self.assertEqual('', image_meta.container_format)
self.assertEqual(0, image_meta.size)
self.assertEqual('', image_meta.checksum)
self.assertEqual('', image_meta.disk_format)
def test_null_substitution(self):
image = {'name': None,<|fim▁hole|> 'container_format': None,
'disk_format': None,
}
image_meta = objects.ImageMeta.from_dict(image)
self.assertEqual('', image_meta.name)
self.assertEqual('', image_meta.checksum)
self.assertEqual('', image_meta.owner)
self.assertEqual(0, image_meta.size)
self.assertEqual(0, image_meta.virtual_size)
self.assertEqual('', image_meta.container_format)
self.assertEqual('', image_meta.disk_format)
class TestImageMetaProps(test.NoDBTestCase):
def test_normal_props(self):
props = {'os_type': 'windows',
'hw_video_model': 'vga',
'hw_video_ram': '512',
'hw_qemu_guest_agent': 'yes',
# Fill sane values for the rest here
}
virtprops = objects.ImageMetaProps.from_dict(props)
self.assertEqual('windows', virtprops.os_type)
self.assertEqual('vga', virtprops.hw_video_model)
self.assertEqual(512, virtprops.hw_video_ram)
self.assertTrue(virtprops.hw_qemu_guest_agent)
def test_default_props(self):
props = {}
virtprops = objects.ImageMetaProps.from_dict(props)
for prop in virtprops.fields:
self.assertIsNone(virtprops.get(prop))
def test_default_prop_value(self):
props = {}
virtprops = objects.ImageMetaProps.from_dict(props)
self.assertEqual("hvm", virtprops.get("hw_vm_mode", "hvm"))
def test_non_existent_prop(self):
props = {}
virtprops = objects.ImageMetaProps.from_dict(props)
self.assertRaises(AttributeError,
virtprops.get,
"doesnotexist")
def test_legacy_compat(self):
legacy_props = {
'architecture': 'x86_64',
'owner_id': '123',
'vmware_adaptertype': 'lsiLogic',
'vmware_disktype': 'preallocated',
'vmware_image_version': '2',
'vmware_ostype': 'rhel3_64Guest',
'auto_disk_config': 'yes',
'ipxe_boot': 'yes',
'xenapi_device_id': '3',
'xenapi_image_compression_level': '2',
'vmware_linked_clone': 'false',
'xenapi_use_agent': 'yes',
'xenapi_skip_agent_inject_ssh': 'no',
'xenapi_skip_agent_inject_files_at_boot': 'no',
'cache_in_nova': 'yes',
'vm_mode': 'hvm',
'bittorrent': 'yes',
'mappings': [],
'block_device_mapping': [],
'bdm_v2': 'yes',
'root_device_name': '/dev/vda',
'hypervisor_version_requires': '>=1.5.3',
'hypervisor_type': 'qemu',
}
image_meta = objects.ImageMetaProps.from_dict(legacy_props)
self.assertEqual('x86_64', image_meta.hw_architecture)
self.assertEqual('123', image_meta.img_owner_id)
self.assertEqual('lsilogic', image_meta.hw_scsi_model)
self.assertEqual('preallocated', image_meta.hw_disk_type)
self.assertEqual(2, image_meta.img_version)
self.assertEqual('rhel3_64Guest', image_meta.os_distro)
self.assertTrue(image_meta.hw_auto_disk_config)
self.assertTrue(image_meta.hw_ipxe_boot)
self.assertEqual(3, image_meta.hw_device_id)
self.assertEqual(2, image_meta.img_compression_level)
self.assertFalse(image_meta.img_linked_clone)
self.assertTrue(image_meta.img_use_agent)
self.assertFalse(image_meta.os_skip_agent_inject_ssh)
self.assertFalse(image_meta.os_skip_agent_inject_files_at_boot)
self.assertTrue(image_meta.img_cache_in_nova)
self.assertTrue(image_meta.img_bittorrent)
self.assertEqual([], image_meta.img_mappings)
self.assertEqual([], image_meta.img_block_device_mapping)
self.assertTrue(image_meta.img_bdm_v2)
self.assertEqual("/dev/vda", image_meta.img_root_device_name)
self.assertEqual('>=1.5.3', image_meta.img_hv_requested_version)
self.assertEqual('qemu', image_meta.img_hv_type)
def test_legacy_compat_vmware_adapter_types(self):
legacy_types = ['lsiLogic', 'busLogic', 'ide', 'lsiLogicsas',
'paraVirtual', None, '']
for legacy_type in legacy_types:
legacy_props = {
'vmware_adaptertype': legacy_type,
}
image_meta = objects.ImageMetaProps.from_dict(legacy_props)
if legacy_type == 'ide':
self.assertEqual('ide', image_meta.hw_disk_bus)
elif not legacy_type:
self.assertFalse(image_meta.obj_attr_is_set('hw_disk_bus'))
self.assertFalse(image_meta.obj_attr_is_set('hw_scsi_model'))
else:
self.assertEqual('scsi', image_meta.hw_disk_bus)
if legacy_type == 'lsiLogicsas':
expected = 'lsisas1068'
elif legacy_type == 'paraVirtual':
expected = 'vmpvscsi'
else:
expected = legacy_type.lower()
self.assertEqual(expected, image_meta.hw_scsi_model)
def test_duplicate_legacy_and_normal_props(self):
# Both keys are referring to the same object field
props = {'hw_scsi_model': 'virtio-scsi',
'vmware_adaptertype': 'lsiLogic',
}
virtprops = objects.ImageMetaProps.from_dict(props)
# The normal property always wins vs. the legacy field since
# _set_attr_from_current_names is called finally
self.assertEqual('virtio-scsi', virtprops.hw_scsi_model)
def test_get(self):
props = objects.ImageMetaProps(os_distro='linux')
self.assertEqual('linux', props.get('os_distro'))
self.assertIsNone(props.get('img_version'))
self.assertEqual(1, props.get('img_version', 1))
def test_set_numa_mem(self):
props = {'hw_numa_nodes': 2,
'hw_numa_mem.0': "2048",
'hw_numa_mem.1': "4096"}
virtprops = objects.ImageMetaProps.from_dict(props)
self.assertEqual(2, virtprops.hw_numa_nodes)
self.assertEqual([2048, 4096], virtprops.hw_numa_mem)
def test_set_numa_mem_sparse(self):
props = {'hw_numa_nodes': 2,
'hw_numa_mem.0': "2048",
'hw_numa_mem.1': "1024",
'hw_numa_mem.3': "4096"}
virtprops = objects.ImageMetaProps.from_dict(props)
self.assertEqual(2, virtprops.hw_numa_nodes)
self.assertEqual([2048, 1024], virtprops.hw_numa_mem)
def test_set_numa_mem_no_count(self):
props = {'hw_numa_mem.0': "2048",
'hw_numa_mem.3': "4096"}
virtprops = objects.ImageMetaProps.from_dict(props)
self.assertIsNone(virtprops.get("hw_numa_nodes"))
self.assertEqual([2048], virtprops.hw_numa_mem)
def test_set_numa_cpus(self):
props = {'hw_numa_nodes': 2,
'hw_numa_cpus.0': "0-3",
'hw_numa_cpus.1': "4-7"}
virtprops = objects.ImageMetaProps.from_dict(props)
self.assertEqual(2, virtprops.hw_numa_nodes)
self.assertEqual([set([0, 1, 2, 3]), set([4, 5, 6, 7])],
virtprops.hw_numa_cpus)
def test_set_numa_cpus_sparse(self):
props = {'hw_numa_nodes': 4,
'hw_numa_cpus.0': "0-3",
'hw_numa_cpus.1': "4,5",
'hw_numa_cpus.3': "6-7"}
virtprops = objects.ImageMetaProps.from_dict(props)
self.assertEqual(4, virtprops.hw_numa_nodes)
self.assertEqual([set([0, 1, 2, 3]), set([4, 5])],
virtprops.hw_numa_cpus)
def test_set_numa_cpus_no_count(self):
props = {'hw_numa_cpus.0': "0-3",
'hw_numa_cpus.3': "4-7"}
virtprops = objects.ImageMetaProps.from_dict(props)
self.assertIsNone(virtprops.get("hw_numa_nodes"))
self.assertEqual([set([0, 1, 2, 3])],
virtprops.hw_numa_cpus)
def test_obj_make_compatible(self):
props = {
'img_config_drive': 'mandatory',
'os_admin_user': 'root',
'hw_vif_multiqueue_enabled': True,
'img_hv_type': 'kvm',
'img_hv_requested_version': '>= 1.0',
'os_require_quiesce': True,
}
obj = objects.ImageMetaProps(**props)
primitive = obj.obj_to_primitive('1.0')
self.assertFalse(any([x in primitive['nova_object.data']
for x in props]))
for bus in ('lxc', 'uml'):
obj.hw_disk_bus = bus
self.assertRaises(exception.ObjectActionError,
obj.obj_to_primitive, '1.0')<|fim▁end|> | 'checksum': None,
'owner': None,
'size': None,
'virtual_size': None, |
<|file_name|>views.py<|end_file_name|><|fim▁begin|><|fim▁hole|>
from jarbas.core.models import Company
from jarbas.core.serializers import CompanySerializer
from jarbas.chamber_of_deputies.serializers import format_cnpj
class CompanyDetailView(RetrieveAPIView):
lookup_field = 'cnpj'
queryset = Company.objects.all()
serializer_class = CompanySerializer
def get_object(self):
cnpj = self.kwargs.get(self.lookup_field, '00000000000000')
return get_object_or_404(Company, cnpj=format_cnpj(cnpj))
def healthcheck(request):
"""A simple view to run a health check in Django and in the database"""
with connection.cursor() as cursor:
cursor.execute('SELECT 1')
cursor.fetchone()
return HttpResponse()<|fim▁end|> | from django.db import connection
from django.http import HttpResponse
from django.shortcuts import get_object_or_404
from rest_framework.generics import RetrieveAPIView |
<|file_name|>default_test.go<|end_file_name|><|fim▁begin|>package pool
import (
"testing"
"time"
"github.com/micro/go-micro/v3/network/transport"
"github.com/micro/go-micro/v3/network/transport/memory"
)
func testPool(t *testing.T, size int, ttl time.Duration) {
// mock transport
tr := memory.NewTransport()
options := Options{
TTL: ttl,
Size: size,
Transport: tr,
}
// zero pool
p := newPool(options)
// listen<|fim▁hole|> }
defer l.Close()
// accept loop
go func() {
for {
if err := l.Accept(func(s transport.Socket) {
for {
var msg transport.Message
if err := s.Recv(&msg); err != nil {
return
}
if err := s.Send(&msg); err != nil {
return
}
}
}); err != nil {
return
}
}
}()
for i := 0; i < 10; i++ {
// get a conn
c, err := p.Get(l.Addr())
if err != nil {
t.Fatal(err)
}
msg := &transport.Message{
Body: []byte(`hello world`),
}
if err := c.Send(msg); err != nil {
t.Fatal(err)
}
var rcv transport.Message
if err := c.Recv(&rcv); err != nil {
t.Fatal(err)
}
if string(rcv.Body) != string(msg.Body) {
t.Fatalf("got %v, expected %v", rcv.Body, msg.Body)
}
// release the conn
p.Release(c, nil)
p.Lock()
if i := len(p.conns[l.Addr()]); i > size {
p.Unlock()
t.Fatalf("pool size %d is greater than expected %d", i, size)
}
p.Unlock()
}
}
func TestClientPool(t *testing.T) {
testPool(t, 0, time.Minute)
testPool(t, 2, time.Minute)
}<|fim▁end|> | l, err := tr.Listen(":0")
if err != nil {
t.Fatal(err) |
<|file_name|>index.ts<|end_file_name|><|fim▁begin|>import { suite } from 'uvu'
import * as assert from 'uvu/assert'
import browserEnv from 'browser-env'
import Component from '../src'
import sinon from 'sinon'
import templates from './fixtures/templates'
import { definitions, definitionFunction } from './fixtures/definitions'
import rewire from 'rewire'
/* -------------------------------------------------------------------------------------
INIT BROWSER ENV
------------------------------------------------------------------------------------- */
browserEnv(['window', 'document', 'navigator'])
/* -------------------------------------------------------------------------------------
UTILS
------------------------------------------------------------------------------------- */
// Util to quickly boot brindille component on body from template
function createRootComponent(template = '', definitions = null) {
if (template) document.body.innerHTML = template
return new Component(document.body, definitions)
}
// Creating a spy on console.warn displayed by our app
function spyOnWarnings(context) {
context.warn = console.warn
console.warn = sinon.spy()
return console.warn
}
// Restoring console.warn from context
function restoreWarnings(context) {
console.warn = context.warn
}
/* -------------------------------------------------------------------------------------
TESTS
------------------------------------------------------------------------------------- */
const test = suite('Component')
let stubWarn
test.before.each(() => {
stubWarn = sinon.stub(console, 'warn')
})
test.after.each(() => {
stubWarn.restore()
})
test('Construct root component from empty body', () => {
const rootComponent = createRootComponent()
assert.ok(rootComponent)
})
test('Handle a data-component value that does not match a valid component by displaying warning in console', () => {
const rootComponent = createRootComponent(templates.fake, definitions)
assert.is(rootComponent.componentInstances.length, 0)
assert.ok(console.warn['calledOnce'])
})
test('Handle a data-component value that matches a valid component', () => {
const rootComponent = createRootComponent(templates.simple, definitions)
assert.is(rootComponent.componentInstances.length, 1)
})
test('Handle data-component on form tag', () => {
createRootComponent(templates.formNo, definitions)
assert.ok(console.warn['calledOnce'])
})
test('Use function as definitions', () => {
const rootComponent = createRootComponent(
templates.simple,
definitionFunction
)
assert.is(rootComponent.componentInstances.length, 1)
})
test('Use other types as definitions', () => {
const rootComponent0 = createRootComponent(templates.simple, 'foo')
const rootComponent1 = createRootComponent(templates.simple, 2)
const rootComponent2 = createRootComponent(templates.simple, null)
const rootComponent3 = createRootComponent(templates.simple, undefined)
assert.is(rootComponent0.componentInstances.length, 0)
assert.is(rootComponent1.componentInstances.length, 0)
assert.is(rootComponent2.componentInstances.length, 0)
assert.is(rootComponent3.componentInstances.length, 0)
assert.is(console.warn['callCount'], 2)
})
test('Force component init with null definitions', () => {
const rootComponent = createRootComponent(templates.simple, null)
rootComponent.init(null)
assert.is(rootComponent.componentInstances.length, 0)
assert.is(console.warn['callCount'], 1)
})
test('Handle simple nested component', () => {
const rootComponent = createRootComponent(templates.nested, definitions)
assert.is(rootComponent.componentInstances.length, 1)
assert.is(rootComponent.componentInstances[0].componentInstances.length, 1)
})
test('Nested components should be passed main definitions from parent', () => {
const rootComponent = createRootComponent(templates.nested, definitions)
assert.equal(
rootComponent.componentInstances[0].definitions,
rootComponent.definitions
)
})
test('Refs attribute should be registered in parent', () => {
const rootComponent = createRootComponent(templates.refs, definitions)
assert.is(rootComponent.refs['test'], rootComponent.componentInstances[0])
})
test('Nested refs should only be attributed to direct parent', () => {
const rootComponent = createRootComponent(templates.nestedRefs, definitions)
assert.is(rootComponent.refs['test'], rootComponent.componentInstances[0])
assert.is(
rootComponent.refs['test'].refs['another'],
rootComponent.componentInstances[0].componentInstances[0]
)
assert.not(rootComponent.refs['another'])
})
test('Dispose method should destroy component dom node', () => {
const rootComponent = createRootComponent(templates.simple, definitions)
rootComponent.dispose()
assert.not(rootComponent.$el)
})
test('Dispose called on parent should also dispose all children', () => {
const rootComponent = createRootComponent(templates.nestedRefs, definitions)
const childComponent = rootComponent.refs['test']
const childChildComponent = childComponent.refs.another
rootComponent.dispose()
assert.equal(rootComponent.refs, {})
assert.equal(childComponent.refs, {})
assert.not(childComponent.$el)
assert.not(childChildComponent.$el)
})
test('replaceContent should launch a new parse on component', () => {
const rootComponent = createRootComponent(templates.simple, definitions)
rootComponent.replaceContent(templates.replace)
assert.ok(rootComponent.refs['another'])
})
<|fim▁hole|> rootComponent.replaceContent(templates.replace)
assert.ok(rootComponent.refs['another'])
assert.not(rootComponent.refs['test'])
})
test('findInstance should return first direct child instance for a given component name', () => {
const rootComponent = createRootComponent(
templates.multipleInstances,
definitions
)
const childOne = rootComponent.refs['testOne']
const childTwo = rootComponent.refs['testTwo']
const searchedInstance = rootComponent.findInstance('TestComponent')
const searchedInstanceNoResult = rootComponent.findInstance('SomethingElse')
assert.is(searchedInstance, childOne)
assert.is.not(searchedInstance, childTwo)
assert.not(searchedInstanceNoResult)
})
test('findInstance should return first nested child instance for a given component name', () => {
const rootComponent = createRootComponent(
templates.nestedMultipleInstances,
definitions
)
const child = rootComponent.refs['child']
const subChildOne = child.refs['testOne']
const subChildTwo = child.refs['testTwo']
const searchedInstance = rootComponent.findInstance('TestComponent')
assert.is(searchedInstance, subChildOne)
assert.is.not(searchedInstance, subChildTwo)
})
test('findAllInstances should return array of direct child instances for a given component name', () => {
const rootComponent = createRootComponent(
templates.multipleInstances,
definitions
)
const childOne = rootComponent.refs['testOne']
const childTwo = rootComponent.refs['testTwo']
const searchedInstances = rootComponent.findAllInstances('TestComponent')
const searchedInstancesNoResult = rootComponent.findAllInstances(
'SomethingElse'
)
assert.is(searchedInstances[0], childOne)
assert.is(searchedInstances[1], childTwo)
assert.not(searchedInstancesNoResult.length)
})
test('findAllInstances should return array of nested child instances for a given component name', () => {
const rootComponent = createRootComponent(
templates.nestedMultipleInstances,
definitions
)
const child = rootComponent.refs['child']
const subChildOne = child.refs['testOne']
const subChildTwo = child.refs['testTwo']
const searchedInstances = rootComponent.findAllInstances('TestComponent')
assert.is(searchedInstances[0], subChildOne)
assert.is(searchedInstances[1], subChildTwo)
})
test('$one', () => {
const rootComponent = createRootComponent(
templates.simpleWithContent,
definitions
)
assert.is(rootComponent.$one('.foo'), rootComponent.$el.querySelector('.foo'))
assert.is(rootComponent.$one('.bar'), rootComponent.$el.querySelector('.bar'))
assert.is.not(
rootComponent.$one('.foo'),
rootComponent.$el.querySelector('.bar')
)
assert.is.not(
rootComponent.$one('.bar'),
rootComponent.$el.querySelector('.two')
)
})
test('$all', () => {
const rootComponent = createRootComponent(
templates.simpleWithContent,
definitions
)
assert.is(rootComponent.$all('.bar').length, 2)
assert.is.not(
rootComponent.$all('.bar'),
rootComponent.$el.querySelectorAll('.bar')
)
assert.is.not(
rootComponent.$all('.bar'),
[].slice.call(rootComponent.$el.querySelectorAll('.bar'))
)
})
test('Root component auto assign', () => {
const rootComponent = createRootComponent(
templates.deeperNesting,
definitions
)
const depth0 = rootComponent.refs['child']
const depth1 = depth0.refs.test
const depth2 = depth1.refs.foo
assert.is(rootComponent.root, rootComponent)
assert.is(depth0.root, rootComponent)
assert.is(depth1.root, rootComponent)
assert.is(depth2.root, rootComponent)
})
test('toArray', () => {
const rewiredBrindilleComponent = rewire('../src')
const toArray = rewiredBrindilleComponent.__get__('toArray')
assert.equal(toArray(null), [])
assert.equal(toArray(1), [1])
assert.equal(toArray('a'), ['a'])
assert.equal(toArray(['a']), ['a'])
})
test.run()<|fim▁end|> |
test('replaceContent should clear out refs and _componentInstances to replace them with new ones', () => {
const rootComponent = createRootComponent(templates.refs, definitions)
|
<|file_name|>get_project_var_cmd.go<|end_file_name|><|fim▁begin|>package cmd
import (
"github.com/fatih/color"
out "github.com/plouc/go-gitlab-client/cli/output"
"github.com/spf13/cobra"
)
func init() {
getCmd.AddCommand(getProjectVarCmd)
}
var getProjectVarCmd = &cobra.Command{
Use: resourceCmd("project-var", "project-var"),
Aliases: []string{"pv"},
Short: "Get the details of a project's specific variable",
RunE: func(cmd *cobra.Command, args []string) error {
ids, err := config.aliasIdsOrArgs(currentAlias, "project-var", args)
if err != nil {
return err
}
color.Yellow("Fetching project variable (id: %s, key: %s)…", ids["project_id"], ids["var_key"])
loader.Start()
variable, meta, err := client.ProjectVariable(ids["project_id"], ids["var_key"])
loader.Stop()
if err != nil {
return err
}
out.Variable(output, outputFormat, variable)
printMeta(meta, false)
<|fim▁hole|><|fim▁end|> | return nil
},
} |
<|file_name|>validation-controller-factory.ts<|end_file_name|><|fim▁begin|>import { Container, Optional } from 'aurelia-dependency-injection';
import {
GlobalValidationConfiguration,
ValidationControllerFactory,
ValidationController,
Validator,
validateTrigger
} from '../src/aurelia-validation';
describe('ValidationControllerFactory', () => {
it('createForCurrentScope', () => {
const container = new Container();
const standardValidator = {};
container.registerInstance(Validator, standardValidator);
const config = new GlobalValidationConfiguration();
config.defaultValidationTrigger(validateTrigger.manual);
container.registerInstance(GlobalValidationConfiguration, config);
const childContainer = container.createChild();
const factory = childContainer.get(ValidationControllerFactory);
const controller = factory.createForCurrentScope();
expect(controller['validator']).toBe(standardValidator);
expect(controller.validateTrigger).toBe(validateTrigger.manual);
expect(container.get(Optional.of(ValidationController))).toBe(null);
expect(childContainer.get(Optional.of(ValidationController))).toBe(controller);
<|fim▁hole|> const customValidator = {};
expect(factory.createForCurrentScope(customValidator as Validator)['validator']).toBe(customValidator);
});
});<|fim▁end|> | |
<|file_name|>comparison_instructions.rs<|end_file_name|><|fim▁begin|>// Copyright (c) The Diem Core Contributors
// SPDX-License-Identifier: Apache-2.0
extern crate test_generation;
use itertools::Itertools;
use test_generation::abstract_state::{AbstractState, AbstractValue};
use vm::file_format::{Bytecode, SignatureToken};
mod common;
const INTEGER_TYPES: &[SignatureToken] = &[
SignatureToken::U8,
SignatureToken::U64,
SignatureToken::U128,
];
#[test]
fn bytecode_comparison_integers() {
for (op, ty) in [
Bytecode::Lt,
Bytecode::Gt,
Bytecode::Le,
Bytecode::Ge,
Bytecode::Eq,
Bytecode::Neq,
]
.iter()
.cartesian_product(INTEGER_TYPES.iter())
{
let mut state1 = AbstractState::new();
state1.stack_push(AbstractValue::new_primitive(ty.clone()));
state1.stack_push(AbstractValue::new_primitive(ty.clone()));
let (state2, _) = common::run_instruction(op.clone(), state1);
assert_eq!(
state2.stack_peek(0),
Some(AbstractValue::new_primitive(SignatureToken::Bool)),
"stack type postcondition not met"<|fim▁hole|> );
}
}
#[test]
fn bytecode_eq_bool() {
let mut state1 = AbstractState::new();
state1.stack_push(AbstractValue::new_primitive(SignatureToken::Bool));
state1.stack_push(AbstractValue::new_primitive(SignatureToken::Bool));
let (state2, _) = common::run_instruction(Bytecode::Eq, state1);
assert_eq!(
state2.stack_peek(0),
Some(AbstractValue::new_primitive(SignatureToken::Bool)),
"stack type postcondition not met"
);
}
#[test]
fn bytecode_neq_u64() {
let mut state1 = AbstractState::new();
state1.stack_push(AbstractValue::new_primitive(SignatureToken::U64));
state1.stack_push(AbstractValue::new_primitive(SignatureToken::U64));
let (state2, _) = common::run_instruction(Bytecode::Neq, state1);
assert_eq!(
state2.stack_peek(0),
Some(AbstractValue::new_primitive(SignatureToken::Bool)),
"stack type postcondition not met"
);
}
#[test]
fn bytecode_neq_bool() {
let mut state1 = AbstractState::new();
state1.stack_push(AbstractValue::new_primitive(SignatureToken::Bool));
state1.stack_push(AbstractValue::new_primitive(SignatureToken::Bool));
let (state2, _) = common::run_instruction(Bytecode::Neq, state1);
assert_eq!(
state2.stack_peek(0),
Some(AbstractValue::new_primitive(SignatureToken::Bool)),
"stack type postcondition not met"
);
}<|fim▁end|> | |
<|file_name|>routing.js<|end_file_name|><|fim▁begin|>function checkHeadersSent(res, cb) {
return (err, results) => {
if (res.headersSent) {
if (err) {
return cb(err)
}
return null<|fim▁hole|> cb(err, results)
}
}
exports.finish = function finish(req, res, next) {
const check = checkHeadersSent.bind(null, res)
if (req.method === 'GET') {
return check((err, results) => {
if (err) {
return next(err) // Send to default handler
}
res.json(results)
})
} else if (req.method === 'POST') {
return check((err, results) => {
if (err) {
return next(err) // Send to default handler
}
/* eslint-disable max-len */
// http://www.vinaysahni.com/best-practices-for-a-pragmatic-restful-api?hn#useful-post-responses
if (results) {
res.json(results, 200)
} else {
res.json(204, {})
}
})
} else if (req.method === 'PUT') {
return check((err, results) => {
if (err) {
return next(err) // Send to default handler
}
if (results) {
res.json(results, 200)
} else {
res.json(204, {})
}
})
} else if (req.method === 'PATCH') {
return check((err, results) => {
if (err) {
return next(err) // Send to default handler
}
if (results) {
res.json(results)
} else {
res.json(204, {})
}
})
} else if (req.method === 'DELETE') {
return check((err, results) => {
if (err) {
return next(err) // Send to default handler
}
if (results) {
res.json(results)
} else {
res.json(204, {})
}
})
}
}<|fim▁end|> | } |
<|file_name|>setup.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*-
import os.path
import re
import warnings
try:
from setuptools import setup, find_packages
except ImportError:
from distribute_setup import use_setuptools
use_setuptools()
from setuptools import setup, find_packages
version = '0.2.1'
news = os.path.join(os.path.dirname(__file__), 'docs', 'news.rst')
news = open(news).read()
parts = re.split(r'([0-9\.]+)\s*\n\r?-+\n\r?', news)
found_news = ''
for i in range(len(parts)-1):
if parts[i] == version:
found_news = parts[i+i]
break
if not found_news:
warnings.warn('No news for this version found.')
long_description = """
keepassdb is a Python library that provides functionality for reading and writing
KeePass 1.x (and KeePassX) password databases.
This library brings together work by multiple authors, including:
- Karsten-Kai König <[email protected]>
- Brett Viren <[email protected]>
- Wakayama Shirou <[email protected]>
"""
if found_news:
title = 'Changes in %s' % version
long_description += "\n%s\n%s\n" % (title, '-'*len(title))
long_description += found_news
setup(
name = "keepassdb",
version = version,
author = "Hans Lellelid",
author_email = "[email protected]",
url = "http://github.com/hozn/keepassdb",
license = "GPLv3",
description = "Python library for reading and writing KeePass 1.x databases.",
long_description = long_description,
packages = find_packages(),
include_package_data=True,
package_data={'keepassdb': ['tests/resources/*']},
install_requires=['pycrypto>=2.6,<3.0dev'],
tests_require = ['nose>=1.0.3'],
test_suite = 'keepassdb.tests',
classifiers=[
'Development Status :: 3 - Alpha',
'License :: OSI Approved :: GNU General Public License (GPL)',
'Intended Audience :: Developers',<|fim▁hole|> 'Programming Language :: Python :: 3.1',
'Programming Language :: Python :: 3.2',
'Programming Language :: Python :: 3.3',
'Topic :: Security :: Cryptography',
'Topic :: Software Development :: Libraries :: Python Modules'
],
use_2to3=True,
zip_safe=False # Technically it should be fine, but there are issues w/ 2to3
)<|fim▁end|> | 'Operating System :: OS Independent',
'Programming Language :: Python :: 2.6',
'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: 3.0', |
<|file_name|>tags.go<|end_file_name|><|fim▁begin|>// Copyright 2011 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package msgpack
import (
"strings"
)
// tagOptions is the string following a comma in a struct field's "json"
// tag, or the empty string. It does not include the leading comma.
type tagOptions string
// parseTag splits a struct field's json tag into its name and
// comma-separated options.
func parseTag(tag string) (string, tagOptions) {
if idx := strings.Index(tag, ","); idx != -1 {
return tag[:idx], tagOptions(tag[idx+1:])
}
return tag, tagOptions("")
}
// Contains reports whether a comma-separated list of options
// contains a particular substr flag. substr must be surrounded by a<|fim▁hole|>func (o tagOptions) Contains(optionName string) bool {
if len(o) == 0 {
return false
}
s := string(o)
for s != "" {
var next string
i := strings.IndexRune(s, ',')
if i >= 0 {
s, next = s[:i], s[i+1:]
}
if s == optionName {
return true
}
s = next
}
return false
}<|fim▁end|> | // string boundary or commas. |
<|file_name|>unsafe-mod.rs<|end_file_name|><|fim▁begin|><|fim▁hole|>// These are supported by rustc syntactically but not semantically.
#[cfg(any())]
unsafe mod m { }
#[cfg(any())]
unsafe extern "C++" { }<|fim▁end|> | |
<|file_name|>stockfs.py<|end_file_name|><|fim▁begin|>#!/usr/bin/python
# Copyright 2015 Comcast Cable Communications Management, 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.
#
# End Copyright
# Little external FS (fact service) example
# Wrap Yahoo stock quotes as an FS.
# Pattern must specify a single ticker symbol "symbol".
# Pattern must specify at least one additional property from the set
legalProperties = {"bid", "ask", "change", "percentChange", "lastTradeSize"}
# curl 'http://download.finance.yahoo.com/d/quotes.csv?s=CMCSA&f=abc1p2k3&e=.csv'
# http://www.canbike.ca/information-technology/yahoo-finance-url-download-to-a-csv-file.html
# A more principled approach would allow the pattern to specify only a
# single additional property, but that decision is a separate
# discussion.
# Usage:
#
# curl -d '{"symbol":"CMCSA","bid":"?bid","ask":"?ask"}' 'http://localhost:6666/facts/search'
#
from BaseHTTPServer import BaseHTTPRequestHandler,HTTPServer
import cgi # Better way now?
import json
import urllib2
import urllib
import re
PORT = 6666
def protest (response, message):
response.send_response(200)
response.send_header('Content-type','text/plain')
response.end_headers()
response.wfile.write(message) # Should probably be JSON
def getQuote (symbol):
uri = "http://download.finance.yahoo.com/d/quotes.csv?s=" + symbol + "&f=abc1p2k3&e=.csv"<|fim▁hole|> print "got ", line, "\n"
line = re.sub(r'[%"\n]+', "", line)
print "clean ", line, "\n"
data = line.split(",")
ns = map(float, data)
q = {}
q["bid"] = ns[0]
q["ask"] = ns[1]
q["change"] = ns[2]
q["percentChange"] = ns[3]
q["lastTradeSize"] = ns[4]
return q
class handler(BaseHTTPRequestHandler):
def do_GET(self):
protest(self, "You should POST with json.\n")
return
def do_POST(self):
if not self.path == '/facts/search':
protest(self, "Only can do /facts/search.\n")
return
try:
content_length = int(self.headers['Content-Length'])
js = self.rfile.read(content_length)
m = json.loads(js)
if 'symbol' not in m:
protest(self, "Need symbol.\n")
return
symbol = m["symbol"]
del m["symbol"]
for p in m:
if p not in legalProperties:
protest(self, "Illegal property " + p + ".\n")
return
v = m[p]
if not v.startswith("?"):
protest(self, "Value " + v + " must be a variable.\n")
return
if len(v) < 2:
protest(self, "Need an named variable for " + v + ".\n")
return
q = getQuote(symbol)
print q, "\n"
bindings = {}
satisfied = True
for p in m:
print p, ": ", q[p], "\n"
if p in q:
bindings[m[p]] = q[p]
else:
satisfied = False
break
if satisfied:
js = json.dumps(bindings)
response = '{"Found":[{"Bindingss":[%s]}]}' % (js)
else:
response = '{"Found":[{"Bindingss":[]}]}'
self.send_response(200)
self.send_header('Content-type','application/json')
self.end_headers()
print 'response ', response
self.wfile.write(response)
except Exception as broke:
print broke, "\n"
protest(self, str(broke))
try:
server = HTTPServer(('', PORT), handler)
print 'Started weather FS on port ' , PORT
server.serve_forever()
except KeyboardInterrupt:
print '^C received, shutting down the weather FS on ', PORT
server.socket.close()<|fim▁end|> | print "uri ", uri
line = urllib2.urlopen(uri).read().strip() |
<|file_name|>0003_auto_20161217_2150.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*-
# Generated by Django 1.10.1 on 2016-12-17 20:50
from __future__ import unicode_literals
from django.db import migrations
<|fim▁hole|>
dependencies = [
('jordbruksmark', '0002_auto_20161217_2140'),
]
operations = [
migrations.AlterModelOptions(
name='wochen_menge',
options={'verbose_name': 'Wochen Menge', 'verbose_name_plural': 'Wochen Mengen'},
),
]<|fim▁end|> |
class Migration(migrations.Migration): |
<|file_name|>LocationAnnotator.java<|end_file_name|><|fim▁begin|>/*
* Copyright (C) 2014 Michael Joyce <[email protected]>
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation version 2.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
*/
package ca.nines.ise.util;
import java.util.ArrayDeque;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.UserDataHandler;
import org.w3c.dom.events.Event;
import org.w3c.dom.events.EventListener;
import org.w3c.dom.events.EventTarget;
import org.xml.sax.Attributes;
import org.xml.sax.Locator;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.XMLFilterImpl;
import org.xml.sax.XMLReader;
import org.xml.sax.helpers.LocatorImpl;
/**
* Annotates a DOM with location data during the construction process.
* <p>
* http://javacoalface.blogspot.ca/2011/04/line-and-column-numbers-in-xml-dom.html
* <p>
* @author Michael Joyce <[email protected]>
*/
public class LocationAnnotator extends XMLFilterImpl {
/**
* Locator returned by the construction process.
*/
private Locator locator;
/**
* The systemID of the XML.
*/
private final String source;
/**
* Stack to hold the locators which haven't been completed yet.
*/
private final ArrayDeque<Locator> locatorStack = new ArrayDeque<>();
/**
* Stack holding incomplete elements.
*/
private final ArrayDeque<Element> elementStack = new ArrayDeque<>();
/**
* A data handler to add the location data.
*/
private final UserDataHandler dataHandler = new LocationDataHandler();
/**
* Construct a location annotator for an XMLReader and Document. The systemID
* is determined automatically.
*
* @param xmlReader the reader to use the annotator
* @param dom the DOM to annotate
*/
LocationAnnotator(XMLReader xmlReader, Document dom) {
super(xmlReader);
source = "";
EventListener modListener = new EventListener() {
@Override
public void handleEvent(Event e) {
EventTarget target = e.getTarget();
elementStack.push((Element) target);
}
};
((EventTarget) dom).addEventListener("DOMNodeInserted", modListener, true);
}
/**
* Construct a location annotator for an XMLReader and Document. The systemID
* is NOT determined automatically.
*
* @param source the systemID of the XML
* @param xmlReader the reader to use the annotator
* @param dom the DOM to annotate
*/
LocationAnnotator(String source, XMLReader xmlReader, Document dom) {
super(xmlReader);
this.source = source;
EventListener modListener = new EventListener() {
@Override
public void handleEvent(Event e) {
EventTarget target = e.getTarget();
elementStack.push((Element) target);
}
};
((EventTarget) dom).addEventListener("DOMNodeInserted", modListener, true);
}
/**
* Add the locator to the document during the parse.
*
* @param locator the locator to add
*/
@Override
public void setDocumentLocator(Locator locator) {
super.setDocumentLocator(locator);
this.locator = locator;
}
/**
* Handle the start tag of an element by adding locator data.
*
* @param uri The systemID of the XML.
* @param localName the name of the tag. unused.
* @param qName the FQDN of the tag. unused.
* @param atts the attributes of the tag. unused.
* @throws SAXException
*/
@Override
public void startElement(String uri, String localName, String qName, Attributes atts) throws SAXException {
super.startElement(uri, localName, qName, atts);
locatorStack.push(new LocatorImpl(locator));
}
/**
* Handle the end tag of an element by adding locator data.
*
* @param uri The systemID of the XML.
* @param localName the name of the tag. unused.
* @param qName the FQDN of the tag. unused.
* @throws SAXException
*/
@Override
public void endElement(String uri, String localName, String qName) throws SAXException {
super.endElement(uri, localName, qName);
if (locatorStack.size() > 0) {
Locator startLocator = locatorStack.pop();
LocationData location = new LocationData(
(startLocator.getSystemId() == null ? source : startLocator.getSystemId()),
startLocator.getLineNumber(),
startLocator.getColumnNumber(),
locator.getLineNumber(),
locator.getColumnNumber()
);
Element e = elementStack.pop();
e.setUserData(
LocationData.LOCATION_DATA_KEY, location,
dataHandler);<|fim▁hole|> }
}
/**
* UserDataHandler to insert location data into the XML DOM.
*/
private class LocationDataHandler implements UserDataHandler {
/**
* Handle an even during a parse. An even is a start/end/empty tag or some
* data.
*
* @param operation unused.
* @param key unused
* @param data unused
* @param src the source of the data
* @param dst the destination of the data
*/
@Override
public void handle(short operation, String key, Object data, Node src, Node dst) {
if (src != null && dst != null) {
LocationData locatonData = (LocationData) src.getUserData(LocationData.LOCATION_DATA_KEY);
if (locatonData != null) {
dst.setUserData(LocationData.LOCATION_DATA_KEY, locatonData, dataHandler);
}
}
}
}
}<|fim▁end|> | |
<|file_name|>code.py<|end_file_name|><|fim▁begin|>import inspect
import re
import sys
import traceback
from inspect import CO_VARARGS
from inspect import CO_VARKEYWORDS
from traceback import format_exception_only
from types import TracebackType
from typing import Generic
from typing import Optional
from typing import Pattern
from typing import Tuple
from typing import TypeVar
from typing import Union
from weakref import ref
import attr
import pluggy
import py
import _pytest
from _pytest._io.saferepr import safeformat
from _pytest._io.saferepr import saferepr
if False: # TYPE_CHECKING
from typing import Type
class Code:
""" wrapper around Python code objects """
def __init__(self, rawcode):
if not hasattr(rawcode, "co_filename"):
rawcode = getrawcode(rawcode)
try:
self.filename = rawcode.co_filename
self.firstlineno = rawcode.co_firstlineno - 1
self.name = rawcode.co_name
except AttributeError:
raise TypeError("not a code object: {!r}".format(rawcode))
self.raw = rawcode
def __eq__(self, other):
return self.raw == other.raw
# Ignore type because of https://github.com/python/mypy/issues/4266.
__hash__ = None # type: ignore
def __ne__(self, other):
return not self == other
@property
def path(self):
""" return a path object pointing to source code (note that it
might not point to an actually existing file). """
try:
p = py.path.local(self.raw.co_filename)
# maybe don't try this checking
if not p.check():
raise OSError("py.path check failed.")
except OSError:
# XXX maybe try harder like the weird logic
# in the standard lib [linecache.updatecache] does?
p = self.raw.co_filename
return p
@property
def fullsource(self):
""" return a _pytest._code.Source object for the full source file of the code
"""
from _pytest._code import source
full, _ = source.findsource(self.raw)
return full
def source(self):
""" return a _pytest._code.Source object for the code object's source only
"""
# return source only for that part of code
import _pytest._code
return _pytest._code.Source(self.raw)
def getargs(self, var=False):
""" return a tuple with the argument names for the code object
if 'var' is set True also return the names of the variable and
keyword arguments when present
"""
# handfull shortcut for getting args
raw = self.raw
argcount = raw.co_argcount
if var:
argcount += raw.co_flags & CO_VARARGS
argcount += raw.co_flags & CO_VARKEYWORDS
return raw.co_varnames[:argcount]
class Frame:
"""Wrapper around a Python frame holding f_locals and f_globals
in which expressions can be evaluated."""
def __init__(self, frame):
self.lineno = frame.f_lineno - 1
self.f_globals = frame.f_globals
self.f_locals = frame.f_locals
self.raw = frame
self.code = Code(frame.f_code)
@property
def statement(self):
""" statement this frame is at """
import _pytest._code
if self.code.fullsource is None:
return _pytest._code.Source("")
return self.code.fullsource.getstatement(self.lineno)
def eval(self, code, **vars):
""" evaluate 'code' in the frame
'vars' are optional additional local variables
returns the result of the evaluation
"""
f_locals = self.f_locals.copy()
f_locals.update(vars)
return eval(code, self.f_globals, f_locals)
def exec_(self, code, **vars):
""" exec 'code' in the frame
'vars' are optiona; additional local variables
"""
f_locals = self.f_locals.copy()
f_locals.update(vars)
exec(code, self.f_globals, f_locals)
def repr(self, object):
""" return a 'safe' (non-recursive, one-line) string repr for 'object'
"""
return saferepr(object)
def is_true(self, object):
return object
def getargs(self, var=False):
""" return a list of tuples (name, value) for all arguments
if 'var' is set True also include the variable and keyword
arguments when present
"""
retval = []
for arg in self.code.getargs(var):
try:
retval.append((arg, self.f_locals[arg]))
except KeyError:
pass # this can occur when using Psyco
return retval
class TracebackEntry:
""" a single entry in a traceback """
_repr_style = None
exprinfo = None
def __init__(self, rawentry, excinfo=None):
self._excinfo = excinfo
self._rawentry = rawentry
self.lineno = rawentry.tb_lineno - 1
def set_repr_style(self, mode):
assert mode in ("short", "long")
self._repr_style = mode
@property
def frame(self):
import _pytest._code
return _pytest._code.Frame(self._rawentry.tb_frame)
@property
def relline(self):
return self.lineno - self.frame.code.firstlineno
def __repr__(self):
return "<TracebackEntry %s:%d>" % (self.frame.code.path, self.lineno + 1)
@property
def statement(self):
""" _pytest._code.Source object for the current statement """
source = self.frame.code.fullsource
return source.getstatement(self.lineno)
@property
def path(self):
""" path to the source code """
return self.frame.code.path
@property
def locals(self):
""" locals of underlaying frame """
return self.frame.f_locals
def getfirstlinesource(self):
return self.frame.code.firstlineno
def getsource(self, astcache=None):
""" return failing source code. """
# we use the passed in astcache to not reparse asttrees
# within exception info printing
from _pytest._code.source import getstatementrange_ast
source = self.frame.code.fullsource
if source is None:
return None
key = astnode = None
if astcache is not None:
key = self.frame.code.path
if key is not None:
astnode = astcache.get(key, None)
start = self.getfirstlinesource()
try:
astnode, _, end = getstatementrange_ast(
self.lineno, source, astnode=astnode
)
except SyntaxError:
end = self.lineno + 1
else:
if key is not None:
astcache[key] = astnode
return source[start:end]
source = property(getsource)
def ishidden(self):
""" return True if the current frame has a var __tracebackhide__
resolving to True.
If __tracebackhide__ is a callable, it gets called with the
ExceptionInfo instance and can decide whether to hide the traceback.
mostly for internal use
"""
f = self.frame
tbh = f.f_locals.get(
"__tracebackhide__", f.f_globals.get("__tracebackhide__", False)
)
if tbh and callable(tbh):
return tbh(None if self._excinfo is None else self._excinfo())
return tbh
def __str__(self):
try:
fn = str(self.path)
except py.error.Error:
fn = "???"
name = self.frame.code.name
try:
line = str(self.statement).lstrip()
except KeyboardInterrupt:
raise
except: # noqa
line = "???"
return " File %r:%d in %s\n %s\n" % (fn, self.lineno + 1, name, line)
@property
def name(self):
""" co_name of underlaying code """
return self.frame.code.raw.co_name
class Traceback(list):
""" Traceback objects encapsulate and offer higher level
access to Traceback entries.
"""
Entry = TracebackEntry
def __init__(self, tb, excinfo=None):
""" initialize from given python traceback object and ExceptionInfo """
self._excinfo = excinfo
if hasattr(tb, "tb_next"):
def f(cur):
while cur is not None:
yield self.Entry(cur, excinfo=excinfo)
cur = cur.tb_next
list.__init__(self, f(tb))
else:
list.__init__(self, tb)
def cut(self, path=None, lineno=None, firstlineno=None, excludepath=None):
""" return a Traceback instance wrapping part of this Traceback
by provding any combination of path, lineno and firstlineno, the
first frame to start the to-be-returned traceback is determined
this allows cutting the first part of a Traceback instance e.g.
for formatting reasons (removing some uninteresting bits that deal
with handling of the exception/traceback)
"""
for x in self:
code = x.frame.code
codepath = code.path
if (
(path is None or codepath == path)
and (
excludepath is None
or not hasattr(codepath, "relto")
or not codepath.relto(excludepath)
)
and (lineno is None or x.lineno == lineno)
and (firstlineno is None or x.frame.code.firstlineno == firstlineno)
):
return Traceback(x._rawentry, self._excinfo)
return self
def __getitem__(self, key):
val = super().__getitem__(key)
if isinstance(key, type(slice(0))):
val = self.__class__(val)
return val
def filter(self, fn=lambda x: not x.ishidden()):
""" return a Traceback instance with certain items removed
fn is a function that gets a single argument, a TracebackEntry
instance, and should return True when the item should be added
to the Traceback, False when not
by default this removes all the TracebackEntries which are hidden
(see ishidden() above)
"""
return Traceback(filter(fn, self), self._excinfo)
def getcrashentry(self):
""" return last non-hidden traceback entry that lead
to the exception of a traceback.
"""
for i in range(-1, -len(self) - 1, -1):
entry = self[i]
if not entry.ishidden():
return entry
return self[-1]
def recursionindex(self):
""" return the index of the frame/TracebackEntry where recursion
originates if appropriate, None if no recursion occurred
"""
cache = {}
for i, entry in enumerate(self):
# id for the code.raw is needed to work around
# the strange metaprogramming in the decorator lib from pypi
# which generates code objects that have hash/value equality
# XXX needs a test
key = entry.frame.code.path, id(entry.frame.code.raw), entry.lineno
# print "checking for recursion at", key
values = cache.setdefault(key, [])
if values:
f = entry.frame
loc = f.f_locals
for otherloc in values:
if f.is_true(
f.eval(
co_equal,
__recursioncache_locals_1=loc,
__recursioncache_locals_2=otherloc,
)
):
return i
values.append(entry.frame.f_locals)
return None
co_equal = compile(
"__recursioncache_locals_1 == __recursioncache_locals_2", "?", "eval"
)
_E = TypeVar("_E", bound=BaseException)
@attr.s(repr=False)
class ExceptionInfo(Generic[_E]):
""" wraps sys.exc_info() objects and offers
help for navigating the traceback.
"""
_assert_start_repr = "AssertionError('assert "
_excinfo = attr.ib(type=Optional[Tuple["Type[_E]", "_E", TracebackType]])
_striptext = attr.ib(type=str, default="")
_traceback = attr.ib(type=Optional[Traceback], default=None)
@classmethod
def from_exc_info(
cls,
exc_info: Tuple["Type[_E]", "_E", TracebackType],
exprinfo: Optional[str] = None,
) -> "ExceptionInfo[_E]":
"""returns an ExceptionInfo for an existing exc_info tuple.
.. warning::
Experimental API
:param exprinfo: a text string helping to determine if we should
strip ``AssertionError`` from the output, defaults
to the exception message/``__str__()``
"""
_striptext = ""
if exprinfo is None and isinstance(exc_info[1], AssertionError):
exprinfo = getattr(exc_info[1], "msg", None)
if exprinfo is None:
exprinfo = saferepr(exc_info[1])
if exprinfo and exprinfo.startswith(cls._assert_start_repr):
_striptext = "AssertionError: "
return cls(exc_info, _striptext)
@classmethod
def from_current(
cls, exprinfo: Optional[str] = None
) -> "ExceptionInfo[BaseException]":
"""returns an ExceptionInfo matching the current traceback
.. warning::
Experimental API
:param exprinfo: a text string helping to determine if we should
strip ``AssertionError`` from the output, defaults
to the exception message/``__str__()``
"""
tup = sys.exc_info()
assert tup[0] is not None, "no current exception"
assert tup[1] is not None, "no current exception"
assert tup[2] is not None, "no current exception"
exc_info = (tup[0], tup[1], tup[2])
return cls.from_exc_info(exc_info)
@classmethod
def for_later(cls) -> "ExceptionInfo[_E]":
"""return an unfilled ExceptionInfo
"""
return cls(None)
def fill_unfilled(self, exc_info: Tuple["Type[_E]", _E, TracebackType]) -> None:
"""fill an unfilled ExceptionInfo created with for_later()"""
assert self._excinfo is None, "ExceptionInfo was already filled"
self._excinfo = exc_info
@property
def type(self) -> "Type[_E]":
"""the exception class"""
assert (
self._excinfo is not None
), ".type can only be used after the context manager exits"
return self._excinfo[0]
@property
def value(self) -> _E:
"""the exception value"""
assert (
self._excinfo is not None
), ".value can only be used after the context manager exits"
return self._excinfo[1]
@property
def tb(self) -> TracebackType:
"""the exception raw traceback"""
assert (
self._excinfo is not None
), ".tb can only be used after the context manager exits"
return self._excinfo[2]
@property
def typename(self) -> str:
"""the type name of the exception"""
assert (
self._excinfo is not None
), ".typename can only be used after the context manager exits"
return self.type.__name__
@property
def traceback(self) -> Traceback:
"""the traceback"""
if self._traceback is None:
self._traceback = Traceback(self.tb, excinfo=ref(self))
return self._traceback
@traceback.setter
def traceback(self, value: Traceback) -> None:
self._traceback = value
def __repr__(self) -> str:
if self._excinfo is None:
return "<ExceptionInfo for raises contextmanager>"
return "<ExceptionInfo %s tblen=%d>" % (self.typename, len(self.traceback))
def exconly(self, tryshort: bool = False) -> str:
""" return the exception as a string
when 'tryshort' resolves to True, and the exception is a
_pytest._code._AssertionError, only the actual exception part of
the exception representation is returned (so 'AssertionError: ' is
removed from the beginning)
"""
lines = format_exception_only(self.type, self.value)
text = "".join(lines)
text = text.rstrip()
if tryshort:
if text.startswith(self._striptext):
text = text[len(self._striptext) :]
return text
def errisinstance(
self, exc: Union["Type[BaseException]", Tuple["Type[BaseException]", ...]]
) -> bool:
""" return True if the exception is an instance of exc """
return isinstance(self.value, exc)
def _getreprcrash(self) -> "ReprFileLocation":
exconly = self.exconly(tryshort=True)
entry = self.traceback.getcrashentry()
path, lineno = entry.frame.code.raw.co_filename, entry.lineno
return ReprFileLocation(path, lineno + 1, exconly)
def getrepr(
self,
showlocals: bool = False,
style: str = "long",
abspath: bool = False,
tbfilter: bool = True,
funcargs: bool = False,
truncate_locals: bool = True,
chain: bool = True,
):
"""
Return str()able representation of this exception info.
:param bool showlocals:
Show locals per traceback entry.
Ignored if ``style=="native"``.
:param str style: long|short|no|native traceback style
:param bool abspath:
If paths should be changed to absolute or left unchanged.
:param bool tbfilter:
Hide entries that contain a local variable ``__tracebackhide__==True``.
Ignored if ``style=="native"``.
:param bool funcargs:
Show fixtures ("funcargs" for legacy purposes) per traceback entry.
:param bool truncate_locals:
With ``showlocals==True``, make sure locals can be safely represented as strings.
:param bool chain: if chained exceptions in Python 3 should be shown.
.. versionchanged:: 3.9
Added the ``chain`` parameter.
"""
if style == "native":
return ReprExceptionInfo(
ReprTracebackNative(
traceback.format_exception(
self.type, self.value, self.traceback[0]._rawentry
)
),
self._getreprcrash(),
)
fmt = FormattedExcinfo(
showlocals=showlocals,
style=style,
abspath=abspath,
tbfilter=tbfilter,
funcargs=funcargs,
truncate_locals=truncate_locals,
chain=chain,
)
return fmt.repr_excinfo(self)
def match(self, regexp: "Union[str, Pattern]") -> bool:
"""
Check whether the regular expression 'regexp' is found in the string
representation of the exception using ``re.search``. If it matches
then True is returned (so that it is possible to write
``assert excinfo.match()``). If it doesn't match an AssertionError is
raised.
"""
__tracebackhide__ = True
if not re.search(regexp, str(self.value)):
assert 0, "Pattern {!r} not found in {!r}".format(regexp, str(self.value))
return True
@attr.s
class FormattedExcinfo:
""" presenting information about failing Functions and Generators. """
# for traceback entries
flow_marker = ">"
fail_marker = "E"
showlocals = attr.ib(default=False)
style = attr.ib(default="long")
abspath = attr.ib(default=True)
tbfilter = attr.ib(default=True)
funcargs = attr.ib(default=False)
truncate_locals = attr.ib(default=True)
chain = attr.ib(default=True)
astcache = attr.ib(default=attr.Factory(dict), init=False, repr=False)
def _getindent(self, source):
# figure out indent for given source
try:
s = str(source.getstatement(len(source) - 1))
except KeyboardInterrupt:
raise
except: # noqa
try:
s = str(source[-1])
except KeyboardInterrupt:
raise
except: # noqa
return 0
return 4 + (len(s) - len(s.lstrip()))
def _getentrysource(self, entry):
source = entry.getsource(self.astcache)
if source is not None:
source = source.deindent()
return source
def repr_args(self, entry):
if self.funcargs:
args = []
for argname, argvalue in entry.frame.getargs(var=True):
args.append((argname, saferepr(argvalue)))
return ReprFuncArgs(args)
def get_source(self, source, line_index=-1, excinfo=None, short=False):
""" return formatted and marked up source lines. """
import _pytest._code
lines = []
if source is None or line_index >= len(source.lines):
source = _pytest._code.Source("???")
line_index = 0
if line_index < 0:
line_index += len(source)
space_prefix = " "
if short:
lines.append(space_prefix + source.lines[line_index].strip())
else:
for line in source.lines[:line_index]:
lines.append(space_prefix + line)
lines.append(self.flow_marker + " " + source.lines[line_index])
for line in source.lines[line_index + 1 :]:
lines.append(space_prefix + line)
if excinfo is not None:
indent = 4 if short else self._getindent(source)
lines.extend(self.get_exconly(excinfo, indent=indent, markall=True))
return lines
def get_exconly(self, excinfo, indent=4, markall=False):
lines = []
indent = " " * indent
# get the real exception information out
exlines = excinfo.exconly(tryshort=True).split("\n")
failindent = self.fail_marker + indent[1:]
for line in exlines:
lines.append(failindent + line)
if not markall:
failindent = indent
return lines
def repr_locals(self, locals):
if self.showlocals:
lines = []
keys = [loc for loc in locals if loc[0] != "@"]
keys.sort()
for name in keys:
value = locals[name]
if name == "__builtins__":
lines.append("__builtins__ = <builtins>")
else:
# This formatting could all be handled by the
# _repr() function, which is only reprlib.Repr in
# disguise, so is very configurable.
if self.truncate_locals:
str_repr = saferepr(value)
else:
str_repr = safeformat(value)
# if len(str_repr) < 70 or not isinstance(value,
# (list, tuple, dict)):
lines.append("{:<10} = {}".format(name, str_repr))
# else:
# self._line("%-10s =\\" % (name,))
# # XXX
# pprint.pprint(value, stream=self.excinfowriter)
return ReprLocals(lines)
def repr_traceback_entry(self, entry, excinfo=None):
import _pytest._code
source = self._getentrysource(entry)
if source is None:
source = _pytest._code.Source("???")
line_index = 0
else:
line_index = entry.lineno - entry.getfirstlinesource()
lines = []
style = entry._repr_style
if style is None:
style = self.style
if style in ("short", "long"):
short = style == "short"
reprargs = self.repr_args(entry) if not short else None
s = self.get_source(source, line_index, excinfo, short=short)
lines.extend(s)
if short:
message = "in %s" % (entry.name)
else:
message = excinfo and excinfo.typename or ""
path = self._makepath(entry.path)
filelocrepr = ReprFileLocation(path, entry.lineno + 1, message)
localsrepr = None
if not short:
localsrepr = self.repr_locals(entry.locals)
return ReprEntry(lines, reprargs, localsrepr, filelocrepr, style)
if excinfo:
lines.extend(self.get_exconly(excinfo, indent=4))
return ReprEntry(lines, None, None, None, style)
def _makepath(self, path):
if not self.abspath:
try:
np = py.path.local().bestrelpath(path)
except OSError:
return path
if len(np) < len(str(path)):
path = np
return path
def repr_traceback(self, excinfo):
traceback = excinfo.traceback
if self.tbfilter:
traceback = traceback.filter()
if excinfo.errisinstance(RecursionError):
traceback, extraline = self._truncate_recursive_traceback(traceback)
else:
extraline = None
last = traceback[-1]
entries = []
for index, entry in enumerate(traceback):
einfo = (last == entry) and excinfo or None
reprentry = self.repr_traceback_entry(entry, einfo)
entries.append(reprentry)
return ReprTraceback(entries, extraline, style=self.style)
def _truncate_recursive_traceback(self, traceback):
"""
Truncate the given recursive traceback trying to find the starting point
of the recursion.
The detection is done by going through each traceback entry and finding the
point in which the locals of the frame are equal to the locals of a previous frame (see ``recursionindex()``.
Handle the situation where the recursion process might raise an exception (for example
comparing numpy arrays using equality raises a TypeError), in which case we do our best to
warn the user of the error and show a limited traceback.
"""
try:
recursionindex = traceback.recursionindex()
except Exception as e:
max_frames = 10
extraline = (
"!!! Recursion error detected, but an error occurred locating the origin of recursion.\n"
" The following exception happened when comparing locals in the stack frame:\n"
" {exc_type}: {exc_msg}\n"
" Displaying first and last {max_frames} stack frames out of {total}."
).format(
exc_type=type(e).__name__,
exc_msg=str(e),
max_frames=max_frames,
total=len(traceback),
)
traceback = traceback[:max_frames] + traceback[-max_frames:]
else:
if recursionindex is not None:
extraline = "!!! Recursion detected (same locals & position)"
traceback = traceback[: recursionindex + 1]
else:
extraline = None
return traceback, extraline
def repr_excinfo(self, excinfo):
repr_chain = []
e = excinfo.value
descr = None
seen = set()
while e is not None and id(e) not in seen:
seen.add(id(e))
if excinfo:
reprtraceback = self.repr_traceback(excinfo)
reprcrash = excinfo._getreprcrash()
else:
# fallback to native repr if the exception doesn't have a traceback:
# ExceptionInfo objects require a full traceback to work
reprtraceback = ReprTracebackNative(
traceback.format_exception(type(e), e, None)
)
reprcrash = None
repr_chain += [(reprtraceback, reprcrash, descr)]
if e.__cause__ is not None and self.chain:
e = e.__cause__
excinfo = (
ExceptionInfo((type(e), e, e.__traceback__))
if e.__traceback__
else None
)
descr = "The above exception was the direct cause of the following exception:"
elif (
e.__context__ is not None and not e.__suppress_context__ and self.chain
):
e = e.__context__
excinfo = (
ExceptionInfo((type(e), e, e.__traceback__))
if e.__traceback__
else None
)
descr = "During handling of the above exception, another exception occurred:"
else:
e = None
repr_chain.reverse()
return ExceptionChainRepr(repr_chain)
class TerminalRepr:
def __str__(self):
# FYI this is called from pytest-xdist's serialization of exception
# information.
io = py.io.TextIO()
tw = py.io.TerminalWriter(file=io)
self.toterminal(tw)
return io.getvalue().strip()
def __repr__(self):
return "<{} instance at {:0x}>".format(self.__class__, id(self))
class ExceptionRepr(TerminalRepr):
def __init__(self):
self.sections = []
def addsection(self, name, content, sep="-"):
self.sections.append((name, content, sep))
def toterminal(self, tw):
for name, content, sep in self.sections:
tw.sep(sep, name)
tw.line(content)
class ExceptionChainRepr(ExceptionRepr):
def __init__(self, chain):
super().__init__()
self.chain = chain
# reprcrash and reprtraceback of the outermost (the newest) exception
# in the chain
self.reprtraceback = chain[-1][0]
self.reprcrash = chain[-1][1]
def toterminal(self, tw):
for element in self.chain:
element[0].toterminal(tw)
if element[2] is not None:
tw.line("")
tw.line(element[2], yellow=True)
super().toterminal(tw)
class ReprExceptionInfo(ExceptionRepr):
def __init__(self, reprtraceback, reprcrash):
super().__init__()
self.reprtraceback = reprtraceback
self.reprcrash = reprcrash
def toterminal(self, tw):
self.reprtraceback.toterminal(tw)
super().toterminal(tw)
class ReprTraceback(TerminalRepr):
entrysep = "_ "
def __init__(self, reprentries, extraline, style):
self.reprentries = reprentries
self.extraline = extraline
self.style = style
def toterminal(self, tw):
# the entries might have different styles
for i, entry in enumerate(self.reprentries):
if entry.style == "long":
tw.line("")
entry.toterminal(tw)
if i < len(self.reprentries) - 1:
next_entry = self.reprentries[i + 1]
if (
entry.style == "long"
or entry.style == "short"
and next_entry.style == "long"
):
tw.sep(self.entrysep)
if self.extraline:
tw.line(self.extraline)
class ReprTracebackNative(ReprTraceback):
def __init__(self, tblines):
self.style = "native"
self.reprentries = [ReprEntryNative(tblines)]
self.extraline = None
class ReprEntryNative(TerminalRepr):
style = "native"
def __init__(self, tblines):
self.lines = tblines
def toterminal(self, tw):
tw.write("".join(self.lines))
class ReprEntry(TerminalRepr):
def __init__(self, lines, reprfuncargs, reprlocals, filelocrepr, style):
self.lines = lines
self.reprfuncargs = reprfuncargs
self.reprlocals = reprlocals
self.reprfileloc = filelocrepr
self.style = style
def toterminal(self, tw):
if self.style == "short":
self.reprfileloc.toterminal(tw)
for line in self.lines:
red = line.startswith("E ")
tw.line(line, bold=True, red=red)
return
if self.reprfuncargs:
self.reprfuncargs.toterminal(tw)
for line in self.lines:
red = line.startswith("E ")
tw.line(line, bold=True, red=red)
if self.reprlocals:
tw.line("")
self.reprlocals.toterminal(tw)
if self.reprfileloc:
if self.lines:
tw.line("")
self.reprfileloc.toterminal(tw)
def __str__(self):
return "{}\n{}\n{}".format(
"\n".join(self.lines), self.reprlocals, self.reprfileloc
)
class ReprFileLocation(TerminalRepr):
def __init__(self, path, lineno, message):
self.path = str(path)
self.lineno = lineno
self.message = message
def toterminal(self, tw):
# filename and lineno output for each entry,
# using an output format that most editors unterstand
msg = self.message
i = msg.find("\n")
if i != -1:
msg = msg[:i]
tw.write(self.path, bold=True, red=True)
tw.line(":{}: {}".format(self.lineno, msg))
class ReprLocals(TerminalRepr):
def __init__(self, lines):
self.lines = lines
def toterminal(self, tw):
for line in self.lines:
tw.line(line)
class ReprFuncArgs(TerminalRepr):
def __init__(self, args):
self.args = args
def toterminal(self, tw):
if self.args:
linesofar = ""
for name, value in self.args:
ns = "{} = {}".format(name, value)
if len(ns) + len(linesofar) + 2 > tw.fullwidth:
if linesofar:
tw.line(linesofar)
linesofar = ns
else:
if linesofar:
linesofar += ", " + ns
else:
linesofar = ns
if linesofar:
tw.line(linesofar)
tw.line("")
def getrawcode(obj, trycall=True):<|fim▁hole|> except AttributeError:
obj = getattr(obj, "im_func", obj)
obj = getattr(obj, "func_code", obj)
obj = getattr(obj, "f_code", obj)
obj = getattr(obj, "__code__", obj)
if trycall and not hasattr(obj, "co_firstlineno"):
if hasattr(obj, "__call__") and not inspect.isclass(obj):
x = getrawcode(obj.__call__, trycall=False)
if hasattr(x, "co_firstlineno"):
return x
return obj
# relative paths that we use to filter traceback entries from appearing to the user;
# see filter_traceback
# note: if we need to add more paths than what we have now we should probably use a list
# for better maintenance
_PLUGGY_DIR = py.path.local(pluggy.__file__.rstrip("oc"))
# pluggy is either a package or a single module depending on the version
if _PLUGGY_DIR.basename == "__init__.py":
_PLUGGY_DIR = _PLUGGY_DIR.dirpath()
_PYTEST_DIR = py.path.local(_pytest.__file__).dirpath()
_PY_DIR = py.path.local(py.__file__).dirpath()
def filter_traceback(entry):
"""Return True if a TracebackEntry instance should be removed from tracebacks:
* dynamically generated code (no code to show up for it);
* internal traceback from pytest or its internal libraries, py and pluggy.
"""
# entry.path might sometimes return a str object when the entry
# points to dynamically generated code
# see https://bitbucket.org/pytest-dev/py/issues/71
raw_filename = entry.frame.code.raw.co_filename
is_generated = "<" in raw_filename and ">" in raw_filename
if is_generated:
return False
# entry.path might point to a non-existing file, in which case it will
# also return a str object. see #1133
p = py.path.local(entry.path)
return (
not p.relto(_PLUGGY_DIR) and not p.relto(_PYTEST_DIR) and not p.relto(_PY_DIR)
)<|fim▁end|> | """ return code object for given function. """
try:
return obj.__code__ |
<|file_name|>RestHandler.js<|end_file_name|><|fim▁begin|>//>>built
define("dojox/wire/ml/RestHandler",["dijit","dojo","dojox","dojo/require!dojox/wire/_base,dojox/wire/ml/util"],function(_1,_2,_3){
_2.provide("dojox.wire.ml.RestHandler");
_2.require("dojox.wire._base");
_2.require("dojox.wire.ml.util");
_2.declare("dojox.wire.ml.RestHandler",null,{contentType:"text/plain",handleAs:"text",bind:function(_4,_5,_6,_7){
_4=_4.toUpperCase();
var _8=this;
var _9={url:this._getUrl(_4,_5,_7),contentType:this.contentType,handleAs:this.handleAs,headers:this.headers,preventCache:this.preventCache};
var d=null;
if(_4=="POST"){
_9.postData=this._getContent(_4,_5);
d=_2.rawXhrPost(_9);
}else{
if(_4=="PUT"){
_9.putData=this._getContent(_4,_5);
d=_2.rawXhrPut(_9);
}else{
if(_4=="DELETE"){
d=_2.xhrDelete(_9);
}else{
d=_2.xhrGet(_9);
}
}
}
d.addCallbacks(function(_a){
_6.callback(_8._getResult(_a));
},function(_b){
_6.errback(_b);
});
},_getUrl:function(_c,_d,_e){
var _f;
if(_c=="GET"||_c=="DELETE"){
if(_d.length>0){
_f=_d[0];
}
}else{
if(_d.length>1){
_f=_d[1];
}
}
if(_f){
var _10="";
for(var _11 in _f){
var _12=_f[_11];
if(_12){
_12=encodeURIComponent(_12);
var _13="{"+_11+"}";
var _14=_e.indexOf(_13);
if(_14>=0){
_e=_e.substring(0,_14)+_12+_e.substring(_14+_13.length);
}else{
if(_10){
_10+="&";
}
_10+=(_11+"="+_12);
}
}
<|fim▁hole|>}
}
return _e;
},_getContent:function(_15,_16){
if(_15=="POST"||_15=="PUT"){
return (_16?_16[0]:null);
}else{
return null;
}
},_getResult:function(_17){
return _17;
}});
});<|fim▁end|> | }
if(_10){
_e+="?"+_10;
|
<|file_name|>profile_detail_view_test.py<|end_file_name|><|fim▁begin|>import json
from django.test import TestCase
from rest_framework.test import APIRequestFactory
from rest_framework.test import force_authenticate
from rest_framework import status
from rest_framework.authtoken.models import Token
from core.models import Profile, User
from api.views import ProfileDetail
from api.serializers import UserSerializer
class ProfileDetailViewTestCase(TestCase):
"""Test suite for the api profile list view."""
def setUp(self):
"""Define the test global variables."""
if not User.objects.filter(username='testadmin').exists():
self.admin_user = User.objects.create_superuser(username='testadmin', password='123', email='')
Token.objects.create(user=self.admin_user)
user = User.objects.create(username='testuser1', email='[email protected]', password='sometestpass')<|fim▁hole|> self.factory = APIRequestFactory()
self.view = ProfileDetail.as_view()
def test_dont_get_profile_data_without_authorization(self):
"""Test dont get profile data without authorization"""
request = self.factory.get('/core/api/profile/')
response = self.view(request, pk=self.test_profile.id)
self.assertEqual(response.status_code, status.HTTP_401_UNAUTHORIZED)
def test_get_profile_data(self):
"""Test get profile data"""
request = self.factory.get('/core/api/profile/')
force_authenticate(request, user=self.admin_user, token=self.admin_user.auth_token)
response = self.view(request, pk=self.test_profile.id)
self.assertEqual(response.status_code, status.HTTP_200_OK)
self.assertTrue('user' in response.data)
def test_update_profile_data(self):
"""Test update profile data"""
new_email = '[email protected]'
data = json.dumps({'user': {'email': new_email}})
request = self.factory.patch('/core/api/profile/',
data=data,
content_type='application/json')
force_authenticate(request, user=self.admin_user, token=self.admin_user.auth_token)
response = self.view(request, pk=self.test_profile.id)
self.assertEqual(response.status_code, status.HTTP_200_OK)
self.assertTrue('user' in response.data)
self.assertEqual(response.data['user']['email'], new_email)
def test_delete_profile(self):
"""Test delete profile"""
request = self.factory.delete('/core/api/profile/',
content_type='application/json')
force_authenticate(request, user=self.admin_user, token=self.admin_user.auth_token)
response = self.view(request, pk=self.test_profile.id)
self.assertEqual(response.status_code, status.HTTP_204_NO_CONTENT)
self.assertFalse(Profile.objects.filter(pk=self.test_profile.id).exists())<|fim▁end|> | self.test_profile = Profile.objects.create(user=user)
|
<|file_name|>p1_no_assignee.py<|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/.
from libmozdata import utils as lmdutils
from auto_nag import utils
from auto_nag.bzcleaner import BzCleaner
from auto_nag.escalation import Escalation, NoActivityDays
from auto_nag.nag_me import Nag
from auto_nag.round_robin import RoundRobin
class P1NoAssignee(BzCleaner, Nag):
def __init__(self):
super(P1NoAssignee, self).__init__()
self.escalation = Escalation(
self.people,
data=utils.get_config(self.name(), "escalation"),
skiplist=utils.get_config("workflow", "supervisor_skiplist", []),
)
self.round_robin = RoundRobin.get_instance()
self.components_skiplist = utils.get_config("workflow", "components_skiplist")
def description(self):
return "P1 Bugs, no assignee and no activity for few days"
def nag_template(self):
return self.template()
def get_extra_for_template(self):
return {"ndays": self.ndays}
def get_extra_for_nag_template(self):
return self.get_extra_for_template()
def get_extra_for_needinfo_template(self):
return self.get_extra_for_template()
def ignore_meta(self):
return True
def has_last_comment_time(self):
return True
def has_product_component(self):
return True
def columns(self):
return ["component", "id", "summary", "last_comment"]
def handle_bug(self, bug, data):
# check if the product::component is in the list
if utils.check_product_component(self.components_skiplist, bug):
return None
return bug
def get_mail_to_auto_ni(self, bug):
# For now, disable the needinfo
return None
# Avoid to ni everyday...
if self.has_bot_set_ni(bug):
return None
mail, nick = self.round_robin.get(bug, self.date)
if mail and nick:
return {"mail": mail, "nickname": nick}
return None
def set_people_to_nag(self, bug, buginfo):
priority = "high"
if not self.filter_bug(priority):
return None
owners = self.round_robin.get(bug, self.date, only_one=False, has_nick=False)
real_owner = bug["triage_owner"]
self.add_triage_owner(owners, real_owner=real_owner)
if not self.add(owners, buginfo, priority=priority):
self.add_no_manager(buginfo["id"])
return bug
def get_bz_params(self, date):
self.ndays = NoActivityDays(self.name()).get(
(utils.get_next_release_date() - self.nag_date).days
)
self.date = lmdutils.get_date_ymd(date)
fields = ["triage_owner", "flags"]
params = {
"bug_type": "defect",
"include_fields": fields,
"resolution": "---",
"f1": "priority",
"o1": "equals",
"v1": "P1",
"f2": "days_elapsed",
"o2": "greaterthaneq",
"v2": self.ndays,<|fim▁hole|>
return params
if __name__ == "__main__":
P1NoAssignee().run()<|fim▁end|> | }
utils.get_empty_assignees(params) |
<|file_name|>instancePropertyInStructType_basic.ts<|end_file_name|><|fim▁begin|>// @target: ES5
// ok
module NonGeneric {
struct C {
x: string;
/* get y() {
return 1;
}
set y(v) { } */
fn() { return this; }
constructor(public a: number, private b: number) { }
}
var c = new C(1, 2);
var r = c.fn();
var r2 = r.x;
// var r3 = r.y;
// r.y = 4;
// var r6 = c.y(); // error, should be c.y
}
<|fim▁hole|>module Generic {
struct C<T,U> {
x: T;
/* get y() {
return null;
}
set y(v: U) { } */
fn() { return this; }
constructor(public a: T, private b: U) { }
}
var c = new C(1, '');
var r = c.fn();
var r2 = r.x;
// var r3 = r.y;
// r.y = '';
// var r6 = c.y(); // error
}<|fim▁end|> | |
<|file_name|>__init__.py<|end_file_name|><|fim▁begin|>from flask import Blueprint
main = Blueprint('main', __name__)<|fim▁hole|>from . import errors, views
from ..models import Permission
@main.app_context_processor
def inject_permissions():
return dict(Permission=Permission)<|fim▁end|> | |
<|file_name|>count_sequences.py<|end_file_name|><|fim▁begin|>import argparse<|fim▁hole|>def run(description):
parser = argparse.ArgumentParser(
description = 'Prints the number of sequences in input file to stdout',
usage = 'fastaq count_sequences <infile>')
parser.add_argument('infile', help='Name of input file')
options = parser.parse_args()
print(tasks.count_sequences(options.infile))<|fim▁end|> | from pyfastaq import tasks
|
<|file_name|>jquery.fileupload-angular.min.js<|end_file_name|><|fim▁begin|><|fim▁hole|><|fim▁end|> | version https://git-lfs.github.com/spec/v1
oid sha256:691b4033e555f469bcdba73a60c0e6a24b38ebffbbf94ebe7ba61e3edbf61601
size 6745 |
<|file_name|>isurl.js<|end_file_name|><|fim▁begin|>// Copyright 2015-2018 FormBucket LLC
<|fim▁hole|> // credit: http://stackoverflow.com/questions/5717093/check-if-a-javascript-string-is-an-url
var pattern = new RegExp(
"^(https?:\\/\\/)?" + // protocol
"((([a-z\\d]([a-z\\d-]*[a-z\\d])*)\\.?)+[a-z]{2,}|" + // domain name
"((\\d{1,3}\\.){3}\\d{1,3}))" + // OR ip (v4) address
"(\\:\\d+)?(\\/[-a-z\\d%_.~+]*)*" + // port and path
"(\\?[;&a-z\\d%_.~+=-]*)?" + // query string
"(\\#[-a-z\\d_]*)?$",
"i"
); // fragment locator
return pattern.test(str);
}<|fim▁end|> | // ISURL returns true when the value matches the regex for a uniform resource locator.
export default function isurl(str) { |
<|file_name|>pyclean.py<|end_file_name|><|fim▁begin|># vim: tabstop=4 expandtab shiftwidth=4 autoindent
import INN
import datetime
import logging
import logging.handlers
import os
import os.path
import re
import shelve
import sys
import time
import traceback
# In Python2.4, utils was called Utils
try:
from email.utils import parseaddr
except ImportError:
from email.Utils import parseaddr
# Python 2.4 doesn't have hashlib
try:
from hashlib import md5
except ImportError:
from md5 import md5
try:
import configparser
except ImportError:
import ConfigParser
configparser=ConfigParser
try:
from sys import intern
except ImportError:
pass
# First, define some high-level date/time functions
def now():
return datetime.datetime.utcnow()
# return datetime.datetime.now()
def timestamp(stamp):
return stamp.strftime("%Y-%m-%d %H:%M:%S")
def dateobj(datestr):
"""Take a string formated date (yyyymmdd) and return a datetime object."""
# Python 2.4 compatibility
return datetime.datetime(*(time.strptime(datestr, '%Y%m%d')[0:6]))
# return datetime.datetime.strptime(datestr, '%Y%m%d')
def nowstamp():
"""A shortcut function to return a textual representation of now."""
return timestamp(now())
def last_midnight():
return now().replace(hour=0, minute=0, second=0, microsecond=0)
def next_midnight():
"""Return a datetime object relating to the next midnight.
"""
return last_midnight() + datetime.timedelta(days=1)
def future(days=0, hours=0, mins=0, secs=0):
return now() + datetime.timedelta(days=days, hours=hours,
minutes=mins, seconds=secs)
# -----This section is concerned with setting up a default configuration
def makedir(d):
"""Check if a given directory exists. If it doesn't, check if the
parent exists. If it does then the new directory will be created. If
not then sensible options are exhausted and the program aborts.
"""
if not os.path.isdir(d):
parent = os.path.dirname(d)
if os.path.isdir(parent):
os.mkdir(d, 0o700)
sys.stdout.write("%s: Directory created.\n" % d)
else:
msg = "%s: Unable to make directory. Aborting.\n" % d
sys.stdout.write(msg)
sys.exit(1)
def init_config():
# Configure the Config Parser.
config = configparser.RawConfigParser()
# Logging
config.add_section('logging')
config.set('logging', 'level', 'info')
config.set('logging',
'format', '%(asctime)s %(levelname)s %(message)s')
config.set('logging', 'datefmt', '%Y-%m-%d %H:%M:%S')
config.set('logging', 'retain', 7)
config.set('logging', 'logart_maxlines', 20)
# Binary
config.add_section('binary')
config.set('binary', 'lines_allowed', 15)
config.set('binary', 'allow_pgp', 'true')
config.set('binary', 'reject_suspected', 'false')
config.set('binary', 'fasttrack_references', 'true')
# EMP
config.add_section('emp')
config.set('emp', 'ph_coarse', 'true')
config.set('emp', 'body_threshold', 5)
config.set('emp', 'body_ceiling', 85)
config.set('emp', 'body_maxentries', 5000)
config.set('emp', 'body_timed_trim', 3600)
config.set('emp', 'body_fuzzy', 'true')
config.set('emp', 'phn_threshold', 100)
config.set('emp', 'phn_ceiling', 150)
config.set('emp', 'phn_maxentries', 5000)
config.set('emp', 'phn_timed_trim', 1800)
config.set('emp', 'lphn_threshold', 20)
config.set('emp', 'lphn_ceiling', 30)
config.set('emp', 'lphn_maxentries', 200)
config.set('emp', 'lphn_timed_trim', 1800)
config.set('emp', 'phl_threshold', 20)
config.set('emp', 'phl_ceiling', 80)
config.set('emp', 'phl_maxentries', 5000)
config.set('emp', 'phl_timed_trim', 3600)
config.set('emp', 'fsl_threshold', 20)
config.set('emp', 'fsl_ceiling', 40)
config.set('emp', 'fsl_maxentries', 5000)
config.set('emp', 'fsl_timed_trim', 3600)
config.set('emp', 'ihn_threshold', 10)
config.set('emp', 'ihn_ceiling', 15)
config.set('emp', 'ihn_maxentries', 1000)
config.set('emp', 'ihn_timed_trim', 7200)
config.add_section('groups')
config.set('groups', 'max_crosspost', 10)
config.set('groups', 'max_low_crosspost', 3)
config.add_section('control')
config.set('control', 'reject_cancels', 'false')
config.set('control', 'reject_redundant', 'true')
config.add_section('filters')
config.set('filters', 'newsguy', 'true')
config.set('filters', 'reject_html', 'true')
config.set('filters', 'reject_multipart', 'false')
config.add_section('hostnames')
config.set('hostnames', 'path_hostname', 'true')
# The path section is a bit tricky. First off we try to read a default
# config file. This can define the path to everything, including the
# pyclean.cfg config file. For this reason, all the path entries that
# could generate directories need to come after the config files have
# been read.
config.add_section('paths')
# In accordance with Debian standards, we'll look for
# /etc/default/pyclean. This file can define the path for pyclean's
# etc, which includes the pyclean.cfg file. The location of the
# default file can be overridden by setting the 'PYCLEAN' environment
# variable.
if 'PYCLEAN' in os.environ:
default = os.environ['PYCLEAN']
else:
default = os.path.join('/', 'etc', 'default', 'pyclean')
if os.path.isfile(default):
config.read(default)
# By default, all the paths are subdirectories of the homedir.
homedir = os.path.expanduser('~')
# Define the basedir for pyclean. By default this will be ~/pyclean
basedir = os.path.join(homedir, 'pyclean')
# If the default file hasn't specified an etc path, we need to assume a
# default. Usually /usr/local/news/pyclean/etc.
if not config.has_option('paths', 'etc'):
config.set('paths', 'etc', os.path.join(basedir, 'etc'))
# At this point, we know the basedir is going to be required so we
# attempt to create it.
makedir(basedir)
makedir(config.get('paths', 'etc'))
# Under all circumstances, we now have an etc path. Now to check
# if the config file exists and if so, read it.
configfile = os.path.join(config.get('paths', 'etc'), 'pyclean.cfg')
if os.path.isfile(configfile):
config.read(configfile)
if not config.has_option('paths', 'log'):
config.set('paths', 'log', os.path.join(basedir, 'log'))
# As with the etc section above, we know basedir is required now. No
# harm in trying to create it multiple times.
makedir(basedir)
makedir(config.get('paths', 'log'))
if not config.has_option('paths', 'logart'):
config.set('paths', 'logart', os.path.join(basedir, 'articles'))
makedir(config.get('paths', 'logart'))
if not config.has_option('paths', 'lib'):
config.set('paths', 'lib', os.path.join(basedir, 'lib'))
makedir(config.get('paths', 'lib'))
# The following lines can be uncommented in order to write a config
# file. This is useful for creating an example file.
# with open('example.cfg', 'wb') as configfile:
# config.write(configfile)
return config
class InndFilter:
"""Provide filtering callbacks to innd."""
def __init__(self):
"""This runs every time the filter is loaded or reloaded.
This is a good place to initialize variables and precompile
regular expressions, or maybe reload stats from disk.
"""
self.traceback_loop = 0
try:
self.pyfilter = Filter()
except:
fn = os.path.join(config.get('paths', 'log'), 'init_traceback')
f = open(fn, 'a')
traceback.print_exc(file=f)
f.close()
def filter_before_reload(self):
"""Runs just before the filter gets reloaded.
You can use this method to save state information to be
restored by the __init__() method or down in the main module.
"""
try:
self.pyfilter.closetasks()
logging.info("Re-reading config file")
global config
config = init_config()
except:
fn = os.path.join(config.get('paths', 'log'), 'close_traceback')
f = open(fn, 'a')
traceback.print_exc(file=f)
f.close()
return ""
def filter_close(self):
"""Runs when innd exits.
You can use this method to save state information to be
restored by the __init__() method or down in the main module.
"""
try:
self.pyfilter.closetasks()
except:
fn = os.path.join(config.get('paths', 'log'), 'close_traceback')
f = open(fn, 'a')
traceback.print_exc(file=f)
f.close()
return ""
INN.syslog('notice', "filter_close running, bye!")
def filter_messageid(self, msgid):
"""Filter articles just by their Message-IDs.
This method interacts with the CHECK, IHAVE and TAKETHIS
NNTP commands.
If you return a non-empty string here, the offered article
will be refused before you ever have to waste any bandwidth
looking at it (unless TAKETHIS is used before an earlier CHECK).
Make sure that such a message is properly encoded in UTF-8
so as to comply with the NNTP protocol.
"""
return "" # Deactivate the samples.
def filter_art(self, art):
"""Decide whether to keep offered articles.
art is a dictionary with a bunch of headers, the article's
body, and innd's reckoning of the line count. Items not
in the article will have a value of None.
The available headers are the ones listed near the top of
innd/art.c. At this writing, they are:
Also-Control, Approved, Archive, Archived-At, Bytes, Cancel-Key,
Cancel-Lock, Content-Base, Content-Disposition,
Content-Transfer-Encoding, Content-Type, Control, Date,
Date-Received, Distribution, Expires, Face, Followup-To, From,
In-Reply-To, Injection-Date, Injection-Info, Keywords, Lines,
List-ID, Message-ID, MIME-Version, Newsgroups, NNTP-Posting-Date,
NNTP-Posting-Host, NNTP-Posting-Path, Organization,
Original-Sender, Originator, Path, Posted, Posting-Version,
Received, References, Relay-Version, Reply-To, Sender, Subject,
Summary, Supersedes, User-Agent, X-Auth, X-Auth-Sender,
X-Canceled-By, X-Cancelled-By, X-Complaints-To, X-Face,
X-HTTP-UserAgent, X-HTTP-Via, X-Mailer, X-Modbot, X-Modtrace,
X-Newsposter, X-Newsreader, X-No-Archive, X-Original-Message-ID,
X-Original-NNTP-Posting-Host, X-Original-Trace, X-Originating-IP,
X-PGP-Key, X-PGP-Sig, X-Poster-Trace, X-Postfilter, X-Proxy-User,
X-Submissions-To, X-Trace, X-Usenet-Provider, X-User-ID, Xref.
The body is the buffer in art[__BODY__] and the INN-reckoned
line count is held as an integer in art[__LINES__]. (The
Lines: header is often generated by the poster, and large
differences can be a good indication of a corrupt article.)
If you want to keep an article, return None or "". If you
want to reject, return a non-empty string. The rejection
string will appear in transfer and posting response banners,
and local posters will see them if their messages are
rejected (make sure that such a response is properly encoded
in UTF-8 so as to comply with the NNTP protocol).
"""
try:
return self.pyfilter.filter(art)
except:
if not self.traceback_loop:
fn = os.path.join(config.get('paths', 'log'), 'traceback')
f = open(fn, 'a')
traceback.print_exc(file=f)
f.close()
self.traceback_loop = 1
return ""
def filter_mode(self, oldmode, newmode, reason):
"""Capture server events and do something useful.
When the admin throttles or pauses innd (and lets it go
again), this method will be called. oldmode is the state we
just left, and newmode is where we are going. reason is
usually just a comment string.
The possible values of newmode and oldmode are the five
strings 'running', 'paused', 'throttled', 'shutdown' and
'unknown'. Actually 'unknown' shouldn't happen; it's there
in case feeping creatures invade innd.
"""
INN.syslog('n', 'state change from %s to %s - %s'
% (oldmode, newmode, reason))
class Binary:
"""Perform binary content checking of articles.
"""
def __init__(self):
# Binaries
self.regex_yenc = re.compile('^=ybegin.*', re.M)
self.regex_uuenc = re.compile('^begin[ \t]+\d{3,4}[ \t]+\w+\.\w', re.M)
self.regex_base64 = re.compile('[a-zA-Z0-9+/]{59}')
self.regex_numeric = re.compile('[0-9]{59}')
self.regex_binary = re.compile('[ \t]*\S{40}')
# Feedhosts keeps a tally of how many binary articles are received
# from each upstream peer.
self.feedhosts = {}
self.tagged = 0
def increment(self, pathhost):
"""Increment feedhosts."""
if pathhost in self.feedhosts:
self.feedhosts[pathhost] += 1
else:
self.feedhosts[pathhost] = 1
def report(self):
fn = os.path.join(config.get('paths', 'log'), 'binfeeds')
f = open(fn, 'w')
f.write('# Binary feeders report - %s\n\n'
% nowstamp())
for e in self.feedhosts.keys():
f.write('%s: %s\n' % (e, self.feedhosts[e]))
f.close()
self.feedhosts = {}
def isbin(self, art):
"""The primary function of the Binary class. An article's body is
compared against a number of checks. If the conclusion is that the
payload is binary, the type of binary is returned. Non-binary content
will return False.
"""
# Ignore base64 encoded content.
if 'base64' in str(art[Content_Transfer_Encoding]).lower():
return False
if self.regex_uuenc.search(art[__BODY__]):
return 'uuEnc'
yenc = self.regex_yenc.search(art[__BODY__])
if yenc:
# Extract the matching line
l = yenc.group(0)
if 'line=' in l and 'size=' in l and 'name=' in l:
return 'yEnc'
# Avoid costly checks where articles are shorter than the allowed
# number of binary lines.
if int(art[__LINES__]) < config.getint('binary', 'lines_allowed'):
return False
# Also avoid these costly checks where a References header is present.
skip_refs = ('References' in art and
str(art['References']).startswith('<') and
config.getboolean('binary', 'fasttrack_references') and
int(art[__LINES__]) > 500)
if skip_refs:
return False
# Base64 and suspect binary matching
b64match = 0
suspect = 0
for line in str(art[__BODY__]).split('\n'):
skip_pgp = (line.startswith('-----BEGIN PGP')
and config.getboolean('binary', 'allow_pgp'))
if skip_pgp:
break
if line == "-- ":
# Don't include signatures in binary testing
break
# Resetting the next counter to zero on a non-matching line
# dictates the counted binary lines must be consecutive. We also
# test that a numeric line doesn't trigger a Base64 match.
if (self.regex_base64.match(line) and
not self.regex_numeric.match(line)):
b64match += 1
else:
b64match = 0
if self.regex_binary.match(line):
suspect += 1
else:
suspect = 0
if b64match > config.get('binary', 'lines_allowed'):
return 'base64'
if suspect > config.get('binary', 'lines_allowed'):
return 'binary'
return False
class Filter:
def __init__(self):
"""This runs every time the filter is loaded or reloaded.
This is a good place to initialize variables and precompile
regular expressions, or maybe reload stats from disk.
"""
# Initialize Group Analizer
self.groups = Groups()
# Initialize Binary Filters
self.binary = Binary()
# Posting Host and Posting Account
self.regex_ph = re.compile('posting-host *= *"?([^";]+)')
self.regex_pa = re.compile('posting-account *= *"?([^";]+)')
# Match lines in regex_files formated /regex/ timestamp(YYYYMMDD)
self.regex_fmt = re.compile('/(.+)/[ \t]+(\d{8})')
# A dictionary of files containing regexs that need to be reloaded and
# compiled if the timestamp on them changes. The dict content is the
# timestamp (initially zeroed).
regex_file_list = [
'bad_body',
'bad_cp_groups',
'bad_crosspost_host',
'bad_from',
'bad_groups',
'bad_groups_dizum',
'bad_posthost',
'bad_subject',
'good_posthost',
'ihn_hosts',
'local_bad_body',
'local_bad_cp_groups',
'local_bad_from',
'local_bad_groups',
'local_bad_subject',
'local_hosts',
'log_from']
# Each regex_files key contains a timestamp of last-modified time.
# Setting all keys to zero ensures they are processed on first run.
regex_files = dict((f, 0) for f in regex_file_list)
# Python >= 2.7 has dict comprehension but not earlier versions
# regex_files = {f: 0 for f in regex_file_list}
self.regex_files = regex_files
# A dict of the regexs compiled from the regex_files defined above.
self.etc_re = {}
# Hostname - Not a 100% perfect regex but probably good enough.
self.regex_hostname = re.compile('([a-zA-Z0-9]|[a-zA-Z0-9]'
'[a-zA-Z0-9\-]+[a-zA-Z0-9])'
'(\.[a-zA-Z0-9\-]+)+')
# Path replacement regexs
self.regex_pathhost = re.compile('(![^\.]+)+$') # Strip RH non-FQDNs
# Match email addresses
self.regex_email = \
re.compile('([\w\-][\w\-\.]*)@[\w\-][\w\-\.]+[a-zA-Z]{1,4}')
# Colon/Space seperated fields
self.regex_fields = re.compile('[ \t]*([^:]+):[ \t]+(\S+)')
# Content-Type: text/plain; charset=utf-8
self.regex_ct = re.compile("\s*([^;]+)")
self.regex_ctcs = re.compile('charset="?([^"\s;]+)')
# Symbol matching for ratio-based rejects
self.regex_symbols = re.compile("\\_/ |_\|_|[a-z]\.{2,}[a-z]")
# Match lines that start with a CR
self.regex_crspace = re.compile("^\r ", re.MULTILINE)
# Redundant control message types
self.redundant_controls = ['sendsys', 'senduuname', 'version',
'whogets']
# Set up the EMP filters
self.emp_body = EMP(name='emp_body',
threshold=config.getint('emp', 'body_threshold'),
ceiling=config.getint('emp', 'body_ceiling'),
maxentries=config.getint('emp', 'body_maxentries'),
timedtrim=config.getint('emp', 'body_timed_trim'),
dofuzzy=config.getboolean('emp', 'body_fuzzy'))
self.emp_phn = EMP(name='emp_phn',
threshold=config.getint('emp', 'phn_threshold'),
ceiling=config.getint('emp', 'phn_ceiling'),
maxentries=config.getint('emp', 'phn_maxentries'),
timedtrim=config.getint('emp', 'phn_timed_trim'))
self.emp_lphn = EMP(name='emp_lphn',
threshold=config.getint('emp', 'lphn_threshold'),
ceiling=config.getint('emp', 'lphn_ceiling'),
maxentries=config.getint('emp', 'lphn_maxentries'),
timedtrim=config.getint('emp', 'lphn_timed_trim'))
self.emp_phl = EMP(name='emp_phl',
threshold=config.getint('emp', 'phl_threshold'),
ceiling=config.getint('emp', 'phl_ceiling'),
maxentries=config.getint('emp', 'phl_maxentries'),
timedtrim=config.getint('emp', 'phl_timed_trim'))
self.emp_fsl = EMP(name='emp_fsl',
threshold=config.getint('emp', 'fsl_threshold'),
ceiling=config.getint('emp', 'fsl_ceiling'),
maxentries=config.getint('emp', 'fsl_maxentries'),
timedtrim=config.getint('emp', 'fsl_timed_trim'))
self.emp_ihn = EMP(name='emp_ihn',
threshold=config.getint('emp', 'ihn_threshold'),
ceiling=config.getint('emp', 'ihn_ceiling'),
maxentries=config.getint('emp', 'ihn_maxentries'),
timedtrim=config.getint('emp', 'ihn_timed_trim'))
# Initialize timed events
self.hourly_events(startup=True)
# Set a datetime object for next midnight
self.midnight_trigger = next_midnight()
def filter(self, art):
# Initialize the posting info dict
post = {}
# Trigger timed reloads
if now() > self.hourly_trigger:
self.hourly_events()
if now() > self.midnight_trigger:
self.midnight_events()
# Attempt to split the From address into component parts
if 'From' in art:
post['from_name'], \
post['from_email'] = self.addressParse(art['From'])
if art[Content_Type] is not None:
ct = self.regex_ct.match(art[Content_Type])
if ct:
post['content_type'] = ct.group(1).lower()
ctcs = self.regex_ctcs.search(art[Content_Type])
if ctcs:
post['charset'] = ctcs.group(1).lower()
# Try to establish the injection-host, posting-host and
# posting-account
if art[Injection_Info] is not None:
# Establish Posting Account
ispa = self.regex_pa.search(art[Injection_Info])
if ispa:
post['posting-account'] = ispa.group(1)
# Establish Posting Host
isph = self.regex_ph.search(art[Injection_Info])
if isph:
post['posting-host'] = isph.group(1)
# Establish injection host
isih = self.regex_hostname.match(art[Injection_Info])
if isih:
post['injection-host'] = isih.group(0)
# posting-host might be obtainable from NNTP-Posting-Host
if 'posting-host' not in post and art[NNTP_Posting_Host] is not None:
post['posting-host'] = str(art[NNTP_Posting_Host])
# If the injection-host wasn't found in Injection-Info, try the X-Trace
# header. We only look for a hostname as the first field in X-Trace,
# otherwise it's regex hell.
if 'injection-host' not in post and art[X_Trace] is not None:
isih = self.regex_hostname.match(art[X_Trace])
if isih:
post['injection-host'] = isih.group(0)
# Try to extract a hostname from the Path header
if config.getboolean('hostnames', 'path_hostname'):
# First, check for a !.POSTED tag, as per RFC5537
if 'injection-host' not in post and "!.POSTED" in str(art[Path]):
postsplit = str(art[Path]).split("!.POSTED", 1)
pathhost = postsplit[0].split("!")[-1]
if pathhost:
post['injection-host'] = pathhost
# Last resort, try the right-most entry in the Path header
if 'injection-host' not in post:
subhost = re.sub(self.regex_pathhost, '', art[Path])
pathhost = subhost.split("!")[-1]
if pathhost:
post['injection-host'] = pathhost
# Some services (like Google) use dozens of Injection Hostnames.
# This section looks for substring matches and replaces the entire
# Injection-Host with the substring.
if 'injection-host' in post:
for ihsub in self.ihsubs:
if ihsub in post['injection-host']:
logging.debug("Injection-Host: Replacing %s with %s",
post['injection-host'], ihsub)
post['injection-host'] = ihsub
# Ascertain if the posting-host is meaningful
if 'posting-host' in post:
isbad_ph = self.groups.regex.bad_ph.search(post['posting-host'])
if isbad_ph:
post['bad-posting-host'] = isbad_ph.group(0)
logging.debug('Bad posting host: %s',
post['bad-posting-host'])
# Dizum deserves a scalar all to itself!
dizum = False
if ('injection-host' in post and
post['injection-host'] == 'sewer.dizum.com'):
dizum = True
# The host that fed us this article is first in the Path header.
post['feed-host'] = str(art[Path]).split('!', 1)[0]
# Analyze the Newsgroups header
self.groups.analyze(art[Newsgroups], art[Followup_To])
# Is the source of the post considered local?
local = False
if ('injection-host' in post and
'local_hosts' in self.etc_re and
self.etc_re['local_hosts'].search(post['injection-host'])):
local = True
# --- Everything below is accept / reject code ---
# Reject any messages that don't have a Message-ID
if Message_ID not in art:
logging.warn("Wot no Message-ID! Rejecting message because the "
"implications of accepting it are unpredictable.")
return self.reject(art, post, "No Message-ID header")
# We use Message-ID strings so much, it's useful to have a shortcut.
mid = str(art[Message_ID])
# Now we're convinced we have a MID, log it for local posts.
if local:
logging.debug("Local post: %s", mid)
# Control message handling
if art[Control] is not None:
ctrltype = str(art[Control]).split(" ", 1)[0]
# Reject control messages with supersedes headers
if art[Supersedes] is not None:
return self.reject(
art, post,
'Control %s with Supersedes header' % ctrltype)
if (ctrltype == 'cancel' and
config.getboolean('control', 'reject_cancels')):
return self.reject(art, post, "Control cancel")
elif (ctrltype in self.redundant_controls and
config.getboolean('control', 'reject_redundant')):
return self.reject(
art, post,
"Redundant Control Type: %s" % ctrltype)
else:
logging.info('Control: %s, mid=%s' % (art[Control], mid))
return ''
# No followups is a reject as is more than 2 groups.
if self.groups['futcount'] < 1 or self.groups['futcount'] > 2:
# Max-crosspost check
if self.groups['count'] > config.get('groups', 'max_crosspost'):
return self.reject(art, post, "Crosspost Limit Exceeded")
# Max low crosspost check
if self.groups['count'] > config.get('groups',
'max_low_crosspost'):
if self.groups['lowcp'] > 0:
return self.reject(art, post,
"Crosspost Low Limit Exceeded")
# Lines check
if art[Lines] and int(art[Lines]) != int(art[__LINES__]):
logmes = "Lines Mismatch: Header=%s, INN=%s, mid=%s"
if art[User_Agent] is not None:
logmes += ", Agent=%s"
logging.debug(logmes % (art[Lines], art[__LINES__],
mid, art[User_Agent]))
else:
logging.debug(logmes % (art[Lines], art[__LINES__], mid))
# Newsguy are evil sex spammers
if ('newsguy.com' in mid and
config.getboolean('filters', 'newsguy') and
'sex_groups' in self.groups and
self.groups['sex_groups'] > 0):
return self.reject(art, post, "Newsguy Sex")
# For some reason, this OS2 group has become kook central
if ('comp.os.os2.advocacy' in self.groups['groups'] and
self.groups['count'] > 1):
return self.reject(art, post, "OS2 Crosspost")
if (art[Followup_To] and
'comp.os.os2.advocacy' in str(art[Followup_To])):
return self.reject(art, post, "OS2 Followup")
# Poor snipe is getting the Greg Hall treatment
if 'injection-host' in post:
if post['injection-host'].startswith(
"snipe.eternal-september.org"):
pass
# self.logart("Snipe Post", art, post, 'log_snipe')
else:
if ("sn!pe" in post['from_name'] or
"snipeco" in post['from_email']):
return self.reject(art, post, "Snipe Forge")
# Compare headers against regex files
# Check if posting-host is whitelisted
gph = False
if('posting-host' in post and 'good_posthost' in self.etc_re):
gph = self.etc_re['good_posthost'].search(post['posting-host'])
if gph:
logging.info("Whitelisted posting. host=%s, msgid=%s",
post['posting-host'],
art[Message_ID])
# Reject these posting-hosts
if ('posting-host' in post and not gph and
'bad_posting-host' not in post and
'bad_posthost' in self.etc_re):
bph = self.etc_re['bad_posthost'].search(post['posting-host'])
if bph:
return self.reject(
art, post,
"Bad Posting-Host (%s)" % bph.group(0))
# Test posting-hosts that are not allowed to crosspost
if ('posting-host' in post and not gph and
self.groups['count'] > 1 and
'bad_crosspost_host' in self.etc_re):
ph = post['posting-host']
bph = self.etc_re['bad_crosspost_host'].search(ph)
if bph:
return self.reject(
art, post,
"Bad Crosspost Host (%s)" % bph.group(0))
# Groups where crossposting is not allowed
if (self.groups['count'] > 1 and not gph and
'bad_cp_groups' in self.etc_re):
bcg = self.etc_re['bad_cp_groups'].search(art[Newsgroups])
if bcg:
return self.reject(
art, post,
"Bad Crosspost Group (%s)" % bcg.group(0))
if 'log_from' in self.etc_re:
lf_result = self.etc_re['log_from'].search(art[From])
if lf_result:
self.logart(lf_result.group(0), art, post, 'log_from',
trim=False)
if 'bad_groups' in self.etc_re and not gph:
bg_result = self.etc_re['bad_groups'].search(art[Newsgroups])
if bg_result:
return self.reject(
art, post,
"Bad Group (%s)" % bg_result.group(0))
if dizum and 'bad_groups_dizum' in self.etc_re:
bgd = self.etc_re['bad_groups_dizum'].search(art[Newsgroups])
if bgd:
return self.reject(
art, post,
"Bad Dizum Group (%s)" % bgd.group(0))
# AUK bad crossposts
#if self.groups['kooks'] > 0:
# if ('alt.free.newsservers' in self.groups['groups'] or
# 'alt.privacy.anon-server' in self.groups['groups']):
# return self.reject(art, post, "AUK Bad Crosspost")
if 'bad_from' in self.etc_re and not gph:
bf_result = self.etc_re['bad_from'].search(art[From])
if bf_result:
return self.reject(
art, post,
"Bad From (%s)" % bf_result.group(0))
# Bad subject checking (Currently only on Dizum posts)
if dizum and 'bad_subject' in self.etc_re and not gph:
bs_result = self.etc_re['bad_subject'].search(art[Subject])
if bs_result:
return self.reject(
art, post,
"Bad Subject (%s)" % bs_result.group(0))
if 'bad_body' in self.etc_re and not gph:
bb_result = self.etc_re['bad_body'].search(art[__BODY__])
if bb_result:
return self.reject(
art, post,
"Bad Body (%s)" % bb_result.group(0), "Bad Body")
# The following checks are for locally posted articles
# Groups where crossposting is not allowed
if (local and not gph and self.groups['count'] > 1 and
'local_bad_cp_groups' in self.etc_re):
b = self.etc_re['local_bad_cp_groups'].search(art[Newsgroups])
if b:
return self.reject(
art, post,
"Local Bad Crosspost Group (%s)" % b.group(0))
# Local Bad From
if local and not gph and 'local_bad_from' in self.etc_re:
reg = self.etc_re['local_bad_from']
bf_result = reg.search(art[From])
if bf_result:
return self.reject(
art, post,
"Local Bad From (%s)" % bf_result.group(0),
"Local Reject")
# Local Bad Subject
if local and not gph and 'local_bad_subject' in self.etc_re:
reg = self.etc_re['local_bad_subject']
bs_result = reg.search(art[Subject])
if bs_result:
return self.reject(
art, post,
"Local Bad Subject (%s)" % bs_result.group(0),
"Local Reject")
# Local Bad Groups
if local and not gph and 'local_bad_groups' in self.etc_re:
reg = self.etc_re['local_bad_groups']
bg_result = reg.search(art[Newsgroups])
if bg_result:
return self.reject(
art, post,
"Local Bad Group (%s)" % bg_result.group(0))
# Local Bad Body
if local and not gph and 'local_bad_body' in self.etc_re:
reg = self.etc_re['local_bad_body']
bb_result = reg.search(art[__BODY__])
if bb_result:
return self.reject(
art, post,
"Local Bad Body (%s)" % bb_result.group(0),
"Local Reject")
# Misplaced binary check
if self.groups['bin_allowed_bool']:
# All groups in the post match bin_allowed groups
isbin = False
else:
# Potentially expensive check if article contains binary
isbin = self.binary.isbin(art)
# Generic 'binary' means it looks binary-like but doesn't match any
# known encoding method.
if isbin == 'binary':
if config.getboolean('binary', 'reject_suspected'):
return self.reject(
art, post, "Binary (%s)" % isbin)
else:
self.logart("Binary Suspect", art, post, "bin_suspect",
trim=False)
elif isbin:
self.binary.increment(post['feed-host'])
return self.reject(
art, post, "Binary (%s)" % isbin)
# Misplaced HTML check
if (not self.groups['html_allowed_bool'] and
config.getboolean('filters', 'reject_html') and
'content_type' in post):
if 'text/html' in post['content_type']:
return self.reject(art, post, "HTML Misplaced")
if 'multipart' in post['content_type']:
if config.getboolean('filters', 'reject_multipart'):
return self.reject(art, post, "MIME Multpart")
else:
logging.debug('Multipart: %s' % mid)
# Symbol ratio test
symlen = len(self.regex_symbols.findall(art[__BODY__]))
if symlen > 100:
return self.reject(art, post, "Symbols (%s)" % symlen)
# Start of EMP checks
if (not self.groups['emp_exclude_bool'] and
not self.groups['test_bool']):
ngs = ','.join(self.groups['groups'])
# If a substring matches the Newsgroups header, use just that
# substring as EMP fodder where a Newsgroups name is normally used.
for ngsub in self.ngsubs:
if ngsub in ngs:
logging.debug("Newsgroup substring match: %s", ngsub)
ngs = ngsub
break
# Start of posting-host based checks.
# First try and seed some filter fodder.
if 'posting-account' in post:
# If a Posting-Account is known, it makes better filter fodder
# than the hostname/address which could be dynamic.
fodder = post['posting-account']
elif 'bad-posting-host' in post:
# If we can't trust the info in posting-host, use the
# injection-host. This is a worst-case scenario.
if ('injection-host' in post and
config.getboolean('emp', 'ph_coarse')):
fodder = post['injection-host']
else:
fodder = None
elif 'posting-host' in post:
fodder = post['posting-host']
else:
fodder = None
if fodder:
# Beginning of PHN filters
if 'moderated' in self.groups and self.groups['moderated']:
logging.debug("Bypassing PHN filter due to moderated "
"group in distribution")
elif local:
# Beginning of PHN_Local filter
do_lphn = True
if self.groups['phn_exclude_bool']:
do_lphn = False
if (not do_lphn and art['References'] is None and
'Subject' in art and
str(art['Subject']).startswith("Re:")):
logging.info("emp_lphn: Exclude overridden - "
"Subject Re but no Reference")
do_lphn = True
if (not do_lphn and
self.regex_crspace.search(art[__BODY__])):
logging.info("emp_lphn: Exclude overridden - "
"Carriage Return starts line")
do_lphn = True
if do_lphn and self.emp_lphn.add(fodder + ngs):
return self.reject(art, post, "EMP Local PHN Reject")
else:
# Beginning of standard PHN filter
if self.groups['phn_exclude_bool']:
logging.debug("emp_phn exclude for: %s",
art['Newsgroups'])
elif self.emp_phn.add(fodder + ngs):
return self.reject(art, post, "EMP PHN Reject")
# Beginning of PHL filter
if self.emp_phl.add(fodder + str(art[__LINES__])):
return self.reject(art, post, "EMP PHL Reject")
# Beginning of FSL filter
fsl = str(art[From]) + str(art[Subject]) + str(art[__LINES__])
if self.emp_fsl.add(fsl):
return self.reject(art, post, "EMP FSL Reject")
# Beginning of IHN filter
if ('injection-host' in post and
'ihn_hosts' in self.etc_re and
not self.groups['ihn_exclude_bool']):
ihn_result = self.etc_re['ihn_hosts']. \
search(post['injection-host'])
if ihn_result:
logging.debug("emp_ihn hit: %s", ihn_result.group(0))
if self.emp_ihn.add(post['injection-host'] + ngs):
return self.reject(art, post, "EMP IHN Reject")
# Beginning of EMP Body filter. Do this last, it's most
# expensive in terms of processing.
if art[__BODY__] is not None:
if self.emp_body.add(art[__BODY__]):
return self.reject(art, post, "EMP Body Reject")
if local:
# All tests passed. Log the locally posted message.
logging.info("post: mid=%s, from=%s, groups=%s",
art[Message_ID], art[From], art[Newsgroups])
self.logart('Local Post', art, post, 'local_post')
# The article passed all checks. Return an empty string.
return ""
def addressParse(self, addr):
name, email = parseaddr(addr)
return name.lower(), email.lower()
def xreject(self, reason, art, post):
for logrule in self.log_rules.keys():
if reason.startswith(logrule):
self.logart(reason, art, post, self.log_rules[logrule])
break
logging.info("reject: mid=%s, reason=%s" % (art[Message_ID], reason))
return reason
def reject(self, art, post, reason, short_reason=None):
rulehit = False
for logrule in self.log_rules.keys():
if reason.startswith(logrule):
self.logart(reason, art, post, self.log_rules[logrule])
rulehit = True
break
if rulehit:
logging.info("reject: mid=%s, reason=%s" % (art[Message_ID], reason))
else:
msg = "reject: No matched logging rule: mid={}, reason={}"
logging.warn(msg.format(art[Message_ID], reason))
if short_reason is None:
# Sometimes we don't want to provide the source with a detailed
# reason of why a message was rejected. They could then just
# tweak their payload to circumvent the cause.
return reason
return short_reason
def logart(self, reason, art, post, filename, trim=True):
f = open(os.path.join(config.get('paths', 'logart'), filename), 'a')
f.write('From foo@bar Thu Jan 1 00:00:01 1970\n')
f.write('Info: %s\n' % reason)
for hdr in art.keys():
if hdr == '__BODY__' or hdr == '__LINES__' or art[hdr] is None:
continue
f.write('%s: %s\n' % (hdr, art[hdr]))
for hdr in post.keys():
f.write('%s: %s\n' % (hdr, post[hdr]))
f.write('\n')
if (not trim or
art[__LINES__] <= config.get('logging', 'logart_maxlines')):
f.write(art[__BODY__])
else:
maxlines = config.get('logging', 'logart_maxlines')
loglines = 0
for line in str(art[__BODY__]).split('\n', 1000)[:-1]:
# Ignore quoted lines
if line.startswith(">"):
continue
f.write(line + "\n")
loglines += 1
if loglines >= maxlines:
f.write('[snip]')
break
f.write('\n\n')
f.close
def hourly_events(self, startup=False):
"""Carry out hourly events. Some of these events may be to check if
it's time to do other, less frequent events. Timed events are also
triggered on startup. The "startup" flag enables special handling of
this instance.
"""
if startup:
logging.info("Performing startup tasks")
else:
logging.info('Performing hourly tasks')
self.emp_body.statlog()
self.emp_fsl.statlog()
self.emp_phl.statlog()
self.emp_phn.statlog()
self.emp_lphn.statlog()
self.emp_ihn.statlog()
# Reload logging directives
self.log_rules = self.file2dict('log_rules')
logging.info('Reloaded %s logging directives', len(self.log_rules))
# Reload Injection-Host substrings
self.ihsubs = self.file2list('ih_substrings')
logging.info('Reloaded %s Injection-Host substrings', len(self.ihsubs))
self.ngsubs = self.file2list('ng_emp_subst')
logging.info('Reloaded %s Newsgroup substrings', len(self.ngsubs))
# Set up Regular Expressions
for fn in self.regex_files.keys():
new_regex = self.regex_file(fn)
if new_regex:
self.etc_re[fn] = new_regex
if not startup:
# Re-read the config file.
configfile = os.path.join(config.get('paths', 'etc'),
'pyclean.cfg')
logging.info("Reloading config file: %s" % configfile)
if os.path.isfile(configfile):
config.read(configfile)
else:
logging.info("%s: File not found. Using defaults settings."
% configfile)
# Reset the next timed trigger.
self.hourly_trigger = future(hours=1)
def midnight_events(self):
"""Events that need to occur at midnight each day.
"""
logging.info('Performing midnight tasks')
self.binary.report()
self.emp_body.reset()
self.emp_fsl.reset()
self.emp_phl.reset()
self.emp_phn.reset()
self.emp_lphn.reset()
self.emp_ihn.reset()
# Set the midnight trigger for next day.
self.midnight_trigger = next_midnight()
def regex_file(self, filename):
"""Read a given file and return a regular expression composed of
individual regex's on each line that have not yet expired.
"""
logging.debug('Testing %s regex condition', filename)
fqfn = os.path.join(config.get('paths', 'etc'), filename)
if not os.path.isfile(fqfn):
logging.info('%s: Regex file not found' % filename)
if filename in self.etc_re:
logging.info("%s: Regex file has been deleted", filename)
# The file has been deleted so delete the regex.
self.etc_re.pop(filename, None)
# Reset the last_modified date to zero
self.regex_files[filename] = 0
return False
current_mod_stamp = os.path.getmtime(fqfn)
recorded_mod_stamp = self.regex_files[filename]
if current_mod_stamp <= recorded_mod_stamp:
logging.info('%s: File not modified so not recompiling',
filename)
return False
# The file has been modified: Recompile the regex
logging.info('%s: Recompiling Regular Expression.', filename)
# Reset the file's modstamp
self.regex_files[filename] = current_mod_stamp
# Make a local datetime object for now, just to save setting now in
# the coming loop.
bad_items = []
n = now()
f = open(fqfn, 'r')
for line in f:
valid = self.regex_fmt.match(line)
if valid:
try:
# Is current time beyond that of the datestamp? If it is,
# the entry is considered expired and processing moves to
# the next entry.
if n > dateobj(valid.group(2)):
continue
except ValueError:
# If the timestamp is invalid, just ignore the entry
logging.warn("Invalid timestamp in %s. Line=%s",
filename, line)
continue
# If processing gets here, the entry is a valid regex.
bad_items.append(valid.group(1))
elif line.lstrip().startswith('#'):
# Don't do anything, it's a comment line
pass
elif len(line.strip()) == 0:
# Blank lines are fine
pass
else:
logging.warn("Invalid line in %s: %s", filename, line)
f.close()
num_bad_items = len(bad_items)
if num_bad_items == 0:
# No valid entires exist in the file.
logging.debug('%s: No valid entries found' % filename)
return False
regex = '|'.join(bad_items)
# This should never happen but best to check as || will match
# everything.
regex = regex.replace('||', '|')
logging.info("Compiled %s rules from %s", num_bad_items, filename)
return re.compile(regex)
def file2list(self, filename):
fqfn = os.path.join(config.get('paths', 'etc'), filename)
if not os.path.isfile(fqfn):
logging.info('%s: File not found' % filename)
return []
f = open(fqfn, 'r')
lines = f.readlines()
f.close()
valid = []
for line in lines:
# Strip comments (including inline)
content = line.split('#', 1)[0].strip()
# Ignore empty lines
if len(content) > 0:
valid.append(content)
return valid
def file2dict(self, filename, numeric=False):
"""Read a file and split each line at the first space encountered. The
first element is the key, the rest is the content. If numeric is True
then only integer values will be acccepted."""
d = {}
for line in self.file2list(filename):
valid = self.regex_fields.match(line)
if valid:
k = valid.group(1)
c = valid.group(2)
if numeric:
try:
c = int(c)
except ValueError:
c = 0
d[k] = c
return d
def closetasks(self):
"""Things to do on filter closing.
"""
logging.info("Running shutdown tasks")
# Write to file any entries in the stack
self.emp_body.dump()
self.emp_fsl.dump()
self.emp_phl.dump()
self.emp_phn.dump()
self.emp_lphn.dump()
self.emp_ihn.dump()
class Groups:
def __init__(self):
self.regex = Regex()
# List of tests (that will become zeroed dict items).
self.grps = [
'bin_allowed',
'emp_exclude',
'html_allowed',
'ihn_exclude',
'kooks',
'lowcp',
'moderated',
'phn_exclude',
'sex_groups',
'test'
]
def __getitem__(self, grptest):
return self.grp[grptest]
def __contains__(self, item):
if item in self.grp:
return True
return False
def analyze(self, newsgroups, followupto):
# Zero all dict items we'll use in this post
grp = dict((f, 0) for f in self.grps)
# This will become a list of newsgroups
nglist = []
for ng in str(newsgroups).lower().split(','):
# Strip whitespace from individual Newsgroups
ng = ng.strip()
# Populate a list of newsgroups after stripping spaces
nglist.append(ng)
if self.regex.test.search(ng):
grp['test'] += 1
if self.regex.bin_allowed.search(ng):
grp['bin_allowed'] += 1
if self.regex.emp_exclude.search(ng):
grp['emp_exclude'] += 1
if self.regex.ihn_exclude.search(ng):
grp['ihn_exclude'] += 1
if self.regex.html_allowed.search(ng):
grp['html_allowed'] += 1
if self.regex.kooks.search(ng):
grp['kooks'] += 1
if self.regex.lowcp.search(ng):
grp['lowcp'] += 1
if self.regex.phn_exclude.search(ng):
grp['phn_exclude'] += 1
if self.regex.sex_groups.search(ng):
grp['sex_groups'] += 1
if INN.newsgroup(ng) == 'm':
grp['moderated'] += 1
# Not all bools will be meaningful but it's easier to create them
# generically then specifically.
count = len(nglist)
for ngelement in grp.keys():
ngbool = '%s_bool' % ngelement
grp[ngbool] = grp[ngelement] == count
grp['groups'] = sorted(nglist)
grp['count'] = count
# Create a list of Followup-To groups and count them.
grp['futcount'] = 0
if followupto is not None:
futlist = str(followupto).lower().split(',')
grp['futcount'] = len(futlist)
self.grp = grp
class Regex:
def __init__(self):
# Test groups
test = ['\.test(ing)?(?:$|\.)',
'^es\.pruebas',
'^borland\.public\.test2',
'^cern\.testnews']
self.test = self.regex_compile(test)
# Binary groups
bin_allowed = ['^bin[a.]', '\.bin[aei.]', '\.bin$', '^fur\.artwork',
'^alt\.anonymous\.messages$', '^de\.alt\.dateien',
'^rec\.games\.bolo$', '^comp\.security\.pgp\.test$',
'^sfnet\.tiedostot', '^fido\.', '^unidata\.',
'^alt\.security\.keydist', '^mailing\.',
'^linux\.', '^lucky\.freebsd', '^gnus\.',
'\.lists\.freebsd\.']
self.bin_allowed = self.regex_compile(bin_allowed)
html_allowed = ['^pgsql\.', '^relcom\.', '^gmane', 'microsoft',
'^mailing\.', '^gnus\.']
self.html_allowed = self.regex_compile(html_allowed)
# Exclude from all EMP filters
emp_exclude = ['^alt\.anonymous\.messages', '^free\.', '^local\.',
'^relcom\.', '^mailing\.', '^fa\.', '\.cvs\.',
'^gnu\.', 'lists\.freebsd\.ports\.bugs']
self.emp_exclude = self.regex_compile(emp_exclude)
# Exclude groups from IHN filter
ihn_exclude = ['^alt\.anonymous',
'^alt\.privacy',
'^alt\.prophecies\.nostradamus']
self.ihn_exclude = self.regex_compile(ihn_exclude)
# Exclude groups from PHN filter
phn_exclude = ['^alt\.privacy\.']
self.phn_exclude = self.regex_compile(phn_exclude)
# Bad posting-hosts
bad_ph = ['newsguy\.com', 'tornevall\.net']
self.bad_ph = self.regex_compile(bad_ph)
# Sex groups
sex_groups = ['^alt\.sex']
self.sex_groups = self.regex_compile(sex_groups)
# Kook groups
kooks = ['^alt\.usenet\.kooks',
'^alt\.checkmate',
'^alt\.fan\.cyberchicken',
'^alt\.fan\.karl-malden\.nose']
self.kooks = self.regex_compile(kooks)
# Low cross post groups
lowcp = ['^alt\.free\.newsservers']
self.lowcp = self.regex_compile(lowcp)
def regex_compile(self, regexlist):
textual = '|'.join(regexlist).replace('||', '|')
return re.compile(textual)
class EMP:
def __init__(self,
threshold=3,
ceiling=100,
maxentries=5000,
timedtrim=3600,
dofuzzy=False,
name=False):
# Statistics relating to this EMP instance
if threshold > ceiling:
raise ValueError('Threshold cannot exceed ceiling')
# The hash table itself. Keyed by MD5 hash and containing a hit
# count.
self.table = {}
# Attempt to restore a previous EMP dump
self.restore(name)
self.fuzzy_15char = re.compile('\S{15,}')
self.fuzzy_notletters = re.compile('[^a-zA-Z]')
# Initialize some defaults
self.stats = {'name': name,
'nexttrim': future(secs=timedtrim),
'lasttrim': now(),
'processed': 0,
'accepted': 0,
'rejected': 0,
'threshold': threshold,
'ceiling': ceiling,
'maxentries': maxentries,
'timedtrim': timedtrim,
'dofuzzy': dofuzzy}
logmes = '%(name)s initialized. '
logmes += 'threshold=%(threshold)s, '
logmes += 'ceiling=%(ceiling)s, '
logmes += 'maxentries=%(maxentries)s, '
logmes += 'timedtrim=%(timedtrim)s'
logging.info(logmes % self.stats)
def add(self, content):
"""The content, in this context, is any string we want to hash and
check for EMP collisions. In various places we refer to it as
'hash fodder'.
"""
self.stats['processed'] += 1
if self.stats['dofuzzy']:
# Strip long strings
content = re.sub(self.fuzzy_15char, '', content)
# Remove everything except a-zA-Z
content = re.sub(self.fuzzy_notletters, '', content).lower()
# Bail out if the byte length of the content isn't sufficient for
# generating an effective, unique hash.
if len(content) < 1:
logging.debug("Null content in %s hashing fodder.",
self.stats['name'])
return False
# See if it's time to perform a trim.
n = now()
if n > self.stats['nexttrim']:
secs_since_lasttrim = (n - self.stats['lasttrim']).seconds
decrement = int(secs_since_lasttrim / self.stats['timedtrim'])
logmes = "%s: Trim decrement factor=%s"
logging.debug(logmes % (self.stats['name'], decrement))
if decrement > 0:
self._trim(decrement)
else:
logmes = "%s: Invalid attempt to trim by less than 1"
logging.error(logmes % (self.stats['name'], decrement))
elif len(self.table) > self.stats['maxentries']:
logmes = '%(name)s: Exceeded maxentries of %(maxentries)s'
logging.warn(logmes % self.stats)
self._trim(1)
# MD5 is weak in cryptographic terms, but do I care for the purpose
# of EMP collision checking? Obviously not or I'd use something else.
h = md5(content).digest()
if h in self.table:
# When the ceiling is reached, stop incrementing the count.
if self.table[h] < self.stats['ceiling']:
self.table[h] += 1
else:
logging.debug("%s hash ceiling hit. Not incrementing counter.",
self.stats['name'])
else:
# Initialize the md5 entry.
self.table[h] = 1
if self.table[h] > self.stats['threshold']:
# Houston, we have an EMP reject.
self.stats['rejected'] += 1
return True
self.stats['accepted'] += 1
return False
def _trim(self, decrement):
"""Decrement the counter against each hash. If the counter reaches
zero, delete the hash entry.
"""
# As the EMP table is about to be modified, oldsize records it prior
# to doing any changes. This is only used for reporting purposes.
self.stats['oldsize'] = len(self.table)
# Keep a running check of the largest count against a key.
self.stats['high'] = 0
for h in self.table.keys():
self.table[h] -= decrement
if self.table[h] > self.stats['high']:
self.stats['high'] = self.table[h]
if self.table[h] <= 0:
del self.table[h]
self.stats['size'] = len(self.table)<|fim▁hole|> logging.info("%(name)s: Trim complete. was=%(oldsize)s, now=%(size)s, "
"high=%(high)s, decrement=%(decrement)s",
self.stats)
self.stats['nexttrim'] = \
future(secs=self.stats['timedtrim'])
self.stats['lasttrim'] = now()
def statlog(self):
"""Log details of the EMP hash."""
self.stats['size'] = len(self.table)
logging.info("%(name)s: size=%(size)s, processed=%(processed)s, "
"accepted=%(accepted)s, rejected=%(rejected)s",
self.stats)
def dump(self):
"""Dump the EMP table to disk so we can reload it after a restart.
"""
dumpfile = os.path.join(config.get('paths', 'lib'),
self.stats['name'] + ".db")
dump = shelve.open(dumpfile, flag='n')
for k in self.table:
dump[k] = self.table[k]
dump.close()
def restore(self, name):
"""Restore an EMP dump from disk.
"""
dumpfile = os.path.join(config.get('paths', 'lib'), name + ".db")
if os.path.isfile(dumpfile):
logging.info("Attempting restore of %s dump", name)
dump = shelve.open(dumpfile, flag='r')
# We seem unable to use copy functions between shelves and dicts
# so we do it per record. Speed is not essential at these times.
for k in dump:
self.table[k] = dump[k]
dump.close()
logging.info("Restored %s records to %s", len(self.table), name)
else:
logging.debug("%s: Dump file does not exist. Doing a clean "
"initialzation.", dumpfile)
def reset(self):
"""Reset counters for this emp filter.
"""
self.stats['processed'] = 0
self.stats['accepted'] = 0
self.stats['rejected'] = 0
"""
Okay, that's the end of our class definition. What follows is the
stuff you need to do to get it all working inside innd.
"""
if 'python_filter' not in dir():
python_version = sys.version_info
config = init_config()
logfmt = config.get('logging', 'format')
datefmt = config.get('logging', 'datefmt')
loglevels = {'debug': logging.DEBUG, 'info': logging.INFO,
'warn': logging.WARN, 'error': logging.ERROR}
logging.getLogger().setLevel(logging.DEBUG)
logfile = logging.handlers.TimedRotatingFileHandler(
os.path.join(config.get('paths', 'log'), 'pyclean.log'),
when='midnight',
interval=1,
backupCount=config.getint('logging', 'retain'))
logfile.setLevel(loglevels[config.get('logging', 'level')])
logfile.setFormatter(logging.Formatter(logfmt, datefmt=datefmt))
logging.getLogger().addHandler(logfile)
python_filter = InndFilter()
try:
INN.set_filter_hook(python_filter)
INN.syslog('n', "pyclean successfully hooked into INN")
except Exception as errmsg:
INN.syslog('e', "Cannot obtain INN hook for pyclean: %s" % errmsg[0])
# This looks weird, but creating and interning these strings should let us get
# faster access to header keys (which innd also interns) by losing some strcmps
# under the covers.
Also_Control = intern("Also-Control")
Approved = intern("Approved")
Archive = intern("Archive")
Archived_At = intern("Archived-At")
Bytes = intern("Bytes")
Cancel_Key = intern("Cancel-Key")
Cancel_Lock = intern("Cancel-Lock")
Comments = intern("Comments")
Content_Base = intern("Content-Base")
Content_Disposition = intern("Content-Disposition")
Content_Transfer_Encoding = intern("Content-Transfer-Encoding")
Content_Type = intern("Content-Type")
Control = intern("Control")
Date = intern("Date")
Date_Received = intern("Date-Received")
Distribution = intern("Distribution")
Expires = intern("Expires")
Face = intern("Face")
Followup_To = intern("Followup-To")
From = intern("From")
In_Reply_To = intern("In-Reply-To")
Injection_Date = intern("Injection-Date")
Injection_Info = intern("Injection-Info")
Keywords = intern("Keywords")
Lines = intern("Lines")
List_ID = intern("List-ID")
Message_ID = intern("Message-ID")
MIME_Version = intern("MIME-Version")
Newsgroups = intern("Newsgroups")
NNTP_Posting_Date = intern("NNTP-Posting-Date")
NNTP_Posting_Host = intern("NNTP-Posting-Host")
NNTP_Posting_Path = intern("NNTP-Posting-Path")
Organization = intern("Organization")
Original_Sender = intern("Original-Sender")
Originator = intern("Originator")
Path = intern("Path")
Posted = intern("Posted")
Posting_Version = intern("Posting-Version")
Received = intern("Received")
References = intern("References")
Relay_Version = intern("Relay-Version")
Reply_To = intern("Reply-To")
Sender = intern("Sender")
Subject = intern("Subject")
Summary = intern("Summary")
Supersedes = intern("Supersedes")
User_Agent = intern("User-Agent")
X_Auth = intern("X-Auth")
X_Auth_Sender = intern("X-Auth-Sender")
X_Canceled_By = intern("X-Canceled-By")
X_Cancelled_By = intern("X-Cancelled-By")
X_Complaints_To = intern("X-Complaints-To")
X_Face = intern("X-Face")
X_HTTP_UserAgent = intern("X-HTTP-UserAgent")
X_HTTP_Via = intern("X-HTTP-Via")
X_Mailer = intern("X-Mailer")
X_Modbot = intern("X-Modbot")
X_Modtrace = intern("X-Modtrace")
X_Newsposter = intern("X-Newsposter")
X_Newsreader = intern("X-Newsreader")
X_No_Archive = intern("X-No-Archive")
X_Original_Message_ID = intern("X-Original-Message-ID")
X_Original_NNTP_Posting_Host = intern("X-Original-NNTP-Posting-Host")
X_Original_Trace = intern("X-Original-Trace")
X_Originating_IP = intern("X-Originating-IP")
X_PGP_Key = intern("X-PGP-Key")
X_PGP_Sig = intern("X-PGP-Sig")
X_Poster_Trace = intern("X-Poster-Trace")
X_Postfilter = intern("X-Postfilter")
X_Proxy_User = intern("X-Proxy-User")
X_Submissions_To = intern("X-Submissions-To")
X_Trace = intern("X-Trace")
X_Usenet_Provider = intern("X-Usenet-Provider")
X_User_ID = intern("X-User-ID")
Xref = intern("Xref")
__BODY__ = intern("__BODY__")
__LINES__ = intern("__LINES__")<|fim▁end|> | self.stats['decrement'] = decrement |
<|file_name|>constants.py<|end_file_name|><|fim▁begin|>PRIORITY_EMAIL_NOW = 0
PRIORITY_HIGH = 1
PRIORITY_NORMAL = 3
PRIORITY_LOW = 5
RESULT_SENT = 0
RESULT_SKIPPED = 1<|fim▁hole|>
PRIORITIES = {
'now': PRIORITY_EMAIL_NOW,
'high': PRIORITY_HIGH,
'normal': PRIORITY_NORMAL,
'low': PRIORITY_LOW,
}
PRIORITY_HEADER = 'X-Mail-Queue-Priority'
try:
from django.core.mail import get_connection
EMAIL_BACKEND_SUPPORT = True
except ImportError:
# Django version < 1.2
EMAIL_BACKEND_SUPPORT = False<|fim▁end|> | RESULT_FAILED = 2 |
<|file_name|>shapes.py<|end_file_name|><|fim▁begin|>EGA2RGB = [
(0x00, 0x00, 0x00),
(0x00, 0x00, 0xAA),
(0x00, 0xAA, 0x00),
(0x00, 0xAA, 0xAA),
(0xAA, 0x00, 0x00),
(0xAA, 0x00, 0xAA),
(0xAA, 0x55, 0x00),
(0xAA, 0xAA, 0xAA),<|fim▁hole|> (0x55, 0xFF, 0x55),
(0x55, 0xFF, 0xFF),
(0xFF, 0x55, 0x55),
(0xFF, 0x55, 0xFF),
(0xFF, 0xFF, 0x55),
(0xFF, 0xFF, 0xFF),
]
def load_shapes():
shapes = []
bytes = open("ULT/SHAPES.EGA").read()
for i in range(256):
shape = []
for j in range(16):
for k in range(8):
d = ord(bytes[k + 8 * j + 128 * i])
a, b = divmod(d, 16)
shape.append(EGA2RGB[a])
shape.append(EGA2RGB[b])
shapes.append(shape)
return shapes<|fim▁end|> | (0x55, 0x55, 0x55),
(0x55, 0x55, 0xFF), |
<|file_name|>dates.py<|end_file_name|><|fim▁begin|>from datetime import date, timedelta
from django.conf import settings
date_in_near_future = date.today() + timedelta(days=14)
FOUR_YEARS_IN_DAYS = 1462
election_date_before = lambda r: {
'DATE_TODAY': date.today()
}
election_date_on_election_day = lambda r: {
'DATE_TODAY': date_in_near_future
}<|fim▁hole|>}
processors = settings.TEMPLATE_CONTEXT_PROCESSORS
processors_before = processors + \
("candidates.tests.dates.election_date_before",)
processors_on_election_day = processors + \
("candidates.tests.dates.election_date_on_election_day",)
processors_after = processors + \
("candidates.tests.dates.election_date_after",)<|fim▁end|> | election_date_after = lambda r: {
'DATE_TODAY': date.today() + timedelta(days=28) |
<|file_name|>slow.rs<|end_file_name|><|fim▁begin|>//! Slow, fallback cases where we cannot unambiguously round a float.
//!
//! This occurs when we cannot determine the exact representation using
//! both the fast path (native) cases nor the Lemire/Bellerophon algorithms,
//! and therefore must fallback to a slow, arbitrary-precision representation.
#![doc(hidden)]
use crate::bigint::{Bigint, Limb, LIMB_BITS};
use crate::extended_float::{extended_to_float, ExtendedFloat};
use crate::num::Float;
use crate::number::Number;
use crate::rounding::{round, round_down, round_nearest_tie_even};
use core::cmp;
// ALGORITHM
// ---------
/// Parse the significant digits and biased, binary exponent of a float.
///
/// This is a fallback algorithm that uses a big-integer representation
/// of the float, and therefore is considerably slower than faster
/// approximations. However, it will always determine how to round
/// the significant digits to the nearest machine float, allowing
/// use to handle near half-way cases.
///
/// Near half-way cases are halfway between two consecutive machine floats.
/// For example, the float `16777217.0` has a bitwise representation of
/// `100000000000000000000000 1`. Rounding to a single-precision float,
/// the trailing `1` is truncated. Using round-nearest, tie-even, any
/// value above `16777217.0` must be rounded up to `16777218.0`, while
/// any value before or equal to `16777217.0` must be rounded down
/// to `16777216.0`. These near-halfway conversions therefore may require
/// a large number of digits to unambiguously determine how to round.
#[inline]
pub fn slow<'a, F, Iter1, Iter2>(
num: Number,
fp: ExtendedFloat,
integer: Iter1,
fraction: Iter2,
) -> ExtendedFloat
where
F: Float,
Iter1: Iterator<Item = &'a u8> + Clone,
Iter2: Iterator<Item = &'a u8> + Clone,
{
// Ensure our preconditions are valid:
// 1. The significant digits are not shifted into place.
debug_assert!(fp.mant & (1 << 63) != 0);
// This assumes the sign bit has already been parsed, and we're
// starting with the integer digits, and the float format has been
// correctly validated.
let sci_exp = scientific_exponent(&num);
// We have 2 major algorithms we use for this:
// 1. An algorithm with a finite number of digits and a positive exponent.
// 2. An algorithm with a finite number of digits and a negative exponent.
let (bigmant, digits) = parse_mantissa(integer, fraction, F::MAX_DIGITS);
let exponent = sci_exp + 1 - digits as i32;
if exponent >= 0 {
positive_digit_comp::<F>(bigmant, exponent)
} else {
negative_digit_comp::<F>(bigmant, fp, exponent)
}
}
/// Generate the significant digits with a positive exponent relative to mantissa.<|fim▁hole|> // Now, we can calculate the mantissa and the exponent from this.
// The binary exponent is the binary exponent for the mantissa
// shifted to the hidden bit.
bigmant.pow(10, exponent as u32).unwrap();
// Get the exact representation of the float from the big integer.
// hi64 checks **all** the remaining bits after the mantissa,
// so it will check if **any** truncated digits exist.
let (mant, is_truncated) = bigmant.hi64();
let exp = bigmant.bit_length() as i32 - 64 + F::EXPONENT_BIAS;
let mut fp = ExtendedFloat {
mant,
exp,
};
// Shift the digits into position and determine if we need to round-up.
round::<F, _>(&mut fp, |f, s| {
round_nearest_tie_even(f, s, |is_odd, is_halfway, is_above| {
is_above || (is_halfway && is_truncated) || (is_odd && is_halfway)
});
});
fp
}
/// Generate the significant digits with a negative exponent relative to mantissa.
///
/// This algorithm is quite simple: we have the significant digits `m1 * b^N1`,
/// where `m1` is the bigint mantissa, `b` is the radix, and `N1` is the radix
/// exponent. We then calculate the theoretical representation of `b+h`, which
/// is `m2 * 2^N2`, where `m2` is the bigint mantissa and `N2` is the binary
/// exponent. If we had infinite, efficient floating precision, this would be
/// equal to `m1 / b^-N1` and then compare it to `m2 * 2^N2`.
///
/// Since we cannot divide and keep precision, we must multiply the other:
/// if we want to do `m1 / b^-N1 >= m2 * 2^N2`, we can do
/// `m1 >= m2 * b^-N1 * 2^N2` Going to the decimal case, we can show and example
/// and simplify this further: `m1 >= m2 * 2^N2 * 10^-N1`. Since we can remove
/// a power-of-two, this is `m1 >= m2 * 2^(N2 - N1) * 5^-N1`. Therefore, if
/// `N2 - N1 > 0`, we need have `m1 >= m2 * 2^(N2 - N1) * 5^-N1`, otherwise,
/// we have `m1 * 2^(N1 - N2) >= m2 * 5^-N1`, where the resulting exponents
/// are all positive.
///
/// This allows us to compare both floats using integers efficiently
/// without any loss of precision.
#[allow(clippy::comparison_chain)]
pub fn negative_digit_comp<F: Float>(
bigmant: Bigint,
mut fp: ExtendedFloat,
exponent: i32,
) -> ExtendedFloat {
// Ensure our preconditions are valid:
// 1. The significant digits are not shifted into place.
debug_assert!(fp.mant & (1 << 63) != 0);
// Get the significant digits and radix exponent for the real digits.
let mut real_digits = bigmant;
let real_exp = exponent;
debug_assert!(real_exp < 0);
// Round down our extended-precision float and calculate `b`.
let mut b = fp;
round::<F, _>(&mut b, round_down);
let b = extended_to_float::<F>(b);
// Get the significant digits and the binary exponent for `b+h`.
let theor = bh(b);
let mut theor_digits = Bigint::from_u64(theor.mant);
let theor_exp = theor.exp;
// We need to scale the real digits and `b+h` digits to be the same
// order. We currently have `real_exp`, in `radix`, that needs to be
// shifted to `theor_digits` (since it is negative), and `theor_exp`
// to either `theor_digits` or `real_digits` as a power of 2 (since it
// may be positive or negative). Try to remove as many powers of 2
// as possible. All values are relative to `theor_digits`, that is,
// reflect the power you need to multiply `theor_digits` by.
//
// Both are on opposite-sides of equation, can factor out a
// power of two.
//
// Example: 10^-10, 2^-10 -> ( 0, 10, 0)
// Example: 10^-10, 2^-15 -> (-5, 10, 0)
// Example: 10^-10, 2^-5 -> ( 5, 10, 0)
// Example: 10^-10, 2^5 -> (15, 10, 0)
let binary_exp = theor_exp - real_exp;
let halfradix_exp = -real_exp;
if halfradix_exp != 0 {
theor_digits.pow(5, halfradix_exp as u32).unwrap();
}
if binary_exp > 0 {
theor_digits.pow(2, binary_exp as u32).unwrap();
} else if binary_exp < 0 {
real_digits.pow(2, (-binary_exp) as u32).unwrap();
}
// Compare our theoretical and real digits and round nearest, tie even.
let ord = real_digits.data.cmp(&theor_digits.data);
round::<F, _>(&mut fp, |f, s| {
round_nearest_tie_even(f, s, |is_odd, _, _| {
// Can ignore `is_halfway` and `is_above`, since those were
// calculates using less significant digits.
match ord {
cmp::Ordering::Greater => true,
cmp::Ordering::Less => false,
cmp::Ordering::Equal if is_odd => true,
cmp::Ordering::Equal => false,
}
});
});
fp
}
/// Add a digit to the temporary value.
macro_rules! add_digit {
($c:ident, $value:ident, $counter:ident, $count:ident) => {{
let digit = $c - b'0';
$value *= 10 as Limb;
$value += digit as Limb;
// Increment our counters.
$counter += 1;
$count += 1;
}};
}
/// Add a temporary value to our mantissa.
macro_rules! add_temporary {
// Multiply by the small power and add the native value.
(@mul $result:ident, $power:expr, $value:expr) => {
$result.data.mul_small($power).unwrap();
$result.data.add_small($value).unwrap();
};
// # Safety
//
// Safe is `counter <= step`, or smaller than the table size.
($format:ident, $result:ident, $counter:ident, $value:ident) => {
if $counter != 0 {
// SAFETY: safe, since `counter <= step`, or smaller than the table size.
let small_power = unsafe { f64::int_pow_fast_path($counter, 10) };
add_temporary!(@mul $result, small_power as Limb, $value);
$counter = 0;
$value = 0;
}
};
// Add a temporary where we won't read the counter results internally.
//
// # Safety
//
// Safe is `counter <= step`, or smaller than the table size.
(@end $format:ident, $result:ident, $counter:ident, $value:ident) => {
if $counter != 0 {
// SAFETY: safe, since `counter <= step`, or smaller than the table size.
let small_power = unsafe { f64::int_pow_fast_path($counter, 10) };
add_temporary!(@mul $result, small_power as Limb, $value);
}
};
// Add the maximum native value.
(@max $format:ident, $result:ident, $counter:ident, $value:ident, $max:ident) => {
add_temporary!(@mul $result, $max, $value);
$counter = 0;
$value = 0;
};
}
/// Round-up a truncated value.
macro_rules! round_up_truncated {
($format:ident, $result:ident, $count:ident) => {{
// Need to round-up.
// Can't just add 1, since this can accidentally round-up
// values to a halfway point, which can cause invalid results.
add_temporary!(@mul $result, 10, 1);
$count += 1;
}};
}
/// Check and round-up the fraction if any non-zero digits exist.
macro_rules! round_up_nonzero {
($format:ident, $iter:expr, $result:ident, $count:ident) => {{
for &digit in $iter {
if digit != b'0' {
round_up_truncated!($format, $result, $count);
return ($result, $count);
}
}
}};
}
/// Parse the full mantissa into a big integer.
///
/// Returns the parsed mantissa and the number of digits in the mantissa.
/// The max digits is the maximum number of digits plus one.
pub fn parse_mantissa<'a, Iter1, Iter2>(
mut integer: Iter1,
mut fraction: Iter2,
max_digits: usize,
) -> (Bigint, usize)
where
Iter1: Iterator<Item = &'a u8> + Clone,
Iter2: Iterator<Item = &'a u8> + Clone,
{
// Iteratively process all the data in the mantissa.
// We do this via small, intermediate values which once we reach
// the maximum number of digits we can process without overflow,
// we add the temporary to the big integer.
let mut counter: usize = 0;
let mut count: usize = 0;
let mut value: Limb = 0;
let mut result = Bigint::new();
// Now use our pre-computed small powers iteratively.
// This is calculated as `⌊log(2^BITS - 1, 10)⌋`.
let step: usize = if LIMB_BITS == 32 {
9
} else {
19
};
let max_native = (10 as Limb).pow(step as u32);
// Process the integer digits.
'integer: loop {
// Parse a digit at a time, until we reach step.
while counter < step && count < max_digits {
if let Some(&c) = integer.next() {
add_digit!(c, value, counter, count);
} else {
break 'integer;
}
}
// Check if we've exhausted our max digits.
if count == max_digits {
// Need to check if we're truncated, and round-up accordingly.
// SAFETY: safe since `counter <= step`.
add_temporary!(@end format, result, counter, value);
round_up_nonzero!(format, integer, result, count);
round_up_nonzero!(format, fraction, result, count);
return (result, count);
} else {
// Add our temporary from the loop.
// SAFETY: safe since `counter <= step`.
add_temporary!(@max format, result, counter, value, max_native);
}
}
// Skip leading fraction zeros.
// Required to get an accurate count.
if count == 0 {
for &c in &mut fraction {
if c != b'0' {
add_digit!(c, value, counter, count);
break;
}
}
}
// Process the fraction digits.
'fraction: loop {
// Parse a digit at a time, until we reach step.
while counter < step && count < max_digits {
if let Some(&c) = fraction.next() {
add_digit!(c, value, counter, count);
} else {
break 'fraction;
}
}
// Check if we've exhausted our max digits.
if count == max_digits {
// SAFETY: safe since `counter <= step`.
add_temporary!(@end format, result, counter, value);
round_up_nonzero!(format, fraction, result, count);
return (result, count);
} else {
// Add our temporary from the loop.
// SAFETY: safe since `counter <= step`.
add_temporary!(@max format, result, counter, value, max_native);
}
}
// We will always have a remainder, as long as we entered the loop
// once, or counter % step is 0.
// SAFETY: safe since `counter <= step`.
add_temporary!(@end format, result, counter, value);
(result, count)
}
// SCALING
// -------
/// Calculate the scientific exponent from a `Number` value.
/// Any other attempts would require slowdowns for faster algorithms.
#[inline]
pub fn scientific_exponent(num: &Number) -> i32 {
// Use power reduction to make this faster.
let mut mantissa = num.mantissa;
let mut exponent = num.exponent;
while mantissa >= 10000 {
mantissa /= 10000;
exponent += 4;
}
while mantissa >= 100 {
mantissa /= 100;
exponent += 2;
}
while mantissa >= 10 {
mantissa /= 10;
exponent += 1;
}
exponent as i32
}
/// Calculate `b` from a a representation of `b` as a float.
#[inline]
pub fn b<F: Float>(float: F) -> ExtendedFloat {
ExtendedFloat {
mant: float.mantissa(),
exp: float.exponent(),
}
}
/// Calculate `b+h` from a a representation of `b` as a float.
#[inline]
pub fn bh<F: Float>(float: F) -> ExtendedFloat {
let fp = b(float);
ExtendedFloat {
mant: (fp.mant << 1) + 1,
exp: fp.exp - 1,
}
}<|fim▁end|> | pub fn positive_digit_comp<F: Float>(mut bigmant: Bigint, exponent: i32) -> ExtendedFloat {
// Simple, we just need to multiply by the power of the radix. |
<|file_name|>BaseApiController.java<|end_file_name|><|fim▁begin|>package bartburg.nl.backbaseweather.provision.remote.controller;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.lang.annotation.Annotation;
import java.net.HttpURLConnection;<|fim▁hole|>
import bartburg.nl.backbaseweather.AppConstants;
import bartburg.nl.backbaseweather.provision.remote.annotation.ApiController;
import bartburg.nl.backbaseweather.provision.remote.util.QueryStringUtil;
import static bartburg.nl.backbaseweather.AppConstants.OPEN_WEATHER_MAP_BASE_URL;
import static bartburg.nl.backbaseweather.AppConstants.OPEN_WEATHER_PROTOCOL;
/**
* Created by Bart on 6/3/2017.
*/
public abstract class BaseApiController {
/**
* Do the actual work of requesting data from the server. Note, should not run on main thread.
*
* @param parameters Parameters that will be added to the query string.
* @param onErrorListener Listener that will get called when status code is not 200
* @return The result string or *null* when failed.
*/
@Nullable
public String get(HashMap<String, String> parameters, @Nullable OnErrorListener onErrorListener) {
return get(parameters, onErrorListener, null);
}
/**
* Do the actual work of requesting data from the server. Note, should not run on main thread.
*
* @param parameters Parameters that will be added to the query string.
* @param onErrorListener Listener that will get called when status code is not 200
* @param customRelativePath Use this if you want to provide a custom relative path (not the one from the annotation).
* @return The result string or *null* when failed.
*/
@Nullable
public String get(HashMap<String, String> parameters, @Nullable OnErrorListener onErrorListener, @Nullable String customRelativePath) {
try {
parameters.put("appid", AppConstants.OPEN_WEATHER_MAP_KEY);
URL url = new URL(OPEN_WEATHER_PROTOCOL + OPEN_WEATHER_MAP_BASE_URL + getRelativePath(customRelativePath) + QueryStringUtil.mapToQueryString(parameters));
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setRequestMethod("GET");
urlConnection.connect();
int responseCode = urlConnection.getResponseCode();
String responseMessage = urlConnection.getResponseMessage();
if (responseCode != 200 && onErrorListener != null) {
onErrorListener.onError(responseCode, responseMessage);
} else {
return readInputStream(urlConnection);
}
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
@NonNull
private String readInputStream(HttpURLConnection urlConnection) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(urlConnection.getInputStream()));
StringBuilder sb = new StringBuilder();
String line;
while ((line = br.readLine()) != null) {
sb.append(line).append("\n");
}
br.close();
return sb.toString();
}
public interface OnErrorListener {
void onError(int responseCode, String responseMessage);
}
private String getRelativePath(String customRelativePath) {
if (customRelativePath != null) {
return customRelativePath;
}
Class<? extends BaseApiController> aClass = getClass();
if (aClass.isAnnotationPresent(ApiController.class)) {
Annotation annotation = aClass.getAnnotation(ApiController.class);
ApiController apiController = (ApiController) annotation;
return apiController.relativePath();
}
return "";
}
}<|fim▁end|> | import java.net.URL;
import java.util.HashMap; |
<|file_name|>selectors.js<|end_file_name|><|fim▁begin|>export const getIsAdmin = (state) => state.session.user?.administrator;
export const getUserId = (state) => state.session.user?.id;
export const getDevices = (state) => Object.values(state.devices.items);
<|fim▁hole|><|fim▁end|> | export const getPosition = (id) => (state) => state.positions.items[id]; |
<|file_name|>augmented-assignments-feature-gate.rs<|end_file_name|><|fim▁begin|>// run-pass
use std::ops::AddAssign;
struct Int(i32);
impl AddAssign<i32> for Int {
fn add_assign(&mut self, _: i32) {
}
}
fn main() {<|fim▁hole|><|fim▁end|> | let mut x = Int(0);
x += 1;
} |
<|file_name|>dom_style_sheet.rs<|end_file_name|><|fim▁begin|>// This file was generated by gir (https://github.com/gtk-rs/gir)
// from gir-files (https://github.com/gtk-rs/gir-files.git)
// DO NOT EDIT
use crate::DOMMediaList;
use crate::DOMNode;
use crate::DOMObject;
use glib::object::Cast;
use glib::object::IsA;
use glib::signal::connect_raw;
use glib::signal::SignalHandlerId;
use glib::translate::*;
use glib::StaticType;
use std::boxed::Box as Box_;
use std::fmt;
use std::mem::transmute;
glib::wrapper! {
pub struct DOMStyleSheet(Object<ffi::WebKitDOMStyleSheet, ffi::WebKitDOMStyleSheetClass>) @extends DOMObject;
match fn {
type_ => || ffi::webkit_dom_style_sheet_get_type(),
}
}
pub const NONE_DOM_STYLE_SHEET: Option<&DOMStyleSheet> = None;
pub trait DOMStyleSheetExt: 'static {
#[cfg_attr(feature = "v2_22", deprecated)]
#[doc(alias = "webkit_dom_style_sheet_get_content_type")]
fn content_type(&self) -> Option<glib::GString>;
#[cfg_attr(feature = "v2_22", deprecated)]
#[doc(alias = "webkit_dom_style_sheet_get_disabled")]
fn is_disabled(&self) -> bool;
#[cfg_attr(feature = "v2_22", deprecated)]
#[doc(alias = "webkit_dom_style_sheet_get_href")]
fn href(&self) -> Option<glib::GString>;
#[cfg_attr(feature = "v2_22", deprecated)]
#[doc(alias = "webkit_dom_style_sheet_get_media")]
fn media(&self) -> Option<DOMMediaList>;
#[cfg_attr(feature = "v2_22", deprecated)]
#[doc(alias = "webkit_dom_style_sheet_get_owner_node")]
fn owner_node(&self) -> Option<DOMNode>;
#[cfg_attr(feature = "v2_22", deprecated)]
#[doc(alias = "webkit_dom_style_sheet_get_parent_style_sheet")]
fn parent_style_sheet(&self) -> Option<DOMStyleSheet>;
#[cfg_attr(feature = "v2_22", deprecated)]
#[doc(alias = "webkit_dom_style_sheet_get_title")]
fn title(&self) -> Option<glib::GString>;
#[cfg_attr(feature = "v2_22", deprecated)]
#[doc(alias = "webkit_dom_style_sheet_set_disabled")]
fn set_disabled(&self, value: bool);
#[doc(alias = "get_property_type")]
fn type_(&self) -> Option<glib::GString>;
fn connect_property_disabled_notify<F: Fn(&Self) + 'static>(&self, f: F) -> SignalHandlerId;
fn connect_property_href_notify<F: Fn(&Self) + 'static>(&self, f: F) -> SignalHandlerId;
fn connect_property_media_notify<F: Fn(&Self) + 'static>(&self, f: F) -> SignalHandlerId;
fn connect_property_owner_node_notify<F: Fn(&Self) + 'static>(&self, f: F) -> SignalHandlerId;
fn connect_property_parent_style_sheet_notify<F: Fn(&Self) + 'static>(
&self,
f: F,
) -> SignalHandlerId;
fn connect_property_title_notify<F: Fn(&Self) + 'static>(&self, f: F) -> SignalHandlerId;
fn connect_property_type_notify<F: Fn(&Self) + 'static>(&self, f: F) -> SignalHandlerId;
}
impl<O: IsA<DOMStyleSheet>> DOMStyleSheetExt for O {
fn content_type(&self) -> Option<glib::GString> {
unsafe {
from_glib_full(ffi::webkit_dom_style_sheet_get_content_type(
self.as_ref().to_glib_none().0,
))
}
}
fn is_disabled(&self) -> bool {
unsafe {
from_glib(ffi::webkit_dom_style_sheet_get_disabled(
self.as_ref().to_glib_none().0,
))
}
}
fn href(&self) -> Option<glib::GString> {
unsafe {
from_glib_full(ffi::webkit_dom_style_sheet_get_href(
self.as_ref().to_glib_none().0,
))
}
}
fn media(&self) -> Option<DOMMediaList> {
unsafe {
from_glib_full(ffi::webkit_dom_style_sheet_get_media(
self.as_ref().to_glib_none().0,
))
}
}
fn owner_node(&self) -> Option<DOMNode> {
unsafe {
from_glib_none(ffi::webkit_dom_style_sheet_get_owner_node(
self.as_ref().to_glib_none().0,
))
}
}
fn parent_style_sheet(&self) -> Option<DOMStyleSheet> {
unsafe {
from_glib_full(ffi::webkit_dom_style_sheet_get_parent_style_sheet(
self.as_ref().to_glib_none().0,
))<|fim▁hole|> fn title(&self) -> Option<glib::GString> {
unsafe {
from_glib_full(ffi::webkit_dom_style_sheet_get_title(
self.as_ref().to_glib_none().0,
))
}
}
fn set_disabled(&self, value: bool) {
unsafe {
ffi::webkit_dom_style_sheet_set_disabled(
self.as_ref().to_glib_none().0,
value.to_glib(),
);
}
}
fn type_(&self) -> Option<glib::GString> {
unsafe {
let mut value = glib::Value::from_type(<glib::GString as StaticType>::static_type());
glib::gobject_ffi::g_object_get_property(
self.to_glib_none().0 as *mut glib::gobject_ffi::GObject,
b"type\0".as_ptr() as *const _,
value.to_glib_none_mut().0,
);
value
.get()
.expect("Return Value for property `type` getter")
}
}
fn connect_property_disabled_notify<F: Fn(&Self) + 'static>(&self, f: F) -> SignalHandlerId {
unsafe extern "C" fn notify_disabled_trampoline<P, F: Fn(&P) + 'static>(
this: *mut ffi::WebKitDOMStyleSheet,
_param_spec: glib::ffi::gpointer,
f: glib::ffi::gpointer,
) where
P: IsA<DOMStyleSheet>,
{
let f: &F = &*(f as *const F);
f(&DOMStyleSheet::from_glib_borrow(this).unsafe_cast_ref())
}
unsafe {
let f: Box_<F> = Box_::new(f);
connect_raw(
self.as_ptr() as *mut _,
b"notify::disabled\0".as_ptr() as *const _,
Some(transmute::<_, unsafe extern "C" fn()>(
notify_disabled_trampoline::<Self, F> as *const (),
)),
Box_::into_raw(f),
)
}
}
fn connect_property_href_notify<F: Fn(&Self) + 'static>(&self, f: F) -> SignalHandlerId {
unsafe extern "C" fn notify_href_trampoline<P, F: Fn(&P) + 'static>(
this: *mut ffi::WebKitDOMStyleSheet,
_param_spec: glib::ffi::gpointer,
f: glib::ffi::gpointer,
) where
P: IsA<DOMStyleSheet>,
{
let f: &F = &*(f as *const F);
f(&DOMStyleSheet::from_glib_borrow(this).unsafe_cast_ref())
}
unsafe {
let f: Box_<F> = Box_::new(f);
connect_raw(
self.as_ptr() as *mut _,
b"notify::href\0".as_ptr() as *const _,
Some(transmute::<_, unsafe extern "C" fn()>(
notify_href_trampoline::<Self, F> as *const (),
)),
Box_::into_raw(f),
)
}
}
fn connect_property_media_notify<F: Fn(&Self) + 'static>(&self, f: F) -> SignalHandlerId {
unsafe extern "C" fn notify_media_trampoline<P, F: Fn(&P) + 'static>(
this: *mut ffi::WebKitDOMStyleSheet,
_param_spec: glib::ffi::gpointer,
f: glib::ffi::gpointer,
) where
P: IsA<DOMStyleSheet>,
{
let f: &F = &*(f as *const F);
f(&DOMStyleSheet::from_glib_borrow(this).unsafe_cast_ref())
}
unsafe {
let f: Box_<F> = Box_::new(f);
connect_raw(
self.as_ptr() as *mut _,
b"notify::media\0".as_ptr() as *const _,
Some(transmute::<_, unsafe extern "C" fn()>(
notify_media_trampoline::<Self, F> as *const (),
)),
Box_::into_raw(f),
)
}
}
fn connect_property_owner_node_notify<F: Fn(&Self) + 'static>(&self, f: F) -> SignalHandlerId {
unsafe extern "C" fn notify_owner_node_trampoline<P, F: Fn(&P) + 'static>(
this: *mut ffi::WebKitDOMStyleSheet,
_param_spec: glib::ffi::gpointer,
f: glib::ffi::gpointer,
) where
P: IsA<DOMStyleSheet>,
{
let f: &F = &*(f as *const F);
f(&DOMStyleSheet::from_glib_borrow(this).unsafe_cast_ref())
}
unsafe {
let f: Box_<F> = Box_::new(f);
connect_raw(
self.as_ptr() as *mut _,
b"notify::owner-node\0".as_ptr() as *const _,
Some(transmute::<_, unsafe extern "C" fn()>(
notify_owner_node_trampoline::<Self, F> as *const (),
)),
Box_::into_raw(f),
)
}
}
fn connect_property_parent_style_sheet_notify<F: Fn(&Self) + 'static>(
&self,
f: F,
) -> SignalHandlerId {
unsafe extern "C" fn notify_parent_style_sheet_trampoline<P, F: Fn(&P) + 'static>(
this: *mut ffi::WebKitDOMStyleSheet,
_param_spec: glib::ffi::gpointer,
f: glib::ffi::gpointer,
) where
P: IsA<DOMStyleSheet>,
{
let f: &F = &*(f as *const F);
f(&DOMStyleSheet::from_glib_borrow(this).unsafe_cast_ref())
}
unsafe {
let f: Box_<F> = Box_::new(f);
connect_raw(
self.as_ptr() as *mut _,
b"notify::parent-style-sheet\0".as_ptr() as *const _,
Some(transmute::<_, unsafe extern "C" fn()>(
notify_parent_style_sheet_trampoline::<Self, F> as *const (),
)),
Box_::into_raw(f),
)
}
}
fn connect_property_title_notify<F: Fn(&Self) + 'static>(&self, f: F) -> SignalHandlerId {
unsafe extern "C" fn notify_title_trampoline<P, F: Fn(&P) + 'static>(
this: *mut ffi::WebKitDOMStyleSheet,
_param_spec: glib::ffi::gpointer,
f: glib::ffi::gpointer,
) where
P: IsA<DOMStyleSheet>,
{
let f: &F = &*(f as *const F);
f(&DOMStyleSheet::from_glib_borrow(this).unsafe_cast_ref())
}
unsafe {
let f: Box_<F> = Box_::new(f);
connect_raw(
self.as_ptr() as *mut _,
b"notify::title\0".as_ptr() as *const _,
Some(transmute::<_, unsafe extern "C" fn()>(
notify_title_trampoline::<Self, F> as *const (),
)),
Box_::into_raw(f),
)
}
}
fn connect_property_type_notify<F: Fn(&Self) + 'static>(&self, f: F) -> SignalHandlerId {
unsafe extern "C" fn notify_type_trampoline<P, F: Fn(&P) + 'static>(
this: *mut ffi::WebKitDOMStyleSheet,
_param_spec: glib::ffi::gpointer,
f: glib::ffi::gpointer,
) where
P: IsA<DOMStyleSheet>,
{
let f: &F = &*(f as *const F);
f(&DOMStyleSheet::from_glib_borrow(this).unsafe_cast_ref())
}
unsafe {
let f: Box_<F> = Box_::new(f);
connect_raw(
self.as_ptr() as *mut _,
b"notify::type\0".as_ptr() as *const _,
Some(transmute::<_, unsafe extern "C" fn()>(
notify_type_trampoline::<Self, F> as *const (),
)),
Box_::into_raw(f),
)
}
}
}
impl fmt::Display for DOMStyleSheet {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
f.write_str("DOMStyleSheet")
}
}<|fim▁end|> | }
}
|
<|file_name|>nview.hpp<|end_file_name|><|fim▁begin|>/*=============================================================================
Copyright (c) 2009 Hartmut Kaiser
Distributed under the Boost Software License, Version 1.0. (See accompanying
file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
==============================================================================*/
#if !defined(BOOST_FUSION_NVIEW_SEP_23_2009_0948PM)
#define BOOST_FUSION_NVIEW_SEP_23_2009_0948PM
#include <boost/mpl/size.hpp>
#include <boost/mpl/if.hpp>
#include <boost/mpl/vector_c.hpp>
#include <boost/utility/result_of.hpp>
#include <boost/type_traits/remove_reference.hpp>
#include <boost/type_traits/add_reference.hpp>
#include <boost/type_traits/add_const.hpp>
#include <boost/fusion/support/is_view.hpp>
#include <boost/fusion/support/category_of.hpp>
#include <boost/fusion/support/sequence_base.hpp>
#include <boost/fusion/container/vector.hpp>
#include <boost/fusion/view/transform_view.hpp>
#include <boost/config.hpp>
namespace boost { namespace fusion
{
namespace detail
{
struct addref
{
template<typename Sig>
struct result;
template<typename U>
struct result<addref(U)> : add_reference<U> {};
#ifdef BOOST_NO_CXX11_RVALUE_REFERENCES
template <typename T>
typename add_reference<T>::type
operator()(T& x) const
{
return x;
}
#else
template <typename T>
typename result<addref(T)>::type
operator()(T&& x) const
{
return x;
}
#endif
};
struct addconstref
{
template<typename Sig>
struct result;
template<typename U>
struct result<addconstref(U)>
: add_reference<typename add_const<U>::type>
{};
template <typename T>
typename add_reference<typename add_const<T>::type>::type
operator()(T& x) const
{
return x;
}
template <typename T>
typename add_reference<typename add_const<T>::type>::type
operator()(T const& x) const
{
return x;
}
};
}
struct nview_tag;
struct random_access_traversal_tag;
struct fusion_sequence_tag;
template<typename Sequence, typename Indicies>
struct nview
: sequence_base<nview<Sequence, Indicies> >
{
typedef nview_tag fusion_tag;
typedef fusion_sequence_tag tag; // this gets picked up by MPL
typedef random_access_traversal_tag category;
typedef mpl::true_ is_view;
typedef Indicies index_type;
typedef typename mpl::size<Indicies>::type size;
typedef typename mpl::if_<
is_const<Sequence>, detail::addconstref, detail::addref
>::type transform_type;
typedef transform_view<Sequence, transform_type> transform_view_type;
typedef typename result_of::as_vector<transform_view_type>::type
sequence_type;
explicit nview(Sequence& val)
: seq(sequence_type(transform_view_type(val, transform_type())))
{}
sequence_type seq;
};
}}
<|fim▁hole|>
#endif<|fim▁end|> | // define the nview() generator functions
#include <boost/fusion/view/nview/detail/nview_impl.hpp>
|
<|file_name|>generate-deriving-span-tests.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python
#
# Copyright 2013 The Rust Project Developers. See the COPYRIGHT
# file at the top-level directory of this distribution and at
# http://rust-lang.org/COPYRIGHT.
#
# Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
# http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
# <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
# option. This file may not be copied, modified, or distributed
# except according to those terms.
"""
This script creates a pile of compile-fail tests check that all the
derives have spans that point to the fields, rather than the
#[derive(...)] line.
sample usage: src/etc/generate-deriving-span-tests.py
"""
import os, datetime, stat, re
TEST_DIR = os.path.abspath(
os.path.join(os.path.dirname(__file__), '../test/ui/derives/'))
YEAR = datetime.datetime.now().year
TEMPLATE = """// Copyright {year} 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.
// This file was auto-generated using 'src/etc/generate-deriving-span-tests.py'
{error_deriving}
struct Error;
{code}
fn main() {{}}
"""
ENUM_STRING = """
#[derive({traits})]
enum Enum {{
A(
Error {errors}
)
}}
"""
ENUM_STRUCT_VARIANT_STRING = """
#[derive({traits})]
enum Enum {{
A {{
x: Error {errors}
}}
}}
"""
STRUCT_STRING = """
#[derive({traits})]
struct Struct {{
x: Error {errors}
}}
"""
STRUCT_TUPLE_STRING = """
#[derive({traits})]
struct Struct(
Error {errors}
);
"""
ENUM_TUPLE, ENUM_STRUCT, STRUCT_FIELDS, STRUCT_TUPLE = range(4)
def create_test_case(type, trait, super_traits, error_count):
string = [ENUM_STRING, ENUM_STRUCT_VARIANT_STRING, STRUCT_STRING, STRUCT_TUPLE_STRING][type]
all_traits = ','.join([trait] + super_traits)
super_traits = ','.join(super_traits)
error_deriving = '#[derive(%s)]' % super_traits if super_traits else ''
errors = '\n'.join('//~%s ERROR' % ('^' * n) for n in range(error_count))
code = string.format(traits = all_traits, errors = errors)
return TEMPLATE.format(year = YEAR, error_deriving=error_deriving, code = code)
def write_file(name, string):
test_file = os.path.join(TEST_DIR, 'derives-span-%s.rs' % name)
with open(test_file) as f:
old_str = f.read()
old_str_ignoring_date = re.sub(r'^// Copyright \d+',
'// Copyright {year}'.format(year = YEAR), old_str)<|fim▁hole|> return 0
# set write permission if file exists, so it can be changed
if os.path.exists(test_file):
os.chmod(test_file, stat.S_IWUSR)
with open(test_file, 'w') as f:
f.write(string)
# mark file read-only
os.chmod(test_file, stat.S_IRUSR|stat.S_IRGRP|stat.S_IROTH)
return 1
ENUM = 1
STRUCT = 2
ALL = STRUCT | ENUM
traits = {
'Default': (STRUCT, [], 1),
'FromPrimitive': (0, [], 0), # only works for C-like enums
'Decodable': (0, [], 0), # FIXME: quoting gives horrible spans
'Encodable': (0, [], 0), # FIXME: quoting gives horrible spans
}
for (trait, supers, errs) in [('Clone', [], 1),
('PartialEq', [], 2),
('PartialOrd', ['PartialEq'], 1),
('Eq', ['PartialEq'], 1),
('Ord', ['Eq', 'PartialOrd', 'PartialEq'], 1),
('Debug', [], 1),
('Hash', [], 1)]:
traits[trait] = (ALL, supers, errs)
files = 0
for (trait, (types, super_traits, error_count)) in traits.items():
mk = lambda ty: create_test_case(ty, trait, super_traits, error_count)
if types & ENUM:
files += write_file(trait + '-enum', mk(ENUM_TUPLE))
files += write_file(trait + '-enum-struct-variant', mk(ENUM_STRUCT))
if types & STRUCT:
files += write_file(trait + '-struct', mk(STRUCT_FIELDS))
files += write_file(trait + '-tuple-struct', mk(STRUCT_TUPLE))
print('Generated {files} deriving span test{}.'.format('s' if files != 1 else '', files = files))<|fim▁end|> | if old_str_ignoring_date == string:
# if all we're doing is updating the copyright year, ignore it |
<|file_name|>item_chooser.js<|end_file_name|><|fim▁begin|>define([
'backbone',
'text!templates/item_chooser.tpl',
'models/item',
'models/trigger',
'models/instance',
'models/media',
'views/item_chooser_row',
'views/trigger_creator',
'vent',
'util',
],
function(
Backbone,
Template,
Item,
Trigger,
Instance,
Media,
ItemChooserRowView,
TriggerCreatorView,
vent,
util
)
{
return Backbone.Marionette.CompositeView.extend(
{
template: _.template(Template),
itemView: ItemChooserRowView,
itemViewContainer: ".items",
itemViewOptions: function(model, index)
{
return {
parent: this.options.parent
}
},
events: {
"click .new-item": "onClickNewItem"
},
/* TODO move complex sets like this into a controller */
onClickNewItem: function()
{
var loc = util.default_location();
var trigger = new Trigger ({game_id:this.options.parent.get("game_id"), scene_id:this.options.parent.get("scene_id"), latitude:loc.latitude, longitude:loc.longitude });
var instance = new Instance ({game_id: this.options.parent.get("game_id")});
var item = new Item ({game_id: this.options.parent.get("game_id")});
var trigger_creator = new TriggerCreatorView({scene: this.options.parent, game_object: item, instance: instance, model: trigger});<|fim▁hole|> // Marionette override
appendBuffer: function(compositeView, buffer)
{
var $container = this.getItemViewContainer(compositeView);
$container.find(".foot").before(buffer);
},
appendHtml: function(compositeView, itemView, index)
{
if (compositeView.isBuffering) {
compositeView.elBuffer.appendChild(itemView.el);
}
else {
// If we've already rendered the main collection, just
// append the new items directly into the element.
var $container = this.getItemViewContainer(compositeView);
$container.find(".foot").before(itemView.el);
}
}
});
});<|fim▁end|> | vent.trigger("application:popup:show", trigger_creator, "Add Item to Scene");
},
|
<|file_name|>prints.client.routes.js<|end_file_name|><|fim▁begin|>'use strict';
// Setting up route
angular.module('prints').config(['$stateProvider',
function($stateProvider) {
$stateProvider.
state('listPrints', {<|fim▁hole|> }
]);<|fim▁end|> | url: '/prints',
templateUrl: 'modules/prints/views/print-client-list.html'
}); |
<|file_name|>characterdata.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/. */
//! DOM bindings for `CharacterData`.
use dom::bindings::cell::DOMRefCell;
use dom::bindings::codegen::Bindings::CharacterDataBinding::CharacterDataMethods;
use dom::bindings::codegen::Bindings::NodeBinding::NodeBinding::NodeMethods;
use dom::bindings::codegen::Bindings::ProcessingInstructionBinding::ProcessingInstructionMethods;
use dom::bindings::codegen::InheritTypes::{CharacterDataTypeId, NodeTypeId};
use dom::bindings::codegen::UnionTypes::NodeOrString;
use dom::bindings::error::{Error, ErrorResult, Fallible};
use dom::bindings::inheritance::Castable;
use dom::bindings::js::{LayoutJS, Root};
use dom::bindings::str::DOMString;
use dom::comment::Comment;
use dom::document::Document;
use dom::element::Element;
use dom::node::{ChildrenMutation, Node, NodeDamage};
use dom::processinginstruction::ProcessingInstruction;
use dom::text::Text;
use dom::virtualmethods::vtable_for;
use dom_struct::dom_struct;
use servo_config::opts;
use std::cell::Ref;
// https://dom.spec.whatwg.org/#characterdata
#[dom_struct]
pub struct CharacterData {
node: Node,
data: DOMRefCell<DOMString>,
}
impl CharacterData {
pub fn new_inherited(data: DOMString, document: &Document) -> CharacterData {
CharacterData {
node: Node::new_inherited(document),
data: DOMRefCell::new(data),
}
}
pub fn clone_with_data(&self, data: DOMString, document: &Document) -> Root<Node> {
match self.upcast::<Node>().type_id() {
NodeTypeId::CharacterData(CharacterDataTypeId::Comment) => {
Root::upcast(Comment::new(data, &document))
}
NodeTypeId::CharacterData(CharacterDataTypeId::ProcessingInstruction) => {
let pi = self.downcast::<ProcessingInstruction>().unwrap();
Root::upcast(ProcessingInstruction::new(pi.Target(), data, &document))
},
NodeTypeId::CharacterData(CharacterDataTypeId::Text) => {
Root::upcast(Text::new(data, &document))
},
_ => unreachable!(),
}
}
#[inline]
pub fn data(&self) -> Ref<DOMString> {
self.data.borrow()
}
#[inline]
pub fn append_data(&self, data: &str) {
self.data.borrow_mut().push_str(data);
self.content_changed();
}
fn content_changed(&self) {
let node = self.upcast::<Node>();
node.dirty(NodeDamage::OtherNodeDamage);
}
}
impl CharacterDataMethods for CharacterData {
// https://dom.spec.whatwg.org/#dom-characterdata-data
fn Data(&self) -> DOMString {
self.data.borrow().clone()
}
// https://dom.spec.whatwg.org/#dom-characterdata-data
fn SetData(&self, data: DOMString) {<|fim▁hole|> *self.data.borrow_mut() = data;
self.content_changed();
let node = self.upcast::<Node>();
node.ranges().replace_code_units(node, 0, old_length, new_length);
// If this is a Text node, we might need to re-parse (say, if our parent
// is a <style> element.) We don't need to if this is a Comment or
// ProcessingInstruction.
if self.is::<Text>() {
if let Some(parent_node) = node.GetParentNode() {
let mutation = ChildrenMutation::ChangeText;
vtable_for(&parent_node).children_changed(&mutation);
}
}
}
// https://dom.spec.whatwg.org/#dom-characterdata-length
fn Length(&self) -> u32 {
self.data.borrow().encode_utf16().count() as u32
}
// https://dom.spec.whatwg.org/#dom-characterdata-substringdata
fn SubstringData(&self, offset: u32, count: u32) -> Fallible<DOMString> {
let data = self.data.borrow();
// Step 1.
let mut substring = String::new();
let remaining;
match split_at_utf16_code_unit_offset(&data, offset) {
Ok((_, astral, s)) => {
// As if we had split the UTF-16 surrogate pair in half
// and then transcoded that to UTF-8 lossily,
// since our DOMString is currently strict UTF-8.
if astral.is_some() {
substring = substring + "\u{FFFD}";
}
remaining = s;
}
// Step 2.
Err(()) => return Err(Error::IndexSize),
}
match split_at_utf16_code_unit_offset(remaining, count) {
// Steps 3.
Err(()) => substring = substring + remaining,
// Steps 4.
Ok((s, astral, _)) => {
substring = substring + s;
// As if we had split the UTF-16 surrogate pair in half
// and then transcoded that to UTF-8 lossily,
// since our DOMString is currently strict UTF-8.
if astral.is_some() {
substring = substring + "\u{FFFD}";
}
}
};
Ok(DOMString::from(substring))
}
// https://dom.spec.whatwg.org/#dom-characterdata-appenddatadata
fn AppendData(&self, data: DOMString) {
// FIXME(ajeffrey): Efficient append on DOMStrings?
self.append_data(&*data);
}
// https://dom.spec.whatwg.org/#dom-characterdata-insertdataoffset-data
fn InsertData(&self, offset: u32, arg: DOMString) -> ErrorResult {
self.ReplaceData(offset, 0, arg)
}
// https://dom.spec.whatwg.org/#dom-characterdata-deletedataoffset-count
fn DeleteData(&self, offset: u32, count: u32) -> ErrorResult {
self.ReplaceData(offset, count, DOMString::new())
}
// https://dom.spec.whatwg.org/#dom-characterdata-replacedata
fn ReplaceData(&self, offset: u32, count: u32, arg: DOMString) -> ErrorResult {
let mut new_data;
{
let data = self.data.borrow();
let prefix;
let replacement_before;
let remaining;
match split_at_utf16_code_unit_offset(&data, offset) {
Ok((p, astral, r)) => {
prefix = p;
// As if we had split the UTF-16 surrogate pair in half
// and then transcoded that to UTF-8 lossily,
// since our DOMString is currently strict UTF-8.
replacement_before = if astral.is_some() { "\u{FFFD}" } else { "" };
remaining = r;
}
// Step 2.
Err(()) => return Err(Error::IndexSize),
};
let replacement_after;
let suffix;
match split_at_utf16_code_unit_offset(remaining, count) {
// Steps 3.
Err(()) => {
replacement_after = "";
suffix = "";
}
Ok((_, astral, s)) => {
// As if we had split the UTF-16 surrogate pair in half
// and then transcoded that to UTF-8 lossily,
// since our DOMString is currently strict UTF-8.
replacement_after = if astral.is_some() { "\u{FFFD}" } else { "" };
suffix = s;
}
};
// Step 4: Mutation observers.
// Step 5 to 7.
new_data = String::with_capacity(
prefix.len() +
replacement_before.len() +
arg.len() +
replacement_after.len() +
suffix.len());
new_data.push_str(prefix);
new_data.push_str(replacement_before);
new_data.push_str(&arg);
new_data.push_str(replacement_after);
new_data.push_str(suffix);
}
*self.data.borrow_mut() = DOMString::from(new_data);
self.content_changed();
// Steps 8-11.
let node = self.upcast::<Node>();
node.ranges().replace_code_units(
node, offset, count, arg.encode_utf16().count() as u32);
Ok(())
}
// https://dom.spec.whatwg.org/#dom-childnode-before
fn Before(&self, nodes: Vec<NodeOrString>) -> ErrorResult {
self.upcast::<Node>().before(nodes)
}
// https://dom.spec.whatwg.org/#dom-childnode-after
fn After(&self, nodes: Vec<NodeOrString>) -> ErrorResult {
self.upcast::<Node>().after(nodes)
}
// https://dom.spec.whatwg.org/#dom-childnode-replacewith
fn ReplaceWith(&self, nodes: Vec<NodeOrString>) -> ErrorResult {
self.upcast::<Node>().replace_with(nodes)
}
// https://dom.spec.whatwg.org/#dom-childnode-remove
fn Remove(&self) {
let node = self.upcast::<Node>();
node.remove_self();
}
// https://dom.spec.whatwg.org/#dom-nondocumenttypechildnode-previouselementsibling
fn GetPreviousElementSibling(&self) -> Option<Root<Element>> {
self.upcast::<Node>().preceding_siblings().filter_map(Root::downcast).next()
}
// https://dom.spec.whatwg.org/#dom-nondocumenttypechildnode-nextelementsibling
fn GetNextElementSibling(&self) -> Option<Root<Element>> {
self.upcast::<Node>().following_siblings().filter_map(Root::downcast).next()
}
}
#[allow(unsafe_code)]
pub trait LayoutCharacterDataHelpers {
unsafe fn data_for_layout(&self) -> &str;
}
#[allow(unsafe_code)]
impl LayoutCharacterDataHelpers for LayoutJS<CharacterData> {
#[inline]
unsafe fn data_for_layout(&self) -> &str {
&(*self.unsafe_get()).data.borrow_for_layout()
}
}
/// Split the given string at the given position measured in UTF-16 code units from the start.
///
/// * `Err(())` indicates that `offset` if after the end of the string
/// * `Ok((before, None, after))` indicates that `offset` is between Unicode code points.
/// The two string slices are such that:
/// `before == s.to_utf16()[..offset].to_utf8()` and
/// `after == s.to_utf16()[offset..].to_utf8()`
/// * `Ok((before, Some(ch), after))` indicates that `offset` is "in the middle"
/// of a single Unicode code point that would be represented in UTF-16 by a surrogate pair
/// of two 16-bit code units.
/// `ch` is that code point.
/// The two string slices are such that:
/// `before == s.to_utf16()[..offset - 1].to_utf8()` and
/// `after == s.to_utf16()[offset + 1..].to_utf8()`
///
/// # Panics
///
/// Note that the third variant is only ever returned when the `-Z replace-surrogates`
/// command-line option is specified.
/// When it *would* be returned but the option is *not* specified, this function panics.
fn split_at_utf16_code_unit_offset(s: &str, offset: u32) -> Result<(&str, Option<char>, &str), ()> {
let mut code_units = 0;
for (i, c) in s.char_indices() {
if code_units == offset {
let (a, b) = s.split_at(i);
return Ok((a, None, b));
}
code_units += 1;
if c > '\u{FFFF}' {
if code_units == offset {
if opts::get().replace_surrogates {
debug_assert!(c.len_utf8() == 4);
return Ok((&s[..i], Some(c), &s[i + c.len_utf8()..]))
}
panic!("\n\n\
Would split a surrogate pair in CharacterData API.\n\
If you see this in real content, please comment with the URL\n\
on https://github.com/servo/servo/issues/6873\n\
\n");
}
code_units += 1;
}
}
if code_units == offset {
Ok((s, None, ""))
} else {
Err(())
}
}<|fim▁end|> | let old_length = self.Length();
let new_length = data.encode_utf16().count() as u32; |
<|file_name|>mixins.py<|end_file_name|><|fim▁begin|># -*- coding: UTF-8 -*-
# Copyright 2014-2017 Luc Saffre
# This file is part of Lino Welfare.
#
# Lino Welfare is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as
# published by the Free Software Foundation, either version 3 of the
# License, or (at your option) any later version.
#
# Lino Welfare 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
# Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public
# License along with Lino Welfare. If not, see
# <http://www.gnu.org/licenses/>.
"""
Model mixins for `lino_welfare.modlib.aids`.
.. autosummary::
"""
from __future__ import unicode_literals
<|fim▁hole|>logger = logging.getLogger(__name__)
from django.conf import settings
from django.db import models
from django.core.exceptions import ValidationError
from django.utils.translation import ugettext_lazy as _
from django.utils.translation import pgettext_lazy as pgettext
from lino.api import dd, rt
from lino import mixins
from etgen.html import E, tostring
from lino.utils.ranges import encompass
from lino.modlib.checkdata.choicelists import Checker
from lino.modlib.users.mixins import UserAuthored
from lino_xl.lib.contacts.mixins import ContactRelated
from lino_xl.lib.excerpts.mixins import Certifiable
from lino.mixins.periods import rangefmt
from .choicelists import ConfirmationStates
from .roles import AidsStaff
def e2text(v):
return tostring(v)
# if isinstance(v, types.GeneratorType):
# return "".join([e2text(x) for x in v])
# if E.iselement(v):
# return tostring(v)
# return unicode(v)
class SignConfirmation(dd.Action):
"""Sign this database object.
This is available if signer is either empty or equals the
requesting user. Except for system managers who can sign as
somebody else by manually setting the signer field before running
this action.
"""
label = pgettext("aids", "Sign")
show_in_workflow = True
show_in_bbar = False
# icon_name = 'flag_green'
required_states = "requested"
help_text = _("You sign this confirmation, making most "
"fields read-only.")
def get_action_permission(self, ar, obj, state):
user = ar.get_user()
if obj.signer_id and obj.signer != user \
and not user.user_type.has_required_roles([AidsStaff]):
return False
return super(SignConfirmation,
self).get_action_permission(ar, obj, state)
def run_from_ui(self, ar, **kw):
obj = ar.selected_rows[0]
def ok(ar):
if not obj.signer_id:
obj.signer = ar.get_user()
obj.state = ConfirmationStates.confirmed
obj.save()
ar.set_response(refresh=True)
d = dict(text=obj.confirmation_text())
d.update(client=e2text(obj.client.get_full_name(nominative=True)))
msg = _("You confirm that %(client)s %(text)s") % d
ar.confirm(ok, msg, _("Are you sure?"))
class RevokeConfirmation(dd.Action):
label = pgettext("aids", "Revoke")
show_in_workflow = True
show_in_bbar = False
# icon_name = 'flag_green'
required_states = "confirmed"
help_text = _("You revoke your signatore from this confirmation.")
def get_action_permission(self, ar, obj, state):
user = ar.get_user()
if obj.signer != user and not user.user_type.has_required_roles([AidsStaff]):
return False
return super(RevokeConfirmation,
self).get_action_permission(ar, obj, state)
def run_from_ui(self, ar, **kw):
obj = ar.selected_rows[0]
def ok(ar):
# obj.signer = None
obj.state = ConfirmationStates.requested
obj.save()
ar.set_response(refresh=True)
d = dict(text=obj.confirmation_text())
d.update(client=e2text(obj.client.get_full_name(nominative=True)))
msg = _("You revoke your confirmation that %(client)s %(text)s") % d
ar.confirm(ok, msg, _("Are you sure?"))
class Confirmable(mixins.DateRange):
"""Base class for both :class:`Granting` and :class:`Confirmation`.
.. attribute:: signer
The agent who has signed or is expected to sign this item.
.. attribute:: state
The confirmation state of this object. Pointer to
:class:`ConfirmationStates`.
"""
class Meta:
abstract = True
manager_roles_required = dd.login_required()
workflow_state_field = 'state'
signer = dd.ForeignKey(
settings.SITE.user_model,
verbose_name=pgettext("aids", "Signer"),
blank=True, null=True,
related_name="%(app_label)s_%(class)s_set_by_signer",
)
state = ConfirmationStates.field(
default=ConfirmationStates.as_callable('requested'))
sign = SignConfirmation()
revoke = RevokeConfirmation()
@classmethod
def on_analyze(cls, site):
cls.CONFIRMED_FIELDS = dd.fields_list(
cls,
cls.get_confirmable_fields())
super(Confirmable, cls).on_analyze(site)
@classmethod
def get_confirmable_fields(cls):
return ''
@classmethod
def setup_parameters(cls, fields):
fields.update(signer=dd.ForeignKey(
settings.SITE.user_model,
verbose_name=pgettext("aids", "Signer"),
blank=True, null=True))
fields.update(state=ConfirmationStates.field(blank=True))
super(Confirmable, cls).setup_parameters(fields)
@classmethod
def get_simple_parameters(cls):
for p in super(Confirmable, cls).get_simple_parameters():
yield p
yield 'signer'
yield 'state'
def full_clean(self):
super(Confirmable, self).full_clean()
if self.signer is None and self.state == ConfirmationStates.confirmed:
self.state = ConfirmationStates.requested
# raise ValidationError(_("Cannot confirm without signer!"))
def get_row_permission(self, ar, state, ba):
"""A signed confirmation cannot be modified, even not by a privileged
user.
"""
if not super(Confirmable, self).get_row_permission(ar, state, ba):
return False
if self.state == ConfirmationStates.confirmed \
and self.signer is not None \
and self.signer != ar.get_user():
return ba.action.readonly
return True
def disabled_fields(self, ar):
if self.state != ConfirmationStates.requested:
return self.CONFIRMED_FIELDS
return super(Confirmable, self).disabled_fields(ar)
def get_printable_context(self, ar=None, **kw):
kw.update(when=self.get_period_text())
return super(Confirmable, self).get_printable_context(ar, **kw)
def confirmation_text(self):
kw = dict()
kw.update(when=self.get_period_text())
at = self.get_aid_type()
if at:
kw.update(what=str(at))
else:
kw.update(what=str(self))
return _("receives %(what)s %(when)s.") % kw
def confirmation_address(self):
at = self.get_aid_type()
if at and at.address_type:
addr = self.client.get_address_by_type(at)
else:
addr = self.client.get_primary_address()
if addr is not None:
return addr.living_at_text()
def get_excerpt_title(self):
at = self.get_aid_type()
if at:
return at.get_excerpt_title()
return str(self)
@dd.python_2_unicode_compatible
class Confirmation(
Confirmable, UserAuthored, ContactRelated,
mixins.Created, Certifiable):
"""Base class for all aid confirmations.
Subclassed by :class:`SimpleConfirmation
<lino_welfare.modlib.aids.models.SimpleConfirmation>`,
:class:`IncomeConfirmation
<lino_welfare.modlib.aids.models.IncomeConfirmation>` and
:class:`RefundConfirmation
<lino_welfare.modlib.aids.models.RefundConfirmation>`.
"""
class Meta:
abstract = True
allow_cascaded_delete = ['client']
client = dd.ForeignKey(
'pcsw.Client', related_name="%(app_label)s_%(class)s_set_by_client")
granting = dd.ForeignKey('aids.Granting', blank=True, null=True)
remark = dd.RichTextField(
_("Remark"), blank=True, format='html')
language = dd.LanguageField(blank=True)
@classmethod
def setup_parameters(cls, fields):
# fields.update(client=dd.ForeignKey(
# 'pcsw.Client', blank=True, null=True))
# fields.update(
# granting=dd.ForeignKey('aids.Granting', blank=True, null=True))
fields.update(gender=dd.Genders.field(blank=True, null=True))
super(Confirmation, cls).setup_parameters(fields)
@classmethod
def get_simple_parameters(cls):
s = list(super(Confirmation, cls).get_simple_parameters())
s += ['client', 'granting']
return s
def __str__(self):
if self.granting is not None:
return '%s/%s' % (self.granting, self.pk)
return '%s #%s' % (self._meta.verbose_name, self.pk)
def get_date_range_veto(obj):
"""
Return an error message if this confirmation lies outside of
granted period.
"""
pk = dd.plugins.aids.no_date_range_veto_until
if pk and obj.pk and obj.pk <= pk:
return
gp = obj.granting.get_period()
if obj.start_date or obj.end_date:
cp = obj.get_period()
if cp[1] is None: cp = (cp[0], cp[0])
if not encompass(gp, cp):
return _(
"Date range %(p1)s lies outside of granted "
"period %(p2)s.") % dict(
p2=rangefmt(gp), p1=rangefmt(cp))
def full_clean(self):
super(Confirmation, self).full_clean()
if self.granting is None:
return
msg = self.get_date_range_veto()
if msg is not None:
raise ValidationError(msg)
if not self.language:
obj = self.recipient
if obj is None:
self.language = self.client.language
else:
if isinstance(obj, rt.models.contacts.Role):
self.language = obj.person.language
else:
self.language = obj.language
def on_create(self, ar):
if self.granting_id:
self.signer = self.granting.signer
self.client = self.granting.client
if self.granting.aid_type_id:
at = self.granting.aid_type
self.company = at.company
self.contact_person = at.contact_person
self.contact_role = at.contact_role
super(Confirmation, self).on_create(ar)
@classmethod
def get_confirmable_fields(cls):
return 'client signer granting remark start_date end_date'
def get_print_language(self):
return self.language
def get_excerpt_options(self, ar, **kw):
# Set project field when creating an excerpt from Client.
kw.update(project=self.client)
return super(Confirmation, self).get_excerpt_options(ar, **kw)
def get_aid_type(self):
if self.granting_id and self.granting.aid_type_id:
return self.granting.aid_type
return None
def get_granting(self, **aidtype_filter):
if self.granting_id:
return rt.models.aids.Granting.objects.get_by_aidtype(
self.granting.client, self, **aidtype_filter)
def get_urgent_granting(self):
"""Return the one and only one urgent aid granting for the client and
period defined for this confirmation. Return None if there is
no such granting, or if there is more than one such granting.
Used in :xfile:`medical_refund.body.html`.
"""
return self.get_granting(is_urgent=True)
@classmethod
def get_template_group(cls):
# Used by excerpts and printable. The individual confirmation
# models use a common tree of templates.
return 'aids/Confirmation'
def get_body_template(self):
"""Overrides :meth:`lino.core.model.Model.get_body_template`."""
at = self.get_aid_type()
if at is not None:
return at.body_template
dd.update_field(Confirmation, 'start_date', default=dd.today,
verbose_name=_('Period from'))
dd.update_field(Confirmation, 'end_date', default=dd.today,
verbose_name=_('until'))
# dd.update_field(Confirmation, 'user', verbose_name=_('Requested by'))
dd.update_field(Confirmation, 'company',
verbose_name=_("Recipient (Organization)"))
dd.update_field(Confirmation, 'contact_person',
verbose_name=_("Recipient (Person)"))
class ConfirmationChecker(Checker):
model = Confirmation
verbose_name = _("Check for confirmations outside of granted period")
def get_responsible_user(self, obj):
return obj.client.get_primary_coach()
def get_checkdata_problems(self, obj, fix=False):
if obj.granting is None:
msg = _("Confirmation without granting")
yield (False, msg)
return
msg = obj.get_date_range_veto()
if msg is not None:
yield (False, msg)
ConfirmationChecker.activate()<|fim▁end|> | from builtins import str
import logging |
<|file_name|>test_caxs.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python3
# -*- coding: utf-8 -*-
from os import listdir
import os
import re
import sys
from argparse import ArgumentParser
import random
import subprocess
from math import sqrt
import ast
from adderror import adderror
"""ENSAMBLE, -d directory -n number of models """
"""-k number of selected structure"""
"""-r repet of program"""
files = []
pdb_files = []
exp_file = []
list_of_random_items_modified = []
list_of_random_items = []
selected_files_for_ensamble = []
def argument():
parser = ArgumentParser()
parser.add_argument("-d", "--dir", dest="myDirVariable",
help="Choose dir", metavar="DIR", required=True)
parser.add_argument("-n", metavar='N', type=int,
dest="number_of_selected_files",
help="Number of selected structure",
required=True)
parser.add_argument("-k", metavar='K', type=int,
dest="k_number_of_options",
help="Number of possibility structure, less then selected files",
required=True)
parser.add_argument("-q", metavar='Q', type=int,
dest="mixing_koeficient", help="Mixing koeficient",
default=1)
parser.add_argument("-r", metavar='R', type=int,
dest="repeat", help="Number of repetitions",
default=1)
parser.add_argument("--verbose", help="increase output verbosity",
action="store_true")
args = parser.parse_args()
global files
global list_of_random_items_modified
files = listdir(args.myDirVariable)
list_of_random_items_modified = [None]*args.k_number_of_options
return(args)
def rmsd_pymol(structure_1, structure_2):<|fim▁hole|> align {s3}, {s4}
quit
""".format(s1=structure_1, s2=structure_2,
s3=os.path.splitext(structure_1)[0],
s4=os.path.splitext(structure_2)[0]))
out_pymol = subprocess.check_output(" pymol -c file_for_pymol.pml | grep Executive:", shell=True)
#part for home:
out_pymol = subprocess.check_output(" pymol -c file_for_pymol.pml | grep Executive:", shell=True)
#part for META:out_pymol = subprocess.check_output("module add pymol-1.8.2.1-gcc; pymol -c file_for_pymol.pml | grep Executive:;module rm pymol-1.8.2.1-gcc", shell=True)
rmsd = float(out_pymol[out_pymol.index(b'=')+1:out_pymol.index(b'(')-1])
print('RMSD ', structure_1, ' and ', structure_2, ' = ', rmsd)
return rmsd
def searching_pdb():
for line in files:
line = line.rstrip()
if re.search('.pdb$', line):
#if re.search('.pdb.dat', line):
pdb_files.append(line)
#if re.search('exp.dat', line):
#print('experimental file', line)
# exp_file.append(line)
total_number_of_pdb_files = len(pdb_files)
return(total_number_of_pdb_files)
def argument_processing(args, total_number_of_pdb_files):
#print(args)
print('Parametrs ')
print('Total number of pdb files', total_number_of_pdb_files)
if total_number_of_pdb_files < args.number_of_selected_files:
print("Number od pdb files is ", total_number_of_pdb_files)
sys.exit(0)
if args.k_number_of_options > args.number_of_selected_files:
print("Number of selected structure is only", args.number_of_selected_files)
sys.exit(0)
if args.mixing_koeficient != 1:
print ("For q>1 is not implemented now \n")
sys.exit(0)
print('Files from directory', args.myDirVariable)
print('The number of the selected files',
args.number_of_selected_files)
print('The number of selected options', args.k_number_of_options)
print('All pdb.dat files \n', pdb_files)
global selected_files_for_ensamble
selected_files_for_ensamble = random.sample(pdb_files,
args.number_of_selected_files)
print('Randomly selected files: \n', selected_files_for_ensamble)
global list_of_random_items
list_of_random_items = random.sample(selected_files_for_ensamble,
args.k_number_of_options)
print('Randomly selected files: \n', list_of_random_items)
def using_adderror():
for i in range(args.k_number_of_options):
list_of_random_items_modified[i] = adderror("exp.dat",list_of_random_items[i]+'.dat')
str1 = ''.join(str(e)+"\n" for e in list_of_random_items_modified)
str2 = ''.join(str(e)+"\n" for e in list_of_random_items)
print(str1)
print(str2)
return(str1, str2)
def find_index(strings):
for e in list_of_random_items:
value_of_index[e] = selected_files_for_ensamble.index(e)
print(selected_files_for_ensamble.index(e))
with open("input_for_ensamble_fit", "w") as f:
f.write(strings[0])
def ensamble_fit():
ensable_output=[None]*args.k_number_of_options
for i in range(k_number_of_options):
command = "/storage/brno3-cerit/home/krab1k/saxs-ensamble-fit/core/ensamble-fit -L -p /storage/brno2/home/petrahrozkova/SAXS/mod -n " + str(args.number_of_selected_files) + " -m /storage/brno2/home/petrahrozkova/SAXS/" +list_of_random_items_modified[i]+".dat"
subprocess.call(command,shell=True)
ensable_output[i] = result_rmsd()
return(ensable_output)
def result_rmsd():
with open('result', 'r') as f:
(f.readline())
result = f.readline()
values_of_index_result = result.split(',')[4:]
return(values_of_index_result)
def pymol_processing(ensable_output):
sum_rmsd = 0
values_of_index_result = ensable_output[0]
dictionary_index_and_structure = dict()
for i, j in enumerate(selected_files_for_ensamble):
dictionary_index_and_structure[i] = j
for i, j in enumerate(values_of_index_result):
f = float(j)
if f != 0:
computed_rmsd = rmsd_pymol(selected_files_for_ensamble[i],
list_of_random_items[0])
print('Adjusted rmsd ', f*computed_rmsd, '\n')
sum_rmsd += f*computed_rmsd
print('Sum of RMSD', sum_rmsd)
if __name__ == '__main__':
args = argument()
total_number_of_pdb_files = searching_pdb()
for i in range(args.repeat):
argument_processing(args, total_number_of_pdb_files)
strings = using_adderror()
#find_index(strings)
# ensamble_output = ensamble-fit()
ensamble_output=[None]*2
ensamble_output[0] = result_rmsd()
if args.k_number_of_options ==1:
pymol_processing(ensamble_output)
else:
print("not implemented")<|fim▁end|> | with open("file_for_pymol.pml", "w") as file_for_pymol:
file_for_pymol.write("""
load {s1}
load {s2} |
<|file_name|>bootstrap-slider.js<|end_file_name|><|fim▁begin|>/*! =========================================================
* bootstrap-slider.js
*
* Maintainers:
* Kyle Kemp
* - Twitter: @seiyria
* - Github: seiyria
* Rohit Kalkur
* - Twitter: @Rovolutionary
* - Github: rovolution
*
* =========================================================
*
* 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.
* ========================================================= */
/**
* Bridget makes jQuery widgets
* v1.0.1
* MIT license
*/
(function(root, factory) {
if(typeof define === "function" && define.amd) {
define(["jquery"], factory);
} else if(typeof module === "object" && module.exports) {
var jQuery;
try {
jQuery = require("jquery");
} catch (err) {
jQuery = null;
}
module.exports = factory(jQuery);
} else {
root.Slider = factory(root.jQuery);
}
}(this, function($) {
// Reference to Slider constructor
var Slider;
(function( $ ) {
'use strict';
// -------------------------- utils -------------------------- //
var slice = Array.prototype.slice;
function noop() {}
// -------------------------- definition -------------------------- //
function defineBridget( $ ) {
// bail if no jQuery
if ( !$ ) {
return;
}
// -------------------------- addOptionMethod -------------------------- //
/**
* adds option method -> $().plugin('option', {...})
* @param {Function} PluginClass - constructor class
*/
function addOptionMethod( PluginClass ) {
// don't overwrite original option method
if ( PluginClass.prototype.option ) {
return;
}
// option setter
PluginClass.prototype.option = function( opts ) {
// bail out if not an object
if ( !$.isPlainObject( opts ) ){
return;
}
this.options = $.extend( true, this.options, opts );
};
}
// -------------------------- plugin bridge -------------------------- //
// helper function for logging errors
// $.error breaks jQuery chaining
var logError = typeof console === 'undefined' ? noop :
function( message ) {
console.error( message );
};
/**
* jQuery plugin bridge, access methods like $elem.plugin('method')
* @param {String} namespace - plugin name
* @param {Function} PluginClass - constructor class
*/
function bridge( namespace, PluginClass ) {
// add to jQuery fn namespace
$.fn[ namespace ] = function( options ) {
if ( typeof options === 'string' ) {
// call plugin method when first argument is a string
// get arguments for method
var args = slice.call( arguments, 1 );
for ( var i=0, len = this.length; i < len; i++ ) {
var elem = this[i];
var instance = $.data( elem, namespace );
if ( !instance ) {
logError( "cannot call methods on " + namespace + " prior to initialization; " +
"attempted to call '" + options + "'" );
continue;
}
if ( !$.isFunction( instance[options] ) || options.charAt(0) === '_' ) {
logError( "no such method '" + options + "' for " + namespace + " instance" );
continue;
}
// trigger method with arguments
var returnValue = instance[ options ].apply( instance, args);
// break look and return first value if provided
if ( returnValue !== undefined && returnValue !== instance) {
return returnValue;
}
}
// return this if no return value
return this;
} else {
var objects = this.map( function() {
var instance = $.data( this, namespace );
if ( instance ) {
// apply options & init
instance.option( options );
instance._init();
} else {
// initialize new instance
instance = new PluginClass( this, options );
$.data( this, namespace, instance );
}
return $(this);
});
if(!objects || objects.length > 1) {
return objects;
} else {
return objects[0];
}
}
};
}
// -------------------------- bridget -------------------------- //
/**
* converts a Prototypical class into a proper jQuery plugin
* the class must have a ._init method
* @param {String} namespace - plugin name, used in $().pluginName
* @param {Function} PluginClass - constructor class
*/
$.bridget = function( namespace, PluginClass ) {
addOptionMethod( PluginClass );
bridge( namespace, PluginClass );
};
return $.bridget;
}
// get jquery from browser global
defineBridget( $ );
})( $ );
/*************************************************
BOOTSTRAP-SLIDER SOURCE CODE
**************************************************/
(function($) {
var ErrorMsgs = {
formatInvalidInputErrorMsg : function(input) {
return "Invalid input value '" + input + "' passed in";
},
callingContextNotSliderInstance : "Calling context element does not have instance of Slider bound to it. Check your code to make sure the JQuery object returned from the call to the slider() initializer is calling the method"
};
/*************************************************
CONSTRUCTOR
**************************************************/
Slider = function(element, options) {
createNewSlider.call(this, element, options);
return this;
};
function createNewSlider(element, options) {
/*************************************************
Create Markup
**************************************************/
if(typeof element === "string") {
this.element = document.querySelector(element);
} else if(element instanceof HTMLElement) {
this.element = element;
}
var origWidth = this.element.style.width;
var updateSlider = false;
var parent = this.element.parentNode;
var sliderTrackSelection;
var sliderMinHandle;
var sliderMaxHandle;
if (this.sliderElem) {
updateSlider = true;
} else {
/* Create elements needed for slider */
this.sliderElem = document.createElement("div");
this.sliderElem.className = "slider";
/* Create slider track elements */
var sliderTrack = document.createElement("div");
sliderTrack.className = "slider-track";
sliderTrackSelection = document.createElement("div");
sliderTrackSelection.className = "slider-selection";
sliderMinHandle = document.createElement("div");
sliderMinHandle.className = "slider-handle min-slider-handle";
sliderMaxHandle = document.createElement("div");
sliderMaxHandle.className = "slider-handle max-slider-handle";
sliderTrack.appendChild(sliderTrackSelection);
sliderTrack.appendChild(sliderMinHandle);
sliderTrack.appendChild(sliderMaxHandle);
var createAndAppendTooltipSubElements = function(tooltipElem) {
var arrow = document.createElement("div");
arrow.className = "tooltip-arrow";
var inner = document.createElement("div");
inner.className = "tooltip-inner";
tooltipElem.appendChild(arrow);
tooltipElem.appendChild(inner);
};
/* Create tooltip elements */
var sliderTooltip = document.createElement("div");
sliderTooltip.className = "tooltip tooltip-main";
createAndAppendTooltipSubElements(sliderTooltip);
var sliderTooltipMin = document.createElement("div");
sliderTooltipMin.className = "tooltip tooltip-min";
createAndAppendTooltipSubElements(sliderTooltipMin);
var sliderTooltipMax = document.createElement("div");
sliderTooltipMax.className = "tooltip tooltip-max";
createAndAppendTooltipSubElements(sliderTooltipMax);
/* Append components to sliderElem */
this.sliderElem.appendChild(sliderTrack);
this.sliderElem.appendChild(sliderTooltip);
this.sliderElem.appendChild(sliderTooltipMin);
this.sliderElem.appendChild(sliderTooltipMax);
/* Append slider element to parent container, right before the original <input> element */
parent.insertBefore(this.sliderElem, this.element);
/* Hide original <input> element */
this.element.style.display = "none";
}
/* If JQuery exists, cache JQ references */
if($) {
this.$element = $(this.element);
this.$sliderElem = $(this.sliderElem);
}
/*************************************************
Process Options
**************************************************/
options = options ? options : {};
var optionTypes = Object.keys(this.defaultOptions);
for(var i = 0; i < optionTypes.length; i++) {
var optName = optionTypes[i];
// First check if an option was passed in via the constructor
var val = options[optName];
// If no data attrib, then check data atrributes
val = (typeof val !== 'undefined') ? val : getDataAttrib(this.element, optName);
// Finally, if nothing was specified, use the defaults
val = (val !== null) ? val : this.defaultOptions[optName];
// Set all options on the instance of the Slider
if(!this.options) {
this.options = {};
}
this.options[optName] = val;
}
function getDataAttrib(element, optName) {
var dataName = "data-slider-" + optName;
var dataValString = element.getAttribute(dataName);
try {
return JSON.parse(dataValString);
}
catch(err) {
return dataValString;
}
}
/*************************************************
Setup
**************************************************/
this.eventToCallbackMap = {};
this.sliderElem.id = this.options.id;
this.touchCapable = 'ontouchstart' in window || (window.DocumentTouch && document instanceof window.DocumentTouch);
this.tooltip = this.sliderElem.querySelector('.tooltip-main');
this.tooltipInner = this.tooltip.querySelector('.tooltip-inner');
this.tooltip_min = this.sliderElem.querySelector('.tooltip-min');
this.tooltipInner_min = this.tooltip_min.querySelector('.tooltip-inner');
this.tooltip_max = this.sliderElem.querySelector('.tooltip-max');
this.tooltipInner_max= this.tooltip_max.querySelector('.tooltip-inner');
if (updateSlider === true) {
// Reset classes
this._removeClass(this.sliderElem, 'slider-horizontal');
this._removeClass(this.sliderElem, 'slider-vertical');
this._removeClass(this.tooltip, 'hide');
this._removeClass(this.tooltip_min, 'hide');
this._removeClass(this.tooltip_max, 'hide');
// Undo existing inline styles for track
["left", "top", "width", "height"].forEach(function(prop) {
this._removeProperty(this.trackSelection, prop);
}, this);
// Undo inline styles on handles
[this.handle1, this.handle2].forEach(function(handle) {
this._removeProperty(handle, 'left');
this._removeProperty(handle, 'top');
}, this);
// Undo inline styles and classes on tooltips
[this.tooltip, this.tooltip_min, this.tooltip_max].forEach(function(tooltip) {
this._removeProperty(tooltip, 'left');
this._removeProperty(tooltip, 'top');
this._removeProperty(tooltip, 'margin-left');
this._removeProperty(tooltip, 'margin-top');
this._removeClass(tooltip, 'right');
this._removeClass(tooltip, 'top');
}, this);
}
if(this.options.orientation === 'vertical') {
this._addClass(this.sliderElem,'slider-vertical');
this.stylePos = 'top';
this.mousePos = 'pageY';
this.sizePos = 'offsetHeight';
this._addClass(this.tooltip, 'right');
this.tooltip.style.left = '100%';
this._addClass(this.tooltip_min, 'right');
this.tooltip_min.style.left = '100%';
this._addClass(this.tooltip_max, 'right');
this.tooltip_max.style.left = '100%';
} else {
this._addClass(this.sliderElem, 'slider-horizontal');
this.sliderElem.style.width = origWidth;
this.options.orientation = 'horizontal';
this.stylePos = 'left';
this.mousePos = 'pageX';
this.sizePos = 'offsetWidth';
this._addClass(this.tooltip, 'top');
this.tooltip.style.top = -this.tooltip.outerHeight - 14 + 'px';
this._addClass(this.tooltip_min, 'top');
this.tooltip_min.style.top = -this.tooltip_min.outerHeight - 14 + 'px';
this._addClass(this.tooltip_max, 'top');
this.tooltip_max.style.top = -this.tooltip_max.outerHeight - 14 + 'px';
}
if (this.options.value instanceof Array) {
this.options.range = true;
} else if (this.options.range) {
// User wants a range, but value is not an array
this.options.value = [this.options.value, this.options.max];
}
this.trackSelection = sliderTrackSelection || this.trackSelection;
if (this.options.selection === 'none') {
this._addClass(this.trackSelection, 'hide');
}
this.handle1 = sliderMinHandle || this.handle1;
this.handle2 = sliderMaxHandle || this.handle2;
if (updateSlider === true) {
// Reset classes
this._removeClass(this.handle1, 'round triangle');
this._removeClass(this.handle2, 'round triangle hide');
}
var availableHandleModifiers = ['round', 'triangle', 'custom'];
var isValidHandleType = availableHandleModifiers.indexOf(this.options.handle) !== -1;
if (isValidHandleType) {
this._addClass(this.handle1, this.options.handle);
this._addClass(this.handle2, this.options.handle);
}
this.offset = this._offset(this.sliderElem);
this.size = this.sliderElem[this.sizePos];
this.setValue(this.options.value);
/******************************************
Bind Event Listeners
******************************************/
// Bind keyboard handlers
this.handle1Keydown = this._keydown.bind(this, 0);
this.handle1.addEventListener("keydown", this.handle1Keydown, false);
this.handle2Keydown = this._keydown.bind(this, 1);
this.handle2.addEventListener("keydown", this.handle2Keydown, false);
if (this.touchCapable) {
// Bind touch handlers
this.mousedown = this._mousedown.bind(this);
this.sliderElem.addEventListener("touchstart", this.mousedown, false);
} else {
// Bind mouse handlers
this.mousedown = this._mousedown.bind(this);
this.sliderElem.addEventListener("mousedown", this.mousedown, false);
}
// Bind tooltip-related handlers
if(this.options.tooltip === 'hide') {
this._addClass(this.tooltip, 'hide');
this._addClass(this.tooltip_min, 'hide');
this._addClass(this.tooltip_max, 'hide');
} else if(this.options.tooltip === 'always') {
this._showTooltip();
this._alwaysShowTooltip = true;
} else {
this.showTooltip = this._showTooltip.bind(this);
this.hideTooltip = this._hideTooltip.bind(this);
this.sliderElem.addEventListener("mouseenter", this.showTooltip, false);<|fim▁hole|> this.sliderElem.addEventListener("mouseleave", this.hideTooltip, false);
this.handle1.addEventListener("focus", this.showTooltip, false);
this.handle1.addEventListener("blur", this.hideTooltip, false);
this.handle2.addEventListener("focus", this.showTooltip, false);
this.handle2.addEventListener("blur", this.hideTooltip, false);
}
if(this.options.enabled) {
this.enable();
} else {
this.disable();
}
}
/*************************************************
INSTANCE PROPERTIES/METHODS
- Any methods bound to the prototype are considered
part of the plugin's `public` interface
**************************************************/
Slider.prototype = {
_init: function() {}, // NOTE: Must exist to support bridget
constructor: Slider,
defaultOptions: {
id: "",
min: 0,
max: 10,
step: 1,
precision: 0,
orientation: 'horizontal',
value: 5,
range: false,
selection: 'before',
tooltip: 'show',
tooltip_split: false,
handle: 'round',
reversed: false,
enabled: true,
formatter: function(val) {
if(val instanceof Array) {
return val[0] + " : " + val[1];
} else {
return val;
}
},
natural_arrow_keys: false
},
over: false,
inDrag: false,
getValue: function() {
if (this.options.range) {
return this.options.value;
}
return this.options.value[0];
},
setValue: function(val, triggerSlideEvent) {
if (!val) {
val = 0;
}
this.options.value = this._validateInputValue(val);
var applyPrecision = this._applyPrecision.bind(this);
if (this.options.range) {
this.options.value[0] = applyPrecision(this.options.value[0]);
this.options.value[1] = applyPrecision(this.options.value[1]);
this.options.value[0] = Math.max(this.options.min, Math.min(this.options.max, this.options.value[0]));
this.options.value[1] = Math.max(this.options.min, Math.min(this.options.max, this.options.value[1]));
} else {
this.options.value = applyPrecision(this.options.value);
this.options.value = [ Math.max(this.options.min, Math.min(this.options.max, this.options.value))];
this._addClass(this.handle2, 'hide');
if (this.options.selection === 'after') {
this.options.value[1] = this.options.max;
} else {
this.options.value[1] = this.options.min;
}
}
this.diff = this.options.max - this.options.min;
if (this.diff > 0) {
this.percentage = [
(this.options.value[0] - this.options.min) * 100 / this.diff,
(this.options.value[1] - this.options.min) * 100 / this.diff,
this.options.step * 100 / this.diff
];
} else {
this.percentage = [0, 0, 100];
}
this._layout();
var sliderValue = this.options.range ? this.options.value : this.options.value[0];
this._setDataVal(sliderValue);
if(triggerSlideEvent === true) {
this._trigger('slide', sliderValue);
}
return this;
},
destroy: function(){
// Remove event handlers on slider elements
this._removeSliderEventHandlers();
// Remove the slider from the DOM
this.sliderElem.parentNode.removeChild(this.sliderElem);
/* Show original <input> element */
this.element.style.display = "";
// Clear out custom event bindings
this._cleanUpEventCallbacksMap();
// Remove data values
this.element.removeAttribute("data");
// Remove JQuery handlers/data
if($) {
this._unbindJQueryEventHandlers();
this.$element.removeData('slider');
}
},
disable: function() {
this.options.enabled = false;
this.handle1.removeAttribute("tabindex");
this.handle2.removeAttribute("tabindex");
this._addClass(this.sliderElem, 'slider-disabled');
this._trigger('slideDisabled');
return this;
},
enable: function() {
this.options.enabled = true;
this.handle1.setAttribute("tabindex", 0);
this.handle2.setAttribute("tabindex", 0);
this._removeClass(this.sliderElem, 'slider-disabled');
this._trigger('slideEnabled');
return this;
},
toggle: function() {
if(this.options.enabled) {
this.disable();
} else {
this.enable();
}
return this;
},
isEnabled: function() {
return this.options.enabled;
},
on: function(evt, callback) {
if($) {
this.$element.on(evt, callback);
this.$sliderElem.on(evt, callback);
} else {
this._bindNonQueryEventHandler(evt, callback);
}
return this;
},
getAttribute: function(attribute) {
if(attribute) {
return this.options[attribute];
} else {
return this.options;
}
},
setAttribute: function(attribute, value) {
this.options[attribute] = value;
return this;
},
refresh: function() {
this._removeSliderEventHandlers();
createNewSlider.call(this, this.element, this.options);
if($) {
// Bind new instance of slider to the element
$.data(this.element, 'slider', this);
}
return this;
},
/******************************+
HELPERS
- Any method that is not part of the public interface.
- Place it underneath this comment block and write its signature like so:
_fnName : function() {...}
********************************/
_removeSliderEventHandlers: function() {
// Remove event listeners from handle1
this.handle1.removeEventListener("keydown", this.handle1Keydown, false);
this.handle1.removeEventListener("focus", this.showTooltip, false);
this.handle1.removeEventListener("blur", this.hideTooltip, false);
// Remove event listeners from handle2
this.handle2.removeEventListener("keydown", this.handle2Keydown, false);
this.handle2.removeEventListener("focus", this.handle2Keydown, false);
this.handle2.removeEventListener("blur", this.handle2Keydown, false);
// Remove event listeners from sliderElem
this.sliderElem.removeEventListener("mouseenter", this.showTooltip, false);
this.sliderElem.removeEventListener("mouseleave", this.hideTooltip, false);
this.sliderElem.removeEventListener("touchstart", this.mousedown, false);
this.sliderElem.removeEventListener("mousedown", this.mousedown, false);
},
_bindNonQueryEventHandler: function(evt, callback) {
if(this.eventToCallbackMap[evt]===undefined) {
this.eventToCallbackMap[evt] = [];
}
this.eventToCallbackMap[evt].push(callback);
},
_cleanUpEventCallbacksMap: function() {
var eventNames = Object.keys(this.eventToCallbackMap);
for(var i = 0; i < eventNames.length; i++) {
var eventName = eventNames[i];
this.eventToCallbackMap[eventName] = null;
}
},
_showTooltip: function() {
if (this.options.tooltip_split === false ){
this._addClass(this.tooltip, 'in');
} else {
this._addClass(this.tooltip_min, 'in');
this._addClass(this.tooltip_max, 'in');
}
this.over = true;
},
_hideTooltip: function() {
if (this.inDrag === false && this.alwaysShowTooltip !== true) {
this._removeClass(this.tooltip, 'in');
this._removeClass(this.tooltip_min, 'in');
this._removeClass(this.tooltip_max, 'in');
}
this.over = false;
},
_layout: function() {
var positionPercentages;
if(this.options.reversed) {
positionPercentages = [ 100 - this.percentage[0], this.percentage[1] ];
} else {
positionPercentages = [ this.percentage[0], this.percentage[1] ];
}
this.handle1.style[this.stylePos] = positionPercentages[0]+'%';
this.handle2.style[this.stylePos] = positionPercentages[1]+'%';
if (this.options.orientation === 'vertical') {
this.trackSelection.style.top = Math.min(positionPercentages[0], positionPercentages[1]) +'%';
this.trackSelection.style.height = Math.abs(positionPercentages[0] - positionPercentages[1]) +'%';
} else {
this.trackSelection.style.left = Math.min(positionPercentages[0], positionPercentages[1]) +'%';
this.trackSelection.style.width = Math.abs(positionPercentages[0] - positionPercentages[1]) +'%';
var offset_min = this.tooltip_min.getBoundingClientRect();
var offset_max = this.tooltip_max.getBoundingClientRect();
if (offset_min.right > offset_max.left) {
this._removeClass(this.tooltip_max, 'top');
this._addClass(this.tooltip_max, 'bottom');
this.tooltip_max.style.top = 18 + 'px';
} else {
this._removeClass(this.tooltip_max, 'bottom');
this._addClass(this.tooltip_max, 'top');
this.tooltip_max.style.top = -30 + 'px';
}
}
var formattedTooltipVal;
if (this.options.range) {
formattedTooltipVal = this.options.formatter(this.options.value);
this._setText(this.tooltipInner, formattedTooltipVal);
this.tooltip.style[this.stylePos] = (positionPercentages[1] + positionPercentages[0])/2 + '%';
if (this.options.orientation === 'vertical') {
this._css(this.tooltip, 'margin-top', -this.tooltip.offsetHeight / 2 + 'px');
} else {
this._css(this.tooltip, 'margin-left', -this.tooltip.offsetWidth / 2 + 'px');
}
if (this.options.orientation === 'vertical') {
this._css(this.tooltip, 'margin-top', -this.tooltip.offsetHeight / 2 + 'px');
} else {
this._css(this.tooltip, 'margin-left', -this.tooltip.offsetWidth / 2 + 'px');
}
var innerTooltipMinText = this.options.formatter(this.options.value[0]);
this._setText(this.tooltipInner_min, innerTooltipMinText);
var innerTooltipMaxText = this.options.formatter(this.options.value[1]);
this._setText(this.tooltipInner_max, innerTooltipMaxText);
this.tooltip_min.style[this.stylePos] = positionPercentages[0] + '%';
if (this.options.orientation === 'vertical') {
this._css(this.tooltip_min, 'margin-top', -this.tooltip_min.offsetHeight / 2 + 'px');
} else {
this._css(this.tooltip_min, 'margin-left', -this.tooltip_min.offsetWidth / 2 + 'px');
}
this.tooltip_max.style[this.stylePos] = positionPercentages[1] + '%';
if (this.options.orientation === 'vertical') {
this._css(this.tooltip_max, 'margin-top', -this.tooltip_max.offsetHeight / 2 + 'px');
} else {
this._css(this.tooltip_max, 'margin-left', -this.tooltip_max.offsetWidth / 2 + 'px');
}
} else {
formattedTooltipVal = this.options.formatter(this.options.value[0]);
this._setText(this.tooltipInner, formattedTooltipVal);
this.tooltip.style[this.stylePos] = positionPercentages[0] + '%';
if (this.options.orientation === 'vertical') {
this._css(this.tooltip, 'margin-top', -this.tooltip.offsetHeight / 2 + 'px');
} else {
this._css(this.tooltip, 'margin-left', -this.tooltip.offsetWidth / 2 + 'px');
}
}
},
_removeProperty: function(element, prop) {
if (element.style.removeProperty) {
element.style.removeProperty(prop);
} else {
element.style.removeAttribute(prop);
}
},
_mousedown: function(ev) {
if(!this.options.enabled) {
return false;
}
this._triggerFocusOnHandle();
this.offset = this._offset(this.sliderElem);
this.size = this.sliderElem[this.sizePos];
var percentage = this._getPercentage(ev);
if (this.options.range) {
var diff1 = Math.abs(this.percentage[0] - percentage);
var diff2 = Math.abs(this.percentage[1] - percentage);
this.dragged = (diff1 < diff2) ? 0 : 1;
} else {
this.dragged = 0;
}
this.percentage[this.dragged] = this.options.reversed ? 100 - percentage : percentage;
this._layout();
if (this.touchCapable) {
document.removeEventListener("touchmove", this.mousemove, false);
document.removeEventListener("touchend", this.mouseup, false);
}
if(this.mousemove){
document.removeEventListener("mousemove", this.mousemove, false);
}
if(this.mouseup){
document.removeEventListener("mouseup", this.mouseup, false);
}
this.mousemove = this._mousemove.bind(this);
this.mouseup = this._mouseup.bind(this);
if (this.touchCapable) {
// Touch: Bind touch events:
document.addEventListener("touchmove", this.mousemove, false);
document.addEventListener("touchend", this.mouseup, false);
}
// Bind mouse events:
document.addEventListener("mousemove", this.mousemove, false);
document.addEventListener("mouseup", this.mouseup, false);
this.inDrag = true;
var val = this._calculateValue();
this._trigger('slideStart', val);
this._setDataVal(val);
this.setValue(val);
this._pauseEvent(ev);
return true;
},
_triggerFocusOnHandle: function(handleIdx) {
if(handleIdx === 0) {
this.handle1.focus();
}
if(handleIdx === 1) {
this.handle2.focus();
}
},
_keydown: function(handleIdx, ev) {
if(!this.options.enabled) {
return false;
}
var dir;
switch (ev.keyCode) {
case 37: // left
case 40: // down
dir = -1;
break;
case 39: // right
case 38: // up
dir = 1;
break;
}
if (!dir) {
return;
}
// use natural arrow keys instead of from min to max
if (this.options.natural_arrow_keys) {
var ifVerticalAndNotReversed = (this.options.orientation === 'vertical' && !this.options.reversed);
var ifHorizontalAndReversed = (this.options.orientation === 'horizontal' && this.options.reversed);
if (ifVerticalAndNotReversed || ifHorizontalAndReversed) {
dir = dir * -1;
}
}
var oneStepValuePercentageChange = dir * this.percentage[2];
var percentage = this.percentage[handleIdx] + oneStepValuePercentageChange;
if (percentage > 100) {
percentage = 100;
} else if (percentage < 0) {
percentage = 0;
}
this.dragged = handleIdx;
this._adjustPercentageForRangeSliders(percentage);
this.percentage[this.dragged] = percentage;
this._layout();
var val = this._calculateValue();
this._trigger('slideStart', val);
this._setDataVal(val);
this.setValue(val, true);
this._trigger('slideStop', val);
this._setDataVal(val);
this._pauseEvent(ev);
return false;
},
_pauseEvent: function(ev) {
if(ev.stopPropagation) {
ev.stopPropagation();
}
if(ev.preventDefault) {
ev.preventDefault();
}
ev.cancelBubble=true;
ev.returnValue=false;
},
_mousemove: function(ev) {
if(!this.options.enabled) {
return false;
}
var percentage = this._getPercentage(ev);
this._adjustPercentageForRangeSliders(percentage);
this.percentage[this.dragged] = this.options.reversed ? 100 - percentage : percentage;
this._layout();
var val = this._calculateValue();
this.setValue(val, true);
return false;
},
_adjustPercentageForRangeSliders: function(percentage) {
if (this.options.range) {
if (this.dragged === 0 && this.percentage[1] < percentage) {
this.percentage[0] = this.percentage[1];
this.dragged = 1;
} else if (this.dragged === 1 && this.percentage[0] > percentage) {
this.percentage[1] = this.percentage[0];
this.dragged = 0;
}
}
},
_mouseup: function() {
if(!this.options.enabled) {
return false;
}
if (this.touchCapable) {
// Touch: Unbind touch event handlers:
document.removeEventListener("touchmove", this.mousemove, false);
document.removeEventListener("touchend", this.mouseup, false);
}
// Unbind mouse event handlers:
document.removeEventListener("mousemove", this.mousemove, false);
document.removeEventListener("mouseup", this.mouseup, false);
this.inDrag = false;
if (this.over === false) {
this._hideTooltip();
}
var val = this._calculateValue();
this._layout();
this._setDataVal(val);
this._trigger('slideStop', val);
return false;
},
_calculateValue: function() {
var val;
if (this.options.range) {
val = [this.options.min,this.options.max];
if (this.percentage[0] !== 0){
val[0] = (Math.max(this.options.min, this.options.min + Math.round((this.diff * this.percentage[0]/100)/this.options.step)*this.options.step));
val[0] = this._applyPrecision(val[0]);
}
if (this.percentage[1] !== 100){
val[1] = (Math.min(this.options.max, this.options.min + Math.round((this.diff * this.percentage[1]/100)/this.options.step)*this.options.step));
val[1] = this._applyPrecision(val[1]);
}
this.options.value = val;
} else {
val = (this.options.min + Math.round((this.diff * this.percentage[0]/100)/this.options.step)*this.options.step);
if (val < this.options.min) {
val = this.options.min;
}
else if (val > this.options.max) {
val = this.options.max;
}
val = parseFloat(val);
val = this._applyPrecision(val);
this.options.value = [val, this.options.value[1]];
}
return val;
},
_applyPrecision: function(val) {
var precision = this.options.precision || this._getNumDigitsAfterDecimalPlace(this.options.step);
return this._applyToFixedAndParseFloat(val, precision);
},
_getNumDigitsAfterDecimalPlace: function(num) {
var match = (''+num).match(/(?:\.(\d+))?(?:[eE]([+-]?\d+))?$/);
if (!match) { return 0; }
return Math.max(0, (match[1] ? match[1].length : 0) - (match[2] ? +match[2] : 0));
},
_applyToFixedAndParseFloat: function(num, toFixedInput) {
var truncatedNum = num.toFixed(toFixedInput);
return parseFloat(truncatedNum);
},
/*
Credits to Mike Samuel for the following method!
Source: http://stackoverflow.com/questions/10454518/javascript-how-to-retrieve-the-number-of-decimals-of-a-string-number
*/
_getPercentage: function(ev) {
if (this.touchCapable && (ev.type === 'touchstart' || ev.type === 'touchmove')) {
ev = ev.touches[0];
}
var percentage = (ev[this.mousePos] - this.offset[this.stylePos])*100/this.size;
percentage = Math.round(percentage/this.percentage[2])*this.percentage[2];
return Math.max(0, Math.min(100, percentage));
},
_validateInputValue: function(val) {
if(typeof val === 'number') {
return val;
} else if(val instanceof Array) {
this._validateArray(val);
return val;
} else {
throw new Error( ErrorMsgs.formatInvalidInputErrorMsg(val) );
}
},
_validateArray: function(val) {
for(var i = 0; i < val.length; i++) {
var input = val[i];
if (typeof input !== 'number') { throw new Error( ErrorMsgs.formatInvalidInputErrorMsg(input) ); }
}
},
_setDataVal: function(val) {
var value = "value: '" + val + "'";
this.element.setAttribute('data', value);
this.element.setAttribute('value', val);
},
_trigger: function(evt, val) {
val = (val || val === 0) ? val : undefined;
var callbackFnArray = this.eventToCallbackMap[evt];
if(callbackFnArray && callbackFnArray.length) {
for(var i = 0; i < callbackFnArray.length; i++) {
var callbackFn = callbackFnArray[i];
callbackFn(val);
}
}
/* If JQuery exists, trigger JQuery events */
if($) {
this._triggerJQueryEvent(evt, val);
}
},
_triggerJQueryEvent: function(evt, val) {
var eventData = {
type: evt,
value: val
};
this.$element.trigger(eventData);
this.$sliderElem.trigger(eventData);
},
_unbindJQueryEventHandlers: function() {
this.$element.off();
this.$sliderElem.off();
},
_setText: function(element, text) {
if(typeof element.innerText !== "undefined") {
element.innerText = text;
} else if(typeof element.textContent !== "undefined") {
element.textContent = text;
}
},
_removeClass: function(element, classString) {
var classes = classString.split(" ");
var newClasses = element.className;
for(var i = 0; i < classes.length; i++) {
var classTag = classes[i];
var regex = new RegExp("(?:\\s|^)" + classTag + "(?:\\s|$)");
newClasses = newClasses.replace(regex, " ");
}
element.className = newClasses.trim();
},
_addClass: function(element, classString) {
var classes = classString.split(" ");
var newClasses = element.className;
for(var i = 0; i < classes.length; i++) {
var classTag = classes[i];
var regex = new RegExp("(?:\\s|^)" + classTag + "(?:\\s|$)");
var ifClassExists = regex.test(newClasses);
if(!ifClassExists) {
newClasses += " " + classTag;
}
}
element.className = newClasses.trim();
},
_offset: function (obj) {
var ol = 0;
var ot = 0;
if (obj.offsetParent) {
do {
ol += obj.offsetLeft;
ot += obj.offsetTop;
} while (obj = obj.offsetParent);
}
return {
left: ol,
top: ot
};
},
_css: function(elementRef, styleName, value) {
if ($) {
$.style(elementRef, styleName, value);
} else {
var style = styleName.replace(/^-ms-/, "ms-").replace(/-([\da-z])/gi, function (all, letter) {
return letter.toUpperCase();
});
elementRef.style[style] = value;
}
}
};
/*********************************
Attach to global namespace
*********************************/
if($) {
var namespace = $.fn.slider ? 'bootstrapSlider' : 'slider';
$.bridget(namespace, Slider);
}
})( $ );
return Slider;
}));<|fim▁end|> | |
<|file_name|>Accounts.java<|end_file_name|><|fim▁begin|>/*
* Copyright (C) 2013 OpenJST Project
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*<|fim▁hole|> * 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 Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package org.openjst.server.mobile.web.rest;
import org.openjst.server.commons.mq.IRestCrud;
import org.openjst.server.commons.mq.QueryListParams;
import org.openjst.server.commons.mq.results.QuerySingleResult;
import org.openjst.server.mobile.mq.model.AccountModel;
import org.openjst.server.mobile.mq.model.AccountSummaryModel;
import javax.ws.rs.*;
import javax.ws.rs.core.MediaType;
/**
* @author Sergey Grachev
*/
@Path("/accounts")
@Produces(MediaType.APPLICATION_JSON)
public interface Accounts extends IRestCrud<AccountModel, QueryListParams> {
@POST
@Path("/generateAccountAPIKey")
QuerySingleResult<String> generateAccountAPIKey(@FormParam("accountId") Long accountId);
@GET
@Path("/{id}/summary")
QuerySingleResult<AccountSummaryModel> getSummary(@PathParam("id") Long accountId);
}<|fim▁end|> | |
<|file_name|>fasta_parser.py<|end_file_name|><|fim▁begin|>#(c) 2013-2014 by Authors
#This file is a part of Ragout program.
#Released under the BSD license (see LICENSE file)
"""
This module provides some basic FASTA I/O
"""
import logging
<|fim▁hole|>logger = logging.getLogger()
class FastaError(Exception):
pass
def read_fasta_dict(filename):
"""
Reads fasta file into dictionary. Also preforms some validation
"""
logger.info("Reading contigs file")
header = None
seq = []
fasta_dict = {}
try:
with open(filename, "r") as f:
for lineno, line in enumerate(f):
line = line.strip()
if line.startswith(">"):
if header:
fasta_dict[header] = "".join(seq)
seq = []
header = line[1:].split(" ")[0]
else:
if not _validate_seq(line):
raise FastaError("Invalid char in \"{0}\" at line {1}"
.format(filename, lineno))
seq.append(line)
if header and len(seq):
fasta_dict[header] = "".join(seq)
except IOError as e:
raise FastaError(e)
return fasta_dict
def write_fasta_dict(fasta_dict, filename):
"""
Writes dictionary with fasta to file
"""
with open(filename, "w") as f:
for header in sorted(fasta_dict):
f.write(">{0}\n".format(header))
for i in range(0, len(fasta_dict[header]), 60):
f.write(fasta_dict[header][i:i + 60] + "\n")
COMPL = maketrans("ATGCURYKMSWBVDHNXatgcurykmswbvdhnx",
"TACGAYRMKSWVBHDNXtacgayrmkswvbhdnx")
def reverse_complement(string):
return string[::-1].translate(COMPL)
def _validate_seq(sequence):
VALID_CHARS = "ACGTURYKMSWBDHVNXatgcurykmswbvdhnx"
if len(sequence.translate(None, VALID_CHARS)):
return False
return True<|fim▁end|> | from string import maketrans
|
<|file_name|>linux_ssh.py<|end_file_name|><|fim▁begin|>from __future__ import unicode_literals
import re
import socket
import time
from netmiko.cisco_base_connection import CiscoSSHConnection
from netmiko.ssh_exception import NetMikoTimeoutException
class LinuxSSH(CiscoSSHConnection):
def disable_paging(self, *args, **kwargs):
"""Linux doesn't have paging by default."""
return ""
def set_base_prompt(self, pri_prompt_terminator='$',
alt_prompt_terminator='#', delay_factor=1):
"""Determine base prompt."""
return super(CiscoSSHConnection, self).set_base_prompt(
pri_prompt_terminator=pri_prompt_terminator,
alt_prompt_terminator=alt_prompt_terminator,
delay_factor=delay_factor)
def send_config_set(self, config_commands=None, exit_config_mode=True, **kwargs):
"""Can't exit from root (if root)"""
if self.username == "root":
exit_config_mode = False
return super(CiscoSSHConnection, self).send_config_set(config_commands=config_commands,
exit_config_mode=exit_config_mode,
**kwargs)
def check_config_mode(self, check_string='#'):
"""Verify root"""
return self.check_enable_mode(check_string=check_string)
def config_mode(self, config_command='sudo su'):
"""Attempt to become root."""
return self.enable(cmd=config_command)
def exit_config_mode(self, exit_config='exit'):
return self.exit_enable_mode(exit_command=exit_config)
def check_enable_mode(self, check_string='#'):<|fim▁hole|> return super(CiscoSSHConnection, self).check_enable_mode(check_string=check_string)
def exit_enable_mode(self, exit_command='exit'):
"""Exit enable mode."""
delay_factor = self.select_delay_factor(delay_factor=0)
output = ""
if self.check_enable_mode():
self.write_channel(self.normalize_cmd(exit_command))
time.sleep(.3 * delay_factor)
self.set_base_prompt()
if self.check_enable_mode():
raise ValueError("Failed to exit enable mode.")
return output
def enable(self, cmd='sudo su', pattern='ssword', re_flags=re.IGNORECASE):
"""Attempt to become root."""
delay_factor = self.select_delay_factor(delay_factor=0)
output = ""
if not self.check_enable_mode():
self.write_channel(self.normalize_cmd(cmd))
time.sleep(.3 * delay_factor)
try:
output += self.read_channel()
if re.search(pattern, output, flags=re_flags):
self.write_channel(self.normalize_cmd(self.secret))
self.set_base_prompt()
except socket.timeout:
raise NetMikoTimeoutException("Timed-out reading channel, data not available.")
if not self.check_enable_mode():
msg = "Failed to enter enable mode. Please ensure you pass " \
"the 'secret' argument to ConnectHandler."
raise ValueError(msg)
return output<|fim▁end|> | """Verify root""" |
<|file_name|>sk1.js<|end_file_name|><|fim▁begin|>window._skel_config = {
prefix: 'css/style',
preloadStyleSheets: true,
resetCSS: true,
boxModel: 'border',
grid: { gutters: 30 },
breakpoints: {
wide: { range: '1200-', containers: 1140, grid: { gutters: 50 } },
narrow: { range: '481-1199', containers: 960 },
mobile: { range: '-480', containers: 'fluid', lockViewport: true, grid: { collapse: true } }
}
};
$(document).ready(function () {
$("#calculate").click(function () {
var opOne = $("#opOneID").val();
var opTwo = $("#opTwoID").val();
var selected = $('#mathFunction :selected').val();
if (opOne.length != 0) {
$("#resultID").val(process(selected, opOne, opTwo)); // puts the result into the correct dom element resultID on the page.
}
else if (opTwo.length != 0) {
$("#resultID").val(process(selected, opOne, opTwo)); // puts the result into the correct dom element resultID on the page.
}
});
$("#clear").click(function () {
$("#opOneID").val('');
$("#opTwoID").val('');
$("#resultID").val('');
});
$("#pnlRemove").click(function () {
/* this function remove the fron panelof the cube so you can see inside and changes the bottom image which is the manchester United chrest with the image that ]
was the front panel image] this only shows the panels being changed by using code*/
var imageName = 'img/v8liv.PNG';
var changepnl = $('#btmpnl');
var pnlID = $('#v8front');
$(pnlID).hide(); // hide the front panel
$('#btmpnl').attr('src', imageName); // change the bottom image to v8rear.PNG
});
$('#mathFunction :selected').val();
$('#mathFunction').change(function () {
/* this fucntion calls the calucate funtion with the number to be converted with the conversion type which comes from the select tag, eg pk is pounds to kilo's
this function fires when the select dropdown box changes */
var opOne = $("#opOneID").val();
var opTwo = $("#opTwoID").val();<|fim▁hole|> // console.log($('#conversion :selected').val()); //write it out to the console to verify what was
$("#resultID").val(process(selected, opOne,opTwo)); // puts the convertion into the correct dom element on the page.
}).change();
});
function process(selected, opOne,opTwo) {
switch (selected) {
case "+":
return Calc.AddNo(opOne,opTwo);
break;
case "-":
return Calc.SubNo(opOne, opTwo);
break;
case "/":
return Calc.DivideNo(opOne, opTwo);
break;
case "*":
return Calc.MultplyNo(opOne, opTwo);
break;
default:
return "Error ! ";
// code to be executed if n is different from case 1 and 2
}
}<|fim▁end|> | var selected = $('#mathFunction :selected').val();
|
<|file_name|>default.component.ts<|end_file_name|><|fim▁begin|>import { Component, OnDestroy, OnInit, Input } from '@angular/core';
import { control, Collection } from 'openlayers';
import { MapComponent } from '../map.component';
<|fim▁hole|> selector: 'aol-control-defaults',
template: ''
})
export class DefaultControlComponent implements OnInit, OnDestroy {
instance: Collection<control.Control>;
@Input() attribution: boolean;
@Input() attributionOptions: olx.control.AttributionOptions;
@Input() rotate: boolean;
@Input() rotateOptions: olx.control.RotateOptions;
@Input() zoom: boolean;
@Input() zoomOptions: olx.control.ZoomOptions;
constructor(private map: MapComponent) {
}
ngOnInit() {
// console.log('ol.control.defaults init: ', this);
this.instance = control.defaults(this);
this.instance.forEach((control) => this.map.instance.addControl(control));
}
ngOnDestroy() {
// console.log('removing aol-control-defaults');
this.instance.forEach((control) => this.map.instance.removeControl(control));
}
}<|fim▁end|> | @Component({ |
<|file_name|>rssi.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python
# RSSI production test
import serial, sys, optparse, time, fdpexpect
parser = optparse.OptionParser("update_mode")
parser.add_option("--baudrate", type='int', default=57600, help='baud rate')
parser.add_option("--rtscts", action='store_true', default=False, help='enable rtscts')<|fim▁hole|>parser.add_option("--xonxoff", action='store_true', default=False, help='enable xonxoff')
opts, args = parser.parse_args()
if len(args) == 0:
print("usage: rssi.py <DEVICE...>")
sys.exit(1)
def rssi(device):
port = serial.Serial(device, opts.baudrate, timeout=0,
dsrdtr=opts.dsrdtr, rtscts=opts.rtscts, xonxoff=opts.xonxoff)
ser = fdpexpect.fdspawn(port.fileno(), logfile=sys.stdout)
ser.send('+++')
time.sleep(1)
ser.send('\r\nATI\r\n')
try:
ser.expect(['OK','SiK .* on HM-TRP'], timeout=2)
except fdpexpect.TIMEOUT:
print("timeout")
return
ser.send('AT&F\r\n')
try:
ser.expect(['OK'], timeout=2)
except fdpexpect.TIMEOUT:
print("timeout")
return
ser.send('AT&T=RSSI\r\n')
ctr = 0
while ctr < 200:
try:
count = port.inWaiting()
if count == 0:
count = 1
buf = port.read(count)
if len(buf) == 0:
continue
sys.stdout.write(buf)
sys.stdout.flush()
ctr = ctr + 1
except KeyboardInterrupt:
sys.exit(0)
port.close()
for d in args:
print("Putting %s into rssi test mode" % d)
rssi(d)<|fim▁end|> | parser.add_option("--dsrdtr", action='store_true', default=False, help='enable dsrdtr') |
<|file_name|>qimage_test.py<|end_file_name|><|fim▁begin|>'''Test cases for QImage'''
import unittest
import py3kcompat as py3k
from PySide.QtGui import *
from helper import UsesQApplication, adjust_filename
xpm = [
"27 22 206 2",
" c None",
". c #FEFEFE",
"+ c #FFFFFF",
"@ c #F9F9F9",
"# c #ECECEC",
"$ c #D5D5D5",
"% c #A0A0A0",
"& c #767676",
"* c #525252",
"= c #484848",
"- c #4E4E4E",
"; c #555555",
"> c #545454",
", c #5A5A5A",
"' c #4B4B4B",
") c #4A4A4A",
"! c #4F4F4F",
"~ c #585858",
"{ c #515151",
"] c #4C4C4C",
"^ c #B1B1B1",
"/ c #FCFCFC",
"( c #FDFDFD",
"_ c #C1C1C1",
": c #848484",
"< c #616161",
"[ c #5E5E5E",
"} c #CECECE",
"| c #E2E2E2",
"1 c #E4E4E4",
"2 c #DFDFDF",
"3 c #D2D2D2",
"4 c #D8D8D8",
"5 c #D4D4D4",
"6 c #E6E6E6",
"7 c #F1F1F1",
"8 c #838383",
"9 c #8E8E8E",
"0 c #8F8F8F",
"a c #CBCBCB",
"b c #CCCCCC",
"c c #E9E9E9",
"d c #F2F2F2",
"e c #EDEDED",
"f c #B5B5B5",
"g c #A6A6A6",
"h c #ABABAB",
"i c #BBBBBB",
"j c #B0B0B0",
"k c #EAEAEA",
"l c #6C6C6C",
"m c #BCBCBC",
"n c #F5F5F5",
"o c #FAFAFA",
"p c #B6B6B6",
"q c #F3F3F3",
"r c #CFCFCF",
"s c #FBFBFB",
"t c #CDCDCD",
"u c #DDDDDD",
"v c #999999",
"w c #F0F0F0",
"x c #2B2B2B",
"y c #C3C3C3",
"z c #A4A4A4",
"A c #D7D7D7",
"B c #E7E7E7",
"C c #6E6E6E",
"D c #9D9D9D",
"E c #BABABA",
"F c #AEAEAE",
"G c #898989",
"H c #646464",
"I c #BDBDBD",
"J c #CACACA",
"K c #2A2A2A",
"L c #212121",
"M c #B7B7B7",
"N c #F4F4F4",
"O c #737373",
"P c #828282",
"Q c #4D4D4D",
"R c #000000",
"S c #151515",
"T c #B2B2B2",
"U c #D6D6D6",
"V c #D3D3D3",
"W c #2F2F2F",
"X c #636363",
"Y c #A1A1A1",
"Z c #BFBFBF",
"` c #E0E0E0",
" . c #6A6A6A",
".. c #050505",
"+. c #A3A3A3",
"@. c #202020",
"#. c #5F5F5F",
"$. c #B9B9B9",
"%. c #C7C7C7",
"&. c #D0D0D0",
"*. c #3E3E3E",
"=. c #666666",
"-. c #DBDBDB",
";. c #424242",
">. c #C2C2C2",
",. c #1A1A1A",
"'. c #2C2C2C",
"). c #F6F6F6",
"!. c #AAAAAA",
"~. c #DCDCDC",
"{. c #2D2D2D",
"]. c #2E2E2E",
"^. c #A7A7A7",
"/. c #656565",
"(. c #333333",
"_. c #464646",
":. c #C4C4C4",
"<. c #B8B8B8",
"[. c #292929",
"}. c #979797",
"|. c #EFEFEF",
"1. c #909090",
"2. c #8A8A8A",
"3. c #575757",
"4. c #676767",
"5. c #C5C5C5",
"6. c #7A7A7A",
"7. c #797979",
"8. c #989898",
"9. c #EEEEEE",
"0. c #707070",
"a. c #C8C8C8",
"b. c #111111",
"c. c #AFAFAF",
"d. c #474747",
"e. c #565656",
"f. c #E3E3E3",
"g. c #494949",
"h. c #5B5B5B",
"i. c #222222",
"j. c #353535",
"k. c #D9D9D9",
"l. c #0A0A0A",
"m. c #858585",
"n. c #E5E5E5",
"o. c #0E0E0E",
"p. c #9A9A9A",
"q. c #6F6F6F",
"r. c #868686",
"s. c #060606",
"t. c #1E1E1E",
"u. c #E8E8E8",
"v. c #A5A5A5",
"w. c #0D0D0D",
"x. c #030303",
"y. c #272727",
"z. c #131313",
"A. c #1F1F1F",
"B. c #757575",
"C. c #F7F7F7",
"D. c #414141",
"E. c #080808",
"F. c #6B6B6B",
"G. c #313131",
"H. c #C0C0C0",
"I. c #C9C9C9",
"J. c #0B0B0B",
"K. c #232323",
"L. c #434343",
"M. c #3D3D3D",
"N. c #282828",
"O. c #7C7C7C",
"P. c #252525",
"Q. c #3A3A3A",
"R. c #F8F8F8",
"S. c #1B1B1B",
"T. c #949494",
"U. c #3B3B3B",
"V. c #242424",
"W. c #383838",
"X. c #6D6D6D",
"Y. c #818181",
"Z. c #939393",
"`. c #9E9E9E",
" + c #929292",
".+ c #7D7D7D",
"++ c #ADADAD",
"@+ c #DADADA",
"#+ c #919191",
"$+ c #E1E1E1",
"%+ c #BEBEBE",
"&+ c #ACACAC",
"*+ c #9C9C9C",
"=+ c #B3B3B3",
"-+ c #808080",
";+ c #A8A8A8",
">+ c #393939",
",+ c #747474",
"'+ c #7F7F7F",
")+ c #D1D1D1",
"!+ c #606060",
"~+ c #5C5C5C",
"{+ c #686868",
"]+ c #7E7E7E",
"^+ c #787878",
"/+ c #595959",
". . . + @ # $ % & * = - ; > , ' ) ! ~ { ] ^ / . . + + ",
". ( + _ : < [ & } | 1 2 $ 3 4 5 3 6 7 + + 8 9 + . + . ",
". + 0 9 a ( 3 a b c d e c f g h i g j $ k + l m + . + ",
"+ 2 8 n o p | ( q r s . # t + + + u ^ v e w + x + + + ",<|fim▁hole|> "Q >.C ,.'.} e + ).!.k + . + + . ~.{.> ].x f 7 ^./.k (.",
"_.:.4 @ <.[.}.|.1.2.+ + + >.} 4 B + ( @ _ 3.4.5.6.r 7.",
"3.8.9.~ 0.+ a.Q b.+ + c.d.#.=.$ |.b #.e.z ^ ; ^. .f.g.",
"-.h.+ i.S M + # p j.% n 9.5.k.H l.m.V ^.n.o.M + M p.q.",
"7 r.N s.1.R t.<.|.| u.v.~ w.x.E + s y.z.A.B.C.+ 5 D.q ",
").p.2 E.0.9 F.%.O {._ @.+ + i { [ i.G.H.P I.+ s q.} + ",
").p.6 J.R b.K.L.M.A.! b.g.K [.R M k + N.I + + >.O.+ . ",
").8.9.N.P...R R R R E.t.W n.+ Q.R.6 @.| + . + S.+ + . ",
"n }.w T.U.B.<.i.@ Y + + U.+ c u V.= B B 7 u.W.c + . + ",
"N T.# + }.X.Y.,.8.F.8 Z.[.`. +.+}.4 ++@+O.< ~.+ ( . + ",
"d #+1 + _ ~.u.$+b $.y @+| $+%+I.&+k.h W +.9.+ ( . + . ",
"w 0 |.*+. >.<.=+++++p a.p -+;+5.k.>+,+@ + . . + . + + ",
"q '+9.R.^ I.t b %.I.)+4 $+n.I.,+ .|.+ . . . + . + + + ",
". p !+( + + + + + + E 0. .-+8.f.+ + . . + + . + + + + ",
". ( A ~+{+]+^+l > /+D f.c q . + . . + + . + + + + + + "
]
class QImageTest(UsesQApplication):
'''Test case for calling setPixel with float as argument'''
def testQImageStringBuffer(self):
'''Test if the QImage signatures receiving string buffers exist.'''
img0 = QImage(adjust_filename('sample.png', __file__))
# btw let's test the bits() method
img1 = QImage(img0.bits(), img0.width(), img0.height(), img0.format())
self.assertEqual(img0, img1)
img2 = QImage(img0.bits(), img0.width(), img0.height(), img0.bytesPerLine(), img0.format())
self.assertEqual(img0, img2)
## test scanLine method
data1 = img0.scanLine(0)
data2 = img1.scanLine(0)
self.assertEqual(data1, data2)
# PySide python 3.x does not support slice yet
if not py3k.IS_PY3K:
buff = py3k.buffer(img0.bits()[:img0.bytesPerLine()])
self.assertEqual(data1, buff)
self.assertEqual(data2, buff)
def testEmptyBuffer(self):
img = QImage(py3k.buffer(''), 100, 100, QImage.Format_ARGB32)
def testEmptyStringAsBuffer(self):
img = QImage(py3k.b(''), 100, 100, QImage.Format_ARGB32)
def testXpmConstructor(self):
label = QLabel()
img = QImage(xpm)
self.assertFalse(img.isNull())
self.assertEqual(img.width(), 27)
self.assertEqual(img.height(), 22)
if __name__ == '__main__':
unittest.main()<|fim▁end|> | "+ y z . @ A k B 7 n + ( s | p 8 C D 2 E 4 + + F G + . ",
"# H I $ J G K L - M N . 2 O P Q R R S T U s s V W j + ",
"X Y Z @ o ` _ g ...+.( 4 @.#.m G $.%.7 &.X *.=.-.;.&.", |
<|file_name|>LKDemoController.java<|end_file_name|><|fim▁begin|>package com.lichkin.framework.springboot.controllers.impl;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;
import com.lichkin.framework.bases.LKDatas;
import com.lichkin.framework.bases.annotations.WithOutLogin;
import com.lichkin.framework.springboot.controllers.LKController;
<|fim▁hole|> */
@Controller
@RequestMapping(value = "/demo")
public class LKDemoController extends LKController {
/**
* 页面跳转
* @param requestDatas 请求参数,由框架自动解析请求的参数并注入。
* @param subUrl 子路径
* @return 页面路径,附带了请求参数及请求路径的相关信息。
*/
@WithOutLogin
@RequestMapping(value = "/{subUrl}.html", method = RequestMethod.GET)
public ModelAndView toGo(final LKDatas requestDatas, @PathVariable(value = "subUrl") final String subUrl) {
return getModelAndView(requestDatas);
}
}<|fim▁end|> | /**
* 页面跳转逻辑
* @author SuZhou LichKin Information Technology Co., Ltd.
|
<|file_name|>ed.js<|end_file_name|><|fim▁begin|>/*global chrome */<|fim▁hole|>// Check if the feature is enable
let promise = new Promise(function (resolve) {
chrome.storage.sync.get({
isEdEnable: true
}, function (items) {
if (items.isEdEnable === true) {
resolve();
}
});
});
promise.then(function () {
/*global removeIfExist */
/*eslint no-undef: "error"*/
removeIfExist(".blockheader");
removeIfExist(".blockcontent .upload-infos");
removeIfExist(".blockfooter");
});<|fim▁end|> | |
<|file_name|>bitcoin_bs.ts<|end_file_name|><|fim▁begin|><?xml version="1.0" ?><!DOCTYPE TS><TS language="bs" version="2.0">
<defaultcodec>UTF-8</defaultcodec>
<context>
<name>AboutDialog</name>
<message>
<location filename="../forms/aboutdialog.ui" line="+14"/>
<source>About Ponscoin</source>
<translation>O Ponscoinu</translation>
</message>
<message>
<location line="+39"/>
<source><b>Ponscoin</b> version</source>
<translation><b>Ponscoin</b> verzija</translation>
</message>
<message>
<location line="+57"/>
<source>
This is experimental software.
Distributed under the MIT/X11 software license, see the accompanying file COPYING or http://www.opensource.org/licenses/mit-license.php.
This product includes software developed by the OpenSSL Project for use in the OpenSSL Toolkit (http://www.openssl.org/) and cryptographic software written by Eric Young ([email protected]) and UPnP software written by Thomas Bernard.</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../aboutdialog.cpp" line="+14"/>
<source>Copyright</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+0"/>
<source>The Ponscoin developers</source>
<translation type="unfinished"/>
</message>
</context>
<context>
<name>AddressBookPage</name>
<message>
<location filename="../forms/addressbookpage.ui" line="+14"/>
<source>Address Book</source>
<translation>Adresar</translation>
</message>
<message>
<location line="+19"/>
<source>Double-click to edit address or label</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+27"/>
<source>Create a new address</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+14"/>
<source>Copy the currently selected address to the system clipboard</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-11"/>
<source>&New Address</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../addressbookpage.cpp" line="+63"/>
<source>These are your Ponscoin addresses for receiving payments. You may want to give a different one to each sender so you can keep track of who is paying you.</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../forms/addressbookpage.ui" line="+14"/>
<source>&Copy Address</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+11"/>
<source>Show &QR Code</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+11"/>
<source>Sign a message to prove you own a Ponscoin address</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Sign &Message</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+25"/>
<source>Delete the currently selected address from the list</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+27"/>
<source>Export the data in the current tab to a file</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>&Export</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-44"/>
<source>Verify a message to ensure it was signed with a specified Ponscoin address</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>&Verify Message</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+14"/>
<source>&Delete</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../addressbookpage.cpp" line="-5"/>
<source>These are your Ponscoin addresses for sending payments. Always check the amount and the receiving address before sending coins.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+13"/>
<source>Copy &Label</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>&Edit</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Send &Coins</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+260"/>
<source>Export Address Book Data</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Comma separated file (*.csv)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+13"/>
<source>Error exporting</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+0"/>
<source>Could not write to file %1.</source>
<translation type="unfinished"/>
</message>
</context>
<context>
<name>AddressTableModel</name>
<message>
<location filename="../addresstablemodel.cpp" line="+144"/>
<source>Label</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+0"/>
<source>Address</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+36"/>
<source>(no label)</source>
<translation type="unfinished"/>
</message>
</context>
<context>
<name>AskPassphraseDialog</name>
<message>
<location filename="../forms/askpassphrasedialog.ui" line="+26"/>
<source>Passphrase Dialog</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+21"/>
<source>Enter passphrase</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+14"/>
<source>New passphrase</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+14"/>
<source>Repeat new passphrase</source>
<translation type="unfinished"/>
</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 type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Encrypt wallet</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>This operation needs your wallet passphrase to unlock the wallet.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+5"/>
<source>Unlock wallet</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>This operation needs your wallet passphrase to decrypt the wallet.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+5"/>
<source>Decrypt wallet</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Change passphrase</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Enter the old and new passphrase to the wallet.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+46"/>
<source>Confirm wallet encryption</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Warning: If you encrypt your wallet and lose your passphrase, you will <b>LOSE ALL OF YOUR LITECOINS</b>!</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+0"/>
<source>Are you sure you wish to encrypt your wallet?</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+15"/>
<source>IMPORTANT: Any previous backups you have made of your wallet file should be replaced with the newly generated, encrypted wallet file. For security reasons, previous backups of the unencrypted wallet file will become useless as soon as you start using the new, encrypted wallet.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+100"/>
<location line="+24"/>
<source>Warning: The Caps Lock key is on!</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-130"/>
<location line="+58"/>
<source>Wallet encrypted</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-56"/>
<source>Ponscoin will close now to finish the encryption process. Remember that encrypting your wallet cannot fully protect your ponscoins from being stolen by malware infecting your computer.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+13"/>
<location line="+7"/>
<location line="+42"/>
<location line="+6"/>
<source>Wallet encryption failed</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-54"/>
<source>Wallet encryption failed due to an internal error. Your wallet was not encrypted.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+7"/>
<location line="+48"/>
<source>The supplied passphrases do not match.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-37"/>
<source>Wallet unlock failed</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<location line="+11"/>
<location line="+19"/>
<source>The passphrase entered for the wallet decryption was incorrect.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-20"/>
<source>Wallet decryption failed</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+14"/>
<source>Wallet passphrase was successfully changed.</source>
<translation type="unfinished"/>
</message>
</context>
<context>
<name>BitcoinGUI</name>
<message>
<location filename="../bitcoingui.cpp" line="+233"/>
<source>Sign &message...</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+280"/>
<source>Synchronizing with network...</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-349"/>
<source>&Overview</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Show general overview of wallet</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+20"/>
<source>&Transactions</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Browse transaction history</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+7"/>
<source>Edit the list of stored addresses and labels</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-14"/>
<source>Show the list of addresses for receiving payments</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+31"/>
<source>E&xit</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Quit application</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+4"/>
<source>Show information about Ponscoin</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>About &Qt</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Show information about Qt</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>&Options...</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+6"/>
<source>&Encrypt Wallet...</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>&Backup Wallet...</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>&Change Passphrase...</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+285"/>
<source>Importing blocks from disk...</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Reindexing blocks on disk...</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-347"/>
<source>Send coins to a Ponscoin address</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+49"/>
<source>Modify configuration options for Ponscoin</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+9"/>
<source>Backup wallet to another location</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>Change the passphrase used for wallet encryption</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+6"/>
<source>&Debug window</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Open debugging and diagnostic console</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-4"/>
<source>&Verify message...</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-165"/>
<location line="+530"/>
<source>Ponscoin</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-530"/>
<source>Wallet</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+101"/>
<source>&Send</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+7"/>
<source>&Receive</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+14"/>
<source>&Addresses</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+22"/>
<source>&About Ponscoin</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+9"/>
<source>&Show / Hide</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Show or hide the main Window</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Encrypt the private keys that belong to your wallet</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+7"/>
<source>Sign messages with your Ponscoin addresses to prove you own them</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>Verify messages to ensure they were signed with specified Ponscoin addresses</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+28"/>
<source>&File</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+7"/>
<source>&Settings</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+6"/>
<source>&Help</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+9"/>
<source>Tabs toolbar</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+17"/>
<location line="+10"/>
<source>[testnet]</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+47"/>
<source>Ponscoin client</source>
<translation type="unfinished"/>
</message>
<message numerus="yes">
<location line="+141"/>
<source>%n active connection(s) to Ponscoin network</source>
<translation type="unfinished"><numerusform></numerusform><numerusform></numerusform><numerusform></numerusform></translation>
</message>
<message>
<location line="+22"/>
<source>No block source available...</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+12"/>
<source>Processed %1 of %2 (estimated) blocks of transaction history.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+4"/>
<source>Processed %1 blocks of transaction history.</source>
<translation type="unfinished"/>
</message>
<message numerus="yes">
<location line="+20"/>
<source>%n hour(s)</source>
<translation type="unfinished"><numerusform></numerusform><numerusform></numerusform><numerusform></numerusform></translation>
</message>
<message numerus="yes">
<location line="+4"/>
<source>%n day(s)</source>
<translation type="unfinished"><numerusform></numerusform><numerusform></numerusform><numerusform></numerusform></translation>
</message>
<message numerus="yes">
<location line="+4"/>
<source>%n week(s)</source>
<translation type="unfinished"><numerusform></numerusform><numerusform></numerusform><numerusform></numerusform></translation>
</message>
<message>
<location line="+4"/>
<source>%1 behind</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+14"/>
<source>Last received block was generated %1 ago.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>Transactions after this will not yet be visible.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+22"/>
<source>Error</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Warning</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Information</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+70"/>
<source>This transaction is over the size limit. You can still send it for a fee of %1, which goes to the nodes that process your transaction and helps to support the network. Do you want to pay the fee?</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-140"/>
<source>Up to date</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+31"/>
<source>Catching up...</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+113"/>
<source>Confirm transaction fee</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+8"/>
<source>Sent transaction</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+0"/>
<source>Incoming transaction</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Date: %1
Amount: %2
Type: %3
Address: %4
</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+33"/>
<location line="+23"/>
<source>URI handling</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-23"/>
<location line="+23"/>
<source>URI can not be parsed! This can be caused by an invalid Ponscoin address or malformed URI parameters.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+17"/>
<source>Wallet is <b>encrypted</b> and currently <b>unlocked</b></source>
<translation type="unfinished"/>
</message>
<message>
<location line="+8"/>
<source>Wallet is <b>encrypted</b> and currently <b>locked</b></source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../bitcoin.cpp" line="+111"/>
<source>A fatal error occurred. Ponscoin can no longer continue safely and will quit.</source>
<translation type="unfinished"/>
</message>
</context>
<context>
<name>ClientModel</name>
<message>
<location filename="../clientmodel.cpp" line="+104"/>
<source>Network Alert</source>
<translation type="unfinished"/>
</message>
</context>
<context>
<name>EditAddressDialog</name>
<message>
<location filename="../forms/editaddressdialog.ui" line="+14"/>
<source>Edit Address</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+11"/>
<source>&Label</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+10"/>
<source>The label associated with this address book entry</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+7"/>
<source>&Address</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+10"/>
<source>The address associated with this address book entry. This can only be modified for sending addresses.</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../editaddressdialog.cpp" line="+21"/>
<source>New receiving address</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+4"/>
<source>New sending address</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Edit receiving address</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+4"/>
<source>Edit sending address</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+76"/>
<source>The entered address "%1" is already in the address book.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-5"/>
<source>The entered address "%1" is not a valid Ponscoin address.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+10"/>
<source>Could not unlock wallet.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+5"/>
<source>New key generation failed.</source>
<translation type="unfinished"/>
</message>
</context>
<context>
<name>GUIUtil::HelpMessageBox</name>
<message>
<location filename="../guiutil.cpp" line="+424"/>
<location line="+12"/>
<source>Ponscoin-Qt</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-12"/>
<source>version</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>Usage:</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>command-line options</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+4"/>
<source>UI options</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Set language, for example "de_DE" (default: system locale)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Start minimized</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Show splash screen on startup (default: 1)</source>
<translation type="unfinished"/>
</message>
</context>
<context>
<name>OptionsDialog</name>
<message>
<location filename="../forms/optionsdialog.ui" line="+14"/>
<source>Options</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+16"/>
<source>&Main</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+6"/>
<source>Optional transaction fee per kB that helps make sure your transactions are processed quickly. Most transactions are 1 kB.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+15"/>
<source>Pay transaction &fee</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+31"/>
<source>Automatically start Ponscoin after logging in to the system.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>&Start Ponscoin on system login</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+35"/>
<source>Reset all client options to default.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>&Reset Options</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+13"/>
<source>&Network</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+6"/>
<source>Automatically open the Ponscoin client port on the router. This only works when your router supports UPnP and it is enabled.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Map port using &UPnP</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+7"/>
<source>Connect to the Ponscoin network through a SOCKS proxy (e.g. when connecting through Tor).</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>&Connect through SOCKS proxy:</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+9"/>
<source>Proxy &IP:</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+19"/>
<source>IP address of the proxy (e.g. 127.0.0.1)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+7"/>
<source>&Port:</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+19"/>
<source>Port of the proxy (e.g. 9050)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+7"/>
<source>SOCKS &Version:</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+13"/>
<source>SOCKS version of the proxy (e.g. 5)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+36"/>
<source>&Window</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+6"/>
<source>Show only a tray icon after minimizing the window.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>&Minimize to the tray instead of the taskbar</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+7"/>
<source>Minimize instead of exit the application when the window is closed. When this option is enabled, the application will be closed only after selecting Quit in the menu.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>M&inimize on close</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+21"/>
<source>&Display</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+8"/>
<source>User Interface &language:</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+13"/>
<source>The user interface language can be set here. This setting will take effect after restarting Ponscoin.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+11"/>
<source>&Unit to show amounts in:</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+13"/>
<source>Choose the default subdivision unit to show in the interface and when sending coins.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+9"/>
<source>Whether to show Ponscoin addresses in the transaction list or not.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>&Display addresses in transaction list</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+71"/>
<source>&OK</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+7"/>
<source>&Cancel</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+10"/>
<source>&Apply</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../optionsdialog.cpp" line="+53"/>
<source>default</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+130"/>
<source>Confirm options reset</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Some settings may require a client restart to take effect.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+0"/>
<source>Do you want to proceed?</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+42"/>
<location line="+9"/>
<source>Warning</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-9"/>
<location line="+9"/>
<source>This setting will take effect after restarting Ponscoin.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+29"/>
<source>The supplied proxy address is invalid.</source>
<translation type="unfinished"/>
</message>
</context>
<context>
<name>OverviewPage</name>
<message>
<location filename="../forms/overviewpage.ui" line="+14"/>
<source>Form</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+50"/>
<location line="+166"/>
<source>The displayed information may be out of date. Your wallet automatically synchronizes with the Ponscoin network after a connection is established, but this process has not completed yet.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-124"/>
<source>Balance:</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+29"/>
<source>Unconfirmed:</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-78"/>
<source>Wallet</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+107"/>
<source>Immature:</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+13"/>
<source>Mined balance that has not yet matured</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+46"/>
<source><b>Recent transactions</b></source>
<translation type="unfinished"/>
</message>
<message>
<location line="-101"/>
<source>Your current balance</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+29"/>
<source>Total of transactions that have yet to be confirmed, and do not yet count toward the current balance</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../overviewpage.cpp" line="+116"/>
<location line="+1"/>
<source>out of sync</source>
<translation type="unfinished"/>
</message>
</context>
<context>
<name>PaymentServer</name>
<message>
<location filename="../paymentserver.cpp" line="+107"/>
<source>Cannot start ponscoin: click-to-pay handler</source>
<translation type="unfinished"/>
</message>
</context>
<context>
<name>QRCodeDialog</name>
<message>
<location filename="../forms/qrcodedialog.ui" line="+14"/>
<source>QR Code Dialog</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+59"/>
<source>Request Payment</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+56"/>
<source>Amount:</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-44"/>
<source>Label:</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+19"/>
<source>Message:</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+71"/>
<source>&Save As...</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../qrcodedialog.cpp" line="+62"/>
<source>Error encoding URI into QR Code.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+40"/>
<source>The entered amount is invalid, please check.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+23"/>
<source>Resulting URI too long, try to reduce the text for label / message.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+25"/>
<source>Save QR Code</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+0"/>
<source>PNG Images (*.png)</source>
<translation type="unfinished"/>
</message>
</context>
<context>
<name>RPCConsole</name>
<message>
<location filename="../forms/rpcconsole.ui" line="+46"/>
<source>Client name</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+10"/>
<location line="+23"/>
<location line="+26"/>
<location line="+23"/>
<location line="+23"/>
<location line="+36"/>
<location line="+53"/>
<location line="+23"/>
<location line="+23"/>
<location filename="../rpcconsole.cpp" line="+339"/>
<source>N/A</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-217"/>
<source>Client version</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-45"/>
<source>&Information</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+68"/>
<source>Using OpenSSL version</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+49"/>
<source>Startup time</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+29"/>
<source>Network</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+7"/>
<source>Number of connections</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+23"/>
<source>On testnet</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+23"/>
<source>Block chain</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+7"/>
<source>Current number of blocks</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+23"/>
<source>Estimated total blocks</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+23"/>
<source>Last block time</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+52"/>
<source>&Open</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+16"/>
<source>Command-line options</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+7"/>
<source>Show the Ponscoin-Qt help message to get a list with possible Ponscoin command-line options.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>&Show</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+24"/>
<source>&Console</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-260"/>
<source>Build date</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-104"/>
<source>Ponscoin - Debug window</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+25"/>
<source>Ponscoin Core</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+279"/>
<source>Debug log file</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+7"/>
<source>Open the Ponscoin debug log file from the current data directory. This can take a few seconds for large log files.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+102"/>
<source>Clear console</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../rpcconsole.cpp" line="-30"/>
<source>Welcome to the Ponscoin RPC console.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Use up and down arrows to navigate history, and <b>Ctrl-L</b> to clear screen.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Type <b>help</b> for an overview of available commands.</source>
<translation type="unfinished"/>
</message>
</context>
<context>
<name>SendCoinsDialog</name>
<message>
<location filename="../forms/sendcoinsdialog.ui" line="+14"/>
<location filename="../sendcoinsdialog.cpp" line="+124"/>
<location line="+5"/>
<location line="+5"/>
<location line="+5"/>
<location line="+6"/>
<location line="+5"/>
<location line="+5"/>
<source>Send Coins</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+50"/>
<source>Send to multiple recipients at once</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Add &Recipient</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+20"/>
<source>Remove all transaction fields</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Clear &All</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+22"/>
<source>Balance:</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+10"/>
<source>123.456 BTC</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+31"/>
<source>Confirm the send action</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>S&end</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../sendcoinsdialog.cpp" line="-59"/>
<source><b>%1</b> to %2 (%3)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+5"/>
<source>Confirm send coins</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Are you sure you want to send %1?</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+0"/>
<source> and </source>
<translation type="unfinished"/>
</message>
<message>
<location line="+23"/>
<source>The recipient address is not valid, please recheck.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+5"/>
<source>The amount to pay must be larger than 0.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+5"/>
<source>The amount exceeds your balance.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+5"/>
<source>The total exceeds your balance when the %1 transaction fee is included.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+6"/>
<source>Duplicate address found, can only send to each address once per send operation.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+5"/>
<source>Error: Transaction creation failed!</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+5"/>
<source>Error: The transaction was rejected. This might happen if some of the coins in your wallet were already spent, such as if you used a copy of wallet.dat and coins were spent in the copy but not marked as spent here.</source>
<translation type="unfinished"/>
</message>
</context>
<context>
<name>SendCoinsEntry</name>
<message>
<location filename="../forms/sendcoinsentry.ui" line="+14"/>
<source>Form</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+15"/>
<source>A&mount:</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+13"/>
<source>Pay &To:</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+34"/>
<source>The address to send the payment to (e.g. Ler4HNAEfwYhBmGXcFP2Po1NpRUEiK8km2)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+60"/>
<location filename="../sendcoinsentry.cpp" line="+26"/>
<source>Enter a label for this address to add it to your address book</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-78"/>
<source>&Label:</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+28"/>
<source>Choose address from address book</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+10"/>
<source>Alt+A</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+7"/>
<source>Paste address from clipboard</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+10"/>
<source>Alt+P</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+7"/>
<source>Remove this recipient</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../sendcoinsentry.cpp" line="+1"/>
<source>Enter a Ponscoin address (e.g. Ler4HNAEfwYhBmGXcFP2Po1NpRUEiK8km2)</source>
<translation type="unfinished"/>
</message>
</context>
<context>
<name>SignVerifyMessageDialog</name>
<message>
<location filename="../forms/signverifymessagedialog.ui" line="+14"/>
<source>Signatures - Sign / Verify a Message</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+13"/>
<source>&Sign Message</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+6"/>
<source>You can sign messages with your addresses to prove you own them. Be careful not to sign anything vague, as phishing attacks may try to trick you into signing your identity over to them. Only sign fully-detailed statements you agree to.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+18"/>
<source>The address to sign the message with (e.g. Ler4HNAEfwYhBmGXcFP2Po1NpRUEiK8km2)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+10"/>
<location line="+213"/>
<source>Choose an address from the address book</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-203"/>
<location line="+213"/>
<source>Alt+A</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-203"/>
<source>Paste address from clipboard</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+10"/>
<source>Alt+P</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+12"/>
<source>Enter the message you want to sign here</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+7"/>
<source>Signature</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+27"/>
<source>Copy the current signature to the system clipboard</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+21"/>
<source>Sign the message to prove you own this Ponscoin address</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Sign &Message</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+14"/>
<source>Reset all sign message fields</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<location line="+146"/>
<source>Clear &All</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-87"/>
<source>&Verify Message</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+6"/>
<source>Enter the signing address, message (ensure you copy line breaks, spaces, tabs, etc. exactly) and signature below to verify the message. Be careful not to read more into the signature than what is in the signed message itself, to avoid being tricked by a man-in-the-middle attack.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+21"/>
<source>The address the message was signed with (e.g. Ler4HNAEfwYhBmGXcFP2Po1NpRUEiK8km2)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+40"/>
<source>Verify the message to ensure it was signed with the specified Ponscoin address</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Verify &Message</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+14"/>
<source>Reset all verify message fields</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../signverifymessagedialog.cpp" line="+27"/>
<location line="+3"/>
<source>Enter a Ponscoin address (e.g. Ler4HNAEfwYhBmGXcFP2Po1NpRUEiK8km2)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-2"/>
<source>Click "Sign Message" to generate signature</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Enter Ponscoin signature</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+82"/>
<location line="+81"/>
<source>The entered address is invalid.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-81"/>
<location line="+8"/>
<location line="+73"/>
<location line="+8"/>
<source>Please check the address and try again.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-81"/>
<location line="+81"/>
<source>The entered address does not refer to a key.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-73"/>
<source>Wallet unlock was cancelled.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+8"/>
<source>Private key for the entered address is not available.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+12"/>
<source>Message signing failed.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+5"/>
<source>Message signed.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+59"/>
<source>The signature could not be decoded.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+0"/>
<location line="+13"/>
<source>Please check the signature and try again.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+0"/>
<source>The signature did not match the message digest.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+7"/>
<source>Message verification failed.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+5"/>
<source>Message verified.</source>
<translation type="unfinished"/>
</message>
</context>
<context>
<name>SplashScreen</name>
<message>
<location filename="../splashscreen.cpp" line="+22"/>
<source>The Ponscoin developers</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>[testnet]</source>
<translation type="unfinished"/>
</message>
</context>
<context>
<name>TransactionDesc</name>
<message>
<location filename="../transactiondesc.cpp" line="+20"/>
<source>Open until %1</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+6"/>
<source>%1/offline</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>%1/unconfirmed</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>%1 confirmations</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+18"/>
<source>Status</source>
<translation type="unfinished"/>
</message>
<message numerus="yes">
<location line="+7"/>
<source>, broadcast through %n node(s)</source>
<translation type="unfinished"><numerusform></numerusform><numerusform></numerusform><numerusform></numerusform></translation>
</message>
<message>
<location line="+4"/>
<source>Date</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+7"/>
<source>Source</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+0"/>
<source>Generated</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+5"/>
<location line="+17"/>
<source>From</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<location line="+22"/>
<location line="+58"/>
<source>To</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-77"/>
<location line="+2"/>
<source>own address</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-2"/>
<source>label</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+37"/>
<location line="+12"/>
<location line="+45"/>
<location line="+17"/>
<location line="+30"/>
<source>Credit</source>
<translation type="unfinished"/>
</message>
<message numerus="yes">
<location line="-102"/>
<source>matures in %n more block(s)</source>
<translation type="unfinished"><numerusform></numerusform><numerusform></numerusform><numerusform></numerusform></translation><|fim▁hole|> <message>
<location line="+2"/>
<source>not accepted</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+44"/>
<location line="+8"/>
<location line="+15"/>
<location line="+30"/>
<source>Debit</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-39"/>
<source>Transaction fee</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+16"/>
<source>Net amount</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+6"/>
<source>Message</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>Comment</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>Transaction ID</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Generated coins must mature 120 blocks before they can be spent. When you generated this block, it was broadcast to the network to be added to the block chain. If it fails to get into the chain, its state will change to "not accepted" and it won't be spendable. This may occasionally happen if another node generates a block within a few seconds of yours.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+7"/>
<source>Debug information</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+8"/>
<source>Transaction</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Inputs</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+23"/>
<source>Amount</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>true</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+0"/>
<source>false</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-209"/>
<source>, has not been successfully broadcast yet</source>
<translation type="unfinished"/>
</message>
<message numerus="yes">
<location line="-35"/>
<source>Open for %n more block(s)</source>
<translation type="unfinished"><numerusform></numerusform><numerusform></numerusform><numerusform></numerusform></translation>
</message>
<message>
<location line="+70"/>
<source>unknown</source>
<translation type="unfinished"/>
</message>
</context>
<context>
<name>TransactionDescDialog</name>
<message>
<location filename="../forms/transactiondescdialog.ui" line="+14"/>
<source>Transaction details</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+6"/>
<source>This pane shows a detailed description of the transaction</source>
<translation type="unfinished"/>
</message>
</context>
<context>
<name>TransactionTableModel</name>
<message>
<location filename="../transactiontablemodel.cpp" line="+225"/>
<source>Date</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+0"/>
<source>Type</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+0"/>
<source>Address</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+0"/>
<source>Amount</source>
<translation type="unfinished"/>
</message>
<message numerus="yes">
<location line="+57"/>
<source>Open for %n more block(s)</source>
<translation type="unfinished"><numerusform></numerusform><numerusform></numerusform><numerusform></numerusform></translation>
</message>
<message>
<location line="+3"/>
<source>Open until %1</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Offline (%1 confirmations)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Unconfirmed (%1 of %2 confirmations)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Confirmed (%1 confirmations)</source>
<translation type="unfinished"/>
</message>
<message numerus="yes">
<location line="+8"/>
<source>Mined balance will be available when it matures in %n more block(s)</source>
<translation type="unfinished"><numerusform></numerusform><numerusform></numerusform><numerusform></numerusform></translation>
</message>
<message>
<location line="+5"/>
<source>This block was not received by any other nodes and will probably not be accepted!</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Generated but not accepted</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+43"/>
<source>Received with</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>Received from</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Sent to</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>Payment to yourself</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>Mined</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+38"/>
<source>(n/a)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+199"/>
<source>Transaction status. Hover over this field to show number of confirmations.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>Date and time that the transaction was received.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>Type of transaction.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>Destination address of transaction.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>Amount removed from or added to balance.</source>
<translation type="unfinished"/>
</message>
</context>
<context>
<name>TransactionView</name>
<message>
<location filename="../transactionview.cpp" line="+52"/>
<location line="+16"/>
<source>All</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-15"/>
<source>Today</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>This week</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>This month</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Last month</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>This year</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Range...</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+11"/>
<source>Received with</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>Sent to</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>To yourself</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Mined</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Other</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+7"/>
<source>Enter address or label to search</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+7"/>
<source>Min amount</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+34"/>
<source>Copy address</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Copy label</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Copy amount</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Copy transaction ID</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Edit label</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Show transaction details</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+139"/>
<source>Export Transaction Data</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Comma separated file (*.csv)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+8"/>
<source>Confirmed</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Date</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Type</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Label</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Address</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Amount</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>ID</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+4"/>
<source>Error exporting</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+0"/>
<source>Could not write to file %1.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+100"/>
<source>Range:</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+8"/>
<source>to</source>
<translation type="unfinished"/>
</message>
</context>
<context>
<name>WalletModel</name>
<message>
<location filename="../walletmodel.cpp" line="+193"/>
<source>Send Coins</source>
<translation type="unfinished"/>
</message>
</context>
<context>
<name>WalletView</name>
<message>
<location filename="../walletview.cpp" line="+42"/>
<source>&Export</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Export the data in the current tab to a file</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+193"/>
<source>Backup Wallet</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+0"/>
<source>Wallet Data (*.dat)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Backup Failed</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+0"/>
<source>There was an error trying to save the wallet data to the new location.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+4"/>
<source>Backup Successful</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+0"/>
<source>The wallet data was successfully saved to the new location.</source>
<translation type="unfinished"/>
</message>
</context>
<context>
<name>bitcoin-core</name>
<message>
<location filename="../bitcoinstrings.cpp" line="+94"/>
<source>Ponscoin version</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+102"/>
<source>Usage:</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-29"/>
<source>Send command to -server or ponscoind</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-23"/>
<source>List commands</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-12"/>
<source>Get help for a command</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+24"/>
<source>Options:</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+24"/>
<source>Specify configuration file (default: ponscoin.conf)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Specify pid file (default: ponscoind.pid)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-1"/>
<source>Specify data directory</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-9"/>
<source>Set database cache size in megabytes (default: 25)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-28"/>
<source>Listen for connections on <port> (default: 9333 or testnet: 19333)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+5"/>
<source>Maintain at most <n> connections to peers (default: 125)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-48"/>
<source>Connect to a node to retrieve peer addresses, and disconnect</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+82"/>
<source>Specify your own public address</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Threshold for disconnecting misbehaving peers (default: 100)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-134"/>
<source>Number of seconds to keep misbehaving peers from reconnecting (default: 86400)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-29"/>
<source>An error occurred while setting up the RPC port %u for listening on IPv4: %s</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+27"/>
<source>Listen for JSON-RPC connections on <port> (default: 9332 or testnet: 19332)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+37"/>
<source>Accept command line and JSON-RPC commands</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+76"/>
<source>Run in the background as a daemon and accept commands</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+37"/>
<source>Use the test network</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-112"/>
<source>Accept connections from outside (default: 1 if no -proxy or -connect)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-80"/>
<source>%s, you must set a rpcpassword in the configuration file:
%s
It is recommended you use the following random password:
rpcuser=ponscoinrpc
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 "Ponscoin Alert" [email protected]
</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+17"/>
<source>An error occurred while setting up the RPC port %u for listening on IPv6, falling back to IPv4: %s</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Bind to given address and always listen on it. Use [host]:port notation for IPv6</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Cannot obtain a lock on data directory %s. Ponscoin is probably already running.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Error: The transaction was rejected! This might happen if some of the coins in your wallet were already spent, such as if you used a copy of wallet.dat and coins were spent in the copy but not marked as spent here.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+4"/>
<source>Error: This transaction requires a transaction fee of at least %s because of its amount, complexity, or use of recently received funds!</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Execute command when a relevant alert is received (%s in cmd is replaced by message)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Execute command when a wallet transaction changes (%s in cmd is replaced by TxID)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+11"/>
<source>Set maximum size of high-priority/low-fee transactions in bytes (default: 27000)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+6"/>
<source>This is a pre-release test build - use at your own risk - do not use for mining or merchant applications</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+5"/>
<source>Warning: -paytxfee is set very high! This is the transaction fee you will pay if you send a transaction.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Warning: Displayed transactions may not be correct! You may need to upgrade, or other nodes may need to upgrade.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Warning: Please check that your computer's date and time are correct! If your clock is wrong Ponscoin will not work properly.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Warning: error reading wallet.dat! All keys read correctly, but transaction data or address book entries might be missing or incorrect.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Warning: wallet.dat corrupt, data salvaged! Original wallet.dat saved as wallet.{timestamp}.bak in %s; if your balance or transactions are incorrect you should restore from a backup.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+14"/>
<source>Attempt to recover private keys from a corrupt wallet.dat</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>Block creation options:</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+5"/>
<source>Connect only to the specified node(s)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Corrupted block database detected</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Discover own IP address (default: 1 when listening and no -externalip)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Do you want to rebuild the block database now?</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>Error initializing block database</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Error initializing wallet database environment %s!</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Error loading block database</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+4"/>
<source>Error opening block database</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>Error: Disk space is low!</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Error: Wallet locked, unable to create transaction!</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Error: system error: </source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Failed to listen on any port. Use -listen=0 if you want this.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Failed to read block info</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Failed to read block</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Failed to sync block index</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Failed to write block index</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Failed to write block info</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Failed to write block</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Failed to write file info</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Failed to write to coin database</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Failed to write transaction index</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Failed to write undo data</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>Find peers using DNS lookup (default: 1 unless -connect)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Generate coins (default: 0)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>How many blocks to check at startup (default: 288, 0 = all)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>How thorough the block verification is (0-4, default: 3)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+19"/>
<source>Not enough file descriptors available.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+8"/>
<source>Rebuild block chain index from current blk000??.dat files</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+16"/>
<source>Set the number of threads to service RPC calls (default: 4)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+26"/>
<source>Verifying blocks...</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Verifying wallet...</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-69"/>
<source>Imports blocks from external blk000??.dat file</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-76"/>
<source>Set the number of script verification threads (up to 16, 0 = auto, <0 = leave that many cores free, default: 0)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+77"/>
<source>Information</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Invalid -tor address: '%s'</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Invalid amount for -minrelaytxfee=<amount>: '%s'</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Invalid amount for -mintxfee=<amount>: '%s'</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+8"/>
<source>Maintain a full transaction index (default: 0)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>Maximum per-connection receive buffer, <n>*1000 bytes (default: 5000)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Maximum per-connection send buffer, <n>*1000 bytes (default: 1000)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>Only accept block chain matching built-in checkpoints (default: 1)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Only connect to nodes in network <net> (IPv4, IPv6 or Tor)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>Output extra debugging information. Implies all other -debug* options</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Output extra network debugging information</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>Prepend debug output with timestamp</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+5"/>
<source>SSL options: (see the Ponscoin Wiki for SSL setup instructions)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Select the version of socks proxy to use (4-5, default: 5)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Send trace/debug info to console instead of debug.log file</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Send trace/debug info to debugger</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+5"/>
<source>Set maximum block size in bytes (default: 250000)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Set minimum block size in bytes (default: 0)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>Shrink debug.log file on client startup (default: 1 when no -debug)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Signing transaction failed</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>Specify connection timeout in milliseconds (default: 5000)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+4"/>
<source>System error: </source>
<translation type="unfinished"/>
</message>
<message>
<location line="+4"/>
<source>Transaction amount too small</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Transaction amounts must be positive</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Transaction too large</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+7"/>
<source>Use UPnP to map the listening port (default: 0)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Use UPnP to map the listening port (default: 1 when listening)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Use proxy to reach tor hidden services (default: same as -proxy)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>Username for JSON-RPC connections</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+4"/>
<source>Warning</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Warning: This version is obsolete, upgrade required!</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>You need to rebuild the databases using -reindex to change -txindex</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>wallet.dat corrupt, salvage failed</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-50"/>
<source>Password for JSON-RPC connections</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-67"/>
<source>Allow JSON-RPC connections from specified IP address</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+76"/>
<source>Send commands to node running on <ip> (default: 127.0.0.1)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-120"/>
<source>Execute command when the best block changes (%s in cmd is replaced by block hash)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+147"/>
<source>Upgrade wallet to latest format</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-21"/>
<source>Set key pool size to <n> (default: 100)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-12"/>
<source>Rescan the block chain for missing wallet transactions</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+35"/>
<source>Use OpenSSL (https) for JSON-RPC connections</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-26"/>
<source>Server certificate file (default: server.cert)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Server private key (default: server.pem)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-151"/>
<source>Acceptable ciphers (default: TLSv1+HIGH:!SSLv2:!aNULL:!eNULL:!AH:!3DES:@STRENGTH)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+165"/>
<source>This help message</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+6"/>
<source>Unable to bind to %s on this computer (bind returned error %d, %s)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-91"/>
<source>Connect through socks proxy</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-10"/>
<source>Allow DNS lookups for -addnode, -seednode and -connect</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+55"/>
<source>Loading addresses...</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-35"/>
<source>Error loading wallet.dat: Wallet corrupted</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Error loading wallet.dat: Wallet requires newer version of Ponscoin</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+93"/>
<source>Wallet needed to be rewritten: restart Ponscoin to complete</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-95"/>
<source>Error loading wallet.dat</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+28"/>
<source>Invalid -proxy address: '%s'</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+56"/>
<source>Unknown network specified in -onlynet: '%s'</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-1"/>
<source>Unknown -socks proxy version requested: %i</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-96"/>
<source>Cannot resolve -bind address: '%s'</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Cannot resolve -externalip address: '%s'</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+44"/>
<source>Invalid amount for -paytxfee=<amount>: '%s'</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Invalid amount</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-6"/>
<source>Insufficient funds</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+10"/>
<source>Loading block index...</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-57"/>
<source>Add a node to connect to and attempt to keep the connection open</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-25"/>
<source>Unable to bind to %s on this computer. Ponscoin is probably already running.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+64"/>
<source>Fee per KB to add to transactions you send</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+19"/>
<source>Loading wallet...</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-52"/>
<source>Cannot downgrade wallet</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Cannot write default address</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+64"/>
<source>Rescanning...</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-57"/>
<source>Done loading</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+82"/>
<source>To use the %s option</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-74"/>
<source>Error</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-31"/>
<source>You must set rpcpassword=<password> in the configuration file:
%s
If the file does not exist, create it with owner-readable-only file permissions.</source>
<translation type="unfinished"/>
</message>
</context>
</TS><|fim▁end|> | </message> |
<|file_name|>DXImageTransform.Microsoft.MaskFilter.js<|end_file_name|><|fim▁begin|>class dximagetransform_microsoft_maskfilter {
constructor() {
// Variant Color () {get} {set}
this.Color = undefined;<|fim▁hole|>}
module.exports = dximagetransform_microsoft_maskfilter;<|fim▁end|> |
}
|
<|file_name|>build.rs<|end_file_name|><|fim▁begin|>fn main() {
let out_dir = std::env::var("OUT_DIR").unwrap();
let out_path = |f : &str| format!("{}/{}", out_dir, f);
std::process::Command::new("gcc")<|fim▁hole|> &out_path("morpha_interface.o")])
.status().unwrap();
std::process::Command::new("ar")
.args(&["-crs", &out_path("/libmorpha_interface.a"),
&out_path("/morpha_interface.o")])
.status().unwrap();
println!("cargo:rustc-link-search=native={}", out_dir);
println!("cargo:rustc-link-lib=static=morpha_interface");
}<|fim▁end|> | .args(&["src/morpha_interface.c", "-c", "-fPIC", "-o", |
<|file_name|>i18n.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
*/
/**
* `I18nMutateOpCode` defines OpCodes for `I18nMutateOpCodes` array.
*
* OpCodes contain three parts:
* 1) Parent node index offset.
* 2) Reference node index offset.
* 3) The OpCode to execute.
*
* See: `I18nCreateOpCodes` for example of usage.
*/
import {SanitizerFn} from './sanitization';
export const enum I18nMutateOpCode {
/**
* Stores shift amount for bits 17-3 that contain reference index.
*/
SHIFT_REF = 3,
/**
* Stores shift amount for bits 31-17 that contain parent index.
*/
SHIFT_PARENT = 17,
/**
* Mask for OpCode
*/
MASK_OPCODE = 0b111,
/**
* OpCode to select a node. (next OpCode will contain the operation.)
*/
Select = 0b000,
/**
* OpCode to append the current node to `PARENT`.
*/
AppendChild = 0b001,
/**
* OpCode to remove the `REF` node from `PARENT`.
*/
Remove = 0b011,
/**
* OpCode to set the attribute of a node.
*/
Attr = 0b100,
/**
* OpCode to simulate elementEnd()
*/
ElementEnd = 0b101,
/**
* OpCode to read the remove OpCodes for the nested ICU
*/
RemoveNestedIcu = 0b110,
}
/**
* Marks that the next string is for element.
*
* See `I18nMutateOpCodes` documentation.
*/
export const ELEMENT_MARKER: ELEMENT_MARKER = {
marker: 'element'
};
export interface ELEMENT_MARKER {
marker: 'element';
}
/**
* Marks that the next string is for comment.
*
* See `I18nMutateOpCodes` documentation.
*/
export const COMMENT_MARKER: COMMENT_MARKER = {
marker: 'comment'
};
export interface COMMENT_MARKER {
marker: 'comment';
}
/**
* Array storing OpCode for dynamically creating `i18n` blocks.
*
* Example:
* ```ts
* <I18nCreateOpCode>[
* // For adding text nodes
* // ---------------------
* // Equivalent to:
* // const node = lView[index++] = document.createTextNode('abc');
* // lView[1].insertBefore(node, lView[2]);
* 'abc', 1 << SHIFT_PARENT | 2 << SHIFT_REF | InsertBefore,
*
* // Equivalent to:
* // const node = lView[index++] = document.createTextNode('xyz');
* // lView[1].appendChild(node);
* 'xyz', 1 << SHIFT_PARENT | AppendChild,
*
* // For adding element nodes
* // ---------------------
* // Equivalent to:
* // const node = lView[index++] = document.createElement('div');
* // lView[1].insertBefore(node, lView[2]);
* ELEMENT_MARKER, 'div', 1 << SHIFT_PARENT | 2 << SHIFT_REF | InsertBefore,
*
* // Equivalent to:
* // const node = lView[index++] = document.createElement('div');
* // lView[1].appendChild(node);
* ELEMENT_MARKER, 'div', 1 << SHIFT_PARENT | AppendChild,
*
* // For adding comment nodes
* // ---------------------
* // Equivalent to:
* // const node = lView[index++] = document.createComment('');
* // lView[1].insertBefore(node, lView[2]);
* COMMENT_MARKER, '', 1 << SHIFT_PARENT | 2 << SHIFT_REF | InsertBefore,
*
* // Equivalent to:
* // const node = lView[index++] = document.createComment('');
* // lView[1].appendChild(node);
* COMMENT_MARKER, '', 1 << SHIFT_PARENT | AppendChild,
*
* // For moving existing nodes to a different location
* // --------------------------------------------------
* // Equivalent to:
* // const node = lView[1];
* // lView[2].insertBefore(node, lView[3]);
* 1 << SHIFT_REF | Select, 2 << SHIFT_PARENT | 3 << SHIFT_REF | InsertBefore,
*
* // Equivalent to:
* // const node = lView[1];
* // lView[2].appendChild(node);
* 1 << SHIFT_REF | Select, 2 << SHIFT_PARENT | AppendChild,
*
* // For removing existing nodes
* // --------------------------------------------------
* // const node = lView[1];
* // removeChild(tView.data(1), node, lView);
* 1 << SHIFT_REF | Remove,
*
* // For writing attributes
* // --------------------------------------------------
* // const node = lView[1];
* // node.setAttribute('attr', 'value');
* 1 << SHIFT_REF | Select, 'attr', 'value'
* // NOTE: Select followed by two string (vs select followed by OpCode)
* ];
* ```
* NOTE:
* - `index` is initial location where the extra nodes should be stored in the EXPANDO section of
* `LVIewData`.
*
* See: `applyI18nCreateOpCodes`;
*/
export interface I18nMutateOpCodes extends Array<number|string|ELEMENT_MARKER|COMMENT_MARKER|null> {
}
export const enum I18nUpdateOpCode {
/**
* Stores shift amount for bits 17-2 that contain reference index.
*/
SHIFT_REF = 2,
/**
* Mask for OpCode
*/
MASK_OPCODE = 0b11,
/**
* OpCode to update a text node.
*/
Text = 0b00,
/**
* OpCode to update a attribute of a node.
*/
Attr = 0b01,
/**
* OpCode to switch the current ICU case.
*/
IcuSwitch = 0b10,
/**
* OpCode to update the current ICU case.
*/
IcuUpdate = 0b11,
}
/**
* Stores DOM operations which need to be applied to update DOM render tree due to changes in
* expressions.
*
* The basic idea is that `i18nExp` OpCodes capture expression changes and update a change
* mask bit. (Bit 1 for expression 1, bit 2 for expression 2 etc..., bit 32 for expression 32 and
* higher.) The OpCodes then compare its own change mask against the expression change mask to
* determine if the OpCodes should execute.
*
* These OpCodes can be used by both the i18n block as well as ICU sub-block.
*
* ## Example
*
* Assume
* ```ts
* if (rf & RenderFlags.Update) {
* i18nExp(ctx.exp1); // If changed set mask bit 1
* i18nExp(ctx.exp2); // If changed set mask bit 2
* i18nExp(ctx.exp3); // If changed set mask bit 3
* i18nExp(ctx.exp4); // If changed set mask bit 4
* i18nApply(0); // Apply all changes by executing the OpCodes.
* }
* ```
* We can assume that each call to `i18nExp` sets an internal `changeMask` bit depending on the
* index of `i18nExp`.
*
* ### OpCodes
* ```ts
* <I18nUpdateOpCodes>[
* // The following OpCodes represent: `<div i18n-title="pre{{exp1}}in{{exp2}}post">`
* // If `changeMask & 0b11`
* // has changed then execute update OpCodes.
* // has NOT changed then skip `7` values and start processing next OpCodes.
* 0b11, 7,
* // Concatenate `newValue = 'pre'+lView[bindIndex-4]+'in'+lView[bindIndex-3]+'post';`.
* 'pre', -4, 'in', -3, 'post',
* // Update attribute: `elementAttribute(1, 'title', sanitizerFn(newValue));`
* 1 << SHIFT_REF | Attr, 'title', sanitizerFn,
*
* // The following OpCodes represent: `<div i18n>Hello {{exp3}}!">`
* // If `changeMask & 0b100`
* // has changed then execute update OpCodes.
* // has NOT changed then skip `4` values and start processing next OpCodes.
* 0b100, 4,
* // Concatenate `newValue = 'Hello ' + lView[bindIndex -2] + '!';`.
* 'Hello ', -2, '!',
* // Update text: `lView[1].textContent = newValue;`
* 1 << SHIFT_REF | Text,
*
* // The following OpCodes represent: `<div i18n>{exp4, plural, ... }">`
* // If `changeMask & 0b1000`
* // has changed then execute update OpCodes.
* // has NOT changed then skip `4` values and start processing next OpCodes.
* 0b1000, 4,
* // Concatenate `newValue = lView[bindIndex -1];`.
* -1,
* // Switch ICU: `icuSwitchCase(lView[1], 0, newValue);`
* 0 << SHIFT_ICU | 1 << SHIFT_REF | IcuSwitch,
*
* // Note `changeMask & -1` is always true, so the IcuUpdate will always execute.
* -1, 1,
* // Update ICU: `icuUpdateCase(lView[1], 0);`
* 0 << SHIFT_ICU | 1 << SHIFT_REF | IcuUpdate,
*
* ];
* ```
*
*/
export interface I18nUpdateOpCodes extends Array<string|number|SanitizerFn|null> {}
/**
* Store information for the i18n translation block.
*/
export interface TI18n {
/**
* Number of slots to allocate in expando.
*
* This is the max number of DOM elements which will be created by this i18n + ICU blocks. When
* the DOM elements are being created they are stored in the EXPANDO, so that update OpCodes can
* write into them.
*/
vars: number;
/**
* A set of OpCodes which will create the Text Nodes and ICU anchors for the translation blocks.
*
* NOTE: The ICU anchors are filled in with ICU Update OpCode.
*/
create: I18nMutateOpCodes;
/**
* A set of OpCodes which will be executed on each change detection to determine if any changes to
* DOM are required.
*/
update: I18nUpdateOpCodes;
/**
* A list of ICUs in a translation block (or `null` if block has no ICUs).
*
* Example:
* Given: `<div i18n>You have {count, plural, ...} and {state, switch, ...}</div>`
* There would be 2 ICUs in this array.
* 1. `{count, plural, ...}`
* 2. `{state, switch, ...}`
*/
icus: TIcu[]|null;
}
/**
* Defines the ICU type of `select` or `plural`
*/
export const enum IcuType {
select = 0,
plural = 1,
}
export interface TIcu {
/**
* Defines the ICU type of `select` or `plural`
*/
type: IcuType;
/**
* Number of slots to allocate in expando for each case.
*
* This is the max number of DOM elements which will be created by this i18n + ICU blocks. When
* the DOM elements are being created they are stored in the EXPANDO, so that update OpCodes can
* write into them.
*/
vars: number[];
/**
* An optional array of child/sub ICUs.
*
* In case of nested ICUs such as:
* ```
* {�0�, plural,
* =0 {zero}
* other {�0� {�1�, select,
* cat {cats}
* dog {dogs}
* other {animals}
* }!
* }
* }
* ```
* When the parent ICU is changing it must clean up child ICUs as well. For this reason it needs
* to know which child ICUs to run clean up for as well.
*
* In the above example this would be:
* ```ts
* [
* [], // `=0` has no sub ICUs
* [1], // `other` has one subICU at `1`st index.
* ]
* ```
*
* The reason why it is Array of Arrays is because first array represents the case, and second
* represents the child ICUs to clean up. There may be more than one child ICUs per case.<|fim▁hole|> childIcus: number[][];
/**
* A list of case values which the current ICU will try to match.
*
* The last value is `other`
*/
cases: any[];
/**
* A set of OpCodes to apply in order to build up the DOM render tree for the ICU
*/
create: I18nMutateOpCodes[];
/**
* A set of OpCodes to apply in order to destroy the DOM render tree for the ICU.
*/
remove: I18nMutateOpCodes[];
/**
* A set of OpCodes to apply in order to update the DOM render tree for the ICU bindings.
*/
update: I18nUpdateOpCodes[];
}
// Note: This hack is necessary so we don't erroneously get a circular dependency
// failure based on types.
export const unusedValueExportToPlacateAjd = 1;<|fim▁end|> | */ |
<|file_name|>fetchUrl.go<|end_file_name|><|fim▁begin|>//
package main
/*
Packages must be imported:
"core/common/page"
"core/spider"
Pckages may be imported:
"core/pipeline": scawler result persistent;
"github.com/PuerkitoBio/goquery": html dom parser.
*/
import (
"github.com/PuerkitoBio/goquery"
"github.com/hu17889/go_spider/core/common/page"
"github.com/hu17889/go_spider/core/pipeline"
"github.com/hu17889/go_spider/core/spider"
"strings"
"fmt"
)
type MyPageProcesser struct {
}
func NewMyPageProcesser() *MyPageProcesser {
return &MyPageProcesser{}
}
// Parse html dom here and record the parse result that we want to Page.
// Package goquery (http://godoc.org/github.com/PuerkitoBio/goquery) is used to parse html.
func (this *MyPageProcesser) Process(p *page.Page) {
if !p.IsSucc() {
println(p.Errormsg())
return
}
query := p.GetHtmlParser()
var urls []string
query.Find("h3[class='repo-list-name'] a").Each(func(i int, s *goquery.Selection) {
href, _ := s.Attr("href")
urls = append(urls, "http://www.stelladot.com/"+href)
})<|fim▁hole|> name = strings.Trim(name, " \t\n")
repository := query.Find(".entry-title .js-current-repository").Text()
repository = strings.Trim(repository, " \t\n")
//readme, _ := query.Find("#readme").Html()
if name == "" {
p.SetSkip(true)
}
// the entity we want to save by Pipeline
p.AddField("author", name)
p.AddField("project", repository)
//p.AddField("readme", readme)
}
func (this *MyPageProcesser) Finish() {
fmt.Printf("TODO:before end spider \r\n")
}
func main() {
// Spider input:
// PageProcesser ;
// Task name used in Pipeline for record;
spider.NewSpider(NewMyPageProcesser(), "TaskName").
AddUrl("http://www.stelladot.com/shop/", "html"). // Start url, html is the responce type ("html" or "json" or "jsonp" or "text")
AddPipeline(pipeline.NewPipelineConsole()). // Print result on screen
SetThreadnum(3). // Crawl request by three Coroutines
Run()
}<|fim▁end|> | // these urls will be saved and crawed by other coroutines.
p.AddTargetRequests(urls, "html")
name := query.Find(".entry-title .author").Text() |
<|file_name|>oc_version.py<|end_file_name|><|fim▁begin|># pylint: skip-file
# pylint: disable=too-many-instance-attributes
class OCVersion(OpenShiftCLI):
''' Class to wrap the oc command line tools '''
# pylint allows 5
# pylint: disable=too-many-arguments
def __init__(self,
config,
debug):
''' Constructor for OCVersion '''
super(OCVersion, self).__init__(None, config)
self.debug = debug
@staticmethod
def openshift_installed():
''' check if openshift is installed '''
import yum
yum_base = yum.YumBase()<|fim▁hole|> return True
else:
return False
@staticmethod
def filter_versions(stdout):
''' filter the oc version output '''
version_dict = {}
version_search = ['oc', 'openshift', 'kubernetes']
for line in stdout.strip().split('\n'):
for term in version_search:
if not line:
continue
if line.startswith(term):
version_dict[term] = line.split()[-1]
# horrible hack to get openshift version in Openshift 3.2
# By default "oc version in 3.2 does not return an "openshift" version
if "openshift" not in version_dict:
version_dict["openshift"] = version_dict["oc"]
return version_dict
@staticmethod
def add_custom_versions(versions):
''' create custom versions strings '''
versions_dict = {}
for tech, version in versions.items():
# clean up "-" from version
if "-" in version:
version = version.split("-")[0]
if version.startswith('v'):
versions_dict[tech + '_numeric'] = version[1:].split('+')[0]
# "v3.3.0.33" is what we have, we want "3.3"
versions_dict[tech + '_short'] = version[1:4]
return versions_dict
def get(self):
'''get and return version information '''
results = {}
results["installed"] = OCVersion.openshift_installed()
if not results["installed"]:
return results
version_results = self.openshift_cmd(['version'], output=True, output_type='raw')
if version_results['returncode'] == 0:
filtered_vers = OCVersion.filter_versions(version_results['results'])
custom_vers = OCVersion.add_custom_versions(filtered_vers)
results['returncode'] = version_results['returncode']
results.update(filtered_vers)
results.update(custom_vers)
return results
raise OpenShiftCLIError('Problem detecting openshift version.')<|fim▁end|> | if yum_base.rpmdb.searchNevra(name='atomic-openshift'): |
<|file_name|>sinf64.rs<|end_file_name|><|fim▁begin|>#![feature(core, core_intrinsics, core_float)]
extern crate core;
#[cfg(test)]
mod tests {
use core::intrinsics::sinf64;
use core::num::Float;
use core::f64;
use core::f64::consts::PI;
<|fim▁hole|> // pub fn sinf64(x: f64) -> f64;
#[test]
fn sinf64_test1() {
let x: f64 = f64::nan();
let result: f64 = unsafe { sinf64(x) };
assert_eq!(result.is_nan(), true);
}
#[test]
fn sinf64_test2() {
let x: f64 = f64::infinity();
let result: f64 = unsafe { sinf64(x) };
assert_eq!(result.is_nan(), true);
}
#[test]
fn sinf64_test3() {
let x: f64 = f64::neg_infinity();
let result: f64 = unsafe { sinf64(x) };
assert_eq!(result.is_nan(), true);
}
#[test]
fn sinf64_test4() {
let x: f64 = 0.0 * PI / 180.0;
let result: f64 = unsafe { sinf64(x) };
assert_eq!(result, 0.0);
}
#[test]
fn sinf64_test5() {
let x: f64 = 45.0 * PI / 180.0;
let result: f64 = unsafe { sinf64(x) };
assert_eq!(result, 0.7071067811865475);
}
#[test]
fn sinf64_test6() {
let x: f64 = 90.0 * PI / 180.0;
let result: f64 = unsafe { sinf64(x) };
assert_eq!(result, 1.0);
}
}<|fim▁end|> | |
<|file_name|>514f4b9bc74_added_columns_for_duel_win_lose_streaks_.py<|end_file_name|><|fim▁begin|>"""Added columns for duel win/lose streaks in the tb_user_duel_stats table
Revision ID: 514f4b9bc74
Revises: 1d6dbeb93c9
Create Date: 2015-12-22 00:17:51.509756
"""
# revision identifiers, used by Alembic.
revision = '514f4b9bc74'
down_revision = '1d6dbeb93c9'
branch_labels = None
depends_on = None
from alembic import op
import sqlalchemy as sa
def upgrade():
### commands auto generated by Alembic - please adjust! ###
op.add_column('tb_user_duel_stats', sa.Column('current_streak', sa.Integer(), nullable=False))
op.add_column('tb_user_duel_stats', sa.Column('longest_losestreak', sa.Integer(), nullable=False))
op.add_column('tb_user_duel_stats', sa.Column('longest_winstreak', sa.Integer(), nullable=False))
### end Alembic commands ###
<|fim▁hole|>
def downgrade():
### commands auto generated by Alembic - please adjust! ###
op.drop_column('tb_user_duel_stats', 'longest_winstreak')
op.drop_column('tb_user_duel_stats', 'longest_losestreak')
op.drop_column('tb_user_duel_stats', 'current_streak')
### end Alembic commands ###<|fim▁end|> | |
<|file_name|>codeFixNoPropertyAccessFromIndexSignature_fixAll.ts<|end_file_name|><|fim▁begin|>/// <reference path='fourslash.ts'/>
// @noPropertyAccessFromIndexSignature: true
//// interface A {
//// foo: string
//// }
//// interface B {
//// [k: string]: string
//// }
//// interface C {
//// foo: string
//// [k: string]: string
//// }
//// declare const a: A;
//// declare const b: B;
//// declare const c: C;
//// declare const d: C | undefined;
//// a.foo;
//// a["foo"];
//// b.foo;
//// b["foo"];
//// c.foo;
//// c["foo"];
//// c.bar;
//// c["bar"];
//// d?.foo;
//// d?.["foo"];
//// d?.bar;
//// d?.["bar"];
verify.codeFixAll({
fixId: 'fixNoPropertyAccessFromIndexSignature',
<|fim▁hole|>`interface A {
foo: string
}
interface B {
[k: string]: string
}
interface C {
foo: string
[k: string]: string
}
declare const a: A;
declare const b: B;
declare const c: C;
declare const d: C | undefined;
a.foo;
a["foo"];
b["foo"];
b["foo"];
c.foo;
c["foo"];
c["bar"];
c["bar"];
d?.foo;
d?.["foo"];
d?.["bar"];
d?.["bar"];`,
});<|fim▁end|> | fixAllDescription: ts.Diagnostics.Use_element_access_for_all_undeclared_properties.message,
newFileContent:
|
<|file_name|>lib.rs<|end_file_name|><|fim▁begin|>// Copyright 2015 Hyunsik Choi
//
// 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.
//! hdfs-rs is a library for accessing to HDFS cluster.
//! Basically, this library provides libhdfs APIs bindings.
//! It also provides more idiomatic and abstract Rust APIs,
//! hiding manual memory management and some thread-safety problem of libhdfs.
//! Rust APIs are highly recommended for most users.
extern crate libc;
#[macro_use]
extern crate log;
extern crate url;
<|fim▁hole|>pub mod binding;
/// Rust APIs wrapping libhdfs API, providing better semantic and abstraction
pub mod dfs;
/// Mini HDFS Cluster for easily building unit tests
pub mod minidfs;
pub mod util;<|fim▁end|> | /// libhdfs binding APIs
|
<|file_name|>12.07-002.js<|end_file_name|><|fim▁begin|>// Copyright JS Foundation and other contributors, http://js.foundation
//
// 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 sum = 0;
for (var i = 0; i < 10; i++)
for (var j = 0; j < 20; j++)
{
if (j > 9)
continue;
<|fim▁hole|> }
assert(sum === 100);<|fim▁end|> | sum += 1; |
<|file_name|>test.js<|end_file_name|><|fim▁begin|>// import should from 'should';
import { createStore } from 'redux';
import reredeux, { deux, LABELS } from '../src';
const { INIT, SELECT, ACTION, REDUCER, VALUE } = LABELS;
import todo from './todo';
import counter from './counter';
import phonebook from './phonebook';
const app = reredeux('example', [
counter,
todo,
deux('nest', [
phonebook
])
]);
let store;
let state;
describe('app', () => {
beforeEach(() => {
store = createStore(app[REDUCER], app[INIT]);
state = store.getState();
});
describe(INIT, () => {
describe('example', () => {
describe('counter', () => {
it('eql to 0', () => {
state.example.counter
.should.be.eql(0);
});
});
describe('todo', () => {
it('', () => {
state.example.todo
.should.be.eql([
{ name: 'brush teeth', complete: true },
{ name: 'dishes' , complete: false },
]);
});
});
describe('nest', () => {
describe('phonebook', () => {
it('== []', () => {
state.example.nest.phonebook
.should.be.eql([
{ name: 'person1', number: '1(222)333-4444'},
{ name: 'person2', number: '1(333)444-5555'},
]);
});
});
});
});
});
describe(SELECT, () => {
describe('example', () => {
describe('counter', () => {
describe(VALUE, () => {
it('== 0', () => {
app[SELECT].example.counter[VALUE](state)
.should.be.eql(0);
});
});
describe('succ', () => {
it('== 1', () => {
app[SELECT].example.counter.succ(state)
.should.be.eql(1);
});
});
describe('pred', () => {
it('== -1', () => {
app[SELECT].example.counter.pred(state)
.should.be.eql(-1);
});
});
});
describe('todo', () => {
describe('value', () => {
it('returns all the data', () => {
app[SELECT].example.todo.value(state)
.should.be.eql([
{ name: 'brush teeth', complete: true },
{ name: 'dishes' , complete: false },
]);
});
});
describe('titles', () => {
it('returns a list of todo titles', () => {
app[SELECT].example.todo.titles(state)
.should.be.eql(['brush teeth', 'dishes']);
});
});
describe('statuses', () => {
it('returns a list of completion status', () => {
app[SELECT].example.todo.statuses(state)
.should.be.eql([true, false]);
});
});
describe('completed', () => {<|fim▁hole|> it('returns only complete todos', () => {
app[SELECT].example.todo.completed(state)
.should.be.eql([
{ name: 'brush teeth', complete: true },
]);
});
});
describe('pending', () => {
it('returns only incomplete todos', () => {
app[SELECT].example.todo.pending(state)
.should.be.eql([
{ name: 'dishes' , complete: false },
]);
});
});
});
describe('nest', () => {
describe('phonebook', () => {
describe('value', () => {
it('returns the list of entries', () => {
app[SELECT].example.nest.phonebook.value(state)
.should.be.eql([
{ name: 'person1', number: '1(222)333-4444'},
{ name: 'person2', number: '1(333)444-5555'},
]);
});
});
describe('nameToNumber', () => {
it('returns the map from name to number', () => {
app[SELECT].example.nest.phonebook.nameToNumber(state)
.should.be.eql({
'person1': { name: 'person1', number: '1(222)333-4444'},
'person2': { name: 'person2', number: '1(333)444-5555'},
});
});
});
describe('numberToName', () => {
it('returns the map from number to name', () => {
app[SELECT].example.nest.phonebook.numberToName(state)
.should.be.eql({
'1(222)333-4444': { name: 'person1', number: '1(222)333-4444'},
'1(333)444-5555': { name: 'person2', number: '1(333)444-5555'},
});
});
});
});
});
});
});
describe(ACTION, () => {
it('increment', () => {
app[ACTION].increment()
.should.have.property('type');
app[ACTION].increment()
.should.not.have.property('payload');
});
it('decrement', () => {
app[ACTION].decrement()
.should.have.property('type');
app[ACTION].decrement()
.should.not.have.property('payload');
});
});
describe(REDUCER, () => {
describe('counter', () => {
it('increment', () => {
store.dispatch(app[ACTION].increment());
state = store.getState();
state.example.counter
.should.be.eql(1);
});
it('decrement', () => {
store.dispatch(app[ACTION].decrement());
state = store.getState();
state.example.counter
.should.be.eql(-1);
});
});
});
});<|fim▁end|> | |
<|file_name|>block_test.go<|end_file_name|><|fim▁begin|>// Copyright 2017 The go-xenio Authors
// Copyright 2015 The go-ethereum Authors
//
// This file is part of the go-xenio library.
//
// The go-xenio library is free software: you can redistribute it and/or modify
// it under the terms of the GNU Lesser General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// The go-xenio library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public License
// along with the go-xenio library. If not, see <http://www.gnu.org/licenses/>.
package tests
import (
"testing"
)
func TestBlockchain(t *testing.T) {
t.Parallel()
bt := new(testMatcher)
// General state tests are 'exported' as blockchain tests, but we can run them natively.
bt.skipLoad(`^GeneralStateTests/`)
// Skip random failures due to selfish mining test.
bt.skipLoad(`^bcForgedTest/bcForkUncle\.json`)
bt.skipLoad(`^bcMultiChainTest/(ChainAtoChainB_blockorder|CallContractFromNotBestBlock)`)
bt.skipLoad(`^bcTotalDifficultyTest/(lotsOfLeafs|lotsOfBranches|sideChainWithMoreTransactions)`)
// Constantinople is not implemented yet.
bt.skipLoad(`(?i)(constantinople)`)
// Still failing tests
bt.skipLoad(`^bcWalletTest.*_Byzantium$`)
<|fim▁hole|> }
})
}<|fim▁end|> | bt.walk(t, blockTestDir, func(t *testing.T, name string, test *BlockTest) {
if err := bt.checkFailure(t, name, test.Run()); err != nil {
t.Error(err) |
<|file_name|>formkit.js<|end_file_name|><|fim▁begin|>/*
$(document.body).ready(function() {
FormKit.install();
FormKit.initialize(document.body);
});
Inside Ajax Region:
$(document.body).ready(function() {<|fim▁hole|> });
*/
var FormKit = {
register: function(initHandler,installHandler) {
$(FormKit).bind('formkit.initialize',initHandler);
if( installHandler ) {
$(this).bind('formkit.install',installHandler);
}
},
initialize: function(scopeEl) {
if(!scopeEl)
scopeEl = document.body;
$(FormKit).trigger('formkit.initialize',[scopeEl]);
},
install: function() {
$(FormKit).trigger('formkit.install');
}
};<|fim▁end|> | FormKit.initialize( div element ); |
<|file_name|>ColorsUtil.java<|end_file_name|><|fim▁begin|>package ca.six.views.util;
import android.graphics.Color;
public class ColorsUtil {
public static boolean isLight(int color) {
return Math.sqrt(
Color.red(color) * Color.red(color) * 0.241 +
Color.green(color) * Color.green(color) * 0.691 +
Color.blue(color) * Color.blue(color) * 0.068) > 130;<|fim▁hole|> return Color.BLACK;
}
return Color.WHITE;
}
}<|fim▁end|> | }
public static int getBaseColor(int color) {
if (isLight(color)) { |
<|file_name|>interalSimpleDownloader.py<|end_file_name|><|fim▁begin|>import xml.etree.ElementTree as etree
import base64
from struct import unpack, pack
import sys
import io
import os
import time
import itertools
import xbmcaddon
import xbmc
import urllib2,urllib
import traceback
import urlparse
import posixpath
import re
import socket
from flvlib import tags
from flvlib import helpers
from flvlib.astypes import MalformedFLV
import zlib
from StringIO import StringIO
import hmac
import hashlib
import base64
addon_id = 'plugin.video.israelive'
selfAddon = xbmcaddon.Addon(id=addon_id)
__addonname__ = selfAddon.getAddonInfo('name')
__icon__ = selfAddon.getAddonInfo('icon')
downloadPath = xbmc.translatePath(selfAddon.getAddonInfo('profile'))#selfAddon["profile"])
#F4Mversion=''
class interalSimpleDownloader():
outputfile =''
clientHeader=None
def __init__(self):
self.init_done=False
def thisme(self):
return 'aaaa'
def openUrl(self,url, ischunkDownloading=False):
try:
post=None
openner = urllib2.build_opener(urllib2.HTTPHandler, urllib2.HTTPSHandler)
if post:
req = urllib2.Request(url, post)
else:
req = urllib2.Request(url)
ua_header=False
if self.clientHeader:
for n,v in self.clientHeader:
req.add_header(n,v)
if n=='User-Agent':
ua_header=True
if not ua_header:
req.add_header('User-Agent','Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/33.0.1750.154 Safari/537.36')
#response = urllib2.urlopen(req)
if self.proxy and ( (not ischunkDownloading) or self.use_proxy_for_chunks ):
req.set_proxy(self.proxy, 'http')
response = openner.open(req)
return response
except:
#print 'Error in getUrl'
traceback.print_exc()
return None
def getUrl(self,url, ischunkDownloading=False):
try:
post=None
openner = urllib2.build_opener(urllib2.HTTPHandler, urllib2.HTTPSHandler)
if post:
req = urllib2.Request(url, post)
else:
req = urllib2.Request(url)
ua_header=False
if self.clientHeader:
for n,v in self.clientHeader:
req.add_header(n,v)
if n=='User-Agent':
ua_header=True
if not ua_header:
req.add_header('User-Agent','Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/33.0.1750.154 Safari/537.36')
#response = urllib2.urlopen(req)
if self.proxy and ( (not ischunkDownloading) or self.use_proxy_for_chunks ):
req.set_proxy(self.proxy, 'http')
response = openner.open(req)
data=response.read()
return data
except:
#print 'Error in getUrl'
traceback.print_exc()
return None
def init(self, out_stream, url, proxy=None,g_stopEvent=None, maxbitRate=0):
try:
self.init_done=False
self.init_url=url
self.clientHeader=None
self.status='init'
self.proxy = proxy
self.maxbitRate=maxbitRate
if self.proxy and len(self.proxy)==0:
self.proxy=None
self.out_stream=out_stream
self.g_stopEvent=g_stopEvent
if '|' in url:
sp = url.split('|')
url = sp[0]
self.clientHeader = sp[1]
self.clientHeader= urlparse.parse_qsl(self.clientHeader)
#print 'header recieved now url and headers are',url, self.clientHeader
self.status='init done'
self.url=url
#self.downloadInternal( url)
return True
#os.remove(self.outputfile)
except:
traceback.print_exc()<|fim▁hole|> return False
def keep_sending_video(self,dest_stream, segmentToStart=None, totalSegmentToSend=0):
try:
self.status='download Starting'
self.downloadInternal(self.url,dest_stream)
except:
traceback.print_exc()
self.status='finished'
def downloadInternal(self,url,dest_stream):
try:
url=self.url
fileout=dest_stream
self.status='bootstrap done'
while True:
response=self.openUrl(url)
buf="start"
firstBlock=True
try:
while (buf != None and len(buf) > 0):
if self.g_stopEvent and self.g_stopEvent.isSet():
return
buf = response.read(200 * 1024)
fileout.write(buf)
#print 'writing something..............'
fileout.flush()
try:
if firstBlock:
firstBlock=False
if self.maxbitRate and self.maxbitRate>0:# this is for being sports for time being
#print 'maxbitrate',self.maxbitRate
ec=EdgeClass(buf,url,'http://www.en.beinsports.net/i/PerformConsole_BEIN/player/bin-release/PerformConsole.swf',sendToken=False)
ec.switchStream(self.maxbitRate,"DOWN")
except:
traceback.print_exc()
response.close()
fileout.close()
#print time.asctime(), "Closing connection"
except socket.error, e:
#print time.asctime(), "Client Closed the connection."
try:
response.close()
fileout.close()
except Exception, e:
return
except Exception, e:
traceback.print_exc(file=sys.stdout)
response.close()
fileout.close()
except:
traceback.print_exc()
return
class EdgeClass():
def __init__(self, data, url, swfUrl, sendToken=False, switchStream=None):
self.url = url
self.swfUrl = swfUrl
self.domain = self.url.split('://')[1].split('/')[0]
self.control = 'http://%s/control/' % self.domain
self.onEdge = self.extractTags(data,onEdge=True)
self.sessionID=self.onEdge['session']
self.path=self.onEdge['streamName']
#print 'session',self.onEdge['session']
#print 'Edge variable',self.onEdge
#print 'self.control',self.control
#self.MetaData = self.extractTags(data,onMetaData=True)
if sendToken:
self.sendNewToken(self.onEdge['session'],self.onEdge['streamName'],self.swfUrl,self.control)
def getURL(self, url, post=False, sessionID=False, sessionToken=False):
try:
#print 'GetURL --> url = '+url
opener = urllib2.build_opener()
if sessionID and sessionToken:
opener.addheaders = [('User-Agent', 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10.7; rv:14.0) Gecko/20100101 Firefox/14.0.1' ),
('x-Akamai-Streaming-SessionToken', sessionToken ),
('x-Akamai-Streaming-SessionID', sessionID ),
('Content-Type', 'text/xml' )]
elif sessionID:
opener.addheaders = [('User-Agent', 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10.7; rv:14.0) Gecko/20100101 Firefox/14.0.1' ),
('x-Akamai-Streaming-SessionID', sessionID ),
('Content-Type', 'text/xml' )]
else:
opener.addheaders = [('User-Agent', 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10.7; rv:14.0) Gecko/20100101 Firefox/14.0.1' )]
if not post:
usock=opener.open(url)
else:
usock=opener.open(url,':)')
response=usock.read()
usock.close()
except urllib2.URLError, e:
#print 'Error reason: ', e
return False
else:
return response
def extractTags(self, filedata, onEdge=True,onMetaData=False):
f = StringIO(filedata)
flv = tags.FLV(f)
try:
tag_generator = flv.iter_tags()
for i, tag in enumerate(tag_generator):
if isinstance(tag, tags.ScriptTag):
if tag.name == "onEdge" and onEdge:
return tag.variable
elif tag.name == "onMetaData" and onMetaData:
return tag.variable
except MalformedFLV, e:
return False
except tags.EndOfFile:
return False
f.close()
return False
def decompressSWF(self,f):
if type(f) is str:
f = StringIO(f)
f.seek(0, 0)
magic = f.read(3)
if magic == "CWS":
return "FWS" + f.read(5) + zlib.decompress(f.read())
elif magic == "FWS":
#SWF Not Compressed
f.seek(0, 0)
return f.read()
else:
#Not SWF
return None
def MD5(self,data):
m = hashlib.md5()
m.update(data)
return m.digest()
def makeToken(self,sessionID,swfUrl):
swfData = self.getURL(swfUrl)
decData = self.decompressSWF(swfData)
swfMD5 = self.MD5(decData)
data = sessionID+swfMD5
sig = hmac.new('foo', data, hashlib.sha1)
return base64.encodestring(sig.digest()).replace('\n','')
def sendNewToken(self,sessionID,path,swf,domain):
sessionToken = self.makeToken(sessionID,swf)
commandUrl = domain+path+'?cmd=sendingNewToken&v=2.7.6&swf='+swf.replace('http://','http%3A//')
self.getURL(commandUrl,True,sessionID,sessionToken)
def switchStream(self, bitrate, upDown="UP"):
newStream=self.path
#print 'newStream before ',newStream
newStream=re.sub('_[0-9]*@','_'+str(bitrate)+'@',newStream)
#print 'newStream after ',newStream,bitrate
sessionToken =None# self.makeToken(sessionID,swf)
commandUrl = self.control+newStream+'?cmd=&reason=SWITCH_'+upDown+',1784,1000,1.3,2,'+self.path+'v=2.11.3'
self.getURL(commandUrl,True,self.sessionID,sessionToken)<|fim▁end|> | self.status='finished' |
<|file_name|>local.py<|end_file_name|><|fim▁begin|>"""Dev server used for running a chalice app locally.
This is intended only for local development purposes.
"""
from __future__ import print_function
import re
import threading
import time
import uuid
import base64
import functools
import warnings
from collections import namedtuple
import json
from six.moves.BaseHTTPServer import HTTPServer
from six.moves.BaseHTTPServer import BaseHTTPRequestHandler
from six.moves.socketserver import ThreadingMixIn
from typing import (
List,
Any,
Dict,
Tuple,
Callable,
Optional,
Union,
) # noqa
from chalice.app import Chalice # noqa
from chalice.app import CORSConfig # noqa
from chalice.app import ChaliceAuthorizer # noqa
from chalice.app import CognitoUserPoolAuthorizer # noqa
from chalice.app import RouteEntry # noqa
from chalice.app import Request # noqa
from chalice.app import AuthResponse # noqa
from chalice.app import BuiltinAuthConfig # noqa
from chalice.config import Config # noqa
from chalice.compat import urlparse, parse_qs
MatchResult = namedtuple('MatchResult', ['route', 'captured', 'query_params'])
EventType = Dict[str, Any]
ContextType = Dict[str, Any]
HeaderType = Dict[str, Any]
ResponseType = Dict[str, Any]
HandlerCls = Callable[..., 'ChaliceRequestHandler']
ServerCls = Callable[..., 'HTTPServer']
class Clock(object):
def time(self):
# type: () -> float
return time.time()
def create_local_server(app_obj, config, host, port):
# type: (Chalice, Config, str, int) -> LocalDevServer
app_obj.__class__ = LocalChalice
return LocalDevServer(app_obj, config, host, port)
class LocalARNBuilder(object):
ARN_FORMAT = ('arn:aws:execute-api:{region}:{account_id}'
':{api_id}/{stage}/{method}/{resource_path}')
LOCAL_REGION = 'mars-west-1'
LOCAL_ACCOUNT_ID = '123456789012'
LOCAL_API_ID = 'ymy8tbxw7b'
LOCAL_STAGE = 'api'
def build_arn(self, method, path):
# type: (str, str) -> str
# In API Gateway the method and URI are separated by a / so typically
# the uri portion omits the leading /. In the case where the entire
# url is just '/' API Gateway adds a / to the end so that the arn end
# with a '//'.
if path != '/':
path = path[1:]
return self.ARN_FORMAT.format(
region=self.LOCAL_REGION,
account_id=self.LOCAL_ACCOUNT_ID,
api_id=self.LOCAL_API_ID,
stage=self.LOCAL_STAGE,
method=method,
resource_path=path
)
class ARNMatcher(object):
def __init__(self, target_arn):
# type: (str) -> None
self._arn = target_arn
def _resource_match(self, resource):
# type: (str) -> bool
# Arn matching supports two special case characetrs that are not
# escapable. * represents a glob which translates to a non-greedy
# match of any number of characters. ? which is any single character.
# These are easy to translate to a regex using .*? and . respectivly.
escaped_resource = re.escape(resource)
resource_regex = escaped_resource.replace(r'\?', '.').replace(
r'\*', '.*?')
resource_regex = '^%s$' % resource_regex
return re.match(resource_regex, self._arn) is not None
def does_any_resource_match(self, resources):
# type: (List[str]) -> bool
for resource in resources:
if self._resource_match(resource):
return True
return False
class RouteMatcher(object):
def __init__(self, route_urls):
# type: (List[str]) -> None
# Sorting the route_urls ensures we always check
# the concrete routes for a prefix before the
# variable/capture parts of the route, e.g
# '/foo/bar' before '/foo/{capture}'
self.route_urls = sorted(route_urls)
def match_route(self, url):
# type: (str) -> MatchResult
"""Match the url against known routes.
This method takes a concrete route "/foo/bar", and
matches it against a set of routes. These routes can
use param substitution corresponding to API gateway patterns.
For example::
match_route('/foo/bar') -> '/foo/{name}'
"""
# Otherwise we need to check for param substitution
parsed_url = urlparse(url)
query_params = parse_qs(parsed_url.query, keep_blank_values=True)
path = parsed_url.path
# API Gateway removes the trailing slash if the route is not the root
# path. We do the same here so our route matching works the same way.
if path != '/' and path.endswith('/'):
path = path[:-1]
parts = path.split('/')
captured = {}
for route_url in self.route_urls:
url_parts = route_url.split('/')
if len(parts) == len(url_parts):
for i, j in zip(parts, url_parts):
if j.startswith('{') and j.endswith('}'):
captured[j[1:-1]] = i
continue
if i != j:
break
else:
return MatchResult(route_url, captured, query_params)
raise ValueError("No matching route found for: %s" % url)
class LambdaEventConverter(object):
LOCAL_SOURCE_IP = '127.0.0.1'
"""Convert an HTTP request to an event dict used by lambda."""
def __init__(self, route_matcher, binary_types=None):
# type: (RouteMatcher, List[str]) -> None
self._route_matcher = route_matcher
if binary_types is None:
binary_types = []
self._binary_types = binary_types
def _is_binary(self, headers):
# type: (Dict[str,Any]) -> bool
return headers.get('content-type', '') in self._binary_types
def create_lambda_event(self, method, path, headers, body=None):
# type: (str, str, Dict[str, str], str) -> EventType
view_route = self._route_matcher.match_route(path)
event = {
'requestContext': {
'httpMethod': method,
'resourcePath': view_route.route,
'identity': {
'sourceIp': self.LOCAL_SOURCE_IP
},
'path': path.split('?')[0],
},
'headers': {k.lower(): v for k, v in headers.items()},
'pathParameters': view_route.captured,
'stageVariables': {},
}
if view_route.query_params:
event['multiValueQueryStringParameters'] = view_route.query_params
else:
# If no query parameters are provided, API gateway maps
# this to None so we're doing this for parity.
event['multiValueQueryStringParameters'] = None
if self._is_binary(headers) and body is not None:
event['body'] = base64.b64encode(body).decode('ascii')
event['isBase64Encoded'] = True
else:
event['body'] = body
return event
class LocalGatewayException(Exception):
CODE = 0
def __init__(self, headers, body=None):
# type: (HeaderType, Optional[bytes]) -> None
self.headers = headers
self.body = body
class InvalidAuthorizerError(LocalGatewayException):
CODE = 500
class ForbiddenError(LocalGatewayException):
CODE = 403
class NotAuthorizedError(LocalGatewayException):
CODE = 401
class LambdaContext(object):
def __init__(self, function_name, memory_size,
max_runtime_ms=3000, time_source=None):
# type: (str, int, int, Optional[Clock]) -> None
if time_source is None:
time_source = Clock()
self._time_source = time_source
self._start_time = self._current_time_millis()
self._max_runtime = max_runtime_ms
# Below are properties that are found on the real LambdaContext passed
# by lambda and their associated documentation.
# Name of the Lambda function that is executing.
self.function_name = function_name
# The Lambda function version that is executing. If an alias is used
# to invoke the function, then function_version will be the version
# the alias points to.
# Chalice local obviously does not support versioning so it will always
# be set to $LATEST.
self.function_version = '$LATEST'
# The ARN used to invoke this function. It can be function ARN or
# alias ARN. An unqualified ARN executes the $LATEST version and
# aliases execute the function version it is pointing to.
self.invoked_function_arn = ''
# Memory limit, in MB, you configured for the Lambda function. You set
# the memory limit at the time you create a Lambda function and you
# can change it later.
self.memory_limit_in_mb = memory_size
# AWS request ID associated with the request. This is the ID returned
# to the client that called the invoke method.
self.aws_request_id = str(uuid.uuid4())
# The name of the CloudWatch log group where you can find logs written
# by your Lambda function.
self.log_group_name = ''
# The name of the CloudWatch log stream where you can find logs
# written by your Lambda function. The log stream may or may not
# change for each invocation of the Lambda function.
#
# The value is null if your Lambda function is unable to create a log
# stream, which can happen if the execution role that grants necessary
# permissions to the Lambda function does not include permissions for
# the CloudWatch Logs actions.
self.log_stream_name = ''
# The last two attributes have the following comment in the
# documentation:
# Information about the client application and device when invoked
# through the AWS Mobile SDK, it can be null.
# Chalice local doens't need to set these since they are specifically
# for the mobile SDK.
self.identity = None
self.client_context = None
def _current_time_millis(self):
# type: () -> float
return self._time_source.time() * 1000
def get_remaining_time_in_millis(self):
# type: () -> float
runtime = self._current_time_millis() - self._start_time
return self._max_runtime - runtime
LocalAuthPair = Tuple[EventType, LambdaContext]
class LocalGatewayAuthorizer(object):
"""A class for running user defined authorizers in local mode."""
def __init__(self, app_object):
# type: (Chalice) -> None
self._app_object = app_object
self._arn_builder = LocalARNBuilder()
def authorize(self, raw_path, lambda_event, lambda_context):
# type: (str, EventType, LambdaContext) -> LocalAuthPair
method = lambda_event['requestContext']['httpMethod']
route_entry = self._route_for_event(lambda_event)
if not route_entry:
return lambda_event, lambda_context
authorizer = route_entry.authorizer
if not authorizer:
return lambda_event, lambda_context
# If authorizer is Cognito then try to parse the JWT and simulate an
# APIGateway validated request
if isinstance(authorizer, CognitoUserPoolAuthorizer):
if "headers" in lambda_event\
and "authorization" in lambda_event["headers"]:
token = lambda_event["headers"]["authorization"]
claims = self._decode_jwt_payload(token)
try:
cognito_username = claims["cognito:username"]
except KeyError:
# If a key error is raised when trying to get the cognito
# username then it is a machine-to-machine communication.
# This kind of cognito authorization flow is not
# supported in local mode. We can ignore it here to allow
# users to test their code local with a different cognito
# authorization flow.
warnings.warn(
'%s for machine-to-machine communicaiton is not '
'supported in local mode. All requests made against '
'a route will be authorized to allow local testing.'
% authorizer.__class__.__name__
)
return lambda_event, lambda_context
auth_result = {"context": {"claims": claims},
"principalId": cognito_username}
lambda_event = self._update_lambda_event(lambda_event,
auth_result)
if not isinstance(authorizer, ChaliceAuthorizer):
# Currently the only supported local authorizer is the
# BuiltinAuthConfig type. Anything else we will err on the side of
# allowing local testing by simply admiting the request. Otherwise
# there is no way for users to test their code in local mode.
warnings.warn(
'%s is not a supported in local mode. All requests made '
'against a route will be authorized to allow local testing.'
% authorizer.__class__.__name__
)
return lambda_event, lambda_context
arn = self._arn_builder.build_arn(method, raw_path)
auth_event = self._prepare_authorizer_event(arn, lambda_event,
lambda_context)
auth_result = authorizer(auth_event, lambda_context)
if auth_result is None:
raise InvalidAuthorizerError(
{'x-amzn-RequestId': lambda_context.aws_request_id,
'x-amzn-ErrorType': 'AuthorizerConfigurationException'},
b'{"message":null}'
)
authed = self._check_can_invoke_view_function(arn, auth_result)
if authed:
lambda_event = self._update_lambda_event(lambda_event, auth_result)
else:
raise ForbiddenError(
{'x-amzn-RequestId': lambda_context.aws_request_id,
'x-amzn-ErrorType': 'AccessDeniedException'},
(b'{"Message": '
b'"User is not authorized to access this resource"}'))
return lambda_event, lambda_context
def _check_can_invoke_view_function(self, arn, auth_result):
# type: (str, ResponseType) -> bool
policy = auth_result.get('policyDocument', {})
statements = policy.get('Statement', [])
allow_resource_statements = []
for statement in statements:
if statement.get('Effect') == 'Allow' and \
statement.get('Action') == 'execute-api:Invoke':
for resource in statement.get('Resource'):
allow_resource_statements.append(resource)
arn_matcher = ARNMatcher(arn)
return arn_matcher.does_any_resource_match(allow_resource_statements)
def _route_for_event(self, lambda_event):
# type: (EventType) -> Optional[RouteEntry]
# Authorizer had to be made into an Any type since mypy couldn't
# detect that app.ChaliceAuthorizer was callable.
resource_path = lambda_event.get(
'requestContext', {}).get('resourcePath')
http_method = lambda_event['requestContext']['httpMethod']
try:
route_entry = self._app_object.routes[resource_path][http_method]
except KeyError:
# If a key error is raised when trying to get the route entry
# then this route does not support this method. A method error
# will be raised by the chalice handler method. We can ignore it
# here by returning no authorizer to avoid duplicating the logic.
return None
return route_entry
def _update_lambda_event(self, lambda_event, auth_result):
# type: (EventType, ResponseType) -> EventType
auth_context = auth_result['context']
auth_context.update({
'principalId': auth_result['principalId']
})
lambda_event['requestContext']['authorizer'] = auth_context
return lambda_event
def _prepare_authorizer_event(self, arn, lambda_event, lambda_context):
# type: (str, EventType, LambdaContext) -> EventType
"""Translate event for an authorizer input."""
authorizer_event = lambda_event.copy()
authorizer_event['type'] = 'TOKEN'
try:
authorizer_event['authorizationToken'] = authorizer_event.get(
'headers', {})['authorization']
except KeyError:
raise NotAuthorizedError(
{'x-amzn-RequestId': lambda_context.aws_request_id,
'x-amzn-ErrorType': 'UnauthorizedException'},
b'{"message":"Unauthorized"}')
authorizer_event['methodArn'] = arn
return authorizer_event
def _decode_jwt_payload(self, jwt):
# type: (str) -> Dict
payload_segment = jwt.split(".", 2)[1]
payload = base64.urlsafe_b64decode(self._base64_pad(payload_segment))
return json.loads(payload)
def _base64_pad(self, value):
# type: (str) -> str
rem = len(value) % 4
if rem > 0:
value += "=" * (4 - rem)
return value
class LocalGateway(object):
"""A class for faking the behavior of API Gateway."""
def __init__(self, app_object, config):
# type: (Chalice, Config) -> None
self._app_object = app_object
self._config = config
self.event_converter = LambdaEventConverter(
RouteMatcher(list(app_object.routes)),
self._app_object.api.binary_types
)
self._authorizer = LocalGatewayAuthorizer(app_object)
def _generate_lambda_context(self):
# type: () -> LambdaContext
if self._config.lambda_timeout is None:
timeout = None
else:
timeout = self._config.lambda_timeout * 1000
return LambdaContext(
function_name=self._config.function_name,
memory_size=self._config.lambda_memory_size,
max_runtime_ms=timeout
)
def _generate_lambda_event(self, method, path, headers, body):
# type: (str, str, HeaderType, Optional[str]) -> EventType
lambda_event = self.event_converter.create_lambda_event(
method=method, path=path, headers=headers,
body=body,
)
return lambda_event
def _has_user_defined_options_method(self, lambda_event):
# type: (EventType) -> bool
route_key = lambda_event['requestContext']['resourcePath']
return 'OPTIONS' in self._app_object.routes[route_key]
def handle_request(self, method, path, headers, body):
# type: (str, str, HeaderType, Optional[str]) -> ResponseType
lambda_context = self._generate_lambda_context()
try:
lambda_event = self._generate_lambda_event(
method, path, headers, body)
except ValueError:
# API Gateway will return a different error on route not found
# depending on whether or not we have an authorization token in our
# request. Since we do not do that check until we actually find
# the authorizer that we will call we do not have that information
# available at this point. Instead we just check to see if that
# header is present and change our response if it is. This will
# need to be refactored later if we decide to more closely mirror
# how API Gateway does their auth and routing.
error_headers = {'x-amzn-RequestId': lambda_context.aws_request_id,
'x-amzn-ErrorType': 'UnauthorizedException'}
auth_header = headers.get('authorization')
if auth_header is None:
auth_header = headers.get('Authorization')
if auth_header is not None:
raise ForbiddenError(
error_headers,
(b'{"message": "Authorization header requires '
b'\'Credential\''
b' parameter. Authorization header requires \'Signature\''
b' parameter. Authorization header requires '
b'\'SignedHeaders\' parameter. Authorization header '
b'requires existence of either a \'X-Amz-Date\' or a'
b' \'Date\' header. Authorization=%s"}'
% auth_header.encode('ascii')))
raise ForbiddenError(
error_headers,
b'{"message": "Missing Authentication Token"}')
# This can either be because the user's provided an OPTIONS method
# *or* this is a preflight request, which chalice automatically
# responds to without invoking a user defined route.
if method == 'OPTIONS' and \
not self._has_user_defined_options_method(lambda_event):
# No options route was defined for this path. API Gateway should
# automatically generate our CORS headers.
options_headers = self._autogen_options_headers(lambda_event)
return {
'statusCode': 200,
'headers': options_headers,
'multiValueHeaders': {},
'body': None
}
# The authorizer call will be a noop if there is no authorizer method
# defined for route. Otherwise it will raise a ForbiddenError
# which will be caught by the handler that called this and a 403 or
# 401 will be sent back over the wire.
lambda_event, lambda_context = self._authorizer.authorize(
path, lambda_event, lambda_context)
response = self._app_object(lambda_event, lambda_context)
response = self._handle_binary(response)
return response
def _autogen_options_headers(self, lambda_event):
# type:(EventType) -> HeaderType
route_key = lambda_event['requestContext']['resourcePath']
route_dict = self._app_object.routes[route_key]
route_methods = list(route_dict.keys())
# Chalice ensures that routes with multiple views have the same
# CORS configuration, so if any view has a CORS Config we can use
# that config since they will all be the same.
cors_config = route_dict[route_methods[0]].cors
cors_headers = cors_config.get_access_control_headers()
# We need to add OPTIONS since it is not a part of the CORSConfig
# object. APIGateway handles this entirely based on the API definition.
# So our local version needs to add this manually to our set of allowed
# headers.
route_methods.append('OPTIONS')
# The Access-Control-Allow-Methods header is not added by the
# CORSConfig object it is added to the API Gateway route during
# deployment, so we need to manually add those headers here.
cors_headers.update({
'Access-Control-Allow-Methods': '%s' % ','.join(route_methods)
})
return cors_headers
def _handle_binary(self, response):
# type: (Dict[str,Any]) -> Dict[str,Any]
if response.get('isBase64Encoded'):
body = base64.b64decode(response['body'])
response['body'] = body
return response
class ChaliceRequestHandler(BaseHTTPRequestHandler):
"""A class for mapping raw HTTP events to and from LocalGateway."""
protocol_version = 'HTTP/1.1'
def __init__(self, request, client_address, server, app_object, config):
# type: (bytes, Tuple[str, int], HTTPServer, Chalice, Config) -> None
self.local_gateway = LocalGateway(app_object, config)
BaseHTTPRequestHandler.__init__(
self, request, client_address, server) # type: ignore
def _parse_payload(self):
# type: () -> Tuple[HeaderType, Optional[str]]
body = None
content_length = int(self.headers.get('content-length', '0'))
if content_length > 0:
body = self.rfile.read(content_length)
converted_headers = dict(self.headers)
return converted_headers, body
def _generic_handle(self):
# type: () -> None
headers, body = self._parse_payload()
try:
response = self.local_gateway.handle_request(
method=self.command,
path=self.path,
headers=headers,
body=body
)
status_code = response['statusCode']
headers = response['headers'].copy()
headers.update(response['multiValueHeaders'])
body = response['body']
self._send_http_response(status_code, headers, body)
except LocalGatewayException as e:
self._send_error_response(e)
def _send_error_response(self, error):
# type: (LocalGatewayException) -> None
code = error.CODE
headers = error.headers
body = error.body
self._send_http_response(code, headers, body)
def _send_http_response(self, code, headers, body):
# type: (int, HeaderType, Optional[Union[str,bytes]]) -> None
if body is None:
self._send_http_response_no_body(code, headers)
else:
self._send_http_response_with_body(code, headers, body)
def _send_http_response_with_body(self, code, headers, body):
# type: (int, HeaderType, Union[str,bytes]) -> None
self.send_response(code)
if not isinstance(body, bytes):
body = body.encode('utf-8')
self.send_header('Content-Length', str(len(body)))
content_type = headers.pop(
'Content-Type', 'application/json')
self.send_header('Content-Type', content_type)
self._send_headers(headers)
self.wfile.write(body)
do_GET = do_PUT = do_POST = do_HEAD = do_DELETE = do_PATCH = do_OPTIONS = \
_generic_handle
def _send_http_response_no_body(self, code, headers):
# type: (int, HeaderType) -> None
headers['Content-Length'] = '0'
self.send_response(code)
self._send_headers(headers)
def _send_headers(self, headers):
# type: (HeaderType) -> None
for header_name, header_value in headers.items():
if isinstance(header_value, list):
for value in header_value:
self.send_header(header_name, value)
else:
self.send_header(header_name, header_value)
self.end_headers()
class ThreadedHTTPServer(ThreadingMixIn, HTTPServer):
"""Threading mixin to better support browsers.
When a browser sends a GET request to Chalice it keeps the connection open
for reuse. In the single threaded model this causes Chalice local to become
unresponsive to all clients other than that browser socket. Even sending a
header requesting that the client close the connection is not good enough,
the browswer will simply open another one and sit on it.
"""
daemon_threads = True
class LocalDevServer(object):
def __init__(self, app_object, config, host, port,
handler_cls=ChaliceRequestHandler,
server_cls=ThreadedHTTPServer):
# type: (Chalice, Config, str, int, HandlerCls, ServerCls) -> None
self.app_object = app_object
self.host = host
self.port = port
self._wrapped_handler = functools.partial(<|fim▁hole|> def handle_single_request(self):
# type: () -> None
self.server.handle_request()
def serve_forever(self):
# type: () -> None
print("Serving on http://%s:%s" % (self.host, self.port))
self.server.serve_forever()
def shutdown(self):
# type: () -> None
# This must be called from another thread of else it
# will deadlock.
self.server.shutdown()
class HTTPServerThread(threading.Thread):
"""Thread that manages starting/stopping local HTTP server.
This is a small wrapper around a normal threading.Thread except
that it adds shutdown capability of the HTTP server, which is
not part of the normal threading.Thread interface.
"""
def __init__(self, server_factory):
# type: (Callable[[], LocalDevServer]) -> None
threading.Thread.__init__(self)
self._server_factory = server_factory
self._server = None # type: Optional[LocalDevServer]
self.daemon = True
def run(self):
# type: () -> None
self._server = self._server_factory()
self._server.serve_forever()
def shutdown(self):
# type: () -> None
if self._server is not None:
self._server.shutdown()
class LocalChalice(Chalice):
_THREAD_LOCAL = threading.local()
# This is a known mypy bug where you can't override instance
# variables with properties. So this should be type safe, which
# is why we're adding the type: ignore comments here.
# See: https://github.com/python/mypy/issues/4125
@property # type: ignore
def current_request(self): # type: ignore
# type: () -> Request
return self._THREAD_LOCAL.current_request
@current_request.setter
def current_request(self, value): # type: ignore
# type: (Request) -> None
self._THREAD_LOCAL.current_request = value<|fim▁end|> | handler_cls, app_object=app_object, config=config)
self.server = server_cls((host, port), self._wrapped_handler)
|
<|file_name|>ListExampleFolder.js<|end_file_name|><|fim▁begin|>import React from 'react';
import MobileTearSheet from './MobileTearSheet';
import List from 'material-ui/lib/lists/list';
import ListItem from 'material-ui/lib/lists/list-item';
import ActionInfo from 'material-ui/lib/svg-icons/action/info';
import Divider from 'material-ui/lib/divider';
import Avatar from 'material-ui/lib/avatar';
import FileFolder from 'material-ui/lib/svg-icons/file/folder';
import ActionAssignment from 'material-ui/lib/svg-icons/action/assignment';
import Colors from 'material-ui/lib/styles/colors';
import EditorInsertChart from 'material-ui/lib/svg-icons/editor/insert-chart';
const ListExampleFolder = () => (
<MobileTearSheet>
<List subheader="Folders" insetSubheader={true}>
<ListItem
leftAvatar={<Avatar icon={<FileFolder />} />}
rightIcon={<ActionInfo />}
primaryText="Photos"
secondaryText="Jan 9, 2014"
/>
<ListItem
leftAvatar={<Avatar icon={<FileFolder />} />}
rightIcon={<ActionInfo />}
primaryText="Recipes"
secondaryText="Jan 17, 2014"
/>
<ListItem
leftAvatar={<Avatar icon={<FileFolder />} />}
rightIcon={<ActionInfo />}
primaryText="Work"
secondaryText="Jan 28, 2014"
/><|fim▁hole|> leftAvatar={<Avatar icon={<ActionAssignment />} backgroundColor={Colors.blue500} />}
rightIcon={<ActionInfo />}
primaryText="Vacation itinerary"
secondaryText="Jan 20, 2014"
/>
<ListItem
leftAvatar={<Avatar icon={<EditorInsertChart />} backgroundColor={Colors.yellow600} />}
rightIcon={<ActionInfo />}
primaryText="Kitchen remodel"
secondaryText="Jan 10, 2014"
/>
</List>
</MobileTearSheet>
);
export default ListExampleFolder;<|fim▁end|> | </List>
<Divider inset={true} />
<List subheader="Files" insetSubheader={true}>
<ListItem |
<|file_name|>__init__.py<|end_file_name|><|fim▁begin|>"""Solve the Project Euler problems using functional Python.
https://projecteuler.net/archives
"""
from importlib import import_module
from os import listdir<|fim▁hole|>SOLVED = set(
int(m.group(1))
for f in listdir(abspath(dirname(__file__)))
for m in (match(r"^p(\d{3})\.py$", f),) if m
)
def compute(problem: int):
"""Compute the answer to problem `problem`."""
assert problem in SOLVED, "Problem currently unsolved."
module = import_module("euler.p{:03d}".format(problem))
return module.compute()<|fim▁end|> | from os.path import abspath, dirname
from re import match
|
<|file_name|>FeedBackInfo.java<|end_file_name|><|fim▁begin|>package com.oa.bean;
public class FeedBackInfo {
private Long id;
private String feedbackinfo;
private String userid;
private String date;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getFeedbackinfo() {
return feedbackinfo;
}
public void setFeedbackinfo(String feedbackinfo) {
this.feedbackinfo = feedbackinfo;
}
public String getUserid() {
return userid;
}
public void setUserid(String userid) {
this.userid = userid;
}
public String getDate() {
return date;
}<|fim▁hole|> public void setDate(String date) {
this.date = date;
}
}<|fim▁end|> | |
<|file_name|>InventoryClick.java<|end_file_name|><|fim▁begin|>package com.a4server.gameserver.network.packets.clientpackets;
import com.a4server.gameserver.model.GameLock;
import com.a4server.gameserver.model.GameObject;
import com.a4server.gameserver.model.Hand;
import com.a4server.gameserver.model.Player;
import com.a4server.gameserver.model.inventory.AbstractItem;
import com.a4server.gameserver.model.inventory.Inventory;
import com.a4server.gameserver.model.inventory.InventoryItem;
import com.a4server.gameserver.network.packets.serverpackets.InventoryUpdate;
import com.a4server.util.Utils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import static com.a4server.gameserver.model.GameObject.WAIT_LOCK;
/**
* клик по объекту в инвентаре
* Created by arksu on 26.02.15.
*/
public class InventoryClick extends GameClientPacket
{
private static final Logger _log = LoggerFactory.getLogger(InventoryClick.class.getName());
private int _inventoryId;
private int _objectId;
private int _btn;
private int _mod;
/**
* отступ в пикселах внутри вещи где произошел клик
*/
private int _offsetX;
private int _offsetY;
/**
* слот в который тыкнули
*/
private int _x;
private int _y;
@Override
public void readImpl()
{
_inventoryId = readD();
_objectId = readD();
_btn = readC();
_mod = readC();
_offsetX = readC();
_offsetY = readC();
_x = readC();
_y = readC();
}
@Override
public void run()
{
_log.debug("obj=" + _objectId + " inv=" + _inventoryId + " (" + _x + ", " + _y + ")" + " offset=" + _offsetX + ", " + _offsetY + " mod=" + _mod);
Player player = client.getPlayer();
if (player != null && _btn == 0)
{
try (GameLock ignored = player.lock())
{
// держим в руке что-то?
if (player.getHand() == null)
{
// в руке ничего нет. возьмем из инвентаря
InventoryItem item = null;
if (player.getInventory() != null)
{
item = player.getInventory().findItem(_objectId);
}
// не нашли эту вещь у себя в инвентаре
// попробуем найти в объекте с которым взаимодействуем
if (item == null && player.isInteractive())
{
for (GameObject object : player.getInteractWith())
{
item = object.getInventory() != null ? object.getInventory().findItem(_objectId) : null;
if (item != null)
{
break;
}
}
}
// пробуем взять вещь из инвентаря
if (item != null)
{
GameObject object = item.getParentInventory().getObject();
try (GameLock ignored2 = object.lock())
{
InventoryItem taked = item.getParentInventory().takeItem(item);
// взяли вещь из инвентаря
if (taked != null)
{
object.sendInteractPacket(new InventoryUpdate(item.getParentInventory()));
// какая кнопка была зажата
switch (_mod)
{
case Utils.MOD_ALT:
// сразу перекинем вещь в инвентарь
if (!putItem(player, taked, -1, -1))
{
setHand(player, taked);
}
break;
default:
// ничего не нажато. пихаем в руку
setHand(player, taked);
break;
}
}
}
}
else
{
// возможно какой-то баг или ошибка. привлечем внимание
_log.error("InventoryClick: item=null");
}
}
else
{
// положим в инвентарь то что держим в руке
Hand hand = player.getHand();
if (putItem(player, hand.getItem(), _x - hand.getOffsetX(), _y - hand.getOffsetY()))
{
player.setHand(null);
}
}
}
}
}
/**
* положить вещь в инвентарь
* @param item вещь которую кладем
*/
public boolean putItem(Player player, AbstractItem item, int x, int y)
{
Inventory to = null;
// ищем нужный инвентарь у себя
if (player.getInventory() != null)
{
to = player.getInventory().findInventory(_inventoryId);
}
// а потом в объектах с которыми взаимодействую
if (to == null && player.isInteractive())
{
for (GameObject object : player.getInteractWith())
{
to = object.getInventory() != null ? object.getInventory().findInventory(_inventoryId) : null;
if (to != null)
{
break;
}
}
}
<|fim▁hole|> {
try
{
InventoryItem putItem = to.putItem(item, x, y);
if (putItem != null)
{
to.getObject().sendInteractPacket(new InventoryUpdate(to));
return true;
}
}
finally
{
to.getObject().unlock();
}
}
}
return false;
}
private void setHand(Player player, InventoryItem taked)
{
player.setHand(new Hand(player, taked,
_x - taked.getX(),
_y - taked.getY(),
_offsetX, _offsetY
));
}
}<|fim▁end|> | // положим в инвентарь
if (to != null)
{
if (to.getObject().tryLock(WAIT_LOCK)) |
<|file_name|>$rename.js<|end_file_name|><|fim▁begin|>/**
* Created by sh on 15/7/6.
*/
"use strict";
var type = require("../type");
exports.parse = function (object, define, addition) {
return type.dataParse(object, {type: Object, contents: String}, addition);<|fim▁hole|><|fim▁end|> | }; |
<|file_name|>project_spec.js<|end_file_name|><|fim▁begin|>'use strict';
var chakram = require('chakram'),
expect = chakram.expect,
Request = require('../../commons/request.js'),
request = new Request(),
User = require('../user/user.js'),
user = new User(),
Project = require('./project.js'),
project = new Project(),
ObjectID = require('mongodb').ObjectID,
config = require('../../../../config/config.json');
describe('Project test', function() {
//GET / get project published
it('Get project published - all params', function() {
return request.getBackend('/project?count=*&page=0&query=%7B%22hardwareTags%22:%7B%22$all%22:%5B%22us%22%5D%7D%7D',200).then(function(response) {
expect(response).not.have.to.json([]);
return chakram.wait();
});
});
it.skip('Get project published - without params', function() {
return request.getBackend('/project',400).then(function() {
return chakram.wait();
});
});
it.skip('Get project published - invalid params', function() {
return request.getBackend('/project?p=0',400).then(function() {
return request.getBackend('/project?cont=*',400).then(function() {
return request.getBackend('/project?qery=%7B%22hardwareTags%22:%7B%22$all%22:%5B%22us%22%5D%7D%7D',400).then(function() {
return chakram.wait();
});
});
});
});
it('Get project published - one params', function() {
return request.getBackend('/project?page=1',200).then(function(response1) {
expect(response1).not.have.to.json([]);
return request.getBackend('/project?count=*',200).then(function(response2) {
expect(response2).have.to.json('count', function(number) {
expect(number).to.be.at.least(0);
});
return request.getBackend('/project?query=%7B%22hardwareTags%22:%7B%22$all%22:%5B%22us%22%5D%7D%7D',200).then(function(response3) {
expect(response3).not.have.to.json([]);
return chakram.wait();
});
});
});
});
//GET /project/me
it('Get projects of a user', function() {
var userRandom = user.generateRandomUser();
return request.postBackend('/user',200,userRandom).then(function(response) {
var project1 = project.generateProjectRandom();
var project2 = project.generateProjectRandom();
return request.postBackend('/project',200,project1,{headers:{'Authorization':'Bearer '+response.body.token}}).then(function() {
return request.postBackend('/project',200,project2,{headers:{'Authorization':'Bearer '+response.body.token}}).then(function() {
return request.getBackend('/project/me?page=0&pageSize=1',200,{headers:{'Authorization':'Bearer '+response.body.token}}).then(function(response2) {
expect(response2).have.to.json(function(json) {
expect(json.length).to.be.equal(1);
});
return request.getBackend('/project/me?pageSize=5',200,{headers:{'Authorization':'Bearer '+response.body.token}}).then(function(response3) {<|fim▁hole|> expect(response3).have.to.json(function(json) {
expect(json.length).to.be.equal(2);
});
return chakram.wait();
});
});
});
});
});
});
it.skip('Get projects of a user - without mandatory params', function() {
var userRandom = user.generateRandomUser();
return request.postBackend('/user',200,userRandom).then(function(response) {
return request.getBackend('/project/me?page=0',400,{headers:{'Authorization':'Bearer '+response.body.token}}).then(function() {
return request.getBackend('/project/me',400,{headers:{'Authorization':'Bearer '+response.body.token}}).then(function() {
return chakram.wait();
});
});
});
});
it('Get projects of a user - token is incorrect', function() {
var token = Math.random().toString(36).substr(2) + Math.random().toString(36).substr(2);
return request.getBackend('/project/me',401,{headers:{'Authorization':'Bearer '+token}}).then(function() {
return request.getBackend('/project/me?page=0',401,{headers:{'Authorization':'Bearer '+token}}).then(function() {
return request.getBackend('/project/me?pageSize=1',401,{headers:{'Authorization':'Bearer '+token}}).then(function() {
return request.getBackend('/project/me?page=0&pageSize=1',401,{headers:{'Authorization':'Bearer '+token}}).then(function() {
return chakram.wait();
});
});
});
});
});
//GET /project/shared
it('Get shared projects of a user', function() {
return request.postBackend('/auth/local',200,config.adminLogin).then(function(response) {
return request.getBackend('/project/shared?pageSize=1',200,{headers:{'Authorization':'Bearer '+response.body.token}}).then(function(response2) {
expect(response2).have.to.json(function(json) {
expect(json.length).to.be.equal(1);
});
return request.getBackend('/project/shared?page=0&pageSize=3',200,{headers:{'Authorization':'Bearer '+response.body.token}}).then(function(response3) {
expect(response3).have.to.json(function(json) {
expect(json.length).to.be.equal(3);
});
});
});
});
});
it('Get shared projects of a user - token is incorrect', function() {
var token = Math.random().toString(36).substr(2) + Math.random().toString(36).substr(2);
return request.getBackend('/project/shared',401,{headers:{'Authorization':'Bearer '+token}}).then(function() {
return request.getBackend('/project/shared?page=0',401,{headers:{'Authorization':'Bearer '+token}}).then(function() {
return request.getBackend('/project/shared?pageSize=1',401,{headers:{'Authorization':'Bearer '+token}}).then(function() {
return request.getBackend('/project/shared?page=0&pageSize=1',401,{headers:{'Authorization':'Bearer '+token}}).then(function() {
return chakram.wait();
});
});
});
});
});
it.skip('Get projects of a user - without mandatory params', function() {
return request.postBackend('/auth/local',200,config.adminLogin).then(function(response) {
return request.getBackend('/project/shared?page=0',400,{headers:{'Authorization':'Bearer '+response.body.token}}).then(function() {
return request.getBackend('/project/shared',400,{headers:{'Authorization':'Bearer '+response.body.token}}).then(function() {
return chakram.wait();
});
});
});
});
//GET /project/:id
it('Get a project', function() {
var userRandom = user.generateRandomUser();
return request.postBackend('/user',200,userRandom).then(function(response) {
var project1 = project.generateProjectRandom();
return request.postBackend('/project',200,project1,{headers:{'Authorization':'Bearer '+response.body.token}}).then(function(response2) {
return request.getBackend('/project/'+response2.body,200,{headers:{'Authorization':'Bearer '+response.body.token}}).then(function(response3) {
expect(response3).not.have.to.json({});
chakram.wait();
});
});
});
});
it('Get a project - the project no exist', function() {
var idRandom = new ObjectID();
var userRandom = user.generateRandomUser();
return request.postBackend('/user',200,userRandom).then(function(response) {
return request.getBackend('/project/'+idRandom,404,{headers:{'Authorization':'Bearer '+response.body.token}}).then(function() {
chakram.wait();
});
});
});
it('Get a project - invalid token', function() {
var token = Math.random().toString(36).substr(2) + Math.random().toString(36).substr(2);
var userRandom = user.generateRandomUser();
return request.postBackend('/user',200,userRandom).then(function(response) {
var project1 = project.generateProjectRandom();
return request.postBackend('/project',200,project1,{headers:{'Authorization':'Bearer '+response.body.token}}).then(function(response2) {
return request.getBackend('/project/'+response2.body,401,{headers:{'Authorization':'Bearer '+token}}).then(function() {
chakram.wait();
});
});
});
});
});<|fim▁end|> | |
<|file_name|>index.ts<|end_file_name|><|fim▁begin|>export * from './alert.service';
export * from './authentication.service';
export * from './task.service';
export * from './project.service';
export * from './label.service';<|fim▁hole|><|fim▁end|> | export * from './user.service'; |
<|file_name|>pt-br.js<|end_file_name|><|fim▁begin|>/*
<|fim▁hole|> copy: 'Copyright © $1. Todos os direitos reservados.',
dlgTitle: 'Sobre o CKEditor 4',
moreInfo: 'Para informações sobre a licença por favor visite o nosso site:'
} );<|fim▁end|> | Copyright (c) 2003-2019, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.md or https://ckeditor.com/legal/ckeditor-oss-license
*/
CKEDITOR.plugins.setLang( 'about', 'pt-br', {
|
<|file_name|>issue-11873.rs<|end_file_name|><|fim▁begin|><|fim▁hole|>// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
fn main() {
let mut v = vec!(1);
let mut f = || v.push(2);
let _w = v; //~ ERROR: cannot move out of `v`
f();
}<|fim▁end|> | // Copyright 2012-2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at |
<|file_name|>htmlfieldsetelement.rs<|end_file_name|><|fim▁begin|>/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
use dom::attr::Attr;
use dom::bindings::codegen::Bindings::HTMLFieldSetElementBinding;
use dom::bindings::codegen::Bindings::HTMLFieldSetElementBinding::HTMLFieldSetElementMethods;
use dom::bindings::inheritance::{Castable, ElementTypeId, HTMLElementTypeId, NodeTypeId};
use dom::bindings::js::{Root, RootedReference};
use dom::document::Document;
use dom::element::{AttributeMutation, Element};
use dom::htmlcollection::{CollectionFilter, HTMLCollection};
use dom::htmlelement::HTMLElement;
use dom::htmlformelement::{FormControl, HTMLFormElement};
use dom::htmllegendelement::HTMLLegendElement;
use dom::node::{Node, window_from_node};
use dom::validitystate::ValidityState;
use dom::virtualmethods::VirtualMethods;
use selectors::states::*;
use util::str::{DOMString, StaticStringVec};
#[dom_struct]
pub struct HTMLFieldSetElement {
htmlelement: HTMLElement
}
impl HTMLFieldSetElement {
fn new_inherited(localName: DOMString,
prefix: Option<DOMString>,
document: &Document) -> HTMLFieldSetElement {
HTMLFieldSetElement {
htmlelement:
HTMLElement::new_inherited_with_state(IN_ENABLED_STATE,
localName, prefix, document)
}
}
#[allow(unrooted_must_root)]
pub fn new(localName: DOMString,
prefix: Option<DOMString>,
document: &Document) -> Root<HTMLFieldSetElement> {
let element = HTMLFieldSetElement::new_inherited(localName, prefix, document);
Node::reflect_node(box element, document, HTMLFieldSetElementBinding::Wrap)
}
}
impl HTMLFieldSetElementMethods for HTMLFieldSetElement {
// https://html.spec.whatwg.org/multipage/#dom-fieldset-elements
fn Elements(&self) -> Root<HTMLCollection> {
#[derive(JSTraceable, HeapSizeOf)]
struct ElementsFilter;
impl CollectionFilter for ElementsFilter {
fn filter<'a>(&self, elem: &'a Element, _root: &'a Node) -> bool {
static TAG_NAMES: StaticStringVec = &["button", "fieldset", "input",
"keygen", "object", "output", "select", "textarea"];
TAG_NAMES.iter().any(|&tag_name| tag_name == &**elem.local_name())
}
}
let filter = box ElementsFilter;
let window = window_from_node(self);
HTMLCollection::create(window.r(), self.upcast(), filter)
}
// https://html.spec.whatwg.org/multipage/#dom-cva-validity
fn Validity(&self) -> Root<ValidityState> {
let window = window_from_node(self);
ValidityState::new(window.r())
}
// https://html.spec.whatwg.org/multipage/#dom-fieldset-disabled
make_bool_getter!(Disabled, "disabled");
// https://html.spec.whatwg.org/multipage/#dom-fieldset-disabled
make_bool_setter!(SetDisabled, "disabled");
// https://html.spec.whatwg.org/multipage/#dom-fae-form
fn GetForm(&self) -> Option<Root<HTMLFormElement>> {
self.form_owner()
}
}
impl VirtualMethods for HTMLFieldSetElement {<|fim▁hole|> }
fn attribute_mutated(&self, attr: &Attr, mutation: AttributeMutation) {
self.super_type().unwrap().attribute_mutated(attr, mutation);
match attr.local_name() {
&atom!("disabled") => {
let disabled_state = match mutation {
AttributeMutation::Set(None) => true,
AttributeMutation::Set(Some(_)) => {
// Fieldset was already disabled before.
return;
},
AttributeMutation::Removed => false,
};
let node = self.upcast::<Node>();
let el = self.upcast::<Element>();
el.set_disabled_state(disabled_state);
el.set_enabled_state(!disabled_state);
let mut found_legend = false;
let children = node.children().filter(|node| {
if found_legend {
true
} else if node.is::<HTMLLegendElement>() {
found_legend = true;
false
} else {
true
}
});
let fields = children.flat_map(|child| {
child.traverse_preorder().filter(|descendant| {
match descendant.type_id() {
NodeTypeId::Element(
ElementTypeId::HTMLElement(
HTMLElementTypeId::HTMLButtonElement)) |
NodeTypeId::Element(
ElementTypeId::HTMLElement(
HTMLElementTypeId::HTMLInputElement)) |
NodeTypeId::Element(
ElementTypeId::HTMLElement(
HTMLElementTypeId::HTMLSelectElement)) |
NodeTypeId::Element(
ElementTypeId::HTMLElement(
HTMLElementTypeId::HTMLTextAreaElement)) => {
true
},
_ => false,
}
})
});
if disabled_state {
for field in fields {
let el = field.downcast::<Element>().unwrap();
el.set_disabled_state(true);
el.set_enabled_state(false);
}
} else {
for field in fields {
let el = field.downcast::<Element>().unwrap();
el.check_disabled_attribute();
el.check_ancestors_disabled_state_for_form_control();
}
}
},
_ => {},
}
}
}
impl FormControl for HTMLFieldSetElement {}<|fim▁end|> | fn super_type(&self) -> Option<&VirtualMethods> {
Some(self.upcast::<HTMLElement>() as &VirtualMethods) |
<|file_name|>no.js<|end_file_name|><|fim▁begin|>/*
Copyright (c) 2003-2019, CKSource - Frederico Knabben. All rights reserved.<|fim▁hole|>*/
CKEDITOR.plugins.setLang( 'save', 'no', {
toolbar: 'Lagre'
} );<|fim▁end|> | For licensing, see LICENSE.md or https://ckeditor.com/legal/ckeditor-oss-license |
<|file_name|>test_tf.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*-
from __future__ import absolute_import, division, print_function, unicode_literals
import pytest
from sumy.models import TfDocumentModel
from sumy.nlp.tokenizers import Tokenizer
def test_no_tokenizer_with_string():
with pytest.raises(ValueError):
TfDocumentModel("text without tokenizer")
def test_pretokenized_words():<|fim▁hole|>
terms = tuple(sorted(model.terms))
assert terms == ("wa", "wb")
def test_pretokenized_words_frequencies():
model = TfDocumentModel(("wC", "wC", "WC", "wA", "WB", "wB"))
assert model.term_frequency("wa") == 1
assert model.term_frequency("wb") == 2
assert model.term_frequency("wc") == 3
assert model.term_frequency("wd") == 0
assert model.most_frequent_terms() == ("wc", "wb", "wa")
def test_magnitude():
tokenizer = Tokenizer("english")
text = "wA wB wC wD"
model = TfDocumentModel(text, tokenizer)
assert model.magnitude == pytest.approx(2.0)
def test_terms():
tokenizer = Tokenizer("english")
text = "wA wB wC wD wB wD wE"
model = TfDocumentModel(text, tokenizer)
terms = tuple(sorted(model.terms))
assert terms == ("wa", "wb", "wc", "wd", "we")
def test_term_frequency():
tokenizer = Tokenizer("english")
text = "wA wB wC wA wA wC wD wCwB"
model = TfDocumentModel(text, tokenizer)
assert model.term_frequency("wa") == 3
assert model.term_frequency("wb") == 1
assert model.term_frequency("wc") == 2
assert model.term_frequency("wd") == 1
assert model.term_frequency("wcwb") == 1
assert model.term_frequency("we") == 0
assert model.term_frequency("missing") == 0
def test_most_frequent_terms():
tokenizer = Tokenizer("english")
text = "wE wD wC wB wA wE WD wC wB wE wD WE wC wD wE"
model = TfDocumentModel(text, tokenizer)
assert model.most_frequent_terms(1) == ("we",)
assert model.most_frequent_terms(2) == ("we", "wd")
assert model.most_frequent_terms(3) == ("we", "wd", "wc")
assert model.most_frequent_terms(4) == ("we", "wd", "wc", "wb")
assert model.most_frequent_terms(5) == ("we", "wd", "wc", "wb", "wa")
assert model.most_frequent_terms() == ("we", "wd", "wc", "wb", "wa")
def test_most_frequent_terms_empty():
tokenizer = Tokenizer("english")
model = TfDocumentModel("", tokenizer)
assert model.most_frequent_terms() == ()
assert model.most_frequent_terms(10) == ()
def test_most_frequent_terms_negative_count():
tokenizer = Tokenizer("english")
model = TfDocumentModel("text", tokenizer)
with pytest.raises(ValueError):
model.most_frequent_terms(-1)
def test_normalized_words_frequencies():
words = "a b c d e c b d c e e d e d e".split()
model = TfDocumentModel(tuple(words))
assert model.normalized_term_frequency("a") == pytest.approx(1/5)
assert model.normalized_term_frequency("b") == pytest.approx(2/5)
assert model.normalized_term_frequency("c") == pytest.approx(3/5)
assert model.normalized_term_frequency("d") == pytest.approx(4/5)
assert model.normalized_term_frequency("e") == pytest.approx(5/5)
assert model.normalized_term_frequency("z") == pytest.approx(0.0)
assert model.most_frequent_terms() == ("e", "d", "c", "b", "a")
def test_normalized_words_frequencies_with_smoothing_term():
words = "a b c d e c b d c e e d e d e".split()
model = TfDocumentModel(tuple(words))
assert model.normalized_term_frequency("a", 0.5) == pytest.approx(0.5 + 1/10)
assert model.normalized_term_frequency("b", 0.5) == pytest.approx(0.5 + 2/10)
assert model.normalized_term_frequency("c", 0.5) == pytest.approx(0.5 + 3/10)
assert model.normalized_term_frequency("d", 0.5) == pytest.approx(0.5 + 4/10)
assert model.normalized_term_frequency("e", 0.5) == pytest.approx(0.5 + 5/10)
assert model.normalized_term_frequency("z", 0.5) == pytest.approx(0.5)
assert model.most_frequent_terms() == ("e", "d", "c", "b", "a")<|fim▁end|> | model = TfDocumentModel(("wA", "WB", "wB", "WA")) |
<|file_name|>prometheusremotewrite_test.go<|end_file_name|><|fim▁begin|>package prometheusremotewrite
import (
"bytes"
"fmt"
"github.com/gogo/protobuf/proto"
"github.com/golang/snappy"
"github.com/prometheus/common/model"
"github.com/prometheus/prometheus/prompb"
"strings"
"testing"
"time"
"github.com/influxdata/telegraf"
"github.com/influxdata/telegraf/testutil"
"github.com/stretchr/testify/require"
)
func TestRemoteWriteSerialize(t *testing.T) {
tests := []struct {
name string
config FormatConfig
metric telegraf.Metric
expected []byte
}{
{
name: "simple",
metric: testutil.MustMetric(
"cpu",
map[string]string{
"host": "example.org",
},
map[string]interface{}{
"time_idle": 42.0,
},
time.Unix(0, 0),
),
expected: []byte(`
cpu_time_idle{host="example.org"} 42
`),
},
{
name: "prometheus input untyped",
metric: testutil.MustMetric(
"prometheus",
map[string]string{
"code": "400",
"method": "post",
},
map[string]interface{}{
"http_requests_total": 3.0,
},
time.Unix(0, 0),
telegraf.Untyped,
),
expected: []byte(`
http_requests_total{code="400", method="post"} 3
`),
},
{
name: "prometheus input counter",
metric: testutil.MustMetric(
"prometheus",
map[string]string{
"code": "400",
"method": "post",
},
map[string]interface{}{
"http_requests_total": 3.0,
},
time.Unix(0, 0),
telegraf.Counter,
),
expected: []byte(`
http_requests_total{code="400", method="post"} 3
`),
},
{
name: "prometheus input gauge",
metric: testutil.MustMetric(
"prometheus",
map[string]string{
"code": "400",
"method": "post",
},
map[string]interface{}{
"http_requests_total": 3.0,
},
time.Unix(0, 0),
telegraf.Gauge,
),
expected: []byte(`
http_requests_total{code="400", method="post"} 3
`),
},
{
name: "prometheus input histogram no buckets",
metric: testutil.MustMetric(
"prometheus",
map[string]string{},
map[string]interface{}{
"http_request_duration_seconds_sum": 53423,
"http_request_duration_seconds_count": 144320,
},
time.Unix(0, 0),
telegraf.Histogram,
),
expected: []byte(`
http_request_duration_seconds_count 144320
http_request_duration_seconds_sum 53423
http_request_duration_seconds_bucket{le="+Inf"} 144320
`),
},
{
name: "prometheus input histogram only bucket",
metric: testutil.MustMetric(
"prometheus",
map[string]string{
"le": "0.5",
},
map[string]interface{}{
"http_request_duration_seconds_bucket": 129389.0,
},
time.Unix(0, 0),
telegraf.Histogram,
),
expected: []byte(`
http_request_duration_seconds_count 0
http_request_duration_seconds_sum 0
http_request_duration_seconds_bucket{le="+Inf"} 0
http_request_duration_seconds_bucket{le="0.5"} 129389
`),
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
s, err := NewSerializer(FormatConfig{
MetricSortOrder: SortMetrics,
StringHandling: tt.config.StringHandling,
})
require.NoError(t, err)
data, err := s.Serialize(tt.metric)
actual, err := prompbToText(data)
require.NoError(t, err)
require.Equal(t, strings.TrimSpace(string(tt.expected)),
strings.TrimSpace(string(actual)))
})
}
}
func TestRemoteWriteSerializeBatch(t *testing.T) {
tests := []struct {
name string
config FormatConfig
metrics []telegraf.Metric
expected []byte
}{
{
name: "simple",
metrics: []telegraf.Metric{
testutil.MustMetric(
"cpu",
map[string]string{
"host": "one.example.org",
},
map[string]interface{}{
"time_idle": 42.0,
},
time.Unix(0, 0),
),
testutil.MustMetric(
"cpu",
map[string]string{
"host": "two.example.org",
},
map[string]interface{}{
"time_idle": 42.0,
},
time.Unix(0, 0),
),
},
expected: []byte(`
cpu_time_idle{host="one.example.org"} 42
cpu_time_idle{host="two.example.org"} 42
`),
},
{
name: "multiple metric families",
metrics: []telegraf.Metric{
testutil.MustMetric(
"cpu",
map[string]string{
"host": "one.example.org",
},
map[string]interface{}{
"time_idle": 42.0,
"time_guest": 42.0,
},
time.Unix(0, 0),
),
},
expected: []byte(`
cpu_time_guest{host="one.example.org"} 42
cpu_time_idle{host="one.example.org"} 42
`),
},
{
name: "histogram",
metrics: []telegraf.Metric{
testutil.MustMetric(
"prometheus",
map[string]string{},
map[string]interface{}{
"http_request_duration_seconds_sum": 53423,
"http_request_duration_seconds_count": 144320,
},
time.Unix(0, 0),
telegraf.Histogram,
),
testutil.MustMetric(
"prometheus",
map[string]string{"le": "0.05"},
map[string]interface{}{
"http_request_duration_seconds_bucket": 24054.0,
},
time.Unix(0, 0),
telegraf.Histogram,
),
testutil.MustMetric(
"prometheus",
map[string]string{"le": "0.1"},
map[string]interface{}{
"http_request_duration_seconds_bucket": 33444.0,
},
time.Unix(0, 0),
telegraf.Histogram,
),
testutil.MustMetric(
"prometheus",
map[string]string{"le": "0.2"},
map[string]interface{}{
"http_request_duration_seconds_bucket": 100392.0,
},
time.Unix(0, 0),
telegraf.Histogram,
),
testutil.MustMetric(
"prometheus",
map[string]string{"le": "0.5"},
map[string]interface{}{
"http_request_duration_seconds_bucket": 129389.0,
},
time.Unix(0, 0),
telegraf.Histogram,
),
testutil.MustMetric(
"prometheus",
map[string]string{"le": "1.0"},
map[string]interface{}{
"http_request_duration_seconds_bucket": 133988.0,
},
time.Unix(0, 0),
telegraf.Histogram,
),
testutil.MustMetric(
"prometheus",
map[string]string{"le": "+Inf"},
map[string]interface{}{
"http_request_duration_seconds_bucket": 144320.0,
},
time.Unix(0, 0),
telegraf.Histogram,
),
},
expected: []byte(`
http_request_duration_seconds_count 144320
http_request_duration_seconds_sum 53423
http_request_duration_seconds_bucket{le="+Inf"} 144320
http_request_duration_seconds_bucket{le="0.05"} 24054
http_request_duration_seconds_bucket{le="0.1"} 33444
http_request_duration_seconds_bucket{le="0.2"} 100392
http_request_duration_seconds_bucket{le="0.5"} 129389
http_request_duration_seconds_bucket{le="1"} 133988
`),
},
{
name: "summary with quantile",
metrics: []telegraf.Metric{
testutil.MustMetric(
"prometheus",
map[string]string{},
map[string]interface{}{
"rpc_duration_seconds_sum": 1.7560473e+07,
"rpc_duration_seconds_count": 2693,
},
time.Unix(0, 0),
telegraf.Summary,
),
testutil.MustMetric(
"prometheus",
map[string]string{"quantile": "0.01"},
map[string]interface{}{
"rpc_duration_seconds": 3102.0,
},
time.Unix(0, 0),
telegraf.Summary,
),
testutil.MustMetric(
"prometheus",
map[string]string{"quantile": "0.05"},
map[string]interface{}{
"rpc_duration_seconds": 3272.0,
},
time.Unix(0, 0),
telegraf.Summary,
),
testutil.MustMetric(
"prometheus",
map[string]string{"quantile": "0.5"},
map[string]interface{}{
"rpc_duration_seconds": 4773.0,
},
time.Unix(0, 0),
telegraf.Summary,
),
testutil.MustMetric(
"prometheus",
map[string]string{"quantile": "0.9"},
map[string]interface{}{
"rpc_duration_seconds": 9001.0,
},
time.Unix(0, 0),
telegraf.Summary,
),
testutil.MustMetric(
"prometheus",
map[string]string{"quantile": "0.99"},
map[string]interface{}{
"rpc_duration_seconds": 76656.0,
},
time.Unix(0, 0),
telegraf.Summary,
),
},
expected: []byte(`
rpc_duration_seconds_count 2693
rpc_duration_seconds_sum 17560473
rpc_duration_seconds{quantile="0.01"} 3102
rpc_duration_seconds{quantile="0.05"} 3272
rpc_duration_seconds{quantile="0.5"} 4773
rpc_duration_seconds{quantile="0.9"} 9001
rpc_duration_seconds{quantile="0.99"} 76656
`),
},
{
name: "newer sample",
metrics: []telegraf.Metric{
testutil.MustMetric(
"cpu",
map[string]string{},
map[string]interface{}{
"time_idle": 43.0,
},
time.Unix(1, 0),
),
testutil.MustMetric(<|fim▁hole|> map[string]string{},
map[string]interface{}{
"time_idle": 42.0,
},
time.Unix(0, 0),
),
},
expected: []byte(`
cpu_time_idle 43
`),
},
{
name: "colons are not replaced in metric name from measurement",
metrics: []telegraf.Metric{
testutil.MustMetric(
"cpu::xyzzy",
map[string]string{},
map[string]interface{}{
"time_idle": 42.0,
},
time.Unix(0, 0),
),
},
expected: []byte(`
cpu::xyzzy_time_idle 42
`),
},
{
name: "colons are not replaced in metric name from field",
metrics: []telegraf.Metric{
testutil.MustMetric(
"cpu",
map[string]string{},
map[string]interface{}{
"time:idle": 42.0,
},
time.Unix(0, 0),
),
},
expected: []byte(`
cpu_time:idle 42
`),
},
{
name: "invalid label",
metrics: []telegraf.Metric{
testutil.MustMetric(
"cpu",
map[string]string{
"host-name": "example.org",
},
map[string]interface{}{
"time_idle": 42.0,
},
time.Unix(0, 0),
),
},
expected: []byte(`
cpu_time_idle{host_name="example.org"} 42
`),
},
{
name: "colons are replaced in label name",
metrics: []telegraf.Metric{
testutil.MustMetric(
"cpu",
map[string]string{
"host:name": "example.org",
},
map[string]interface{}{
"time_idle": 42.0,
},
time.Unix(0, 0),
),
},
expected: []byte(`
cpu_time_idle{host_name="example.org"} 42
`),
},
{
name: "discard strings",
metrics: []telegraf.Metric{
testutil.MustMetric(
"cpu",
map[string]string{},
map[string]interface{}{
"time_idle": 42.0,
"cpu": "cpu0",
},
time.Unix(0, 0),
),
},
expected: []byte(`
cpu_time_idle 42
`),
},
{
name: "string as label",
config: FormatConfig{
MetricSortOrder: SortMetrics,
StringHandling: StringAsLabel,
},
metrics: []telegraf.Metric{
testutil.MustMetric(
"cpu",
map[string]string{},
map[string]interface{}{
"time_idle": 42.0,
"cpu": "cpu0",
},
time.Unix(0, 0),
),
},
expected: []byte(`
cpu_time_idle{cpu="cpu0"} 42
`),
},
{
name: "string as label duplicate tag",
config: FormatConfig{
MetricSortOrder: SortMetrics,
StringHandling: StringAsLabel,
},
metrics: []telegraf.Metric{
testutil.MustMetric(
"cpu",
map[string]string{
"cpu": "cpu0",
},
map[string]interface{}{
"time_idle": 42.0,
"cpu": "cpu1",
},
time.Unix(0, 0),
),
},
expected: []byte(`
cpu_time_idle{cpu="cpu0"} 42
`),
},
{
name: "replace characters when using string as label",
config: FormatConfig{
MetricSortOrder: SortMetrics,
StringHandling: StringAsLabel,
},
metrics: []telegraf.Metric{
testutil.MustMetric(
"cpu",
map[string]string{},
map[string]interface{}{
"host:name": "example.org",
"time_idle": 42.0,
},
time.Unix(1574279268, 0),
),
},
expected: []byte(`
cpu_time_idle{host_name="example.org"} 42
`),
},
{
name: "multiple fields grouping",
metrics: []telegraf.Metric{
testutil.MustMetric(
"cpu",
map[string]string{
"cpu": "cpu0",
},
map[string]interface{}{
"time_guest": 8106.04,
"time_system": 26271.4,
"time_user": 92904.33,
},
time.Unix(0, 0),
),
testutil.MustMetric(
"cpu",
map[string]string{
"cpu": "cpu1",
},
map[string]interface{}{
"time_guest": 8181.63,
"time_system": 25351.49,
"time_user": 96912.57,
},
time.Unix(0, 0),
),
testutil.MustMetric(
"cpu",
map[string]string{
"cpu": "cpu2",
},
map[string]interface{}{
"time_guest": 7470.04,
"time_system": 24998.43,
"time_user": 96034.08,
},
time.Unix(0, 0),
),
testutil.MustMetric(
"cpu",
map[string]string{
"cpu": "cpu3",
},
map[string]interface{}{
"time_guest": 7517.95,
"time_system": 24970.82,
"time_user": 94148,
},
time.Unix(0, 0),
),
},
expected: []byte(`
cpu_time_guest{cpu="cpu0"} 8106.04
cpu_time_system{cpu="cpu0"} 26271.4
cpu_time_user{cpu="cpu0"} 92904.33
cpu_time_guest{cpu="cpu1"} 8181.63
cpu_time_system{cpu="cpu1"} 25351.49
cpu_time_user{cpu="cpu1"} 96912.57
cpu_time_guest{cpu="cpu2"} 7470.04
cpu_time_system{cpu="cpu2"} 24998.43
cpu_time_user{cpu="cpu2"} 96034.08
cpu_time_guest{cpu="cpu3"} 7517.95
cpu_time_system{cpu="cpu3"} 24970.82
cpu_time_user{cpu="cpu3"} 94148
`),
},
{
name: "summary with no quantile",
metrics: []telegraf.Metric{
testutil.MustMetric(
"prometheus",
map[string]string{},
map[string]interface{}{
"rpc_duration_seconds_sum": 1.7560473e+07,
"rpc_duration_seconds_count": 2693,
},
time.Unix(0, 0),
telegraf.Summary,
),
},
expected: []byte(`
rpc_duration_seconds_count 2693
rpc_duration_seconds_sum 17560473
`),
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
s, err := NewSerializer(FormatConfig{
MetricSortOrder: SortMetrics,
StringHandling: tt.config.StringHandling,
})
require.NoError(t, err)
data, err := s.SerializeBatch(tt.metrics)
require.NoError(t, err)
actual, err := prompbToText(data)
require.NoError(t, err)
require.Equal(t,
strings.TrimSpace(string(tt.expected)),
strings.TrimSpace(string(actual)))
})
}
}
func prompbToText(data []byte) ([]byte, error) {
var buf = bytes.Buffer{}
protobuff, err := snappy.Decode(nil, data)
if err != nil {
return nil, err
}
var req prompb.WriteRequest
err = proto.Unmarshal(protobuff, &req)
if err != nil {
return nil, err
}
samples := protoToSamples(&req)
for _, sample := range samples {
buf.Write([]byte(fmt.Sprintf("%s %s\n", sample.Metric.String(), sample.Value.String())))
}
if err != nil {
return nil, err
}
return buf.Bytes(), nil
}
func protoToSamples(req *prompb.WriteRequest) model.Samples {
var samples model.Samples
for _, ts := range req.Timeseries {
metric := make(model.Metric, len(ts.Labels))
for _, l := range ts.Labels {
metric[model.LabelName(l.Name)] = model.LabelValue(l.Value)
}
for _, s := range ts.Samples {
samples = append(samples, &model.Sample{
Metric: metric,
Value: model.SampleValue(s.Value),
Timestamp: model.Time(s.Timestamp),
})
}
}
return samples
}<|fim▁end|> | "cpu", |
<|file_name|>todo-list-view.js<|end_file_name|><|fim▁begin|>var $ = require('jquery');
var Backbone = require('backbone');
Backbone.$ = $;
//CHALLENGE: "bring in" the appropriate template for this view
var TodoListView = Backbone.View.extend({
tagName: 'div',<|fim▁hole|> },
render: function () {
var data = [];
this.collection.models.forEach(function (item) {
data.push({title: item.escape('title'), description: item.escape('description') });
});
this.$el.html(myTemplate({todoData:data}));
}
});
module.exports = TodoListView;<|fim▁end|> | className: 'list-group',
initialize: function () {
this.listenTo(this.collection,'all', this.render); |
<|file_name|>bitcoin_fa.ts<|end_file_name|><|fim▁begin|><?xml version="1.0" ?><!DOCTYPE TS><TS language="fa" version="2.0">
<defaultcodec>UTF-8</defaultcodec>
<context>
<name>AboutDialog</name>
<message>
<location filename="../forms/aboutdialog.ui" line="+14"/>
<source>About KCz</source>
<translation>در مورد KCz</translation>
</message>
<message>
<location line="+39"/>
<source><b>KCz</b> version</source>
<translation>نسخه KCz</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>⏎ ⏎ این نسخه نرم افزار آزمایشی است⏎ ⏎ نرم افزار تحت لیسانس MIT/X11 منتشر شده است. به فایل coping یا آدرس http://www.opensource.org/licenses/mit-license.php. مراجعه شود⏎ ⏎ این محصول شامل نرم افزاری است که با OpenSSL برای استفاده از OpenSSL Toolkit (http://www.openssl.org/) و نرم افزار نوشته شده توسط اریک یانگ ([email protected] ) و UPnP توسط توماس برنارد طراحی شده است.</translation>
</message>
<message>
<location filename="../aboutdialog.cpp" line="+14"/>
<source>Copyright</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+0"/>
<source>The KCz developers</source>
<translation type="unfinished"/>
</message>
</context>
<context>
<name>AddressBookPage</name>
<message>
<location filename="../forms/addressbookpage.ui" line="+14"/>
<source>Address Book</source>
<translation>فهرست آدرس</translation>
</message>
<message>
<location line="+19"/>
<source>Double-click to edit address or label</source>
<translation>برای ویرایش آدرس یا بر چسب دو بار کلیک کنید</translation>
</message>
<message>
<location line="+27"/>
<source>Create a new address</source>
<translation>آدرس جدید ایجاد کنید</translation>
</message>
<message>
<location line="+14"/>
<source>Copy the currently selected address to the system clipboard</source>
<translation>آدرس انتخاب شده در سیستم تخته رسم گیره دار کپی کنید</translation>
</message>
<message>
<location line="-11"/>
<source>&New Address</source>
<translation>آدرس جدید</translation>
</message>
<message>
<location filename="../addressbookpage.cpp" line="+63"/>
<source>These are your KCz 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>این آدرسها، آدرسهای KCz شما برای دریافت وجوه هستند. شما ممکن است آدرسهای متفاوت را به هر گیرنده اختصاص دهید که بتوانید مواردی که پرداخت می کنید را پیگیری نمایید</translation>
</message>
<message>
<location filename="../forms/addressbookpage.ui" line="+14"/>
<source>&Copy Address</source>
<translation>کپی آدرس</translation>
</message>
<message>
<location line="+11"/>
<source>Show &QR Code</source>
<translation>نمایش &کد QR</translation>
</message>
<message>
<location line="+11"/>
<source>Sign a message to prove you own a KCz address</source>
<translation>پیام را برای اثبات آدرس KCz خود امضا کنید</translation>
</message>
<message>
<location line="+3"/>
<source>Sign &Message</source>
<translation>امضا و پیام</translation>
</message>
<message>
<location line="+25"/>
<source>Delete the currently selected address from the list</source>
<translation>آدرس انتخاب شده در سیستم تخته رسم گیره دا حذف</translation>
</message>
<message>
<location line="+27"/>
<source>Export the data in the current tab to a file</source>
<translation>داده ها نوارِ جاری را به فایل انتقال دهید</translation>
</message>
<message>
<location line="+3"/>
<source>&Export</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-44"/>
<source>Verify a message to ensure it was signed with a specified KCz address</source>
<translation>یک پیام را برای حصول اطمینان از ورود به سیستم با آدرس KCz مشخص، شناسایی کنید</translation>
</message>
<message>
<location line="+3"/>
<source>&Verify Message</source>
<translation>شناسایی پیام</translation>
</message>
<message>
<location line="+14"/>
<source>&Delete</source>
<translation>حذف</translation>
</message>
<message>
<location filename="../addressbookpage.cpp" line="-5"/>
<source>These are your KCz addresses for sending payments. Always check the amount and the receiving address before sending coins.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+13"/>
<source>Copy &Label</source>
<translation>کپی و برچسب گذاری</translation>
</message>
<message>
<location line="+1"/>
<source>&Edit</source>
<translation>ویرایش</translation>
</message>
<message>
<location line="+1"/>
<source>Send &Coins</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+260"/>
<source>Export Address Book Data</source>
<translation>آدرس انتخاب شده در سیستم تخته رسم گیره دار کپی کنید</translation>
</message>
<message>
<location line="+1"/>
<source>Comma separated file (*.csv)</source>
<translation>Comma separated file (*.csv)</translation>
</message>
<message>
<location line="+13"/>
<source>Error exporting</source>
<translation>خطای صدور</translation>
</message>
<message>
<location line="+0"/>
<source>Could not write to file %1.</source>
<translation>تا فایل %1 نمی شود نوشت</translation>
</message>
</context>
<context>
<name>AddressTableModel</name>
<message>
<location filename="../addresstablemodel.cpp" line="+144"/>
<source>Label</source>
<translation>بر چسب</translation>
</message>
<message>
<location line="+0"/>
<source>Address</source>
<translation>آدرس</translation>
</message>
<message>
<location line="+36"/>
<source>(no label)</source>
<translation>بدون برچسب</translation>
</message>
</context>
<context>
<name>AskPassphraseDialog</name>
<message>
<location filename="../forms/askpassphrasedialog.ui" line="+26"/>
<source>Passphrase Dialog</source>
<translation>دیالوگ Passphrase </translation>
</message>
<message>
<location line="+21"/>
<source>Enter passphrase</source>
<translation>وارد عبارت عبور</translation>
</message>
<message>
<location line="+14"/>
<source>New passphrase</source>
<translation>عبارت عبور نو</translation>
</message>
<message>
<location line="+14"/>
<source>Repeat new passphrase</source>
<translation>تکرار عبارت عبور نو</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>وارد کنید..&lt;br/&gt عبارت عبور نو در پنجره
10 یا بیشتر کاراکتورهای تصادفی استفاده کنید &lt;b&gt لطفا عبارت عبور</translation>
</message>
<message>
<location line="+1"/>
<source>Encrypt wallet</source>
<translation>رمز بندی پنجره</translation>
</message>
<message>
<location line="+3"/>
<source>This operation needs your wallet passphrase to unlock the wallet.</source>
<translation>این عملیت نیاز عبارت عبور پنجره شما دارد برای رمز گشایی آن</translation>
</message>
<message>
<location line="+5"/>
<source>Unlock wallet</source>
<translation>تکرار عبارت عبور نو</translation>
</message>
<message>
<location line="+3"/>
<source>This operation needs your wallet passphrase to decrypt the wallet.</source>
<translation>این عملیت نیاز عبارت عبور شما دارد برای رمز بندی آن</translation>
</message>
<message>
<location line="+5"/>
<source>Decrypt wallet</source>
<translation>رمز بندی پنجره</translation>
</message>
<message>
<location line="+3"/>
<source>Change passphrase</source>
<translation>تغییر عبارت عبور</translation>
</message>
<message>
<location line="+1"/>
<source>Enter the old and new passphrase to the wallet.</source>
<translation>عبارت عبور نو و قدیم در پنجره وارد کنید</translation>
</message>
<message>
<location line="+46"/>
<source>Confirm wallet encryption</source>
<translation>تایید رمز گذاری</translation>
</message>
<message>
<location line="+1"/>
<source>Warning: If you encrypt your wallet and lose your passphrase, you will <b>LOSE ALL OF YOUR BITCOMMODITIZ</b>!</source>
<translation>هشدار: اگر wallet رمزگذاری شود و شما passphrase را گم کنید شما همه اطلاعات KCz را از دست خواهید داد.</translation>
</message>
<message>
<location line="+0"/>
<source>Are you sure you wish to encrypt your wallet?</source>
<translation>آیا اطمینان دارید که می خواهید wallet رمزگذاری شود؟</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 type="unfinished"/>
</message>
<message>
<location line="+100"/>
<location line="+24"/>
<source>Warning: The Caps Lock key is on!</source>
<translation>هشدار: Caps lock key روشن است</translation>
</message>
<message>
<location line="-130"/>
<location line="+58"/>
<source>Wallet encrypted</source>
<translation>تغییر عبارت عبور</translation>
</message>
<message>
<location line="-56"/>
<source>KCz will close now to finish the encryption process. Remember that encrypting your wallet cannot fully protect your KCzs from being stolen by malware infecting your computer.</source>
<translation>Biticon هم اکنون بسته میشود تا فرایند رمزگذاری را تمام کند. به خاطر داشته باشید که رمزگذاری کیف پولتان نمیتواند به طور کامل بیتیکونهای شما را در برابر دزدیده شدن توسط بدافزارهایی که رایانه شما را آلوده میکنند، محافظت نماید.</translation>
</message>
<message>
<location line="+13"/>
<location line="+7"/>
<location line="+42"/>
<location line="+6"/>
<source>Wallet encryption failed</source>
<translation>عبارت عبور نو و قدیم در پنجره وارد کنید</translation>
</message>
<message>
<location line="-54"/>
<source>Wallet encryption failed due to an internal error. Your wallet was not encrypted.</source>
<translation>تنا موفق رمز بندی پنجره ناشی از خطای داخل شد. پنجره شما مرز بندی نشده است</translation>
</message>
<message>
<location line="+7"/>
<location line="+48"/>
<source>The supplied passphrases do not match.</source>
<translation>عبارت عبور عرضه تطابق نشد</translation>
</message>
<message>
<location line="-37"/>
<source>Wallet unlock failed</source>
<translation>نجره رمز گذار شد</translation>
</message>
<message>
<location line="+1"/>
<location line="+11"/>
<location line="+19"/>
<source>The passphrase entered for the wallet decryption was incorrect.</source>
<translation>اموفق رمز بندی پنجر</translation>
</message>
<message>
<location line="-20"/>
<source>Wallet decryption failed</source>
<translation>ناموفق رمز بندی پنجره</translation>
</message>
<message>
<location line="+14"/>
<source>Wallet passphrase was successfully changed.</source>
<translation>wallet passphrase با موفقیت تغییر یافت</translation>
</message>
</context>
<context>
<name>BitcoinGUI</name>
<message>
<location filename="../bitcoingui.cpp" line="+233"/>
<source>Sign &message...</source>
<translation>امضا و پیام</translation>
</message>
<message>
<location line="+280"/>
<source>Synchronizing with network...</source>
<translation>همگام سازی با شبکه ...</translation>
</message>
<message>
<location line="-349"/>
<source>&Overview</source>
<translation>بررسی اجمالی</translation>
</message>
<message>
<location line="+1"/>
<source>Show general overview of wallet</source>
<translation>نمای کلی پنجره نشان بده</translation>
</message>
<message>
<location line="+20"/>
<source>&Transactions</source>
<translation>&معاملات</translation>
</message>
<message>
<location line="+1"/>
<source>Browse transaction history</source>
<translation>نمایش تاریخ معاملات</translation>
</message>
<message>
<location line="+7"/>
<source>Edit the list of stored addresses and labels</source>
<translation>ویرایش لیست آدرسها و بر چسب های ذخیره ای</translation>
</message>
<message>
<location line="-14"/>
<source>Show the list of addresses for receiving payments</source>
<translation>نمایش لیست آدرس ها برای در یافت پر داخت ها</translation>
</message>
<message>
<location line="+31"/>
<source>E&xit</source>
<translation>خروج</translation>
</message>
<message>
<location line="+1"/>
<source>Quit application</source>
<translation>خروج از برنامه </translation>
</message>
<message>
<location line="+4"/>
<source>Show information about KCz</source>
<translation>نمایش اطلاعات در مورد بیتکویین</translation>
</message>
<message>
<location line="+2"/>
<source>About &Qt</source>
<translation>درباره &Qt</translation>
</message>
<message>
<location line="+1"/>
<source>Show information about Qt</source>
<translation>نمایش اطلاعات درباره Qt</translation>
</message>
<message>
<location line="+2"/>
<source>&Options...</source>
<translation>تنظیمات...</translation>
</message>
<message>
<location line="+6"/>
<source>&Encrypt Wallet...</source>
<translation>رمزگذاری wallet</translation>
</message>
<message>
<location line="+3"/>
<source>&Backup Wallet...</source>
<translation>پشتیبان گیری از wallet</translation>
</message>
<message>
<location line="+2"/>
<source>&Change Passphrase...</source>
<translation>تغییر Passphrase</translation>
</message>
<message>
<location line="+285"/>
<source>Importing blocks from disk...</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Reindexing blocks on disk...</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-347"/>
<source>Send coins to a KCz address</source>
<translation>سکه ها را به آدرس bitocin ارسال کن</translation>
</message>
<message>
<location line="+49"/>
<source>Modify configuration options for KCz</source>
<translation>انتخابهای پیکربندی را برای KCz اصلاح کن</translation>
</message>
<message>
<location line="+9"/>
<source>Backup wallet to another location</source>
<translation>نسخه پیشتیبان wallet را به محل دیگر انتقال دهید</translation>
</message>
<message>
<location line="+2"/>
<source>Change the passphrase used for wallet encryption</source>
<translation>عبارت عبور رمز گشایی پنجره تغییر کنید</translation>
</message>
<message>
<location line="+6"/>
<source>&Debug window</source>
<translation>اشکال زدایی از صفحه</translation>
</message>
<message>
<location line="+1"/>
<source>Open debugging and diagnostic console</source>
<translation>کنسول اشکال زدایی و تشخیص را باز کنید</translation>
</message>
<message>
<location line="-4"/>
<source>&Verify message...</source>
<translation>بازبینی پیام</translation>
</message>
<message>
<location line="-165"/>
<location line="+530"/>
<source>KCz</source>
<translation>یت کویین </translation>
</message>
<message>
<location line="-530"/>
<source>Wallet</source>
<translation>wallet</translation>
</message>
<message>
<location line="+101"/>
<source>&Send</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+7"/>
<source>&Receive</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+14"/>
<source>&Addresses</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+22"/>
<source>&About KCz</source>
<translation>در مورد KCz</translation>
</message>
<message>
<location line="+9"/>
<source>&Show / Hide</source>
<translation>&نمایش/ عدم نمایش</translation>
</message>
<message>
<location line="+1"/>
<source>Show or hide the main Window</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Encrypt the private keys that belong to your wallet</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+7"/>
<source>Sign messages with your KCz addresses to prove you own them</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>Verify messages to ensure they were signed with specified KCz addresses</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+28"/>
<source>&File</source>
<translation>فایل</translation>
</message>
<message>
<location line="+7"/>
<source>&Settings</source>
<translation>تنظیمات</translation>
</message>
<message>
<location line="+6"/>
<source>&Help</source>
<translation>کمک</translation>
</message>
<message>
<location line="+9"/>
<source>Tabs toolbar</source>
<translation>نوار ابزار زبانه ها</translation>
</message>
<message>
<location line="+17"/>
<location line="+10"/>
<source>[testnet]</source>
<translation>آزمایش شبکه</translation>
</message>
<message>
<location line="+47"/>
<source>KCz client</source>
<translation>مشتری KCz</translation>
</message>
<message numerus="yes">
<location line="+141"/>
<source>%n active connection(s) to KCz network</source>
<translation><numerusform>در صد ارتباطات فعال بیتکویین با شبکه %n</numerusform></translation>
</message>
<message>
<location line="+22"/>
<source>No block source available...</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+12"/>
<source>Processed %1 of %2 (estimated) blocks of transaction history.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+4"/>
<source>Processed %1 blocks of transaction history.</source>
<translation type="unfinished"/>
</message>
<message numerus="yes">
<location line="+20"/>
<source>%n hour(s)</source>
<translation type="unfinished"><numerusform></numerusform></translation>
</message>
<message numerus="yes">
<location line="+4"/>
<source>%n day(s)</source>
<translation type="unfinished"><numerusform></numerusform></translation>
</message>
<message numerus="yes">
<location line="+4"/>
<source>%n week(s)</source>
<translation type="unfinished"><numerusform></numerusform></translation>
</message>
<message>
<location line="+4"/>
<source>%1 behind</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+14"/>
<source>Last received block was generated %1 ago.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>Transactions after this will not yet be visible.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+22"/>
<source>Error</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Warning</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Information</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+70"/>
<source>This transaction is over the size limit. You can still send it for a fee of %1, which goes to the nodes that process your transaction and helps to support the network. Do you want to pay the fee?</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-140"/>
<source>Up to date</source>
<translation>تا تاریخ</translation>
</message>
<message>
<location line="+31"/>
<source>Catching up...</source>
<translation>ابتلا به بالا</translation>
</message>
<message>
<location line="+113"/>
<source>Confirm transaction fee</source>
<translation>هزینه تراکنش را تایید کنید</translation>
</message>
<message>
<location line="+8"/>
<source>Sent transaction</source>
<translation>معامله ارسال شده</translation>
</message>
<message>
<location line="+0"/>
<source>Incoming transaction</source>
<translation>معامله در یافت شده</translation>
</message>
<message>
<location line="+1"/>
<source>Date: %1
Amount: %2
Type: %3
Address: %4
</source>
<translation>تاریخ %1
مبلغ%2
نوع %3
آدرس %4</translation>
</message>
<message>
<location line="+33"/>
<location line="+23"/>
<source>URI handling</source>
<translation>مدیریت URI</translation>
</message>
<message>
<location line="-23"/>
<location line="+23"/>
<source>URI can not be parsed! This can be caused by an invalid KCz address or malformed URI parameters.</source>
<translation>URI قابل تحلیل نیست. این خطا ممکن است به دلیل ادرس LITECOIN اشتباه یا پارامترهای اشتباه URI رخ داده باشد</translation>
</message>
<message>
<location line="+17"/>
<source>Wallet is <b>encrypted</b> and currently <b>unlocked</b></source>
<translation>زمایش شبکهه</translation>
</message>
<message>
<location line="+8"/>
<source>Wallet is <b>encrypted</b> and currently <b>locked</b></source>
<translation>زمایش شبکه</translation>
</message>
<message>
<location filename="../bitcoin.cpp" line="+111"/>
<source>A fatal error occurred. KCz can no longer continue safely and will quit.</source>
<translation>خطا روی داده است. KCz نمی تواند بدون مشکل ادامه دهد و باید بسته شود</translation>
</message>
</context>
<context>
<name>ClientModel</name>
<message>
<location filename="../clientmodel.cpp" line="+104"/>
<source>Network Alert</source>
<translation>پیام شبکه</translation>
</message>
</context>
<context>
<name>EditAddressDialog</name>
<message>
<location filename="../forms/editaddressdialog.ui" line="+14"/>
<source>Edit Address</source>
<translation>اصلاح آدرس</translation>
</message>
<message>
<location line="+11"/>
<source>&Label</source>
<translation>بر چسب</translation>
</message>
<message>
<location line="+10"/>
<source>The label associated with this address book entry</source>
<translation>بر چسب با دفتر آدرس ورود مرتبط است</translation>
</message>
<message>
<location line="+7"/>
<source>&Address</source>
<translation>آدرس</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>آدرس با دفتر آدرس ورودی مرتبط است. این فقط در مورد آدرسهای ارسال شده است</translation>
</message>
<message>
<location filename="../editaddressdialog.cpp" line="+21"/>
<source>New receiving address</source>
<translation>آدرس در یافت نو</translation>
</message>
<message>
<location line="+4"/>
<source>New sending address</source>
<translation>آدرس ارسال نو</translation>
</message>
<message>
<location line="+3"/>
<source>Edit receiving address</source>
<translation>اصلاح آدرس در یافت</translation>
</message>
<message>
<location line="+4"/>
<source>Edit sending address</source>
<translation>اصلاح آدرس ارسال</translation>
</message>
<message>
<location line="+76"/>
<source>The entered address "%1" is already in the address book.</source>
<translation>%1آدرس وارد شده دیگر در دفتر آدرس است</translation>
</message>
<message>
<location line="-5"/>
<source>The entered address "%1" is not a valid KCz address.</source>
<translation>آدرس وارد شده %1 یک ادرس صحیح KCz نیست</translation>
</message>
<message>
<location line="+10"/>
<source>Could not unlock wallet.</source>
<translation>رمز گشایی پنجره امکان پذیر نیست</translation>
</message>
<message>
<location line="+5"/>
<source>New key generation failed.</source>
<translation>کلید نسل جدید ناموفق است</translation>
</message>
</context>
<context>
<name>GUIUtil::HelpMessageBox</name>
<message>
<location filename="../guiutil.cpp" line="+424"/>
<location line="+12"/>
<source>KCz-Qt</source>
<translation>KCz-Qt</translation>
</message>
<message>
<location line="-12"/>
<source>version</source>
<translation>نسخه</translation>
</message>
<message>
<location line="+2"/>
<source>Usage:</source>
<translation>ستفاده :</translation>
</message>
<message>
<location line="+1"/>
<source>command-line options</source>
<translation>انتخابها برای خطوط دستور command line</translation>
</message>
<message>
<location line="+4"/>
<source>UI options</source>
<translation>انتخابهای UI </translation>
</message>
<message>
<location line="+1"/>
<source>Set language, for example "de_DE" (default: system locale)</source>
<translation>زبان را تنظیم کنید برای مثال "de_DE" (پیش فرض: system locale)</translation>
</message>
<message>
<location line="+1"/>
<source>Start minimized</source>
<translation>شروع حد اقل</translation>
</message>
<message>
<location line="+1"/>
<source>Show splash screen on startup (default: 1)</source>
<translation>نمایش صفحه splash در STARTUP (پیش فرض:1)</translation>
</message>
</context>
<context>
<name>OptionsDialog</name>
<message>
<location filename="../forms/optionsdialog.ui" line="+14"/>
<source>Options</source>
<translation>اصلی</translation>
</message>
<message>
<location line="+16"/>
<source>&Main</source>
<translation>اصلی</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 type="unfinished"/>
</message>
<message>
<location line="+15"/>
<source>Pay transaction &fee</source>
<translation>دستمزد&پر داخت معامله</translation>
</message>
<message>
<location line="+31"/>
<source>Automatically start KCz after logging in to the system.</source>
<translation>در زمان ورود به سیستم به صورت خودکار KCz را اجرا کن</translation>
</message>
<message>
<location line="+3"/>
<source>&Start KCz on system login</source>
<translation>اجرای KCz در زمان ورود به سیستم</translation>
</message>
<message>
<location line="+35"/>
<source>Reset all client options to default.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>&Reset Options</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+13"/>
<source>&Network</source>
<translation>شبکه</translation>
</message>
<message>
<location line="+6"/>
<source>Automatically open the KCz client port on the router. This only works when your router supports UPnP and it is enabled.</source>
<translation>اتوماتیک باز کردن بندر بیتکویین در روتر . این فقط در مواردی می باشد که روتر با کمک یو پ ن پ کار می کند</translation>
</message>
<message>
<location line="+3"/>
<source>Map port using &UPnP</source>
<translation>درگاه با استفاده از</translation>
</message>
<message>
<location line="+7"/>
<source>Connect to the KCz network through a SOCKS proxy (e.g. when connecting through Tor).</source>
<translation>اتصال به شبکه LITECOIN از طریق پراکسی ساکس (برای مثال وقتی از طریق نرم افزار TOR متصل می شوید)</translation>
</message>
<message>
<location line="+3"/>
<source>&Connect through SOCKS proxy:</source>
<translation>اتصال با پراکسی SOCKS</translation>
</message>
<message>
<location line="+9"/>
<source>Proxy &IP:</source>
<translation>پراکسی و آی.پی.</translation>
</message>
<message>
<location line="+19"/>
<source>IP address of the proxy (e.g. 127.0.0.1)</source>
<translation>درس پروکسی</translation>
</message>
<message>
<location line="+7"/>
<source>&Port:</source>
<translation>درگاه</translation>
</message>
<message>
<location line="+19"/>
<source>Port of the proxy (e.g. 9050)</source>
<translation>درگاه پراکسی (مثال 9050)</translation>
</message>
<message>
<location line="+7"/>
<source>SOCKS &Version:</source>
<translation>SOCKS و نسخه</translation>
</message>
<message>
<location line="+13"/>
<source>SOCKS version of the proxy (e.g. 5)</source>
<translation>نسخه SOCKS از پراکسی (مثال 5)</translation>
</message>
<message>
<location line="+36"/>
<source>&Window</source>
<translation>صفحه</translation>
</message>
<message>
<location line="+6"/>
<source>Show only a tray icon after minimizing the window.</source>
<translation>tray icon را تنها بعد از کوچک کردن صفحه نمایش بده</translation>
</message>
<message>
<location line="+3"/>
<source>&Minimize to the tray instead of the taskbar</source>
<translation>حد اقل رساندن در جای نوار ابزار ها</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>حد اقل رساندن در جای خروج بر نامه وقتیکه پنجره بسته است.وقتیکه این فعال است برنامه خاموش می شود بعد از انتخاب دستور خاموش در منیو</translation>
</message>
<message>
<location line="+3"/>
<source>M&inimize on close</source>
<translation>کوچک کردن صفحه در زمان بستن</translation>
</message>
<message>
<location line="+21"/>
<source>&Display</source>
<translation>نمایش</translation>
</message>
<message>
<location line="+8"/>
<source>User Interface &language:</source>
<translation>میانجی کاربر و زبان</translation>
</message>
<message>
<location line="+13"/>
<source>The user interface language can be set here. This setting will take effect after restarting KCz.</source>
<translation>زبان میانجی کاربر می تواند در اینجا تنظیم شود. این تنظیمات بعد از شروع دوباره RESTART در LITECOIN اجرایی خواهند بود.</translation>
</message>
<message>
<location line="+11"/>
<source>&Unit to show amounts in:</source>
<translation>واحد برای نمایش میزان وجوه در:</translation>
</message>
<message>
<location line="+13"/>
<source>Choose the default subdivision unit to show in the interface and when sending coins.</source>
<translation>بخش فرعی پیش فرض را برای نمایش میانجی و زمان ارسال سکه ها مشخص و انتخاب نمایید</translation>
</message>
<message>
<location line="+9"/>
<source>Whether to show KCz addresses in the transaction list or not.</source>
<translation>تا آدرسهای bITCOIN در فهرست تراکنش نمایش داده شوند یا نشوند.</translation>
</message>
<message>
<location line="+3"/>
<source>&Display addresses in transaction list</source>
<translation>نمایش آدرسها در فهرست تراکنش</translation>
</message>
<message>
<location line="+71"/>
<source>&OK</source>
<translation>تایید</translation>
</message>
<message>
<location line="+7"/>
<source>&Cancel</source>
<translation>رد</translation>
</message>
<message>
<location line="+10"/>
<source>&Apply</source>
<translation>انجام</translation>
</message>
<message>
<location filename="../optionsdialog.cpp" line="+53"/>
<source>default</source>
<translation>پیش فرض</translation>
</message>
<message>
<location line="+130"/>
<source>Confirm options reset</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Some settings may require a client restart to take effect.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+0"/>
<source>Do you want to proceed?</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+42"/>
<location line="+9"/>
<source>Warning</source>
<translation>هشدار</translation>
</message>
<message>
<location line="-9"/>
<location line="+9"/>
<source>This setting will take effect after restarting KCz.</source>
<translation>این تنظیمات پس از اجرای دوباره KCz اعمال می شوند</translation>
</message>
<message>
<location line="+29"/>
<source>The supplied proxy address is invalid.</source>
<translation>آدرس پراکسی داده شده صحیح نیست</translation>
</message>
</context>
<context>
<name>OverviewPage</name>
<message>
<location filename="../forms/overviewpage.ui" line="+14"/>
<source>Form</source>
<translation>تراز</translation>
</message>
<message>
<location line="+50"/>
<location line="+166"/>
<source>The displayed information may be out of date. Your wallet automatically synchronizes with the KCz network after a connection is established, but this process has not completed yet.</source>
<translation>اطلاعات نمایش داده شده روزآمد نیستند.wallet شما به صورت خودکار با شبکه KCz بعد از برقراری اتصال روزآمد می شود اما این فرایند هنوز کامل نشده است.</translation>
</message>
<message>
<location line="-124"/>
<source>Balance:</source>
<translation>راز:</translation>
</message>
<message>
<location line="+29"/>
<source>Unconfirmed:</source>
<translation>تایید نشده</translation>
</message>
<message>
<location line="-78"/>
<source>Wallet</source>
<translation>wallet</translation>
</message>
<message>
<location line="+107"/>
<source>Immature:</source>
<translation>نابالغ</translation>
</message>
<message>
<location line="+13"/>
<source>Mined balance that has not yet matured</source>
<translation>بالانس/تتمه حساب استخراج شده، نابالغ است /تکمیل نشده است</translation>
</message>
<message>
<location line="+46"/>
<source><b>Recent transactions</b></source>
<translation>اخرین معاملات&lt</translation>
</message>
<message>
<location line="-101"/>
<source>Your current balance</source>
<translation>تزار جاری شما</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>تعداد معاملات که تایید شده ولی هنوز در تزار جاری شما بر شمار نرفته است</translation>
</message>
<message>
<location filename="../overviewpage.cpp" line="+116"/>
<location line="+1"/>
<source>out of sync</source>
<translation>روزآمد نشده</translation>
</message>
</context>
<context>
<name>PaymentServer</name>
<message>
<location filename="../paymentserver.cpp" line="+107"/>
<source>Cannot start KCz: click-to-pay handler</source>
<translation type="unfinished"/>
</message>
</context>
<context>
<name>QRCodeDialog</name>
<message>
<location filename="../forms/qrcodedialog.ui" line="+14"/>
<source>QR Code Dialog</source>
<translation>دیالوگ QR CODE</translation>
</message>
<message>
<location line="+59"/>
<source>Request Payment</source>
<translation>درخواست پرداخت</translation>
</message>
<message>
<location line="+56"/>
<source>Amount:</source>
<translation>مقدار:</translation>
</message>
<message>
<location line="-44"/>
<source>Label:</source>
<translation>برچسب:</translation>
</message>
<message>
<location line="+19"/>
<source>Message:</source>
<translation>پیام</translation>
</message>
<message>
<location line="+71"/>
<source>&Save As...</source>
<translation>&ذخیره به عنوان...</translation>
</message>
<message>
<location filename="../qrcodedialog.cpp" line="+62"/>
<source>Error encoding URI into QR Code.</source>
<translation>خطا در زمان رمزدار کردن URI در کد QR</translation>
</message>
<message>
<location line="+40"/>
<source>The entered amount is invalid, please check.</source>
<translation>میزان وجه وارد شده صحیح نیست، لطفا بررسی نمایید</translation>
</message>
<message>
<location line="+23"/>
<source>Resulting URI too long, try to reduce the text for label / message.</source>
<translation>URI ذکر شده بسیار طولانی است، متن برچسب/پیام را کوتاه کنید</translation>
</message>
<message>
<location line="+25"/>
<source>Save QR Code</source>
<translation>ذخیره کد QR</translation>
</message>
<message>
<location line="+0"/>
<source>PNG Images (*.png)</source>
<translation>تصاویر با فرمت PNG (*.png)</translation>
</message>
</context>
<context>
<name>RPCConsole</name>
<message>
<location filename="../forms/rpcconsole.ui" line="+46"/>
<source>Client name</source>
<translation>نام مشتری</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>-</translation>
</message>
<message>
<location line="-217"/>
<source>Client version</source>
<translation>نسخه مشتری</translation>
</message>
<message>
<location line="-45"/>
<source>&Information</source>
<translation>اطلاعات</translation>
</message>
<message><|fim▁hole|> <source>Using OpenSSL version</source>
<translation>استفاده از نسخه OPENSSL</translation>
</message>
<message>
<location line="+49"/>
<source>Startup time</source>
<translation>زمان آغاز STARTUP</translation>
</message>
<message>
<location line="+29"/>
<source>Network</source>
<translation>شبکه</translation>
</message>
<message>
<location line="+7"/>
<source>Number of connections</source>
<translation>تعداد اتصالات</translation>
</message>
<message>
<location line="+23"/>
<source>On testnet</source>
<translation>در testnetکها</translation>
</message>
<message>
<location line="+23"/>
<source>Block chain</source>
<translation>زنجیره بلاک</translation>
</message>
<message>
<location line="+7"/>
<source>Current number of blocks</source>
<translation>تعداد کنونی بلاکها</translation>
</message>
<message>
<location line="+23"/>
<source>Estimated total blocks</source>
<translation>تعداد تخمینی بلاکها</translation>
</message>
<message>
<location line="+23"/>
<source>Last block time</source>
<translation>زمان آخرین بلاک</translation>
</message>
<message>
<location line="+52"/>
<source>&Open</source>
<translation>باز کردن</translation>
</message>
<message>
<location line="+16"/>
<source>Command-line options</source>
<translation>گزینه های command-line</translation>
</message>
<message>
<location line="+7"/>
<source>Show the KCz-Qt help message to get a list with possible KCz command-line options.</source>
<translation>پیام راهنمای KCz-Qt را برای گرفتن فهرست گزینه های command-line نشان بده</translation>
</message>
<message>
<location line="+3"/>
<source>&Show</source>
<translation>نمایش</translation>
</message>
<message>
<location line="+24"/>
<source>&Console</source>
<translation>کنسول</translation>
</message>
<message>
<location line="-260"/>
<source>Build date</source>
<translation>ساخت تاریخ</translation>
</message>
<message>
<location line="-104"/>
<source>KCz - Debug window</source>
<translation>صفحه اشکال زدایی KCz </translation>
</message>
<message>
<location line="+25"/>
<source>KCz Core</source>
<translation> هسته KCz </translation>
</message>
<message>
<location line="+279"/>
<source>Debug log file</source>
<translation>فایلِ لاگِ اشکال زدایی</translation>
</message>
<message>
<location line="+7"/>
<source>Open the KCz debug log file from the current data directory. This can take a few seconds for large log files.</source>
<translation>فایلِ لاگِ اشکال زدایی KCz را از دایرکتوری جاری داده ها باز کنید. این عملیات ممکن است برای فایلهای لاگِ حجیم طولانی شود.</translation>
</message>
<message>
<location line="+102"/>
<source>Clear console</source>
<translation>پاکسازی کنسول</translation>
</message>
<message>
<location filename="../rpcconsole.cpp" line="-30"/>
<source>Welcome to the KCz RPC console.</source>
<translation>به کنسول KCz RPC خوش آمدید</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>دکمه های بالا و پایین برای مرور تاریخچه و Ctrl-L برای پاکسازی صفحه</translation>
</message>
<message>
<location line="+1"/>
<source>Type <b>help</b> for an overview of available commands.</source>
<translation>با تایپ عبارت HELP دستورهای در دسترس را مرور خواهید کرد</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>ارسال سکه ها</translation>
</message>
<message>
<location line="+50"/>
<source>Send to multiple recipients at once</source>
<translation>ارسال چندین در یافت ها فورا</translation>
</message>
<message>
<location line="+3"/>
<source>Add &Recipient</source>
<translation>اضافه کردن دریافت کننده</translation>
</message>
<message>
<location line="+20"/>
<source>Remove all transaction fields</source>
<translation>پاک کردن تمام ستونهای تراکنش</translation>
</message>
<message>
<location line="+3"/>
<source>Clear &All</source>
<translation>پاکسازی همه</translation>
</message>
<message>
<location line="+22"/>
<source>Balance:</source>
<translation>تزار :</translation>
</message>
<message>
<location line="+10"/>
<source>123.456 BTC</source>
<translation>123.456 بتس</translation>
</message>
<message>
<location line="+31"/>
<source>Confirm the send action</source>
<translation>عملیت دوم تایید کنید</translation>
</message>
<message>
<location line="+3"/>
<source>S&end</source>
<translation>&;ارسال</translation>
</message>
<message>
<location filename="../sendcoinsdialog.cpp" line="-59"/>
<source><b>%1</b> to %2 (%3)</source>
<translation>(%3) تا <b>%1</b> درصد%2</translation>
</message>
<message>
<location line="+5"/>
<source>Confirm send coins</source>
<translation>ارسال سکه ها تایید کنید</translation>
</message>
<message>
<location line="+1"/>
<source>Are you sure you want to send %1?</source>
<translation> %1شما متماینید که می خواهید 1% ارسال کنید ؟</translation>
</message>
<message>
<location line="+0"/>
<source> and </source>
<translation>و</translation>
</message>
<message>
<location line="+23"/>
<source>The recipient address is not valid, please recheck.</source>
<translation>آدرس گیرنده نادرست است، لطفا دوباره بررسی کنید.</translation>
</message>
<message>
<location line="+5"/>
<source>The amount to pay must be larger than 0.</source>
<translation>مبلغ پر داخت باید از 0 بیشتر باشد </translation>
</message>
<message>
<location line="+5"/>
<source>The amount exceeds your balance.</source>
<translation>میزان وجه از بالانس/تتمه حساب شما بیشتر است</translation>
</message>
<message>
<location line="+5"/>
<source>The total exceeds your balance when the %1 transaction fee is included.</source>
<translation>کل میزان وجه از بالانس/تتمه حساب شما بیشتر می شود وقتی %1 هزینه تراکنش نیز به ین میزان افزوده می شود</translation>
</message>
<message>
<location line="+6"/>
<source>Duplicate address found, can only send to each address once per send operation.</source>
<translation>آدرس تکراری یافت شده است، در زمان انجام عملیات به هر آدرس تنها یکبار می توانید اطلاعات ارسال کنید</translation>
</message>
<message>
<location line="+5"/>
<source>Error: Transaction creation failed!</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+5"/>
<source>Error: The transaction was rejected. This might happen if some of the coins in your wallet were already spent, such as if you used a copy of wallet.dat and coins were spent in the copy but not marked as spent here.</source>
<translation>خطا: تراکنش تایید نشد. این پیام زمانی روی می دهد که مقداری از سکه های WALLET شما استفاده شده اند برای مثال اگر شما از WALLET.DAT استفاده کرده اید، ممکن است سکه ها استفاده شده باشند اما در اینجا نمایش داده نشوند</translation>
</message>
</context>
<context>
<name>SendCoinsEntry</name>
<message>
<location filename="../forms/sendcoinsentry.ui" line="+14"/>
<source>Form</source>
<translation>تراز</translation>
</message>
<message>
<location line="+15"/>
<source>A&mount:</source>
<translation>A&مبلغ :</translation>
</message>
<message>
<location line="+13"/>
<source>Pay &To:</source>
<translation>به&پر داخت :</translation>
</message>
<message>
<location line="+34"/>
<source>The address to send the payment to (e.g. Ler4HNAEfwYhBmGXcFP2Po1NpRUEiK8km2)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+60"/>
<location filename="../sendcoinsentry.cpp" line="+26"/>
<source>Enter a label for this address to add it to your address book</source>
<translation>برای آدرس بر پسب وارد کنید که در دفتر آدرس اضافه شود</translation>
</message>
<message>
<location line="-78"/>
<source>&Label:</source>
<translation>&بر چسب </translation>
</message>
<message>
<location line="+28"/>
<source>Choose address from address book</source>
<translation>اآدرسن ازدفتر آدرس انتخاب کنید</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>آدرس از تخته رسم گیره دار پست کنید </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>بر داشتن این در یافت کننده</translation>
</message>
<message>
<location filename="../sendcoinsentry.cpp" line="+1"/>
<source>Enter a KCz address (e.g. Ler4HNAEfwYhBmGXcFP2Po1NpRUEiK8km2)</source>
<translation>آدرس بیتکویین وارد کنید (bijvoorbeeld: Ler4HNAEfwYhBmGXcFP2Po1NpRUEiK8km2)</translation>
</message>
</context>
<context>
<name>SignVerifyMessageDialog</name>
<message>
<location filename="../forms/signverifymessagedialog.ui" line="+14"/>
<source>Signatures - Sign / Verify a Message</source>
<translation>امضا - امضا کردن /شناسایی یک پیام</translation>
</message>
<message>
<location line="+13"/>
<source>&Sign Message</source>
<translation>&امضای پیام</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>شما می توانید پیامها را با آدرس خودتان امضا نمایید تا ثابت شود متعلق به شما هستند. مواظب باشید تا چیزی که بدان مطمئن نیستنید را امضا نکنید زیرا حملات فیشینگ در زمان ورود شما به سیستم فریبنده هستند. تنها مواردی را که حاوی اطلاعات دقیق و قابل قبول برای شما هستند را امضا کنید</translation>
</message>
<message>
<location line="+18"/>
<source>The address to sign the message with (e.g. Ler4HNAEfwYhBmGXcFP2Po1NpRUEiK8km2)</source>
<translation>آدرس برای امضا کردن پیام با (برای مثال Ler4HNAEfwYhBmGXcFP2Po1NpRUEiK8km2)</translation>
</message>
<message>
<location line="+10"/>
<location line="+213"/>
<source>Choose an address from the address book</source>
<translation>یک آدرس را از فهرست آدرسها انتخاب کنید</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>آدرس از تخته رسم گیره دار پست کنید </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>پیامی را که میخواهید امضا کنید در اینجا وارد کنید</translation>
</message>
<message>
<location line="+7"/>
<source>Signature</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+27"/>
<source>Copy the current signature to the system clipboard</source>
<translation>این امضا را در system clipboard کپی کن</translation>
</message>
<message>
<location line="+21"/>
<source>Sign the message to prove you own this KCz address</source>
<translation>پیام را برای اثبات آدرس LITECOIN خود امضا کنید</translation>
</message>
<message>
<location line="+3"/>
<source>Sign &Message</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+14"/>
<source>Reset all sign message fields</source>
<translation>تنظیم دوباره تمامی فیلدهای پیام</translation>
</message>
<message>
<location line="+3"/>
<location line="+146"/>
<source>Clear &All</source>
<translation>پاکسازی همه</translation>
</message>
<message>
<location line="-87"/>
<source>&Verify Message</source>
<translation>تایید پیام</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>آدرس/پیام خود را وارد کنید (مطمئن شوید که فاصله بین خطوط، فاصله ها، تب ها و ... را دقیقا کپی می کنید) و سپس امضا کنید تا پیام تایید شود. مراقب باشید که پیام را بیشتر از مطالب درون امضا مطالعه نمایید تا فریب شخص سوم/دزدان اینترنتی را نخورید.</translation>
</message>
<message>
<location line="+21"/>
<source>The address the message was signed with (e.g. Ler4HNAEfwYhBmGXcFP2Po1NpRUEiK8km2)</source>
<translation>آدرس برای امضا کردن پیام با (برای مثال Ler4HNAEfwYhBmGXcFP2Po1NpRUEiK8km2)</translation>
</message>
<message>
<location line="+40"/>
<source>Verify the message to ensure it was signed with the specified KCz address</source>
<translation>پیام را برای اطمنان از ورود به سیستم با آدرس LITECOIN مشخص خود،تایید کنید</translation>
</message>
<message>
<location line="+3"/>
<source>Verify &Message</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+14"/>
<source>Reset all verify message fields</source>
<translation>تنظیم دوباره تمامی فیلدهای پیام تایید شده</translation>
</message>
<message>
<location filename="../signverifymessagedialog.cpp" line="+27"/>
<location line="+3"/>
<source>Enter a KCz address (e.g. Ler4HNAEfwYhBmGXcFP2Po1NpRUEiK8km2)</source>
<translation>آدرس بیتکویین وارد کنید (bijvoorbeeld: Ler4HNAEfwYhBmGXcFP2Po1NpRUEiK8km2)</translation>
</message>
<message>
<location line="-2"/>
<source>Click "Sign Message" to generate signature</source>
<translation>با کلیک بر "امضای پیام" شما یک امضای جدید درست می کنید</translation>
</message>
<message>
<location line="+3"/>
<source>Enter KCz signature</source>
<translation>امضای BITOCOIN خود را وارد کنید</translation>
</message>
<message>
<location line="+82"/>
<location line="+81"/>
<source>The entered address is invalid.</source>
<translation>آدرس وارد شده صحیح نیست</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>اطفا آدرس را بررسی کرده و دوباره امتحان کنید</translation>
</message>
<message>
<location line="-81"/>
<location line="+81"/>
<source>The entered address does not refer to a key.</source>
<translation>آدرس وارد شده با کلید وارد شده مرتبط نیست</translation>
</message>
<message>
<location line="-73"/>
<source>Wallet unlock was cancelled.</source>
<translation>قفل کردن wallet انجام نشد</translation>
</message>
<message>
<location line="+8"/>
<source>Private key for the entered address is not available.</source>
<translation>کلید شخصی برای آدرس وارد شده در دسترس نیست</translation>
</message>
<message>
<location line="+12"/>
<source>Message signing failed.</source>
<translation>پیام امضا کردن انجام نشد</translation>
</message>
<message>
<location line="+5"/>
<source>Message signed.</source>
<translation>پیام امضا شد</translation>
</message>
<message>
<location line="+59"/>
<source>The signature could not be decoded.</source>
<translation>امضا نمی تواند رمزگشایی شود</translation>
</message>
<message>
<location line="+0"/>
<location line="+13"/>
<source>Please check the signature and try again.</source>
<translation>لطفا امضا را بررسی و دوباره تلاش نمایید</translation>
</message>
<message>
<location line="+0"/>
<source>The signature did not match the message digest.</source>
<translation>امضا با تحلیلِ پیام مطابقت ندارد</translation>
</message>
<message>
<location line="+7"/>
<source>Message verification failed.</source>
<translation>عملیات شناسایی پیام انجام نشد</translation>
</message>
<message>
<location line="+5"/>
<source>Message verified.</source>
<translation>پیام شناسایی شد</translation>
</message>
</context>
<context>
<name>SplashScreen</name>
<message>
<location filename="../splashscreen.cpp" line="+22"/>
<source>The KCz developers</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>[testnet]</source>
<translation>آزمایش شبکه</translation>
</message>
</context>
<context>
<name>TransactionDesc</name>
<message>
<location filename="../transactiondesc.cpp" line="+20"/>
<source>Open until %1</source>
<translation>باز کردن تا%1</translation>
</message>
<message>
<location line="+6"/>
<source>%1/offline</source>
<translation>%1 آفلاین</translation>
</message>
<message>
<location line="+2"/>
<source>%1/unconfirmed</source>
<translation>%1 تایید نشده </translation>
</message>
<message>
<location line="+2"/>
<source>%1 confirmations</source>
<translation>ایید %1 </translation>
</message>
<message>
<location line="+18"/>
<source>Status</source>
<translation>وضعیت</translation>
</message>
<message numerus="yes">
<location line="+7"/>
<source>, broadcast through %n node(s)</source>
<translation><numerusform>انتشار از طریق n% گره
انتشار از طریق %n گره</numerusform></translation>
</message>
<message>
<location line="+4"/>
<source>Date</source>
<translation>تاریخ </translation>
</message>
<message>
<location line="+7"/>
<source>Source</source>
<translation>منبع</translation>
</message>
<message>
<location line="+0"/>
<source>Generated</source>
<translation>تولید شده</translation>
</message>
<message>
<location line="+5"/>
<location line="+17"/>
<source>From</source>
<translation>فرستنده</translation>
</message>
<message>
<location line="+1"/>
<location line="+22"/>
<location line="+58"/>
<source>To</source>
<translation>گیرنده</translation>
</message>
<message>
<location line="-77"/>
<location line="+2"/>
<source>own address</source>
<translation>آدرس شما</translation>
</message>
<message>
<location line="-2"/>
<source>label</source>
<translation>برچسب</translation>
</message>
<message>
<location line="+37"/>
<location line="+12"/>
<location line="+45"/>
<location line="+17"/>
<location line="+30"/>
<source>Credit</source>
<translation>بدهی </translation>
</message>
<message numerus="yes">
<location line="-102"/>
<source>matures in %n more block(s)</source>
<translation><numerusform>بلوغ در n% از بیشتر بلاکها
بلوغ در %n از بیشتر بلاکها</numerusform></translation>
</message>
<message>
<location line="+2"/>
<source>not accepted</source>
<translation>غیرقابل قبول</translation>
</message>
<message>
<location line="+44"/>
<location line="+8"/>
<location line="+15"/>
<location line="+30"/>
<source>Debit</source>
<translation>اعتبار</translation>
</message>
<message>
<location line="-39"/>
<source>Transaction fee</source>
<translation>هزینه تراکنش</translation>
</message>
<message>
<location line="+16"/>
<source>Net amount</source>
<translation>هزینه خالص</translation>
</message>
<message>
<location line="+6"/>
<source>Message</source>
<translation>پیام</translation>
</message>
<message>
<location line="+2"/>
<source>Comment</source>
<translation>نظر</translation>
</message>
<message>
<location line="+2"/>
<source>Transaction ID</source>
<translation>شناسه کاربری برای تراکنش</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>سکه های ایجاد شده باید 120 بلاک را قبل از استفاده بالغ کنند. در هنگام ایجاد بلاک، آن بلاک در شبکه منتشر می شود تا به زنجیره بلاکها بپیوندد. اگر در زنجیره قرار نگیرد، پیام وضعیت به غیرقابل قبول تغییر می بپیابد و قابل استفاده نیست. این مورد معمولا زمانی پیش می آید که گره دیگری به طور همزمان بلاکی را با فاصل چند ثانیه ای از شما ایجاد کند.</translation>
</message>
<message>
<location line="+7"/>
<source>Debug information</source>
<translation>اشکال زدایی طلاعات</translation>
</message>
<message>
<location line="+8"/>
<source>Transaction</source>
<translation>تراکنش</translation>
</message>
<message>
<location line="+3"/>
<source>Inputs</source>
<translation>درونداد</translation>
</message>
<message>
<location line="+23"/>
<source>Amount</source>
<translation>مبلغ</translation>
</message>
<message>
<location line="+1"/>
<source>true</source>
<translation>صحیح</translation>
</message>
<message>
<location line="+0"/>
<source>false</source>
<translation>نادرست</translation>
</message>
<message>
<location line="-209"/>
<source>, has not been successfully broadcast yet</source>
<translation>هنوز با مو فقیت ارسال نشده</translation>
</message>
<message numerus="yes">
<location line="-35"/>
<source>Open for %n more block(s)</source>
<translation type="unfinished"><numerusform></numerusform></translation>
</message>
<message>
<location line="+70"/>
<source>unknown</source>
<translation>مشخص نیست </translation>
</message>
</context>
<context>
<name>TransactionDescDialog</name>
<message>
<location filename="../forms/transactiondescdialog.ui" line="+14"/>
<source>Transaction details</source>
<translation>جزییات معاملات</translation>
</message>
<message>
<location line="+6"/>
<source>This pane shows a detailed description of the transaction</source>
<translation>در این قاب شیشه توصیف دقیق معامله نشان می شود</translation>
</message>
</context>
<context>
<name>TransactionTableModel</name>
<message>
<location filename="../transactiontablemodel.cpp" line="+225"/>
<source>Date</source>
<translation>تاریخ</translation>
</message>
<message>
<location line="+0"/>
<source>Type</source>
<translation>نوع</translation>
</message>
<message>
<location line="+0"/>
<source>Address</source>
<translation>ایل جدا </translation>
</message>
<message>
<location line="+0"/>
<source>Amount</source>
<translation>مبلغ</translation>
</message>
<message numerus="yes">
<location line="+57"/>
<source>Open for %n more block(s)</source>
<translation type="unfinished"><numerusform></numerusform></translation>
</message>
<message>
<location line="+3"/>
<source>Open until %1</source>
<translation>از شده تا 1%1</translation>
</message>
<message>
<location line="+3"/>
<source>Offline (%1 confirmations)</source>
<translation>افلایین (%1)</translation>
</message>
<message>
<location line="+3"/>
<source>Unconfirmed (%1 of %2 confirmations)</source>
<translation>تایید نشده (%1/%2)</translation>
</message>
<message>
<location line="+3"/>
<source>Confirmed (%1 confirmations)</source>
<translation>تایید شده (%1)</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>بالانس/تتمه حساب استخراج شده زمانی که %n از بیشتر بلاکها بالغ شدند در دسترس خواهد بود
بالانس/تتمه حساب استخراج شده زمانی که n% از بیشتر بلاکها بالغ شدند در دسترس خواهد بود</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>این بلوک از دیگر گره ها در یافت نشده بدین دلیل شاید قابل قابول نیست</translation>
</message>
<message>
<location line="+3"/>
<source>Generated but not accepted</source>
<translation>تولید شده ولی قبول نشده</translation>
</message>
<message>
<location line="+43"/>
<source>Received with</source>
<translation>در یافت با :</translation>
</message>
<message>
<location line="+2"/>
<source>Received from</source>
<translation>دریافتی از</translation>
</message>
<message>
<location line="+3"/>
<source>Sent to</source>
<translation>ارسال به :</translation>
</message>
<message>
<location line="+2"/>
<source>Payment to yourself</source>
<translation>پر داخت به خودتان</translation>
</message>
<message>
<location line="+2"/>
<source>Mined</source>
<translation>استخراج</translation>
</message>
<message>
<location line="+38"/>
<source>(n/a)</source>
<translation>(کاربرد ندارد)</translation>
</message>
<message>
<location line="+199"/>
<source>Transaction status. Hover over this field to show number of confirmations.</source>
<translation>وضعیت معالمه . عرصه که تعداد تایید نشان می دهد</translation>
</message>
<message>
<location line="+2"/>
<source>Date and time that the transaction was received.</source>
<translation>تاریخ و ساعت در یافت معامله</translation>
</message>
<message>
<location line="+2"/>
<source>Type of transaction.</source>
<translation>نوع معاملات</translation>
</message>
<message>
<location line="+2"/>
<source>Destination address of transaction.</source>
<translation>آدرس مقصود معاملات </translation>
</message>
<message>
<location line="+2"/>
<source>Amount removed from or added to balance.</source>
<translation>مبلغ از تزار شما خارج یا وارد شده</translation>
</message>
</context>
<context>
<name>TransactionView</name>
<message>
<location filename="../transactionview.cpp" line="+52"/>
<location line="+16"/>
<source>All</source>
<translation>همه</translation>
</message>
<message>
<location line="-15"/>
<source>Today</source>
<translation>امروز</translation>
</message>
<message>
<location line="+1"/>
<source>This week</source>
<translation>این هفته</translation>
</message>
<message>
<location line="+1"/>
<source>This month</source>
<translation>این ماه</translation>
</message>
<message>
<location line="+1"/>
<source>Last month</source>
<translation>ماه گذشته</translation>
</message>
<message>
<location line="+1"/>
<source>This year</source>
<translation>امسال</translation>
</message>
<message>
<location line="+1"/>
<source>Range...</source>
<translation>محدوده </translation>
</message>
<message>
<location line="+11"/>
<source>Received with</source>
<translation>در یافت با</translation>
</message>
<message>
<location line="+2"/>
<source>Sent to</source>
<translation>ارسال به</translation>
</message>
<message>
<location line="+2"/>
<source>To yourself</source>
<translation>به خودتان </translation>
</message>
<message>
<location line="+1"/>
<source>Mined</source>
<translation>استخراج</translation>
</message>
<message>
<location line="+1"/>
<source>Other</source>
<translation>یگر </translation>
</message>
<message>
<location line="+7"/>
<source>Enter address or label to search</source>
<translation>برای جستوجو نشانی یا برچسب را وارد کنید</translation>
</message>
<message>
<location line="+7"/>
<source>Min amount</source>
<translation>حد اقل مبلغ </translation>
</message>
<message>
<location line="+34"/>
<source>Copy address</source>
<translation>کپی آدرس </translation>
</message>
<message>
<location line="+1"/>
<source>Copy label</source>
<translation>کپی بر چسب</translation>
</message>
<message>
<location line="+1"/>
<source>Copy amount</source>
<translation>روگرفت مقدار</translation>
</message>
<message>
<location line="+1"/>
<source>Copy transaction ID</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Edit label</source>
<translation>اصلاح بر چسب</translation>
</message>
<message>
<location line="+1"/>
<source>Show transaction details</source>
<translation>جزئیات تراکنش را نمایش بده</translation>
</message>
<message>
<location line="+139"/>
<source>Export Transaction Data</source>
<translation>صادرات تاریخ معامله</translation>
</message>
<message>
<location line="+1"/>
<source>Comma separated file (*.csv)</source>
<translation>Comma فایل جدا </translation>
</message>
<message>
<location line="+8"/>
<source>Confirmed</source>
<translation>تایید شده</translation>
</message>
<message>
<location line="+1"/>
<source>Date</source>
<translation>تاریخ </translation>
</message>
<message>
<location line="+1"/>
<source>Type</source>
<translation>نوع </translation>
</message>
<message>
<location line="+1"/>
<source>Label</source>
<translation>ر چسب</translation>
</message>
<message>
<location line="+1"/>
<source>Address</source>
<translation>ایل جدا </translation>
</message>
<message>
<location line="+1"/>
<source>Amount</source>
<translation>مبلغ</translation>
</message>
<message>
<location line="+1"/>
<source>ID</source>
<translation>آی دی</translation>
</message>
<message>
<location line="+4"/>
<source>Error exporting</source>
<translation>خطای صادرت</translation>
</message>
<message>
<location line="+0"/>
<source>Could not write to file %1.</source>
<translation>تا فایل %1 نمی شود نوشت</translation>
</message>
<message>
<location line="+100"/>
<source>Range:</source>
<translation>>محدوده</translation>
</message>
<message>
<location line="+8"/>
<source>to</source>
<translation>به</translation>
</message>
</context>
<context>
<name>WalletModel</name>
<message>
<location filename="../walletmodel.cpp" line="+193"/>
<source>Send Coins</source>
<translation>ارسال سکه ها</translation>
</message>
</context>
<context>
<name>WalletView</name>
<message>
<location filename="../walletview.cpp" line="+42"/>
<source>&Export</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Export the data in the current tab to a file</source>
<translation>داده ها نوارِ جاری را به فایل انتقال دهید</translation>
</message>
<message>
<location line="+193"/>
<source>Backup Wallet</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+0"/>
<source>Wallet Data (*.dat)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Backup Failed</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+0"/>
<source>There was an error trying to save the wallet data to the new location.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+4"/>
<source>Backup Successful</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+0"/>
<source>The wallet data was successfully saved to the new location.</source>
<translation type="unfinished"/>
</message>
</context>
<context>
<name>bitcoin-core</name>
<message>
<location filename="../bitcoinstrings.cpp" line="+94"/>
<source>KCz version</source>
<translation>سخه بیتکویین</translation>
</message>
<message>
<location line="+102"/>
<source>Usage:</source>
<translation>ستفاده :</translation>
</message>
<message>
<location line="-29"/>
<source>Send command to -server or KCzd</source>
<translation>ارسال فرمان به سرور یا باتکویین</translation>
</message>
<message>
<location line="-23"/>
<source>List commands</source>
<translation>لیست فومان ها</translation>
</message>
<message>
<location line="-12"/>
<source>Get help for a command</source>
<translation>کمک برای فرمان </translation>
</message>
<message>
<location line="+24"/>
<source>Options:</source>
<translation>تنظیمات</translation>
</message>
<message>
<location line="+24"/>
<source>Specify configuration file (default: KCz.conf)</source>
<translation>(: KCz.confپیش فرض: )فایل تنظیمی خاص </translation>
</message>
<message>
<location line="+3"/>
<source>Specify pid file (default: KCzd.pid)</source>
<translation>(KCzd.pidپیش فرض : ) فایل پید خاص</translation>
</message>
<message>
<location line="-1"/>
<source>Specify data directory</source>
<translation>دایرکتور اطلاعاتی خاص</translation>
</message>
<message>
<location line="-9"/>
<source>Set database cache size in megabytes (default: 25)</source>
<translation>سایز کَش بانک داده را بر حسب مگابایت تنظیم کنید (پیش فرض:25)</translation>
</message>
<message>
<location line="-28"/>
<source>Listen for connections on <port> (default: 9333 or testnet: 19333)</source>
<translation>برای اتصالات به <port> (پیشفرض: 9333 یا تستنت: 19333) گوش کنید</translation>
</message>
<message>
<location line="+5"/>
<source>Maintain at most <n> connections to peers (default: 125)</source>
<translation>حداکثر <n> اتصال با همکاران برقرار داشته باشید (پیشفرض: 125)</translation>
</message>
<message>
<location line="-48"/>
<source>Connect to a node to retrieve peer addresses, and disconnect</source>
<translation>اتصال به گره برای دریافت آدرسهای قرینه و قطع اتصال</translation>
</message>
<message>
<location line="+82"/>
<source>Specify your own public address</source>
<translation>آدرس عمومی خود را ذکر کنید</translation>
</message>
<message>
<location line="+3"/>
<source>Threshold for disconnecting misbehaving peers (default: 100)</source>
<translation>آستانه برای قطع ارتباط با همکاران بدرفتار (پیشفرض: 100)</translation>
</message>
<message>
<location line="-134"/>
<source>Number of seconds to keep misbehaving peers from reconnecting (default: 86400)</source>
<translation>مدت زمان به ثانیه برای جلوگیری از همکاران بدرفتار برای اتصال دوباره (پیشفرض: 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>در زمان تنظیم درگاه RPX %u در فهرست کردن %s اشکالی رخ داده است</translation>
</message>
<message>
<location line="+27"/>
<source>Listen for JSON-RPC connections on <port> (default: 9332 or testnet: 19332)</source>
<translation>( 9332پیش فرض :) &lt;poort&gt; JSON-RPC شنوایی برای ارتباطات</translation>
</message>
<message>
<location line="+37"/>
<source>Accept command line and JSON-RPC commands</source>
<translation>JSON-RPC قابل فرمانها و</translation>
</message>
<message>
<location line="+76"/>
<source>Run in the background as a daemon and accept commands</source>
<translation>اجرای در پس زمینه به عنوان شبح و قبول فرمان ها</translation>
</message>
<message>
<location line="+37"/>
<source>Use the test network</source>
<translation>استفاده شبکه آزمایش</translation>
</message>
<message>
<location line="-112"/>
<source>Accept connections from outside (default: 1 if no -proxy or -connect)</source>
<translation>پذیرش اتصالات از بیرون (پیش فرض:1 بدون پراکسی یا اتصال)</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=KCzrpc
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 "KCz Alert" [email protected]
</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+17"/>
<source>An error occurred while setting up the RPC port %u for listening on IPv6, falling back to IPv4: %s</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Bind to given address and always listen on it. Use [host]:port notation for IPv6</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Cannot obtain a lock on data directory %s. KCz is probably already running.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Error: The transaction was rejected! This might happen if some of the coins in your wallet were already spent, such as if you used a copy of wallet.dat and coins were spent in the copy but not marked as spent here.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+4"/>
<source>Error: This transaction requires a transaction fee of at least %s because of its amount, complexity, or use of recently received funds!</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Execute command when a relevant alert is received (%s in cmd is replaced by message)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Execute command when a wallet transaction changes (%s in cmd is replaced by TxID)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+11"/>
<source>Set maximum size of high-priority/low-fee transactions in bytes (default: 27000)</source>
<translation>حجم حداکثر تراکنشهای با/کم اهمیت را به بایت تنظیم کنید (پیش فرض: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 type="unfinished"/>
</message>
<message>
<location line="+5"/>
<source>Warning: -paytxfee is set very high! This is the transaction fee you will pay if you send a transaction.</source>
<translation>هشدار:paytxfee بسیار بالا تعریف شده است! این هزینه تراکنش است که باید در زمان ارسال تراکنش بپردازید</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>هشدار: تراکنش نمایش داده شده ممکن است صحیح نباشد! شما/یا یکی از گره ها به روزآمد سازی نیاز دارید </translation>
</message>
<message>
<location line="+3"/>
<source>Warning: Please check that your computer's date and time are correct! If your clock is wrong KCz will not work properly.</source>
<translation>هشدار: لطفا زمان و تاریخ رایانه خود را تصحیح نمایید! اگر ساعت رایانه شما اشتباه باشد KCz ممکن است صحیح کار نکند</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 type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Warning: wallet.dat corrupt, data salvaged! Original wallet.dat saved as wallet.{timestamp}.bak in %s; if your balance or transactions are incorrect you should restore from a backup.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+14"/>
<source>Attempt to recover private keys from a corrupt wallet.dat</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>Block creation options:</source>
<translation>بستن گزینه ایجاد</translation>
</message>
<message>
<location line="+5"/>
<source>Connect only to the specified node(s)</source>
<translation>تنها در گره (های) مشخص شده متصل شوید</translation>
</message>
<message>
<location line="+3"/>
<source>Corrupted block database detected</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Discover own IP address (default: 1 when listening and no -externalip)</source>
<translation>آدرس آی.پی. خود را شناسایی کنید (پیش فرض:1 در زمان when listening وno -externalip)</translation>
</message>
<message>
<location line="+1"/>
<source>Do you want to rebuild the block database now?</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>Error initializing block database</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Error initializing wallet database environment %s!</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Error loading block database</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+4"/>
<source>Error opening block database</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>Error: Disk space is low!</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Error: Wallet locked, unable to create transaction!</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Error: system error: </source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Failed to listen on any port. Use -listen=0 if you want this.</source>
<translation>شنیدن هر گونه درگاه انجام پذیر نیست. ازlisten=0 برای اینکار استفاده کیند.</translation>
</message>
<message>
<location line="+1"/>
<source>Failed to read block info</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Failed to read block</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Failed to sync block index</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Failed to write block index</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Failed to write block info</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Failed to write block</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Failed to write file info</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Failed to write to coin database</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Failed to write transaction index</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Failed to write undo data</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>Find peers using DNS lookup (default: 1 unless -connect)</source>
<translation>قرینه ها را برای جستجوی DNS بیاب (پیش فرض: 1 مگر در زمان اتصال)</translation>
</message>
<message>
<location line="+1"/>
<source>Generate coins (default: 0)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>How many blocks to check at startup (default: 288, 0 = all)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>How thorough the block verification is (0-4, default: 3)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+19"/>
<source>Not enough file descriptors available.</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+8"/>
<source>Rebuild block chain index from current blk000??.dat files</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+16"/>
<source>Set the number of threads to service RPC calls (default: 4)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+26"/>
<source>Verifying blocks...</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Verifying wallet...</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-69"/>
<source>Imports blocks from external blk000??.dat file</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-76"/>
<source>Set the number of script verification threads (up to 16, 0 = auto, <0 = leave that many cores free, default: 0)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+77"/>
<source>Information</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+3"/>
<source>Invalid -tor address: '%s'</source>
<translation>آدرس نرم افزار تور غلط است %s</translation>
</message>
<message>
<location line="+1"/>
<source>Invalid amount for -minrelaytxfee=<amount>: '%s'</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Invalid amount for -mintxfee=<amount>: '%s'</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+8"/>
<source>Maintain a full transaction index (default: 0)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>Maximum per-connection receive buffer, <n>*1000 bytes (default: 5000)</source>
<translation>حداکثر بافر دریافت شده بر اساس اتصال <n>* 1000 بایت (پیش فرض:5000)</translation>
</message>
<message>
<location line="+1"/>
<source>Maximum per-connection send buffer, <n>*1000 bytes (default: 1000)</source>
<translation>حداکثر بافر دریافت شده بر اساس اتصال <n>* 1000 بایت (پیش فرض:1000)</translation>
</message>
<message>
<location line="+2"/>
<source>Only accept block chain matching built-in checkpoints (default: 1)</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Only connect to nodes in network <net> (IPv4, IPv6 or Tor)</source>
<translation>تنها =به گره ها در شبکه متصا شوید <net> (IPv4, IPv6 or Tor)</translation>
</message>
<message>
<location line="+2"/>
<source>Output extra debugging information. Implies all other -debug* options</source>
<translation>برونداد اطلاعات اشکال زدایی اضافی. گزینه های اشکال زدایی دیگر رفع شدند</translation>
</message>
<message>
<location line="+1"/>
<source>Output extra network debugging information</source>
<translation>برونداد اطلاعات اشکال زدایی اضافی برای شبکه</translation>
</message>
<message>
<location line="+2"/>
<source>Prepend debug output with timestamp</source>
<translation>به خروجی اشکالزدایی برچسب زمان بزنید</translation>
</message>
<message>
<location line="+5"/>
<source>SSL options: (see the KCz Wiki for SSL setup instructions)</source>
<translation>گزینه ssl (به ویکیKCz برای راهنمای راه اندازی ssl مراجعه شود)</translation>
</message>
<message>
<location line="+1"/>
<source>Select the version of socks proxy to use (4-5, default: 5)</source>
<translation>نسخه ای از پراکسی ساکس را برای استفاده انتخاب کنید (4-5 پیش فرض:5)</translation>
</message>
<message>
<location line="+3"/>
<source>Send trace/debug info to console instead of debug.log file</source>
<translation>اطلاعات ردگیری/اشکالزدایی را به جای فایل لاگ اشکالزدایی به کنسول بفرستید</translation>
</message>
<message>
<location line="+1"/>
<source>Send trace/debug info to debugger</source>
<translation>اطلاعات ردگیری/اشکالزدایی را به اشکالزدا بفرستید</translation>
</message>
<message>
<location line="+5"/>
<source>Set maximum block size in bytes (default: 250000)</source>
<translation>حداکثر سایز بلاک بر اساس بایت تنظیم شود (پیش فرض: 250000)</translation>
</message>
<message>
<location line="+1"/>
<source>Set minimum block size in bytes (default: 0)</source>
<translation>حداقل سایز بلاک بر اساس بایت تنظیم شود (پیش فرض: 0)</translation>
</message>
<message>
<location line="+2"/>
<source>Shrink debug.log file on client startup (default: 1 when no -debug)</source>
<translation>فایل debug.log را در startup مشتری کوچک کن (پیش فرض:1 اگر اشکال زدایی روی نداد)</translation>
</message>
<message>
<location line="+1"/>
<source>Signing transaction failed</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+2"/>
<source>Specify connection timeout in milliseconds (default: 5000)</source>
<translation>(میلی ثانیه )فاصله ارتباط خاص</translation>
</message>
<message>
<location line="+4"/>
<source>System error: </source>
<translation type="unfinished"/>
</message>
<message>
<location line="+4"/>
<source>Transaction amount too small</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Transaction amounts must be positive</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Transaction too large</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+7"/>
<source>Use UPnP to map the listening port (default: 0)</source>
<translation>از UPnP برای شناسایی درگاه شنیداری استفاده کنید (پیش فرض:0)</translation>
</message>
<message>
<location line="+1"/>
<source>Use UPnP to map the listening port (default: 1 when listening)</source>
<translation>از UPnP برای شناسایی درگاه شنیداری استفاده کنید (پیش فرض:1 در زمان شنیدن)</translation>
</message>
<message>
<location line="+1"/>
<source>Use proxy to reach tor hidden services (default: same as -proxy)</source>
<translation>برای دستیابی به سرویس مخفیانه نرم افزار تور از پراکسی استفاده کنید (پیش فرض:same as -proxy)</translation>
</message>
<message>
<location line="+2"/>
<source>Username for JSON-RPC connections</source>
<translation>JSON-RPC شناسه برای ارتباطات</translation>
</message>
<message>
<location line="+4"/>
<source>Warning</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>Warning: This version is obsolete, upgrade required!</source>
<translation>هشدار: این نسخه قدیمی است، روزآمدسازی مورد نیاز است</translation>
</message>
<message>
<location line="+1"/>
<source>You need to rebuild the databases using -reindex to change -txindex</source>
<translation type="unfinished"/>
</message>
<message>
<location line="+1"/>
<source>wallet.dat corrupt, salvage failed</source>
<translation type="unfinished"/>
</message>
<message>
<location line="-50"/>
<source>Password for JSON-RPC connections</source>
<translation>JSON-RPC عبارت عبور برای ارتباطات</translation>
</message>
<message>
<location line="-67"/>
<source>Allow JSON-RPC connections from specified IP address</source>
<translation>از آدرس آی پی خاص JSON-RPC قبول ارتباطات</translation>
</message>
<message>
<location line="+76"/>
<source>Send commands to node running on <ip> (default: 127.0.0.1)</source>
<translation>(127.0.0.1پیش فرض: ) &lt;ip&gt; دادن فرمانها برای استفاده گره ها روی</translation>
</message>
<message>
<location line="-120"/>
<source>Execute command when the best block changes (%s in cmd is replaced by block hash)</source>
<translation>زمانی که بهترین بلاک تغییر کرد، دستور را اجرا کن (%s در cmd با block hash جایگزین شده است)</translation>
</message>
<message>
<location line="+147"/>
<source>Upgrade wallet to latest format</source>
<translation>wallet را به جدیدترین فرمت روزآمد کنید</translation>
</message>
<message>
<location line="-21"/>
<source>Set key pool size to <n> (default: 100)</source>
<translation> (100پیش فرض:)&lt;n&gt; گذاشتن اندازه کلید روی </translation>
</message>
<message>
<location line="-12"/>
<source>Rescan the block chain for missing wallet transactions</source>
<translation>اسکان مجدد زنجیر بلوکها برای گم والت معامله</translation>
</message>
<message>
<location line="+35"/>
<source>Use OpenSSL (https) for JSON-RPC connections</source>
<translation>JSON-RPCبرای ارتباطات استفاده کنید OpenSSL (https)</translation>
</message>
<message>
<location line="-26"/>
<source>Server certificate file (default: server.cert)</source>
<translation> (server.certپیش فرض: )گواهی نامه سرور</translation>
</message>
<message>
<location line="+1"/>
<source>Server private key (default: server.pem)</source>
<translation>(server.pemپیش فرض: ) کلید خصوصی سرور</translation>
</message>
<message>
<location line="-151"/>
<source>Acceptable ciphers (default: TLSv1+HIGH:!SSLv2:!aNULL:!eNULL:!AH:!3DES:@STRENGTH)</source>
<translation>رمز های قابل قبول( TLSv1+HIGH:!SSLv2:!aNULL:!eNULL:!AH:!3DES:@STRENGTH)</translation>
</message>
<message>
<location line="+165"/>
<source>This help message</source>
<translation>پیام کمکی</translation>
</message>
<message>
<location line="+6"/>
<source>Unable to bind to %s on this computer (bind returned error %d, %s)</source>
<translation>امکان اتصال به %s از این رایانه وجود ندارد ( bind returned error %d, %s)</translation>
</message>
<message>
<location line="-91"/>
<source>Connect through socks proxy</source>
<translation>اتصال از طریق پراکسی ساکس</translation>
</message>
<message>
<location line="-10"/>
<source>Allow DNS lookups for -addnode, -seednode and -connect</source>
<translation>به DNS اجازه بده تا برای addnode ، seednode و اتصال جستجو کند</translation>
</message>
<message>
<location line="+55"/>
<source>Loading addresses...</source>
<translation>بار گیری آدرس ها</translation>
</message>
<message>
<location line="-35"/>
<source>Error loading wallet.dat: Wallet corrupted</source>
<translation>خطا در بارگیری wallet.dat: کیف پول خراب شده است</translation>
</message>
<message>
<location line="+1"/>
<source>Error loading wallet.dat: Wallet requires newer version of KCz</source>
<translation>خطا در بارگیری wallet.dat: کیف پول به ویرایش جدیدتری از Biticon نیاز دارد</translation>
</message>
<message>
<location line="+93"/>
<source>Wallet needed to be rewritten: restart KCz to complete</source>
<translation>سلام</translation>
</message>
<message>
<location line="-95"/>
<source>Error loading wallet.dat</source>
<translation>خطا در بارگیری wallet.dat</translation>
</message>
<message>
<location line="+28"/>
<source>Invalid -proxy address: '%s'</source>
<translation>آدرس پراکسی اشتباه %s</translation>
</message>
<message>
<location line="+56"/>
<source>Unknown network specified in -onlynet: '%s'</source>
<translation>شبکه مشخص شده غیرقابل شناسایی در onlynet: '%s'</translation>
</message>
<message>
<location line="-1"/>
<source>Unknown -socks proxy version requested: %i</source>
<translation>نسخه پراکسی ساکس غیرقابل شناسایی درخواست شده است: %i</translation>
</message>
<message>
<location line="-96"/>
<source>Cannot resolve -bind address: '%s'</source>
<translation>آدرس قابل اتصال- شناسایی نیست %s</translation>
</message>
<message>
<location line="+1"/>
<source>Cannot resolve -externalip address: '%s'</source>
<translation>آدرس خارجی قابل اتصال- شناسایی نیست %s</translation>
</message>
<message>
<location line="+44"/>
<source>Invalid amount for -paytxfee=<amount>: '%s'</source>
<translation>میزان وجه اشتباه برای paytxfee=<میزان وجه>: %s</translation>
</message>
<message>
<location line="+1"/>
<source>Invalid amount</source>
<translation>میزان وجه اشتباه</translation>
</message>
<message>
<location line="-6"/>
<source>Insufficient funds</source>
<translation>بود جه نا کافی </translation>
</message>
<message>
<location line="+10"/>
<source>Loading block index...</source>
<translation>بار گیری شاخص بلوک</translation>
</message>
<message>
<location line="-57"/>
<source>Add a node to connect to and attempt to keep the connection open</source>
<translation>به اتصال یک گره اضافه کنید و اتصال را باز نگاه دارید</translation>
</message>
<message>
<location line="-25"/>
<source>Unable to bind to %s on this computer. KCz is probably already running.</source>
<translation>اتصال به %s از این رایانه امکان پذیر نیست. KCz احتمالا در حال اجراست.</translation>
</message>
<message>
<location line="+64"/>
<source>Fee per KB to add to transactions you send</source>
<translation>پر داجت برای هر کیلو بیت برای اضافه به معامله ارسال</translation>
</message>
<message>
<location line="+19"/>
<source>Loading wallet...</source>
<translation>بار گیری والت</translation>
</message>
<message>
<location line="-52"/>
<source>Cannot downgrade wallet</source>
<translation>امکان تنزل نسخه در wallet وجود ندارد</translation>
</message>
<message>
<location line="+3"/>
<source>Cannot write default address</source>
<translation>آدرس پیش فرض قابل ذخیره نیست</translation>
</message>
<message>
<location line="+64"/>
<source>Rescanning...</source>
<translation>اسکان مجدد</translation>
</message>
<message>
<location line="-57"/>
<source>Done loading</source>
<translation>بار گیری انجام شده است</translation>
</message>
<message>
<location line="+82"/>
<source>To use the %s option</source>
<translation>برای استفاده از %s از انتخابات</translation>
</message>
<message>
<location line="-74"/>
<source>Error</source>
<translation>خطا</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>%s، شما باید یک rpcpassword را در فایل پیکربندی تنظیم کنید :⏎%s⏎ اگر فایل ایجاد نشد، یک فایل فقط متنی ایجاد کنید.
</translation>
</message>
</context>
</TS><|fim▁end|> | <location line="+68"/> |
<|file_name|>rt.rs<|end_file_name|><|fim▁begin|>// Copyright 2013-2015, The Gtk-rs Project Developers.
// See the COPYRIGHT file at the top-level directory of this distribution.
// Licensed under the MIT license, see the LICENSE file or <http://opensource.org/licenses/MIT>
//! General — Library initialization and miscellaneous functions
use std::cell::Cell;
use std::ptr;
use std::sync::atomic::{AtomicBool, ATOMIC_BOOL_INIT, Ordering};
use glib::translate::*;
use ffi;
thread_local! {
static IS_MAIN_THREAD: Cell<bool> = Cell::new(false)
}
static INITIALIZED: AtomicBool = ATOMIC_BOOL_INIT;
/// Asserts that this is the main thread and either `gdk::init` or `gtk::init` has been called.
macro_rules! assert_initialized_main_thread {
() => (
if !::rt::is_initialized_main_thread() {
if ::rt::is_initialized() {
panic!("GDK may only be used from the main thread.");
}
else {
panic!("GDK has not been initialized. Call `gdk::init` or `gtk::init` first.");
}
}
)
}
/// No-op.
macro_rules! skip_assert_initialized {
() => ()
}
/// Asserts that neither `gdk::init` nor `gtk::init` has been called.
macro_rules! assert_not_initialized {
() => (
if ::rt::is_initialized() {
panic!("This function has to be called before `gdk::init` or `gtk::init`.");
}
)
}
/// Returns `true` if GDK has been initialized.
#[inline]
pub fn is_initialized() -> bool {
skip_assert_initialized!();
INITIALIZED.load(Ordering::Acquire)
}
/// Returns `true` if GDK has been initialized and this is the main thread.
#[inline]
pub fn is_initialized_main_thread() -> bool {
skip_assert_initialized!();
IS_MAIN_THREAD.with(|c| c.get())
}
/// Informs this crate that GDK has been initialized and the current thread is the main one.
pub unsafe fn set_initialized() {
skip_assert_initialized!();
if is_initialized_main_thread() {
return;
}
else if is_initialized() {
panic!("Attempted to initialize GDK from two different threads.");
}
INITIALIZED.store(true, Ordering::Release);
IS_MAIN_THREAD.with(|c| c.set(true));
}
pub fn init() {
assert_not_initialized!();
unsafe {
ffi::gdk_init(ptr::null_mut(), ptr::null_mut());
set_initialized();
}
}
pub fn get_display_arg_name() -> Option<String> {
assert_initialized_main_thread!();
unsafe {
from_glib_none(ffi::gdk_get_display_arg_name())
}
}
pub fn notify_startup_complete() {
assert_initialized_main_thread!();
unsafe { ffi::gdk_notify_startup_complete() }
}
pub fn notify_startup_complete_with_id(startup_id: &str) {
assert_initialized_main_thread!();
unsafe {
ffi::gdk_notify_startup_complete_with_id(startup_id.to_glib_none().0);
}
}<|fim▁hole|> unsafe {
ffi::gdk_set_allowed_backends(backends.to_glib_none().0)
}
}
pub fn get_program_class() -> Option<String> {
assert_initialized_main_thread!();
unsafe {
from_glib_none(ffi::gdk_get_program_class())
}
}
pub fn set_program_class(program_class: &str) {
assert_initialized_main_thread!();
unsafe {
ffi::gdk_set_program_class(program_class.to_glib_none().0)
}
}
pub fn flush() {
assert_initialized_main_thread!();
unsafe { ffi::gdk_flush() }
}
pub fn screen_width() -> i32 {
assert_initialized_main_thread!();
unsafe { ffi::gdk_screen_width() }
}
pub fn screen_height() -> i32 {
assert_initialized_main_thread!();
unsafe { ffi::gdk_screen_height() }
}
pub fn screen_width_mm() -> i32 {
assert_initialized_main_thread!();
unsafe { ffi::gdk_screen_width_mm() }
}
pub fn screen_height_mm() -> i32 {
assert_initialized_main_thread!();
unsafe { ffi::gdk_screen_height_mm() }
}
pub fn beep() {
assert_initialized_main_thread!();
unsafe { ffi::gdk_flush() }
}
pub fn error_trap_push() {
assert_initialized_main_thread!();
unsafe { ffi::gdk_error_trap_push() }
}
pub fn error_trap_pop() -> i32 {
assert_initialized_main_thread!();
unsafe { ffi::gdk_error_trap_pop() }
}
pub fn error_trap_pop_ignored() {
assert_initialized_main_thread!();
unsafe { ffi::gdk_error_trap_pop_ignored() }
}<|fim▁end|> |
#[cfg(feature = "3.10")]
pub fn set_allowed_backends(backends: &str) {
assert_not_initialized!(); |
<|file_name|>SearchField.java<|end_file_name|><|fim▁begin|>package dk.lessismore.nojpa.reflection.db.annotations;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**<|fim▁hole|> * User: seb
*/
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public @interface SearchField {
public static final String NULL = "";
public boolean translate() default false;
public boolean searchReverse() default false;
public float boostFactor() default 3f;
public float reverseBoostFactor() default 0.3f;
public String dynamicSolrPostName() default NULL;
}<|fim▁end|> | * Created : with IntelliJ IDEA. |
<|file_name|>admin.py<|end_file_name|><|fim▁begin|>from django.contrib import admin<|fim▁hole|># Register your models here.
admin.site.register(xbee_module);<|fim▁end|> | from xbee_module.models import xbee_module
|
<|file_name|>DocumentCategorizerContextGenerator.java<|end_file_name|><|fim▁begin|>/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package opennlp.tools.doccat;
<|fim▁hole|>
/**
* Context generator for document categorizer
*/
class DocumentCategorizerContextGenerator {
private FeatureGenerator[] mFeatureGenerators;
DocumentCategorizerContextGenerator(FeatureGenerator... featureGenerators) {
mFeatureGenerators = featureGenerators;
}
public String[] getContext(String[] text, Map<String, Object> extraInformation) {
Collection<String> context = new LinkedList<>();
for (FeatureGenerator mFeatureGenerator : mFeatureGenerators) {
Collection<String> extractedFeatures =
mFeatureGenerator.extractFeatures(text, extraInformation);
context.addAll(extractedFeatures);
}
return context.toArray(new String[context.size()]);
}
}<|fim▁end|> | import java.util.Collection;
import java.util.LinkedList;
import java.util.Map; |
<|file_name|>setting.go<|end_file_name|><|fim▁begin|>// Copyright 2014 The Gogs Authors. All rights reserved.
// Use of this source code is governed by a MIT-style
// license that can be found in the LICENSE file.
package org
import (
"strings"
"github.com/gogits/gogs/models"
"github.com/gogits/gogs/modules/auth"
"github.com/gogits/gogs/modules/base"
"github.com/gogits/gogs/modules/context"
"github.com/gogits/gogs/modules/log"
"github.com/gogits/gogs/modules/setting"
"github.com/gogits/gogs/routers/user"
)
const (
SETTINGS_OPTIONS base.TplName = "org/settings/options"
SETTINGS_DELETE base.TplName = "org/settings/delete"
SETTINGS_HOOKS base.TplName = "org/settings/hooks"
)
func Settings(ctx *context.Context) {
ctx.Data["Title"] = ctx.Tr("org.settings")
ctx.Data["PageIsSettingsOptions"] = true
ctx.HTML(200, SETTINGS_OPTIONS)
}
func SettingsPost(ctx *context.Context, form auth.UpdateOrgSettingForm) {
ctx.Data["Title"] = ctx.Tr("org.settings")
ctx.Data["PageIsSettingsOptions"] = true
if ctx.HasError() {
ctx.HTML(200, SETTINGS_OPTIONS)
return
}
org := ctx.Org.Organization
// Check if organization name has been changed.
if org.LowerName != strings.ToLower(form.Name) {
isExist, err := models.IsUserExist(org.Id, form.Name)
if err != nil {
ctx.Handle(500, "IsUserExist", err)
return
} else if isExist {
ctx.Data["OrgName"] = true
ctx.RenderWithErr(ctx.Tr("form.username_been_taken"), SETTINGS_OPTIONS, &form)
return
} else if err = models.ChangeUserName(org, form.Name); err != nil {
if err == models.ErrUserNameIllegal {
ctx.Data["OrgName"] = true
ctx.RenderWithErr(ctx.Tr("form.illegal_username"), SETTINGS_OPTIONS, &form)
} else {
ctx.Handle(500, "ChangeUserName", err)
}
return
}
// reset ctx.org.OrgLink with new name
ctx.Org.OrgLink = setting.AppSubUrl + "/org/" + form.Name
log.Trace("Organization name changed: %s -> %s", org.Name, form.Name)
}
// In case it's just a case change.
org.Name = form.Name
org.LowerName = strings.ToLower(form.Name)
if ctx.User.IsAdmin {
org.MaxRepoCreation = form.MaxRepoCreation
}
org.FullName = form.FullName
org.Description = form.Description
org.Website = form.Website
org.Location = form.Location
if err := models.UpdateUser(org); err != nil {
ctx.Handle(500, "UpdateUser", err)
return
}
log.Trace("Organization setting updated: %s", org.Name)
ctx.Flash.Success(ctx.Tr("org.settings.update_setting_success"))
ctx.Redirect(ctx.Org.OrgLink + "/settings")
}
func SettingsAvatar(ctx *context.Context, form auth.UploadAvatarForm) {
form.Enable = true
if err := user.UpdateAvatarSetting(ctx, form, ctx.Org.Organization); err != nil {
ctx.Flash.Error(err.Error())
} else {
ctx.Flash.Success(ctx.Tr("org.settings.update_avatar_success"))
}
ctx.Redirect(ctx.Org.OrgLink + "/settings")
}
func SettingsDeleteAvatar(ctx *context.Context) {
if err := ctx.Org.Organization.DeleteAvatar(); err != nil {
ctx.Flash.Error(err.Error())
}
ctx.Redirect(ctx.Org.OrgLink + "/settings")
}
func SettingsDelete(ctx *context.Context) {
ctx.Data["Title"] = ctx.Tr("org.settings")
ctx.Data["PageIsSettingsDelete"] = true
org := ctx.Org.Organization
if ctx.Req.Method == "POST" {
if _, err := models.UserSignIn(ctx.User.Name, ctx.Query("password")); err != nil {
if models.IsErrUserNotExist(err) {
ctx.RenderWithErr(ctx.Tr("form.enterred_invalid_password"), SETTINGS_DELETE, nil)<|fim▁hole|> }
return
}
if err := models.DeleteOrganization(org); err != nil {
if models.IsErrUserOwnRepos(err) {
ctx.Flash.Error(ctx.Tr("form.org_still_own_repo"))
ctx.Redirect(ctx.Org.OrgLink + "/settings/delete")
} else {
ctx.Handle(500, "DeleteOrganization", err)
}
} else {
log.Trace("Organization deleted: %s", org.Name)
ctx.Redirect(setting.AppSubUrl + "/")
}
return
}
ctx.HTML(200, SETTINGS_DELETE)
}
func Webhooks(ctx *context.Context) {
ctx.Data["Title"] = ctx.Tr("org.settings")
ctx.Data["PageIsSettingsHooks"] = true
ctx.Data["BaseLink"] = ctx.Org.OrgLink
ctx.Data["Description"] = ctx.Tr("org.settings.hooks_desc")
ws, err := models.GetWebhooksByOrgID(ctx.Org.Organization.Id)
if err != nil {
ctx.Handle(500, "GetWebhooksByOrgId", err)
return
}
ctx.Data["Webhooks"] = ws
ctx.HTML(200, SETTINGS_HOOKS)
}
func DeleteWebhook(ctx *context.Context) {
if err := models.DeleteWebhookByOrgID(ctx.Org.Organization.Id, ctx.QueryInt64("id")); err != nil {
ctx.Flash.Error("DeleteWebhookByOrgID: " + err.Error())
} else {
ctx.Flash.Success(ctx.Tr("repo.settings.webhook_deletion_success"))
}
ctx.JSON(200, map[string]interface{}{
"redirect": ctx.Org.OrgLink + "/settings/hooks",
})
}<|fim▁end|> | } else {
ctx.Handle(500, "UserSignIn", err) |
<|file_name|>ok.py<|end_file_name|><|fim▁begin|>"""
Source: https://github.com/txt/mase/blob/master/src/ok.md
# Unit tests in Python
Python has some great unit testing tools. The one
shown below is a "less-is-more" approach and is
based on [Kent Beck video on how to write a test engine in just a
few lines of code](https://www.youtube.com/watch?v=nIonZ6-4nuU).
For example usages, see [okok.py](okok.md) which can be loaded via
```
python okok.py
```
Share and enjoy.
"""
def ok(*lst):
print "### ",lst[0].__name__
for one in lst: unittest(one)
return one
class unittest:<|fim▁hole|> t = unittest.tries
f = unittest.fails
return "# TRIES= %s FAIL= %s %%PASS = %s%%" % (
t,f,int(round(t*100/(t+f+0.001))))
def __init__(i,test):
unittest.tries += 1
try:
test()
except Exception,e:
unittest.fails += 1
i.report(test)
def report(i,test):
import traceback
print traceback.format_exc()
print unittest.score(),':',test.__name__<|fim▁end|> | tries = fails = 0 # tracks the record so far
@staticmethod
def score(): |
<|file_name|>agent.py<|end_file_name|><|fim▁begin|># -*- encoding: utf-8 -*-
# Copyright (c) 2015 b<>com
#
# 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.
"""In charge of collecting data from drivers and push it to the publisher."""
import os
import msgpack
import nanomsg
from oslo_log import log
from watcher_metering.agent.manager import MetricManager
LOG = log.getLogger(__name__)
class Agent(MetricManager):
def __init__(self, conf, driver_names, use_nanoconfig_service,
publisher_endpoint, nanoconfig_service_endpoint,
nanoconfig_update_endpoint, nanoconfig_profile):
"""
:param conf: Configuration obtained from a configuration file
:type conf: oslo_config.cfg.ConfigOpts instance
:param driver_names: The list of driver names to register
:type driver_names: list of str
:param use_nanoconfig_service: Indicates whether or not it should use a
nanoconfig service
:type use_nanoconfig_service: bool
:param publisher_endpoint: Publisher server URI
:type publisher_endpoint: str
:param nanoconfig_service_endpoint: Nanoconfig service URI
:type nanoconfig_service_endpoint: str
:param nanoconfig_update_endpoint: Nanoconfig update service URI
:type nanoconfig_update_endpoint: str
:param nanoconfig_profile: Nanoconfig profile URI
:type nanoconfig_profile: str
"""
super(Agent, self).__init__(conf, driver_names)
self.socket = nanomsg.Socket(nanomsg.PUSH)
self.use_nanoconfig_service = use_nanoconfig_service
self.publisher_endpoint = publisher_endpoint
self.nanoconfig_service_endpoint = nanoconfig_service_endpoint
self.nanoconfig_update_endpoint = nanoconfig_update_endpoint
self.nanoconfig_profile = nanoconfig_profile
@property
def namespace(self):
return "watcher_metering.drivers"
def start(self):
LOG.info("[Agent] Starting main thread...")
super(Agent, self).start()
def setup_socket(self):
if self.use_nanoconfig_service:
self.set_nanoconfig_endpoints()
self.socket.configure(self.nanoconfig_profile)
LOG.info("[Agent] Agent nanomsg's profile `%s`",
self.nanoconfig_profile)
else:
LOG.debug("[Agent] Agent connected to: `%s`",
self.publisher_endpoint)
self.socket.connect(self.publisher_endpoint)
LOG.info("[Agent] Ready for pushing to Publisher node")
def set_nanoconfig_endpoints(self):
"""This methods sets both the `NN_CONFIG_SERVICE` and
`NN_CONFIG_UPDATES` environment variable as nanoconfig uses it to
access the nanoconfig service
"""
# NN_CONFIG_SERVICE:
nn_config_service = os.environ.get("NN_CONFIG_SERVICE")
if not self.nanoconfig_service_endpoint and not nn_config_service:
raise ValueError(
"Invalid configuration! No NN_CONFIG_SERVICE set. You need to "
"configure your `nanoconfig_service_endpoint`.")
if self.nanoconfig_service_endpoint:
os.environ["NN_CONFIG_SERVICE"] = self.nanoconfig_service_endpoint
else:
self.nanoconfig_service_endpoint = nn_config_service
# NN_CONFIG_UPDATES
nn_config_updates = os.environ.get("NN_CONFIG_UPDATES")
if not self.nanoconfig_update_endpoint and not nn_config_updates:
raise ValueError(
"Invalid configuration! No NN_CONFIG_UPDATES set. You need to "
"configure your `nanoconfig_update_endpoint`.")
if self.nanoconfig_update_endpoint:
os.environ["NN_CONFIG_UPDATES"] = self.nanoconfig_update_endpoint
else:
self.nanoconfig_update_endpoint = nn_config_updates
def run(self):
self.setup_socket()
super(Agent, self).run()
def stop(self):
self.socket.close()
super(Agent, self).stop()
LOG.debug("[Agent] Stopped")<|fim▁hole|> LOG.debug("[Agent] Preparing to send message %s", msgpack.loads(data))
try:
LOG.debug("[Agent] Sending message...")
# The agent will wait for the publisher server to be listening on
# the related publisher_endpoint before continuing
# In which case, you should start the publisher to make it work!
self.socket.send(data)
LOG.debug("[Agent] Message sent successfully!")
except nanomsg.NanoMsgError as exc:
LOG.error("Exception during sending the message to controller %s",
exc.args[0])<|fim▁end|> |
def update(self, notifier, data):
LOG.debug("[Agent] Updated by: %s", notifier) |
<|file_name|>conf.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*-
#
# Nablarch解説書 documentation build configuration file, created by
# sphinx-quickstart on Fri Jan 08 09:45:59 2016.
#
# This file is execfile()d with the current directory set to its
# containing dir.
#
# Note that not all possible configuration values are present in this
# autogenerated file.
#
# All configuration values have a default; values that are commented out
# serve to show the default.
import sys
import os
import shlex
from datetime import date
# If extensions (or modules to document with autodoc) are in another directory,
# add these directories to sys.path here. If the directory is relative to the
# documentation root, use os.path.abspath to make it absolute, like shown here.
#sys.path.insert(0, os.path.abspath('.'))
# -- General configuration ------------------------------------------------
# If your documentation needs a minimal Sphinx version, state it here.
#needs_sphinx = '1.0'
# Add any Sphinx extension module names here, as strings. They can be
# extensions coming with Sphinx (named 'sphinx.ext.*') or your custom
# ones.
extensions = []
# Add any paths that contain templates here, relative to this directory.
templates_path = ['_templates']
# The suffix(es) of source filenames.
# You can specify multiple suffix as a list of string:
# source_suffix = ['.rst', '.md']
source_suffix = '.rst'
# The encoding of source files.
#source_encoding = 'utf-8-sig'
# The master toctree document.
master_doc = 'index'
# General information about the project.
# project = u'∇Nablarch for commercial '<|fim▁hole|>author = u'koyi Inc'
# The version info for the project you're documenting, acts as replacement for
# |version| and |release|, also used in various other places throughout the
# built documents.
#
# The short X.Y version.
# version = '5U6'
# The full version, including alpha/beta/rc tags.
# release = '5U6'
# The language for content autogenerated by Sphinx. Refer to documentation
# for a list of supported languages.
#
# This is also used if you do content translation via gettext catalogs.
# Usually you set "language" from the command line for these cases.
language = 'ja'
# There are two options for replacing |today|: either, you set today to some
# non-false value, then it is used:
#today = ''
# Else, today_fmt is used as the format for a strftime call.
#today_fmt = '%B %d, %Y'
# List of patterns, relative to source directory, that match files and
# directories to ignore when looking for source files.
exclude_patterns = ['_build']
# The reST default role (used for this markup: `text`) to use for all
# documents.
#default_role = None
# If true, '()' will be appended to :func: etc. cross-reference text.
#add_function_parentheses = True
# If true, the current module name will be prepended to all description
# unit titles (such as .. function::).
#add_module_names = True
# If true, sectionauthor and moduleauthor directives will be shown in the
# output. They are ignored by default.
#show_authors = False
# The name of the Pygments (syntax highlighting) style to use.
pygments_style = 'sphinx'
# A list of ignored prefixes for module index sorting.
#modindex_common_prefix = []
# If true, keep warnings as "system message" paragraphs in the built documents.
keep_warnings = True
# If true, `todo` and `todoList` produce output, else they produce nothing.
todo_include_todos = False
# -- Options for HTML output ----------------------------------------------
# The theme to use for HTML and HTML Help pages. See the documentation for
# a list of builtin themes.
html_theme = "sphinx_rtd_theme"
# html_theme_path = [sphinx_rtd_theme.get_html_theme_path()]
# Theme options are theme-specific and customize the look and feel of a theme
# further. For a list of options available for each theme, see the
# documentation.
#html_theme_options = {}
# Add any paths that contain custom themes here, relative to this directory.
#html_theme_path = []
# The name for this set of Sphinx documents. If None, it defaults to
# "<project> v<release> documentation".
#html_title = None
# A shorter title for the navigation bar. Default is the same as html_title.
#html_short_title = None
# The name of an image file (relative to this directory) to place at the top
# of the sidebar.
#html_logo = None
# The name of an image file (within the static path) to use as favicon of the
# docs. This file should be a Windows icon file (.ico) being 16x16 or 32x32
# pixels large.
#html_favicon = None
# Add any paths that contain custom static files (such as style sheets) here,
# relative to this directory. They are copied after the builtin static files,
# so a file named "default.css" will overwrite the builtin "default.css".
html_static_path = ['_static']
html_style = 'custom.css'
# Add any extra paths that contain custom files (such as robots.txt or
# .htaccess) here, relative to this directory. These files are copied
# directly to the root of the documentation.
#html_extra_path = []
# If not '', a 'Last updated on:' timestamp is inserted at every page bottom,
# using the given strftime format.
#html_last_updated_fmt = '%b %d, %Y'
# If true, SmartyPants will be used to convert quotes and dashes to
# typographically correct entities.
#html_use_smartypants = True
# Custom sidebar templates, maps document names to template names.
#html_sidebars = {}
# Additional templates that should be rendered to pages, maps page names to
# template names.
#html_additional_pages = {}
# If false, no module index is generated.
#html_domain_indices = True
# If false, no index is generated.
#html_use_index = True
# If true, the index is split into individual pages for each letter.
#html_split_index = False
# If true, links to the reST sources are added to the pages.
html_show_sourcelink = False
# If true, "Created using Sphinx" is shown in the HTML footer. Default is True.
#html_show_sphinx = True
# If true, "(C) Copyright ..." is shown in the HTML footer. Default is True.
#html_show_copyright = True
# If true, an OpenSearch description file will be output, and all pages will
# contain a <link> tag referring to it. The value of this option must be the
# base URL from which the finished HTML is served.
#html_use_opensearch = ''
# This is the file name suffix for HTML files (e.g. ".xhtml").
#html_file_suffix = None
# Language to be used for generating the HTML full-text search index.
# Sphinx supports the following languages:
# 'da', 'de', 'en', 'es', 'fi', 'fr', 'hu', 'it', 'ja'
# 'nl', 'no', 'pt', 'ro', 'ru', 'sv', 'tr'
html_search_language = 'ja'
# A dictionary with options for the search language support, empty by default.
# Now only 'ja' uses this config value
#html_search_options = {'type': 'default'}
# The name of a javascript file (relative to the configuration directory) that
# implements a search results scorer. If empty, the default will be used.
#html_search_scorer = 'scorer.js'
# Output file base name for HTML help builder.
htmlhelp_basename = 'Nablarchdoc'
# -- Options for LaTeX output ---------------------------------------------
latex_elements = {
# The paper size ('letterpaper' or 'a4paper').
#'papersize': 'letterpaper',
# The font size ('10pt', '11pt' or '12pt').
#'pointsize': '10pt',
# Additional stuff for the LaTeX preamble.
#'preamble': '',
# Latex figure (float) alignment
#'figure_align': 'htbp',
}
# Grouping the document tree into LaTeX files. List of tuples
# (source start file, target name, title,
# author, documentclass [howto, manual, or own class]).
latex_documents = [
(master_doc, 'Nablarch.tex', u'Nablarch解説書 Documentation',
u'TIS Inc', 'manual'),
]
# The name of an image file (relative to this directory) to place at the top of
# the title page.
#latex_logo = None
# For "manual" documents, if this is true, then toplevel headings are parts,
# not chapters.
#latex_use_parts = False
# If true, show page references after internal links.
#latex_show_pagerefs = False
# If true, show URL addresses after external links.
#latex_show_urls = False
# Documents to append as an appendix to all manuals.
#latex_appendices = []
# If false, no module index is generated.
#latex_domain_indices = True
# -- Options for manual page output ---------------------------------------
# One entry per manual page. List of tuples
# (source start file, name, description, authors, manual section).
man_pages = [
(master_doc, 'nablarch', u'Nablarch解説書 Documentation',
[author], 1)
]
# If true, show URL addresses after external links.
#man_show_urls = False
# -- Options for Texinfo output -------------------------------------------
# Grouping the document tree into Texinfo files. List of tuples
# (source start file, target name, title, author,
# dir menu entry, description, category)
texinfo_documents = [
(master_doc, 'Nablarch', u'Nablarch解説書 Documentation',
author, 'Nablarch', 'One line description of project.',
'Miscellaneous'),
]
# Documents to append as an appendix to all manuals.
#texinfo_appendices = []
# If false, no module index is generated.
#texinfo_domain_indices = True
# How to display URL addresses: 'footnote', 'no', or 'inline'.
#texinfo_show_urls = 'footnote'
# If true, do not generate a @detailmenu in the "Top" node's menu.
#texinfo_no_detailmenu = False
extensions = ['sphinx.ext.todo', 'javasphinx']
[extensions]
todo_include_todos=False
javadoc_url_map = {
'nablarch' : ('http://192.168.160.123/javadoc/', 'javadoc'),
'javax.persistence' : ('http://docs.oracle.com/javaee/7/api/', 'javadoc'),
'javax.validation' : ('http://docs.oracle.com/javaee/7/api/', 'javadoc'),
'javax.servlet' : ('http://docs.oracle.com/javaee/7/api/', 'javadoc')
}<|fim▁end|> | copyright = u'2010-' + str(date.today().year) + u', koyi Inc' |
<|file_name|>BioXASCarbonFilterFarm.cpp<|end_file_name|><|fim▁begin|>#include "BioXASCarbonFilterFarm.h"
BioXASCarbonFilterFarm::BioXASCarbonFilterFarm(const QString &deviceName, QObject *parent) :
BioXASBeamlineComponent(deviceName, parent)
{
// Create upstream actuator.
upstreamActuator_ = new BioXASCarbonFilterFarmActuator(QString("%1%2").arg(deviceName).arg("UpstreamActuator"), this);
addChildControl(upstreamActuator_);
connect( upstreamActuator_, SIGNAL(motorChanged(CLSMAXvMotor*)), this, SIGNAL(upstreamActuatorMotorChanged(CLSMAXvMotor*)) );
connect( upstreamActuator_, SIGNAL(positionStatusChanged(AMControl*)), this, SIGNAL(upstreamActuatorPositionStatusChanged(AMControl*)) );
connect( upstreamActuator_, SIGNAL(windowsChanged()), this, SIGNAL(upstreamActuatorWindowsChanged()) );
connect( upstreamActuator_, SIGNAL(windowPreferencesChanged()), this, SIGNAL(upstreamActuatorWindowPreferencesChanged()) );
// Create downstream actuator.
downstreamActuator_ = new BioXASCarbonFilterFarmActuator(QString("%1%2").arg(deviceName).arg("DownstreamActuator"), this);
addChildControl(downstreamActuator_);
connect( downstreamActuator_, SIGNAL(motorChanged(CLSMAXvMotor*)), this, SIGNAL(downstreamActuatorMotorChanged(CLSMAXvMotor*)) );
connect( downstreamActuator_, SIGNAL(positionStatusChanged(AMControl*)), this, SIGNAL(downstreamActuatorPositionStatusChanged(AMControl*)) );
connect( downstreamActuator_, SIGNAL(windowsChanged()), this, SIGNAL(downstreamActuatorWindowsChanged()) );
connect( downstreamActuator_, SIGNAL(windowPreferencesChanged()), this, SIGNAL(downstreamActuatorWindowPreferencesChanged()) );
// Create filter control.
filter_ = new BioXASCarbonFilterFarmFilterControl(QString("%1%2").arg(name()).arg("Filter"), "um", this);
addChildControl(filter_);
filter_->setUpstreamFilter(upstreamActuator_->filter());
filter_->setDownstreamFilter(downstreamActuator_->filter());
connect( filter_, SIGNAL(valueChanged(double)), this, SIGNAL(filterValueChanged(double)) );
}
BioXASCarbonFilterFarm::~BioXASCarbonFilterFarm()
{
}
bool BioXASCarbonFilterFarm::isConnected() const
{
bool connected = (
upstreamActuator_ && upstreamActuator_->isConnected() &&
downstreamActuator_ && downstreamActuator_->isConnected() &&
filter_ && filter_->isConnected()
);
return connected;
}
double BioXASCarbonFilterFarm::filterValue() const
{
double result = -1;
if (filter_ && filter_->canMeasure())
result = filter_->value();
return result;
}
CLSMAXvMotor* BioXASCarbonFilterFarm::upstreamActuatorMotor() const
{
CLSMAXvMotor *motor = 0;
if (upstreamActuator_)
motor = upstreamActuator_->motor();
return motor;
}
AMControl* BioXASCarbonFilterFarm::upstreamActuatorPositionStatus() const
{
AMControl *positionStatus = 0;
if (upstreamActuator_)
positionStatus = upstreamActuator_->positionStatus();
return positionStatus;
}
CLSMAXvMotor* BioXASCarbonFilterFarm::downstreamActuatorMotor() const
{
CLSMAXvMotor *motor = 0;
if (downstreamActuator_)
motor = downstreamActuator_->motor();
return motor;
}
AMControl* BioXASCarbonFilterFarm::downstreamActuatorPositionStatus() const
{
AMControl *positionStatus = 0;
if (downstreamActuator_)
positionStatus = downstreamActuator_->positionStatus();
return positionStatus;
}
QString BioXASCarbonFilterFarm::windowToString(double window) const
{
QString result;
switch (int(window)) {
case Window::None:
result = "None";
break;
case Window::Bottom:
result = "Bottom";
break;
case Window::Top:
result = "Top";
break;
default:
break;
}
return result;
}
void BioXASCarbonFilterFarm::setUpstreamActuatorMotor(CLSMAXvMotor *newControl)
{
if (upstreamActuator_)
upstreamActuator_->setMotor(newControl);
}
void BioXASCarbonFilterFarm::setUpstreamActuatorPositionStatus(AMControl *newControl)
{
if (upstreamActuator_)
upstreamActuator_->setPositionStatus(newControl);
}
void BioXASCarbonFilterFarm::addUpstreamActuatorWindow(int windowIndex, double positionSetpoint, double positionMin, double positionMax, double filter)
{
if (upstreamActuator_)
upstreamActuator_->addWindow(windowIndex, windowToString(windowIndex), positionSetpoint, positionMin, positionMax, filter);
}
void BioXASCarbonFilterFarm::removeUpstreamActuatorWindow(int windowIndex)
{
if (upstreamActuator_)
upstreamActuator_->removeWindow(windowIndex);
}
void BioXASCarbonFilterFarm::clearUpstreamActuatorWindows()
{
if (upstreamActuator_)
upstreamActuator_->clearWindows();
}
void BioXASCarbonFilterFarm::setUpstreamActuatorWindowPreference(double filter, int windowIndex)
{
if (upstreamActuator_)
upstreamActuator_->setWindowPreference(filter, windowIndex);
}
void BioXASCarbonFilterFarm::removeUpstreamActuatorWindowPreference(double filter)
{
if (upstreamActuator_)
upstreamActuator_->removeWindowPreference(filter);
}
void BioXASCarbonFilterFarm::clearUpstreamActuatorWindowPreferences()
{
if (upstreamActuator_)
upstreamActuator_->clearWindowPreferences();
}
void BioXASCarbonFilterFarm::setDownstreamActuatorMotor(CLSMAXvMotor *newControl)
{
if (downstreamActuator_)
downstreamActuator_->setMotor(newControl);
}
void BioXASCarbonFilterFarm::setDownstreamActuatorPositionStatus(AMControl *newControl)
{
if (downstreamActuator_)
downstreamActuator_->setPositionStatus(newControl);
}
void BioXASCarbonFilterFarm::addDownstreamActuatorWindow(int windowIndex, double positionSetpoint, double positionMin, double positionMax, double filter)
{
if (downstreamActuator_)
downstreamActuator_->addWindow(windowIndex, windowToString(windowIndex), positionSetpoint, positionMin, positionMax, filter);
}
void BioXASCarbonFilterFarm::removeDownstreamActuatorWindow(int windowIndex)
{
if (downstreamActuator_)
downstreamActuator_->removeWindow(windowIndex);
}
void BioXASCarbonFilterFarm::clearDownstreamActuatorWindows()
{
if (downstreamActuator_)
downstreamActuator_->clearWindows();
}
void BioXASCarbonFilterFarm::setDownstreamActuatorWindowPreference(double filter, int windowIndex)
{
if (downstreamActuator_)
downstreamActuator_->setWindowPreference(filter, windowIndex);<|fim▁hole|> if (downstreamActuator_)
downstreamActuator_->removeWindowPreference(filter);
}
void BioXASCarbonFilterFarm::clearDownstreamActuatorWindowPreferences()
{
if (downstreamActuator_)
downstreamActuator_->clearWindowPreferences();
}
void BioXASCarbonFilterFarm::clearWindows()
{
clearUpstreamActuatorWindows();
clearDownstreamActuatorWindows();
}
void BioXASCarbonFilterFarm::clearWindowPreferences()
{
clearUpstreamActuatorWindowPreferences();
clearDownstreamActuatorWindowPreferences();
}<|fim▁end|> | }
void BioXASCarbonFilterFarm::removeDownstreamActuatorWindowPreference(double filter)
{ |
<|file_name|>widget.spec.ts<|end_file_name|><|fim▁begin|>// Copyright (c) Jupyter Development Team.
// Distributed under the terms of the Modified BSD License.
import {
Context,
DocumentRegistry,
TextModelFactory
} from '@jupyterlab/docregistry';
import * as Mock from '@jupyterlab/testutils/lib/mock';
import { UUID } from '@lumino/coreutils';
import { CellRenderer, DataGrid, JSONModel } from '@lumino/datagrid';
import { CSVViewer, GridSearchService } from '../src';
function createContext(): Context<DocumentRegistry.IModel> {
const factory = new TextModelFactory();
const manager = new Mock.ServiceManagerMock();
const path = UUID.uuid4() + '.csv';
return new Context({ factory, manager, path });
}
describe('csvviewer/widget', () => {
const context = createContext();
describe('CSVViewer', () => {
describe('#constructor()', () => {
it('should instantiate a `CSVViewer`', () => {
const widget = new CSVViewer({ context });
expect(widget).toBeInstanceOf(CSVViewer);
widget.dispose();
});
});
describe('#context', () => {
it('should be the context for the file', () => {
const widget = new CSVViewer({ context });
expect(widget.context).toBe(context);
});
});
describe('#dispose()', () => {
it('should dispose of the resources held by the widget', () => {
const widget = new CSVViewer({ context });
expect(widget.isDisposed).toBe(false);
widget.dispose();
expect(widget.isDisposed).toBe(true);
});
it('should be safe to call multiple times', () => {
const widget = new CSVViewer({ context });
expect(widget.isDisposed).toBe(false);
widget.dispose();
widget.dispose();
expect(widget.isDisposed).toBe(true);
});
});
});
describe('GridSearchService', () => {
function createModel(): JSONModel {
return new JSONModel({
data: [
{ index: 0, a: 'other', b: 'match 1' },
{ index: 1, a: 'other', b: 'match 2' }
],
schema: {
primaryKey: ['index'],
fields: [
{
name: 'a'
},
{ name: 'b' }
]
}
});
}
function createGridSearchService(model: JSONModel): GridSearchService {
const grid = new DataGrid();
grid.dataModel = model;
return new GridSearchService(grid);
}
it('searches incrementally and set background color', () => {
const model = createModel();
const searchService = createGridSearchService(model);
const cellRenderer = searchService.cellBackgroundColorRendererFunc({
matchBackgroundColor: 'anotherMatch',
currentMatchBackgroundColor: 'currentMatch',
textColor: '',
horizontalAlignment: 'right'
});
/**
* fake rendering a cell and returns the background color for this coordinate.
*/<|fim▁hole|> const cellConfig = {
value: model.data('body', row, column),
row,
column
} as CellRenderer.CellConfig;
return cellRenderer(cellConfig);
}
// searching for "match", cells at (0,1) and (1,1) should match.
// (0,1) is the current match
const query = /match/;
searchService.find(query);
expect(fakeRenderCell(0, 1)).toBe('currentMatch');
expect(fakeRenderCell(1, 1)).toBe('anotherMatch');
expect(fakeRenderCell(0, 0)).toBe('');
// search again, the current match "moves" to be (1,1)
searchService.find(query);
expect(fakeRenderCell(0, 1)).toBe('anotherMatch');
expect(fakeRenderCell(1, 1)).toBe('currentMatch');
});
});
});<|fim▁end|> | function fakeRenderCell(row: number, column: number) { |
<|file_name|>schema.rs<|end_file_name|><|fim▁begin|>use types::{ChecksumType, Column, ColumnValue};
use v1::row::{Row};
use v1::write::{schema_write};
use v1::read::schema_read;
use v1::parse::parse_string;
use std::io::{Error, ErrorKind, Read, Write};
use std::str;
pub struct Metadata {
pub checksum: ChecksumType,
pub header_bytes: usize,
// ordered list of columns
pub columns: Vec<Column>,
}
impl Metadata {
pub fn parse<R: Read>(reader: &mut R) -> Result<Self, Error> {
let mut s: String = String::new();
match reader.read_to_string(&mut s) {
Ok(_) => {
parse_string(&s).ok_or(Error::new(ErrorKind::Other, "parsing failed"))
}
Err(why) => Err(why),
}
}
pub fn write<W: Write>(&self,
writer: &mut W,
names: &[&str],
values: &[ColumnValue]) {
schema_write(
&self.columns,
writer,
names,<|fim▁hole|> values,
self.header_bytes,
&self.checksum
);
}
pub fn read<R: Read>(&self, reader: &mut R) -> Row {
loop {
let r = schema_read(
&self.columns,
reader,
self.header_bytes,
&self.checksum
);
if r.is_some() {
return r.unwrap();
}
println!("continuing with next row");
}
}
}<|fim▁end|> | |
<|file_name|>ConfigFilesFinder.java<|end_file_name|><|fim▁begin|>package org.xiaotian.config;
import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import org.apache.log4j.Logger;
import org.xiaotian.config.bean.ConfigFile;
import org.xiaotian.config.bean.ConfigFiles;
import org.xiaotian.extend.CMyFile;
/**
* 按照指定方式(配置文件plugin和mapping.xml在同一目录)读写文件的工具类 <BR>
*
* @author xiaotian15
*
*/
public class ConfigFilesFinder {
private static Logger m_logger = Logger.getLogger(ConfigFilesFinder.class);
/**
* 负有所有配置文件信息的ConfigFile集合
*/
private ConfigFiles m_oConfigFiles = null;
/**
* 配置文件存放的根文件夹位置,是查找的入口
*/
private ArrayList<String> m_pConfigFileRootPaths = new ArrayList<String>();
/**
* 要查找的配置文件的名称,如 config.xml
*/
private String m_sConfigXmlFile;
private HashMap<String, ConfigFile> m_mapAlreadyDoneWithFileNames = new HashMap<String, ConfigFile>();
public ConfigFilesFinder(String _sConfigFileRootPath, String _sConfigXmlFile) {
m_pConfigFileRootPaths.add(_sConfigFileRootPath);
this.m_sConfigXmlFile = _sConfigXmlFile;
}
public ConfigFilesFinder(ArrayList<String> _arConfigFileRootPaths,
String _sConfigXmlFile) {
this.m_pConfigFileRootPaths = _arConfigFileRootPaths;
this.m_sConfigXmlFile = _sConfigXmlFile;
}
/**
* 得到已经组织好的配置文件集合
*
* @return 包含config.xml - mapping.xml的CfgFiles对象
* @throws ConfigException
* 可能的文件读取错误
*/
public ConfigFiles getConfigFiles() throws ConfigException {
if (m_oConfigFiles == null) {
m_oConfigFiles = new ConfigFiles();
for (int i = 0; i < m_pConfigFileRootPaths.size(); i++) {
String sConfigFileRootPath = (String) m_pConfigFileRootPaths
.get(i);
if (m_logger.isDebugEnabled())
m_logger.debug("begin to load config files from["
+ sConfigFileRootPath + "]...");
File fRoot = new File(sConfigFileRootPath);
lookupCfgFiles(fRoot);
}
} else {
if (m_logger.isDebugEnabled())
m_logger.debug("the files have been loaded.");
}
return m_oConfigFiles;
}
/**
* 刷新
*/
public ConfigFiles refresh() throws ConfigException {
m_oConfigFiles = null;
return getConfigFiles();
}
/**
* 递归检索指定目录,将查找的文件加入到m_hshFiles中去
*
* @param _file
* 文件夹路径或者文件路径,后者是递归跳出的条件
*/
private void lookupCfgFiles(File _file) {
if (_file.isFile()) {
// 不是指定的文件名
if (!_file.getName().equals(this.m_sConfigXmlFile)) {
return;
}
// 在与Config.xml同级的目录中寻找配置对象的描述文件:mapping.xml
String sMapping = CMyFile.extractFilePath(_file.getPath())
+ ConfigConstants.NAME_FILE_MAPPING;
File fMapping = CMyFile.fileExists(sMapping) ? new File(sMapping)
: null;
// 分解配置文件
String sAbsolutFileName = _file.getAbsolutePath();
String sConfigFileNameExcludeProjectPath = extractConfigFileNameExcludeProjectPath(sAbsolutFileName);
// 判断是否处理,如果处理了,判断Mapping文件是否设置,没有直接返回
ConfigFile configFile = (ConfigFile) m_mapAlreadyDoneWithFileNames
.get(sConfigFileNameExcludeProjectPath);
if (configFile != null) {
if (configFile.getMapping() == null && fMapping != null) {
configFile.setMapping(fMapping);
}
return;
}
// 记录下已经处理的配置文件
configFile = new ConfigFile(_file, fMapping);
m_mapAlreadyDoneWithFileNames.put(
sConfigFileNameExcludeProjectPath, configFile);
if (m_logger.isDebugEnabled()) {
m_logger.debug("load xml file[" + _file.getPath() + "]");
}
m_oConfigFiles.add(configFile);
return;
}
// 递归调用,遍历所有子文件夹
File[] dirs = _file.listFiles();
if (dirs == null) {
m_logger.warn("May be a IOException,find an invalid dir:"
+ _file.getAbsolutePath());
return;
}
for (int i = 0; i < dirs.length; i++) {
lookupCfgFiles(dirs[i]);
}
}
/**
* 获取s_sAppRootPath后面的路径<BR>
*
* @param _sAbsolutFileName
* config文件的root路径
* @return
*/
private String extractConfigFileNameExcludeProjectPath(
String _sAbsolutFileName) {
String sConfigFilePathFlag = File.separatorChar
+ ConfigConstants.CONFIG_ROOT_PATH + File.separatorChar;
String sConfigFileNameExcludeProjectPath = _sAbsolutFileName;
int nPos = _sAbsolutFileName.indexOf(sConfigFilePathFlag);
if (nPos >= 0) {
sConfigFileNameExcludeProjectPath = _sAbsolutFileName
.substring(nPos);
}
return sConfigFileNameExcludeProjectPath;
<|fim▁hole|>}<|fim▁end|> | }
|
<|file_name|>text.mako.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/. */
<%namespace name="helpers" file="/helpers.mako.rs" />
<% from data import Method %>
<% data.new_style_struct("Text",
inherited=False,
gecko_name="TextReset",
additional_methods=[Method("has_underline", "bool"),
Method("has_overline", "bool"),
Method("has_line_through", "bool")]) %>
<%helpers:longhand name="text-overflow" animation_value_type="discrete" boxed="True"
flags="APPLIES_TO_PLACEHOLDER"
spec="https://drafts.csswg.org/css-ui/#propdef-text-overflow">
use std::fmt;
use style_traits::ToCss;
<|fim▁hole|> Ellipsis,
String(Box<str>),
}
#[derive(Clone, Debug, Eq, MallocSizeOf, PartialEq, ToCss)]
pub struct SpecifiedValue {
pub first: Side,
pub second: Option<Side>
}
pub mod computed_value {
pub use super::Side;
#[derive(Clone, Debug, MallocSizeOf, PartialEq)]
pub struct T {
// When the specified value only has one side, that's the "second"
// side, and the sides are logical, so "second" means "end". The
// start side is Clip in that case.
//
// When the specified value has two sides, those are our "first"
// and "second" sides, and they are physical sides ("left" and
// "right").
pub first: Side,
pub second: Side,
pub sides_are_logical: bool
}
}
impl ToCss for computed_value::T {
fn to_css<W>(&self, dest: &mut W) -> fmt::Result where W: fmt::Write {
if self.sides_are_logical {
assert!(self.first == Side::Clip);
self.second.to_css(dest)?;
} else {
self.first.to_css(dest)?;
dest.write_str(" ")?;
self.second.to_css(dest)?;
}
Ok(())
}
}
impl ToComputedValue for SpecifiedValue {
type ComputedValue = computed_value::T;
#[inline]
fn to_computed_value(&self, _context: &Context) -> Self::ComputedValue {
if let Some(ref second) = self.second {
Self::ComputedValue { first: self.first.clone(),
second: second.clone(),
sides_are_logical: false }
} else {
Self::ComputedValue { first: Side::Clip,
second: self.first.clone(),
sides_are_logical: true }
}
}
#[inline]
fn from_computed_value(computed: &Self::ComputedValue) -> Self {
if computed.sides_are_logical {
assert!(computed.first == Side::Clip);
SpecifiedValue { first: computed.second.clone(),
second: None }
} else {
SpecifiedValue { first: computed.first.clone(),
second: Some(computed.second.clone()) }
}
}
}
#[inline]
pub fn get_initial_value() -> computed_value::T {
computed_value::T {
first: Side::Clip,
second: Side::Clip,
sides_are_logical: true,
}
}
pub fn parse<'i, 't>(context: &ParserContext, input: &mut Parser<'i, 't>)
-> Result<SpecifiedValue, ParseError<'i>> {
let first = Side::parse(context, input)?;
let second = input.try(|input| Side::parse(context, input)).ok();
Ok(SpecifiedValue {
first: first,
second: second,
})
}
impl Parse for Side {
fn parse<'i, 't>(_context: &ParserContext, input: &mut Parser<'i, 't>)
-> Result<Side, ParseError<'i>> {
let location = input.current_source_location();
match *input.next()? {
Token::Ident(ref ident) => {
match_ignore_ascii_case! { ident,
"clip" => Ok(Side::Clip),
"ellipsis" => Ok(Side::Ellipsis),
_ => Err(location.new_custom_error(
SelectorParseErrorKind::UnexpectedIdent(ident.clone())
))
}
}
Token::QuotedString(ref v) => {
Ok(Side::String(v.as_ref().to_owned().into_boxed_str()))
}
ref t => Err(location.new_unexpected_token_error(t.clone())),
}
}
}
</%helpers:longhand>
${helpers.single_keyword("unicode-bidi",
"normal embed isolate bidi-override isolate-override plaintext",
animation_value_type="discrete",
spec="https://drafts.csswg.org/css-writing-modes/#propdef-unicode-bidi")}
<%helpers:longhand name="text-decoration-line"
custom_cascade="${product == 'servo'}"
animation_value_type="discrete"
flags="APPLIES_TO_FIRST_LETTER APPLIES_TO_FIRST_LINE APPLIES_TO_PLACEHOLDER",
spec="https://drafts.csswg.org/css-text-decor/#propdef-text-decoration-line">
use std::fmt;
use style_traits::ToCss;
bitflags! {
#[derive(MallocSizeOf, ToComputedValue)]
pub flags SpecifiedValue: u8 {
const NONE = 0,
const UNDERLINE = 0x01,
const OVERLINE = 0x02,
const LINE_THROUGH = 0x04,
const BLINK = 0x08,
% if product == "gecko":
/// Only set by presentation attributes
///
/// Setting this will mean that text-decorations use the color
/// specified by `color` in quirks mode.
///
/// For example, this gives <a href=foo><font color="red">text</font></a>
/// a red text decoration
const COLOR_OVERRIDE = 0x10,
% endif
}
}
impl ToCss for SpecifiedValue {
fn to_css<W>(&self, dest: &mut W) -> fmt::Result where W: fmt::Write {
let mut has_any = false;
macro_rules! write_value {
($line:ident => $css:expr) => {
if self.contains($line) {
if has_any {
dest.write_str(" ")?;
}
dest.write_str($css)?;
has_any = true;
}
}
}
write_value!(UNDERLINE => "underline");
write_value!(OVERLINE => "overline");
write_value!(LINE_THROUGH => "line-through");
write_value!(BLINK => "blink");
if !has_any {
dest.write_str("none")?;
}
Ok(())
}
}
pub mod computed_value {
pub type T = super::SpecifiedValue;
#[allow(non_upper_case_globals)]
pub const none: T = super::SpecifiedValue {
bits: 0
};
}
#[inline] pub fn get_initial_value() -> computed_value::T {
computed_value::none
}
#[inline]
pub fn get_initial_specified_value() -> SpecifiedValue {
SpecifiedValue::empty()
}
/// none | [ underline || overline || line-through || blink ]
pub fn parse<'i, 't>(_context: &ParserContext, input: &mut Parser<'i, 't>)
-> Result<SpecifiedValue, ParseError<'i>> {
let mut result = SpecifiedValue::empty();
if input.try(|input| input.expect_ident_matching("none")).is_ok() {
return Ok(result)
}
let mut empty = true;
loop {
let result: Result<_, ParseError> = input.try(|input| {
let location = input.current_source_location();
match input.expect_ident() {
Ok(ident) => {
(match_ignore_ascii_case! { &ident,
"underline" => if result.contains(UNDERLINE) { Err(()) }
else { empty = false; result.insert(UNDERLINE); Ok(()) },
"overline" => if result.contains(OVERLINE) { Err(()) }
else { empty = false; result.insert(OVERLINE); Ok(()) },
"line-through" => if result.contains(LINE_THROUGH) { Err(()) }
else { empty = false; result.insert(LINE_THROUGH); Ok(()) },
"blink" => if result.contains(BLINK) { Err(()) }
else { empty = false; result.insert(BLINK); Ok(()) },
_ => Err(())
}).map_err(|()| {
location.new_custom_error(SelectorParseErrorKind::UnexpectedIdent(ident.clone()))
})
}
Err(e) => return Err(e.into())
}
});
if result.is_err() {
break;
}
}
if !empty { Ok(result) } else { Err(input.new_custom_error(StyleParseErrorKind::UnspecifiedError)) }
}
% if product == "servo":
fn cascade_property_custom(_declaration: &PropertyDeclaration,
context: &mut computed::Context) {
longhands::_servo_text_decorations_in_effect::derive_from_text_decoration(context);
}
% endif
#[cfg(feature = "gecko")]
impl_bitflags_conversions!(SpecifiedValue);
</%helpers:longhand>
${helpers.single_keyword("text-decoration-style",
"solid double dotted dashed wavy -moz-none",
products="gecko",
animation_value_type="discrete",
flags="APPLIES_TO_FIRST_LETTER APPLIES_TO_FIRST_LINE APPLIES_TO_PLACEHOLDER",
spec="https://drafts.csswg.org/css-text-decor/#propdef-text-decoration-style")}
${helpers.predefined_type(
"text-decoration-color",
"Color",
"computed_value::T::currentcolor()",
initial_specified_value="specified::Color::currentcolor()",
products="gecko",
animation_value_type="AnimatedColor",
ignored_when_colors_disabled=True,
flags="APPLIES_TO_FIRST_LETTER APPLIES_TO_FIRST_LINE APPLIES_TO_PLACEHOLDER",
spec="https://drafts.csswg.org/css-text-decor/#propdef-text-decoration-color",
)}
${helpers.predefined_type(
"initial-letter",
"InitialLetter",
"computed::InitialLetter::normal()",
initial_specified_value="specified::InitialLetter::normal()",
animation_value_type="discrete",
products="gecko",
flags="APPLIES_TO_FIRST_LETTER",
spec="https://drafts.csswg.org/css-inline/#sizing-drop-initials")}<|fim▁end|> |
#[derive(Clone, Debug, Eq, MallocSizeOf, PartialEq, ToCss)]
pub enum Side {
Clip, |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.