file_name large_stringlengths 4 140 | prefix large_stringlengths 0 39k | suffix large_stringlengths 0 36.1k | middle large_stringlengths 0 29.4k | fim_type large_stringclasses 4
values |
|---|---|---|---|---|
destroyObject.js | /*global define*/
define([
'./defaultValue',
'./DeveloperError'
], function(
defaultValue,
DeveloperError) {
"use strict";
function returnTrue() {
return true;
}
/**
* Destroys an object. Each of the object's functions, including functions in its prototype,
* is replaced with a function that throws a {@link DeveloperError}, except for the object's
* <code>isDestroyed</code> function, which is set to a function that returns <code>true</code>.
* The object's properties are removed with <code>delete</code>.
* <br /><br />
* This function is used by objects that hold native resources, e.g., WebGL resources, which
* need to be explicitly released. Client code calls an object's <code>destroy</code> function,
* which then releases the native resource and calls <code>destroyObject</code> to put itself
* in a destroyed state.
*
* @exports destroyObject
*
* @param {Object} object The object to destroy.
* @param {String} [message] The message to include in the exception that is thrown if
* a destroyed object's function is called.
*
* @see DeveloperError
*
* @example
* // How a texture would destroy itself.
* this.destroy = function () {
* _gl.deleteTexture(_texture);
* return Cesium.destroyObject(this);
* };
*/
var destroyObject = function(object, message) {
message = defaultValue(message, 'This object was destroyed, i.e., destroy() was called.');
function throwOnDestroyed() |
for ( var key in object) {
if (typeof object[key] === 'function') {
object[key] = throwOnDestroyed;
}
}
object.isDestroyed = returnTrue;
return undefined;
};
return destroyObject;
}); | {
throw new DeveloperError(message);
} | identifier_body |
particle.rs | struct Particle {
x: f32,
y: f32,
dx: f32,
dy: f32,
frames_left: i32
}
impl Particle {
fn animate(&mut self) {
if self.in_use() {
return; |
--frames_left;
x += dx;
y += dy;
}
fn in_use(&self) -> bool {
self.frames_left > 0
}
}
const POOL_SIZE: i32 = 1000;
struct ParticlePool {
particles: [Particle; POOL_SIZE]
}
impl ParticlePool {
fn create(&self, x: f32, y: f32, dx: f32, dy: f32, lifetime: i32) {
for i in 0..POOL_SIZE {
if !particles[i].in_use() {
particles[i]
}
}
}
fn animate() {
for particle in particles {
particle.animate();
}
}
} | } | random_line_split |
particle.rs | struct Particle {
x: f32,
y: f32,
dx: f32,
dy: f32,
frames_left: i32
}
impl Particle {
fn animate(&mut self) {
if self.in_use() |
--frames_left;
x += dx;
y += dy;
}
fn in_use(&self) -> bool {
self.frames_left > 0
}
}
const POOL_SIZE: i32 = 1000;
struct ParticlePool {
particles: [Particle; POOL_SIZE]
}
impl ParticlePool {
fn create(&self, x: f32, y: f32, dx: f32, dy: f32, lifetime: i32) {
for i in 0..POOL_SIZE {
if !particles[i].in_use() {
particles[i]
}
}
}
fn animate() {
for particle in particles {
particle.animate();
}
}
}
| {
return;
} | conditional_block |
particle.rs | struct Particle {
x: f32,
y: f32,
dx: f32,
dy: f32,
frames_left: i32
}
impl Particle {
fn animate(&mut self) {
if self.in_use() {
return;
}
--frames_left;
x += dx;
y += dy;
}
fn | (&self) -> bool {
self.frames_left > 0
}
}
const POOL_SIZE: i32 = 1000;
struct ParticlePool {
particles: [Particle; POOL_SIZE]
}
impl ParticlePool {
fn create(&self, x: f32, y: f32, dx: f32, dy: f32, lifetime: i32) {
for i in 0..POOL_SIZE {
if !particles[i].in_use() {
particles[i]
}
}
}
fn animate() {
for particle in particles {
particle.animate();
}
}
}
| in_use | identifier_name |
kqueue.rs | use std::{cmp, fmt, ptr};
use std::os::raw::c_int;
use std::os::unix::io::RawFd;
use std::collections::HashMap;
use std::sync::atomic::{AtomicUsize, Ordering, ATOMIC_USIZE_INIT};
use std::time::Duration;
use libc::{self, time_t};
use {io, Ready, PollOpt, Token};
use event::{self, Event};
use sys::unix::cvt;
use sys::unix::io::set_cloexec;
/// Each Selector has a globally unique(ish) ID associated with it. This ID
/// gets tracked by `TcpStream`, `TcpListener`, etc... when they are first
/// registered with the `Selector`. If a type that is previously associated with
/// a `Selector` attempts to register itself with a different `Selector`, the
/// operation will return with an error. This matches windows behavior.
static NEXT_ID: AtomicUsize = ATOMIC_USIZE_INIT;
macro_rules! kevent {
($id: expr, $filter: expr, $flags: expr, $data: expr) => {
libc::kevent {
ident: $id as ::libc::uintptr_t,
filter: $filter,
flags: $flags,
fflags: 0,
data: 0,
udata: $data as *mut _,
}
}
}
pub struct Selector {
id: usize,
kq: RawFd,
}
impl Selector {
pub fn new() -> io::Result<Selector> {
// offset by 1 to avoid choosing 0 as the id of a selector
let id = NEXT_ID.fetch_add(1, Ordering::Relaxed) + 1;
let kq = unsafe { try!(cvt(libc::kqueue())) };
drop(set_cloexec(kq));
Ok(Selector {
id: id,
kq: kq,
})
}
pub fn id(&self) -> usize {
self.id
}
pub fn select(&self, evts: &mut Events, awakener: Token, timeout: Option<Duration>) -> io::Result<bool> {
let timeout = timeout.map(|to| {
libc::timespec {
tv_sec: cmp::min(to.as_secs(), time_t::max_value() as u64) as time_t,
tv_nsec: to.subsec_nanos() as libc::c_long,
}
});
let timeout = timeout.as_ref().map(|s| s as *const _).unwrap_or(ptr::null_mut());
unsafe {
let cnt = try!(cvt(libc::kevent(self.kq,
ptr::null(),
0,
evts.sys_events.0.as_mut_ptr(),
// FIXME: needs a saturating cast here.
evts.sys_events.0.capacity() as c_int,
timeout)));
evts.sys_events.0.set_len(cnt as usize);
Ok(evts.coalesce(awakener))
}
}
pub fn register(&self, fd: RawFd, token: Token, interests: Ready, opts: PollOpt) -> io::Result<()> {
trace!("registering; token={:?}; interests={:?}", token, interests);
let flags = if opts.contains(PollOpt::edge()) { libc::EV_CLEAR } else { 0 } |
if opts.contains(PollOpt::oneshot()) { libc::EV_ONESHOT } else { 0 } |
libc::EV_RECEIPT;
unsafe {
let r = if interests.contains(Ready::readable()) { libc::EV_ADD } else { libc::EV_DELETE };
let w = if interests.contains(Ready::writable()) { libc::EV_ADD } else { libc::EV_DELETE };
let mut changes = [
kevent!(fd, libc::EVFILT_READ, flags | r, usize::from(token)),
kevent!(fd, libc::EVFILT_WRITE, flags | w, usize::from(token)),
];
try!(cvt(libc::kevent(self.kq, changes.as_ptr(), changes.len() as c_int,
changes.as_mut_ptr(), changes.len() as c_int,
::std::ptr::null())));
for change in changes.iter() {
debug_assert_eq!(change.flags & libc::EV_ERROR, libc::EV_ERROR);
if change.data != 0 {
// there’s some error, but we want to ignore ENOENT error for EV_DELETE
let orig_flags = if change.filter == libc::EVFILT_READ { r } else { w };
if !(change.data as i32 == libc::ENOENT && orig_flags & libc::EV_DELETE != 0) {
return Err(::std::io::Error::from_raw_os_error(change.data as i32));
}
}
}
Ok(())
}
}
pub fn reregister(&self, fd: RawFd, token: Token, interests: Ready, opts: PollOpt) -> io::Result<()> {
// Just need to call register here since EV_ADD is a mod if already
// registered
self.register(fd, token, interests, opts)
}
pub fn deregister(&self, fd: RawFd) -> io::Result<()> {
unsafe {
// EV_RECEIPT is a nice way to apply changes and get back per-event results while not
// draining the actual changes.
let filter = libc::EV_DELETE | libc::EV_RECEIPT;
let mut changes = [
kevent!(fd, libc::EVFILT_READ, filter, ptr::null_mut()),
kevent!(fd, libc::EVFILT_WRITE, filter, ptr::null_mut()),
];
try!(cvt(libc::kevent(self.kq, changes.as_ptr(), changes.len() as c_int,
changes.as_mut_ptr(), changes.len() as c_int,
::std::ptr::null())).map(|_| ()));
if changes[0].data as i32 == libc::ENOENT && changes[1].data as i32 == libc::ENOENT {
return Err(::std::io::Error::from_raw_os_error(changes[0].data as i32));
}
for change in changes.iter() {
debug_assert_eq!(libc::EV_ERROR & change.flags, libc::EV_ERROR);
if change.data != 0 && change.data as i32 != libc::ENOENT {
return Err(::std::io::Error::from_raw_os_error(changes[0].data as i32));
}
}
Ok(())
}
}
}
impl fmt::Debug for Selector {
fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
fmt.debug_struct("Selector")
.field("id", &self.id)
.field("kq", &self.kq)
.finish()
}
}
impl Drop for Selector {
fn drop(&mut self) {
unsafe {
let _ = libc::close(self.kq);
}
}
}
pub struct Events {
sys_events: KeventList,
events: Vec<Event>,
event_map: HashMap<Token, usize>,
}
struct KeventList(Vec<libc::kevent>);
unsafe impl Send for KeventList {}
unsafe impl Sync for KeventList {}
impl Events {
pub fn with_capacity(cap: usize) -> Events {
Events {
sys_events: KeventList(Vec::with_capacity(cap)),
events: Vec::with_capacity(cap),
event_map: HashMap::with_capacity(cap)
}
}
#[inline]
pub fn len(&self) -> usize {
self.events.len()
}
#[inline]
pub fn capacity(&self) -> usize {
self.events.capacity()
}
#[inline]
pub fn is_empty(&self) -> bool {
self.events.is_empty()
}
pub fn get(&self, idx: usize) -> Option<Event> {
self.events.get(idx).map(|e| *e)
}
fn coalesce(&mut self, awakener: Token) -> bool {
let mut ret = false;
self.events.clear();
self.event_map.clear();
for e in self.sys_events.0.iter() {
let token = Token(e.udata as usize);
let len = self.events.len();
if token == awakener {
// TODO: Should this return an error if event is an error. It
// is not critical as spurious wakeups are permitted.
ret = true;
continue;
}
let idx = *self.event_map.entry(token)
.or_insert(len);
if idx == len {
// New entry, insert the default
self.events.push(Event::new(Ready::none(), token));
}
if e.flags & libc::EV_ERROR != 0 {
event::kind_mut(&mut self.events[idx]).insert(Ready::error());
}
if e.filter == libc::EVFILT_READ {
event::kind_mut(&mut self.events[idx]).insert(Ready::readable());
} else if e.filter == libc::EVFILT_WRITE {
| if e.flags & libc::EV_EOF != 0 {
event::kind_mut(&mut self.events[idx]).insert(Ready::hup());
// When the read end of the socket is closed, EV_EOF is set on
// flags, and fflags contains the error if there is one.
if e.fflags != 0 {
event::kind_mut(&mut self.events[idx]).insert(Ready::error());
}
}
}
ret
}
pub fn push_event(&mut self, event: Event) {
self.events.push(event);
}
}
impl fmt::Debug for Events {
fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
write!(fmt, "Events {{ len: {} }}", self.sys_events.0.len())
}
}
#[test]
fn does_not_register_rw() {
use ::deprecated::{EventLoopBuilder, Handler};
use ::unix::EventedFd;
struct Nop;
impl Handler for Nop {
type Timeout = ();
type Message = ();
}
// registering kqueue fd will fail if write is requested (On anything but some versions of OS
// X)
let kq = unsafe { libc::kqueue() };
let kqf = EventedFd(&kq);
let mut evtloop = EventLoopBuilder::new().build::<Nop>().expect("evt loop builds");
evtloop.register(&kqf, Token(1234), Ready::readable(),
PollOpt::edge() | PollOpt::oneshot()).unwrap();
}
| event::kind_mut(&mut self.events[idx]).insert(Ready::writable());
}
| conditional_block |
kqueue.rs | use std::{cmp, fmt, ptr};
use std::os::raw::c_int;
use std::os::unix::io::RawFd;
use std::collections::HashMap;
use std::sync::atomic::{AtomicUsize, Ordering, ATOMIC_USIZE_INIT};
use std::time::Duration;
use libc::{self, time_t};
use {io, Ready, PollOpt, Token};
use event::{self, Event};
use sys::unix::cvt;
use sys::unix::io::set_cloexec;
/// Each Selector has a globally unique(ish) ID associated with it. This ID
/// gets tracked by `TcpStream`, `TcpListener`, etc... when they are first
/// registered with the `Selector`. If a type that is previously associated with
/// a `Selector` attempts to register itself with a different `Selector`, the
/// operation will return with an error. This matches windows behavior.
static NEXT_ID: AtomicUsize = ATOMIC_USIZE_INIT;
macro_rules! kevent {
($id: expr, $filter: expr, $flags: expr, $data: expr) => {
libc::kevent {
ident: $id as ::libc::uintptr_t,
filter: $filter,
flags: $flags,
fflags: 0,
data: 0,
udata: $data as *mut _,
}
}
}
pub struct Selector {
id: usize,
kq: RawFd,
}
impl Selector {
pub fn new() -> io::Result<Selector> {
// offset by 1 to avoid choosing 0 as the id of a selector
let id = NEXT_ID.fetch_add(1, Ordering::Relaxed) + 1;
let kq = unsafe { try!(cvt(libc::kqueue())) };
drop(set_cloexec(kq));
Ok(Selector {
id: id,
kq: kq,
})
}
pub fn id(&self) -> usize {
self.id
}
pub fn select(&self, evts: &mut Events, awakener: Token, timeout: Option<Duration>) -> io::Result<bool> {
let timeout = timeout.map(|to| {
libc::timespec {
tv_sec: cmp::min(to.as_secs(), time_t::max_value() as u64) as time_t,
tv_nsec: to.subsec_nanos() as libc::c_long,
}
});
let timeout = timeout.as_ref().map(|s| s as *const _).unwrap_or(ptr::null_mut());
unsafe {
let cnt = try!(cvt(libc::kevent(self.kq,
ptr::null(),
0,
evts.sys_events.0.as_mut_ptr(),
// FIXME: needs a saturating cast here.
evts.sys_events.0.capacity() as c_int,
timeout)));
evts.sys_events.0.set_len(cnt as usize);
Ok(evts.coalesce(awakener))
}
}
pub fn register(&self, fd: RawFd, token: Token, interests: Ready, opts: PollOpt) -> io::Result<()> {
trace!("registering; token={:?}; interests={:?}", token, interests);
let flags = if opts.contains(PollOpt::edge()) { libc::EV_CLEAR } else { 0 } |
if opts.contains(PollOpt::oneshot()) { libc::EV_ONESHOT } else { 0 } |
libc::EV_RECEIPT;
unsafe {
let r = if interests.contains(Ready::readable()) { libc::EV_ADD } else { libc::EV_DELETE };
let w = if interests.contains(Ready::writable()) { libc::EV_ADD } else { libc::EV_DELETE };
let mut changes = [
kevent!(fd, libc::EVFILT_READ, flags | r, usize::from(token)),
kevent!(fd, libc::EVFILT_WRITE, flags | w, usize::from(token)),
];
try!(cvt(libc::kevent(self.kq, changes.as_ptr(), changes.len() as c_int,
changes.as_mut_ptr(), changes.len() as c_int,
::std::ptr::null())));
for change in changes.iter() {
debug_assert_eq!(change.flags & libc::EV_ERROR, libc::EV_ERROR);
if change.data != 0 {
// there’s some error, but we want to ignore ENOENT error for EV_DELETE
let orig_flags = if change.filter == libc::EVFILT_READ { r } else { w };
if !(change.data as i32 == libc::ENOENT && orig_flags & libc::EV_DELETE != 0) {
return Err(::std::io::Error::from_raw_os_error(change.data as i32));
}
}
}
Ok(())
}
}
pub fn reregister(&self, fd: RawFd, token: Token, interests: Ready, opts: PollOpt) -> io::Result<()> {
// Just need to call register here since EV_ADD is a mod if already
// registered
self.register(fd, token, interests, opts)
}
pub fn deregister(&self, fd: RawFd) -> io::Result<()> {
unsafe {
// EV_RECEIPT is a nice way to apply changes and get back per-event results while not
// draining the actual changes.
let filter = libc::EV_DELETE | libc::EV_RECEIPT;
let mut changes = [
kevent!(fd, libc::EVFILT_READ, filter, ptr::null_mut()),
kevent!(fd, libc::EVFILT_WRITE, filter, ptr::null_mut()),
];
try!(cvt(libc::kevent(self.kq, changes.as_ptr(), changes.len() as c_int,
changes.as_mut_ptr(), changes.len() as c_int,
::std::ptr::null())).map(|_| ()));
if changes[0].data as i32 == libc::ENOENT && changes[1].data as i32 == libc::ENOENT {
return Err(::std::io::Error::from_raw_os_error(changes[0].data as i32));
}
for change in changes.iter() {
debug_assert_eq!(libc::EV_ERROR & change.flags, libc::EV_ERROR);
if change.data != 0 && change.data as i32 != libc::ENOENT {
return Err(::std::io::Error::from_raw_os_error(changes[0].data as i32));
}
}
Ok(())
}
}
}
impl fmt::Debug for Selector {
fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
fmt.debug_struct("Selector")
.field("id", &self.id)
.field("kq", &self.kq)
.finish()
}
}
impl Drop for Selector {
fn drop(&mut self) {
unsafe {
let _ = libc::close(self.kq);
}
}
}
pub struct Events {
sys_events: KeventList,
events: Vec<Event>,
event_map: HashMap<Token, usize>,
}
struct KeventList(Vec<libc::kevent>);
unsafe impl Send for KeventList {}
unsafe impl Sync for KeventList {}
impl Events {
pub fn wi | ap: usize) -> Events {
Events {
sys_events: KeventList(Vec::with_capacity(cap)),
events: Vec::with_capacity(cap),
event_map: HashMap::with_capacity(cap)
}
}
#[inline]
pub fn len(&self) -> usize {
self.events.len()
}
#[inline]
pub fn capacity(&self) -> usize {
self.events.capacity()
}
#[inline]
pub fn is_empty(&self) -> bool {
self.events.is_empty()
}
pub fn get(&self, idx: usize) -> Option<Event> {
self.events.get(idx).map(|e| *e)
}
fn coalesce(&mut self, awakener: Token) -> bool {
let mut ret = false;
self.events.clear();
self.event_map.clear();
for e in self.sys_events.0.iter() {
let token = Token(e.udata as usize);
let len = self.events.len();
if token == awakener {
// TODO: Should this return an error if event is an error. It
// is not critical as spurious wakeups are permitted.
ret = true;
continue;
}
let idx = *self.event_map.entry(token)
.or_insert(len);
if idx == len {
// New entry, insert the default
self.events.push(Event::new(Ready::none(), token));
}
if e.flags & libc::EV_ERROR != 0 {
event::kind_mut(&mut self.events[idx]).insert(Ready::error());
}
if e.filter == libc::EVFILT_READ {
event::kind_mut(&mut self.events[idx]).insert(Ready::readable());
} else if e.filter == libc::EVFILT_WRITE {
event::kind_mut(&mut self.events[idx]).insert(Ready::writable());
}
if e.flags & libc::EV_EOF != 0 {
event::kind_mut(&mut self.events[idx]).insert(Ready::hup());
// When the read end of the socket is closed, EV_EOF is set on
// flags, and fflags contains the error if there is one.
if e.fflags != 0 {
event::kind_mut(&mut self.events[idx]).insert(Ready::error());
}
}
}
ret
}
pub fn push_event(&mut self, event: Event) {
self.events.push(event);
}
}
impl fmt::Debug for Events {
fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
write!(fmt, "Events {{ len: {} }}", self.sys_events.0.len())
}
}
#[test]
fn does_not_register_rw() {
use ::deprecated::{EventLoopBuilder, Handler};
use ::unix::EventedFd;
struct Nop;
impl Handler for Nop {
type Timeout = ();
type Message = ();
}
// registering kqueue fd will fail if write is requested (On anything but some versions of OS
// X)
let kq = unsafe { libc::kqueue() };
let kqf = EventedFd(&kq);
let mut evtloop = EventLoopBuilder::new().build::<Nop>().expect("evt loop builds");
evtloop.register(&kqf, Token(1234), Ready::readable(),
PollOpt::edge() | PollOpt::oneshot()).unwrap();
}
| th_capacity(c | identifier_name |
kqueue.rs | use std::{cmp, fmt, ptr};
use std::os::raw::c_int;
use std::os::unix::io::RawFd;
use std::collections::HashMap;
use std::sync::atomic::{AtomicUsize, Ordering, ATOMIC_USIZE_INIT};
use std::time::Duration;
use libc::{self, time_t};
use {io, Ready, PollOpt, Token};
use event::{self, Event};
use sys::unix::cvt;
use sys::unix::io::set_cloexec;
/// Each Selector has a globally unique(ish) ID associated with it. This ID
/// gets tracked by `TcpStream`, `TcpListener`, etc... when they are first
/// registered with the `Selector`. If a type that is previously associated with
/// a `Selector` attempts to register itself with a different `Selector`, the
/// operation will return with an error. This matches windows behavior.
static NEXT_ID: AtomicUsize = ATOMIC_USIZE_INIT;
macro_rules! kevent {
($id: expr, $filter: expr, $flags: expr, $data: expr) => {
libc::kevent {
ident: $id as ::libc::uintptr_t,
filter: $filter,
flags: $flags,
fflags: 0,
data: 0,
udata: $data as *mut _,
}
}
}
pub struct Selector {
id: usize,
kq: RawFd,
}
impl Selector {
pub fn new() -> io::Result<Selector> {
// offset by 1 to avoid choosing 0 as the id of a selector
let id = NEXT_ID.fetch_add(1, Ordering::Relaxed) + 1;
let kq = unsafe { try!(cvt(libc::kqueue())) };
drop(set_cloexec(kq));
Ok(Selector {
id: id,
kq: kq,
})
}
pub fn id(&self) -> usize {
self.id
}
pub fn select(&self, evts: &mut Events, awakener: Token, timeout: Option<Duration>) -> io::Result<bool> {
let timeout = timeout.map(|to| {
libc::timespec {
tv_sec: cmp::min(to.as_secs(), time_t::max_value() as u64) as time_t,
tv_nsec: to.subsec_nanos() as libc::c_long,
}
});
let timeout = timeout.as_ref().map(|s| s as *const _).unwrap_or(ptr::null_mut());
unsafe {
let cnt = try!(cvt(libc::kevent(self.kq,
ptr::null(),
0,
evts.sys_events.0.as_mut_ptr(),
// FIXME: needs a saturating cast here.
evts.sys_events.0.capacity() as c_int,
timeout)));
evts.sys_events.0.set_len(cnt as usize);
Ok(evts.coalesce(awakener))
}
}
pub fn register(&self, fd: RawFd, token: Token, interests: Ready, opts: PollOpt) -> io::Result<()> {
trace!("registering; token={:?}; interests={:?}", token, interests);
let flags = if opts.contains(PollOpt::edge()) { libc::EV_CLEAR } else { 0 } |
if opts.contains(PollOpt::oneshot()) { libc::EV_ONESHOT } else { 0 } |
libc::EV_RECEIPT;
unsafe {
let r = if interests.contains(Ready::readable()) { libc::EV_ADD } else { libc::EV_DELETE };
let w = if interests.contains(Ready::writable()) { libc::EV_ADD } else { libc::EV_DELETE };
let mut changes = [ | ::std::ptr::null())));
for change in changes.iter() {
debug_assert_eq!(change.flags & libc::EV_ERROR, libc::EV_ERROR);
if change.data != 0 {
// there’s some error, but we want to ignore ENOENT error for EV_DELETE
let orig_flags = if change.filter == libc::EVFILT_READ { r } else { w };
if !(change.data as i32 == libc::ENOENT && orig_flags & libc::EV_DELETE != 0) {
return Err(::std::io::Error::from_raw_os_error(change.data as i32));
}
}
}
Ok(())
}
}
pub fn reregister(&self, fd: RawFd, token: Token, interests: Ready, opts: PollOpt) -> io::Result<()> {
// Just need to call register here since EV_ADD is a mod if already
// registered
self.register(fd, token, interests, opts)
}
pub fn deregister(&self, fd: RawFd) -> io::Result<()> {
unsafe {
// EV_RECEIPT is a nice way to apply changes and get back per-event results while not
// draining the actual changes.
let filter = libc::EV_DELETE | libc::EV_RECEIPT;
let mut changes = [
kevent!(fd, libc::EVFILT_READ, filter, ptr::null_mut()),
kevent!(fd, libc::EVFILT_WRITE, filter, ptr::null_mut()),
];
try!(cvt(libc::kevent(self.kq, changes.as_ptr(), changes.len() as c_int,
changes.as_mut_ptr(), changes.len() as c_int,
::std::ptr::null())).map(|_| ()));
if changes[0].data as i32 == libc::ENOENT && changes[1].data as i32 == libc::ENOENT {
return Err(::std::io::Error::from_raw_os_error(changes[0].data as i32));
}
for change in changes.iter() {
debug_assert_eq!(libc::EV_ERROR & change.flags, libc::EV_ERROR);
if change.data != 0 && change.data as i32 != libc::ENOENT {
return Err(::std::io::Error::from_raw_os_error(changes[0].data as i32));
}
}
Ok(())
}
}
}
impl fmt::Debug for Selector {
fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
fmt.debug_struct("Selector")
.field("id", &self.id)
.field("kq", &self.kq)
.finish()
}
}
impl Drop for Selector {
fn drop(&mut self) {
unsafe {
let _ = libc::close(self.kq);
}
}
}
pub struct Events {
sys_events: KeventList,
events: Vec<Event>,
event_map: HashMap<Token, usize>,
}
struct KeventList(Vec<libc::kevent>);
unsafe impl Send for KeventList {}
unsafe impl Sync for KeventList {}
impl Events {
pub fn with_capacity(cap: usize) -> Events {
Events {
sys_events: KeventList(Vec::with_capacity(cap)),
events: Vec::with_capacity(cap),
event_map: HashMap::with_capacity(cap)
}
}
#[inline]
pub fn len(&self) -> usize {
self.events.len()
}
#[inline]
pub fn capacity(&self) -> usize {
self.events.capacity()
}
#[inline]
pub fn is_empty(&self) -> bool {
self.events.is_empty()
}
pub fn get(&self, idx: usize) -> Option<Event> {
self.events.get(idx).map(|e| *e)
}
fn coalesce(&mut self, awakener: Token) -> bool {
let mut ret = false;
self.events.clear();
self.event_map.clear();
for e in self.sys_events.0.iter() {
let token = Token(e.udata as usize);
let len = self.events.len();
if token == awakener {
// TODO: Should this return an error if event is an error. It
// is not critical as spurious wakeups are permitted.
ret = true;
continue;
}
let idx = *self.event_map.entry(token)
.or_insert(len);
if idx == len {
// New entry, insert the default
self.events.push(Event::new(Ready::none(), token));
}
if e.flags & libc::EV_ERROR != 0 {
event::kind_mut(&mut self.events[idx]).insert(Ready::error());
}
if e.filter == libc::EVFILT_READ {
event::kind_mut(&mut self.events[idx]).insert(Ready::readable());
} else if e.filter == libc::EVFILT_WRITE {
event::kind_mut(&mut self.events[idx]).insert(Ready::writable());
}
if e.flags & libc::EV_EOF != 0 {
event::kind_mut(&mut self.events[idx]).insert(Ready::hup());
// When the read end of the socket is closed, EV_EOF is set on
// flags, and fflags contains the error if there is one.
if e.fflags != 0 {
event::kind_mut(&mut self.events[idx]).insert(Ready::error());
}
}
}
ret
}
pub fn push_event(&mut self, event: Event) {
self.events.push(event);
}
}
impl fmt::Debug for Events {
fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
write!(fmt, "Events {{ len: {} }}", self.sys_events.0.len())
}
}
#[test]
fn does_not_register_rw() {
use ::deprecated::{EventLoopBuilder, Handler};
use ::unix::EventedFd;
struct Nop;
impl Handler for Nop {
type Timeout = ();
type Message = ();
}
// registering kqueue fd will fail if write is requested (On anything but some versions of OS
// X)
let kq = unsafe { libc::kqueue() };
let kqf = EventedFd(&kq);
let mut evtloop = EventLoopBuilder::new().build::<Nop>().expect("evt loop builds");
evtloop.register(&kqf, Token(1234), Ready::readable(),
PollOpt::edge() | PollOpt::oneshot()).unwrap();
} | kevent!(fd, libc::EVFILT_READ, flags | r, usize::from(token)),
kevent!(fd, libc::EVFILT_WRITE, flags | w, usize::from(token)),
];
try!(cvt(libc::kevent(self.kq, changes.as_ptr(), changes.len() as c_int,
changes.as_mut_ptr(), changes.len() as c_int, | random_line_split |
feature-flag.directive.ts | import { Directive, TemplateRef, ViewContainerRef, Input } from '@angular/core';
import { FeatureFlagService } from '../services/feature-flag.service';
@Directive({
selector: '[ngFeatureFlag]'
})
export class FeatureFlagDirective {
@Input() ngFeatureFlagHidden = false;
@Input() ngFeatureFlagDefaultTo = false;
@Input() set | (featureFlag: string) {
if (featureFlag === undefined) {
console.error('Feature flag name required!');
return;
}
this.darkLumos.isEnabled(featureFlag)
.subscribe(status => {
if ((status && !this.ngFeatureFlagHidden) ||
(!status && this.ngFeatureFlagHidden)) {
this.viewContainer.createEmbeddedView(this.templateRef);
} else {
this.viewContainer.clear();
}
});
}
constructor(
private templateRef: TemplateRef<any>,
private viewContainer: ViewContainerRef,
private darkLumos: FeatureFlagService
) { }
}
| ngFeatureFlag | identifier_name |
feature-flag.directive.ts | import { Directive, TemplateRef, ViewContainerRef, Input } from '@angular/core';
import { FeatureFlagService } from '../services/feature-flag.service';
@Directive({
selector: '[ngFeatureFlag]'
})
export class FeatureFlagDirective {
@Input() ngFeatureFlagHidden = false;
@Input() ngFeatureFlagDefaultTo = false;
@Input() set ngFeatureFlag(featureFlag: string) {
if (featureFlag === undefined) |
this.darkLumos.isEnabled(featureFlag)
.subscribe(status => {
if ((status && !this.ngFeatureFlagHidden) ||
(!status && this.ngFeatureFlagHidden)) {
this.viewContainer.createEmbeddedView(this.templateRef);
} else {
this.viewContainer.clear();
}
});
}
constructor(
private templateRef: TemplateRef<any>,
private viewContainer: ViewContainerRef,
private darkLumos: FeatureFlagService
) { }
}
| {
console.error('Feature flag name required!');
return;
} | conditional_block |
feature-flag.directive.ts | import { Directive, TemplateRef, ViewContainerRef, Input } from '@angular/core';
import { FeatureFlagService } from '../services/feature-flag.service';
@Directive({
selector: '[ngFeatureFlag]'
}) | @Input() set ngFeatureFlag(featureFlag: string) {
if (featureFlag === undefined) {
console.error('Feature flag name required!');
return;
}
this.darkLumos.isEnabled(featureFlag)
.subscribe(status => {
if ((status && !this.ngFeatureFlagHidden) ||
(!status && this.ngFeatureFlagHidden)) {
this.viewContainer.createEmbeddedView(this.templateRef);
} else {
this.viewContainer.clear();
}
});
}
constructor(
private templateRef: TemplateRef<any>,
private viewContainer: ViewContainerRef,
private darkLumos: FeatureFlagService
) { }
} | export class FeatureFlagDirective {
@Input() ngFeatureFlagHidden = false;
@Input() ngFeatureFlagDefaultTo = false;
| random_line_split |
feature-flag.directive.ts | import { Directive, TemplateRef, ViewContainerRef, Input } from '@angular/core';
import { FeatureFlagService } from '../services/feature-flag.service';
@Directive({
selector: '[ngFeatureFlag]'
})
export class FeatureFlagDirective {
@Input() ngFeatureFlagHidden = false;
@Input() ngFeatureFlagDefaultTo = false;
@Input() set ngFeatureFlag(featureFlag: string) {
if (featureFlag === undefined) {
console.error('Feature flag name required!');
return;
}
this.darkLumos.isEnabled(featureFlag)
.subscribe(status => {
if ((status && !this.ngFeatureFlagHidden) ||
(!status && this.ngFeatureFlagHidden)) {
this.viewContainer.createEmbeddedView(this.templateRef);
} else {
this.viewContainer.clear();
}
});
}
constructor(
private templateRef: TemplateRef<any>,
private viewContainer: ViewContainerRef,
private darkLumos: FeatureFlagService
) |
}
| { } | identifier_body |
common.spec.ts | /*
* The MIT License
*
* Copyright 2019 Azarias Boutin.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
import { expect } from 'chai';
import 'mocha';
import * as chrome from 'sinon-chrome';
global['chrome'] = chrome;
import { join, is10fastFingersUrl, parseJsArray } from '../../src/common';
describe('Common methods', () => {
it('Should join elements togeter', () => {
const simpleJoin = join('a', 'b');
expect(simpleJoin).to.equal('a/b');
const moreJoins = join('x', 'mostElement', '', 'j');
expect(moreJoins).to.equal('x/mostElement//j'); | it('Should be able to detect a valid 10fastfingers url', () => {
const validUrl = 'https://10fastfingers.com';
const valids = [ validUrl, validUrl + '/randomStuff', validUrl + '/' ];
const invalids = [ `a${validUrl}`, `${validUrl}c`, `http://google.fr`, 'http://10fastfingers.com' ];
valids.forEach((v) => expect(is10fastFingersUrl(v), `Valid url : ${v}`).to.be.true);
invalids.forEach((iv) => expect(is10fastFingersUrl(iv), `Invalid url ${iv}`).to.be.false);
});
it('Should correctly parse a js array', () => {
const testValues = [
'[]',
'["1"]',
'["2"]',
'["1", "123", "2", "3"]',
'["23", "45", "1", "1"]',
'["384443","384417"]',
"['384443', '384417', '384417', '384417', '384417']"
];
testValues.forEach((v) => {
const values = eval(v).map((x: string) => +x);
expect(parseJsArray(v)).to.deep.equal(values);
});
});
}); | });
| random_line_split |
sample.py | import json
from typing import NamedTuple
from collections import namedtuple
import kfp
import kfp.dsl as dsl
from kfp import components
from kfp.dsl.types import Integer
def get_current_namespace():
"""Returns current namespace if available, else kubeflow"""
try:
current_namespace = open(
"/var/run/secrets/kubernetes.io/serviceaccount/namespace"
).read()
except:
current_namespace = "kubeflow"
return current_namespace
def create_worker_spec(
worker_num: int = 0
) -> NamedTuple(
"CreatWorkerSpec", [("worker_spec", dict)]
):
"""
Creates pytorch-job worker spec
"""
worker = {}
if worker_num > 0:
worker = {
"replicas": worker_num,
"restartPolicy": "OnFailure",
"template": {
"metadata": {
"annotations": {
"sidecar.istio.io/inject": "false"
}
},
"spec": {
"containers": [
{
"args": [
"--backend",
"gloo",
],
"image": "public.ecr.aws/pytorch-samples/pytorch_dist_mnist:latest",
"name": "pytorch",
"resources": {
"requests": {
"memory": "4Gi",
"cpu": "2000m",
# Uncomment for GPU
# "nvidia.com/gpu": 1,
},
"limits": {
"memory": "4Gi",
"cpu": "2000m",
# Uncomment for GPU
# "nvidia.com/gpu": 1,
},
},
}
]
},
},
}
worker_spec_output = namedtuple(
"MyWorkerOutput", ["worker_spec"]
)
return worker_spec_output(worker)
worker_spec_op = components.func_to_container_op(
create_worker_spec,
base_image="python:slim",
)
@dsl.pipeline(
name="launch-kubeflow-pytorchjob",
description="An example to launch pytorch.",
)
def mnist_train(
namespace: str = get_current_namespace(),
worker_replicas: int = 1,
ttl_seconds_after_finished: int = -1,
job_timeout_minutes: int = 600,
delete_after_done: bool = False, | master = {
"replicas": 1,
"restartPolicy": "OnFailure",
"template": {
"metadata": {
"annotations": {
# See https://github.com/kubeflow/website/issues/2011
"sidecar.istio.io/inject": "false"
}
},
"spec": {
"containers": [
{
# To override default command
# "command": [
# "python",
# "/opt/mnist/src/mnist.py"
# ],
"args": [
"--backend",
"gloo",
],
# Or, create your own image from
# https://github.com/kubeflow/pytorch-operator/tree/master/examples/mnist
"image": "public.ecr.aws/pytorch-samples/pytorch_dist_mnist:latest",
"name": "pytorch",
"resources": {
"requests": {
"memory": "4Gi",
"cpu": "2000m",
# Uncomment for GPU
# "nvidia.com/gpu": 1,
},
"limits": {
"memory": "4Gi",
"cpu": "2000m",
# Uncomment for GPU
# "nvidia.com/gpu": 1,
},
},
}
],
# If imagePullSecrets required
# "imagePullSecrets": [
# {"name": "image-pull-secret"},
# ],
},
},
}
worker_spec_create = worker_spec_op(
worker_replicas
)
# Launch and monitor the job with the launcher
pytorchjob_launcher_op(
# Note: name needs to be a unique pytorchjob name in the namespace.
# Using RUN_ID_PLACEHOLDER is one way of getting something unique.
name=f"name-{kfp.dsl.RUN_ID_PLACEHOLDER}",
namespace=namespace,
master_spec=master,
# pass worker_spec as a string because the JSON serializer will convert
# the placeholder for worker_replicas (which it sees as a string) into
# a quoted variable (eg a string) instead of an unquoted variable
# (number). If worker_replicas is quoted in the spec, it will break in
# k8s. See https://github.com/kubeflow/pipelines/issues/4776
worker_spec=worker_spec_create.outputs[
"worker_spec"
],
ttl_seconds_after_finished=ttl_seconds_after_finished,
job_timeout_minutes=job_timeout_minutes,
delete_after_done=delete_after_done,
)
if __name__ == "__main__":
import kfp.compiler as compiler
pipeline_file = "test.tar.gz"
print(
f"Compiling pipeline as {pipeline_file}"
)
compiler.Compiler().compile(
mnist_train, pipeline_file
)
# # To run:
# client = kfp.Client()
# run = client.create_run_from_pipeline_package(
# pipeline_file,
# arguments={},
# run_name="test pytorchjob run"
# )
# print(f"Created run {run}") | ):
pytorchjob_launcher_op = components.load_component_from_file(
"./component.yaml"
)
| random_line_split |
sample.py | import json
from typing import NamedTuple
from collections import namedtuple
import kfp
import kfp.dsl as dsl
from kfp import components
from kfp.dsl.types import Integer
def get_current_namespace():
|
def create_worker_spec(
worker_num: int = 0
) -> NamedTuple(
"CreatWorkerSpec", [("worker_spec", dict)]
):
"""
Creates pytorch-job worker spec
"""
worker = {}
if worker_num > 0:
worker = {
"replicas": worker_num,
"restartPolicy": "OnFailure",
"template": {
"metadata": {
"annotations": {
"sidecar.istio.io/inject": "false"
}
},
"spec": {
"containers": [
{
"args": [
"--backend",
"gloo",
],
"image": "public.ecr.aws/pytorch-samples/pytorch_dist_mnist:latest",
"name": "pytorch",
"resources": {
"requests": {
"memory": "4Gi",
"cpu": "2000m",
# Uncomment for GPU
# "nvidia.com/gpu": 1,
},
"limits": {
"memory": "4Gi",
"cpu": "2000m",
# Uncomment for GPU
# "nvidia.com/gpu": 1,
},
},
}
]
},
},
}
worker_spec_output = namedtuple(
"MyWorkerOutput", ["worker_spec"]
)
return worker_spec_output(worker)
worker_spec_op = components.func_to_container_op(
create_worker_spec,
base_image="python:slim",
)
@dsl.pipeline(
name="launch-kubeflow-pytorchjob",
description="An example to launch pytorch.",
)
def mnist_train(
namespace: str = get_current_namespace(),
worker_replicas: int = 1,
ttl_seconds_after_finished: int = -1,
job_timeout_minutes: int = 600,
delete_after_done: bool = False,
):
pytorchjob_launcher_op = components.load_component_from_file(
"./component.yaml"
)
master = {
"replicas": 1,
"restartPolicy": "OnFailure",
"template": {
"metadata": {
"annotations": {
# See https://github.com/kubeflow/website/issues/2011
"sidecar.istio.io/inject": "false"
}
},
"spec": {
"containers": [
{
# To override default command
# "command": [
# "python",
# "/opt/mnist/src/mnist.py"
# ],
"args": [
"--backend",
"gloo",
],
# Or, create your own image from
# https://github.com/kubeflow/pytorch-operator/tree/master/examples/mnist
"image": "public.ecr.aws/pytorch-samples/pytorch_dist_mnist:latest",
"name": "pytorch",
"resources": {
"requests": {
"memory": "4Gi",
"cpu": "2000m",
# Uncomment for GPU
# "nvidia.com/gpu": 1,
},
"limits": {
"memory": "4Gi",
"cpu": "2000m",
# Uncomment for GPU
# "nvidia.com/gpu": 1,
},
},
}
],
# If imagePullSecrets required
# "imagePullSecrets": [
# {"name": "image-pull-secret"},
# ],
},
},
}
worker_spec_create = worker_spec_op(
worker_replicas
)
# Launch and monitor the job with the launcher
pytorchjob_launcher_op(
# Note: name needs to be a unique pytorchjob name in the namespace.
# Using RUN_ID_PLACEHOLDER is one way of getting something unique.
name=f"name-{kfp.dsl.RUN_ID_PLACEHOLDER}",
namespace=namespace,
master_spec=master,
# pass worker_spec as a string because the JSON serializer will convert
# the placeholder for worker_replicas (which it sees as a string) into
# a quoted variable (eg a string) instead of an unquoted variable
# (number). If worker_replicas is quoted in the spec, it will break in
# k8s. See https://github.com/kubeflow/pipelines/issues/4776
worker_spec=worker_spec_create.outputs[
"worker_spec"
],
ttl_seconds_after_finished=ttl_seconds_after_finished,
job_timeout_minutes=job_timeout_minutes,
delete_after_done=delete_after_done,
)
if __name__ == "__main__":
import kfp.compiler as compiler
pipeline_file = "test.tar.gz"
print(
f"Compiling pipeline as {pipeline_file}"
)
compiler.Compiler().compile(
mnist_train, pipeline_file
)
# # To run:
# client = kfp.Client()
# run = client.create_run_from_pipeline_package(
# pipeline_file,
# arguments={},
# run_name="test pytorchjob run"
# )
# print(f"Created run {run}")
| """Returns current namespace if available, else kubeflow"""
try:
current_namespace = open(
"/var/run/secrets/kubernetes.io/serviceaccount/namespace"
).read()
except:
current_namespace = "kubeflow"
return current_namespace | identifier_body |
sample.py | import json
from typing import NamedTuple
from collections import namedtuple
import kfp
import kfp.dsl as dsl
from kfp import components
from kfp.dsl.types import Integer
def | ():
"""Returns current namespace if available, else kubeflow"""
try:
current_namespace = open(
"/var/run/secrets/kubernetes.io/serviceaccount/namespace"
).read()
except:
current_namespace = "kubeflow"
return current_namespace
def create_worker_spec(
worker_num: int = 0
) -> NamedTuple(
"CreatWorkerSpec", [("worker_spec", dict)]
):
"""
Creates pytorch-job worker spec
"""
worker = {}
if worker_num > 0:
worker = {
"replicas": worker_num,
"restartPolicy": "OnFailure",
"template": {
"metadata": {
"annotations": {
"sidecar.istio.io/inject": "false"
}
},
"spec": {
"containers": [
{
"args": [
"--backend",
"gloo",
],
"image": "public.ecr.aws/pytorch-samples/pytorch_dist_mnist:latest",
"name": "pytorch",
"resources": {
"requests": {
"memory": "4Gi",
"cpu": "2000m",
# Uncomment for GPU
# "nvidia.com/gpu": 1,
},
"limits": {
"memory": "4Gi",
"cpu": "2000m",
# Uncomment for GPU
# "nvidia.com/gpu": 1,
},
},
}
]
},
},
}
worker_spec_output = namedtuple(
"MyWorkerOutput", ["worker_spec"]
)
return worker_spec_output(worker)
worker_spec_op = components.func_to_container_op(
create_worker_spec,
base_image="python:slim",
)
@dsl.pipeline(
name="launch-kubeflow-pytorchjob",
description="An example to launch pytorch.",
)
def mnist_train(
namespace: str = get_current_namespace(),
worker_replicas: int = 1,
ttl_seconds_after_finished: int = -1,
job_timeout_minutes: int = 600,
delete_after_done: bool = False,
):
pytorchjob_launcher_op = components.load_component_from_file(
"./component.yaml"
)
master = {
"replicas": 1,
"restartPolicy": "OnFailure",
"template": {
"metadata": {
"annotations": {
# See https://github.com/kubeflow/website/issues/2011
"sidecar.istio.io/inject": "false"
}
},
"spec": {
"containers": [
{
# To override default command
# "command": [
# "python",
# "/opt/mnist/src/mnist.py"
# ],
"args": [
"--backend",
"gloo",
],
# Or, create your own image from
# https://github.com/kubeflow/pytorch-operator/tree/master/examples/mnist
"image": "public.ecr.aws/pytorch-samples/pytorch_dist_mnist:latest",
"name": "pytorch",
"resources": {
"requests": {
"memory": "4Gi",
"cpu": "2000m",
# Uncomment for GPU
# "nvidia.com/gpu": 1,
},
"limits": {
"memory": "4Gi",
"cpu": "2000m",
# Uncomment for GPU
# "nvidia.com/gpu": 1,
},
},
}
],
# If imagePullSecrets required
# "imagePullSecrets": [
# {"name": "image-pull-secret"},
# ],
},
},
}
worker_spec_create = worker_spec_op(
worker_replicas
)
# Launch and monitor the job with the launcher
pytorchjob_launcher_op(
# Note: name needs to be a unique pytorchjob name in the namespace.
# Using RUN_ID_PLACEHOLDER is one way of getting something unique.
name=f"name-{kfp.dsl.RUN_ID_PLACEHOLDER}",
namespace=namespace,
master_spec=master,
# pass worker_spec as a string because the JSON serializer will convert
# the placeholder for worker_replicas (which it sees as a string) into
# a quoted variable (eg a string) instead of an unquoted variable
# (number). If worker_replicas is quoted in the spec, it will break in
# k8s. See https://github.com/kubeflow/pipelines/issues/4776
worker_spec=worker_spec_create.outputs[
"worker_spec"
],
ttl_seconds_after_finished=ttl_seconds_after_finished,
job_timeout_minutes=job_timeout_minutes,
delete_after_done=delete_after_done,
)
if __name__ == "__main__":
import kfp.compiler as compiler
pipeline_file = "test.tar.gz"
print(
f"Compiling pipeline as {pipeline_file}"
)
compiler.Compiler().compile(
mnist_train, pipeline_file
)
# # To run:
# client = kfp.Client()
# run = client.create_run_from_pipeline_package(
# pipeline_file,
# arguments={},
# run_name="test pytorchjob run"
# )
# print(f"Created run {run}")
| get_current_namespace | identifier_name |
sample.py | import json
from typing import NamedTuple
from collections import namedtuple
import kfp
import kfp.dsl as dsl
from kfp import components
from kfp.dsl.types import Integer
def get_current_namespace():
"""Returns current namespace if available, else kubeflow"""
try:
current_namespace = open(
"/var/run/secrets/kubernetes.io/serviceaccount/namespace"
).read()
except:
current_namespace = "kubeflow"
return current_namespace
def create_worker_spec(
worker_num: int = 0
) -> NamedTuple(
"CreatWorkerSpec", [("worker_spec", dict)]
):
"""
Creates pytorch-job worker spec
"""
worker = {}
if worker_num > 0:
worker = {
"replicas": worker_num,
"restartPolicy": "OnFailure",
"template": {
"metadata": {
"annotations": {
"sidecar.istio.io/inject": "false"
}
},
"spec": {
"containers": [
{
"args": [
"--backend",
"gloo",
],
"image": "public.ecr.aws/pytorch-samples/pytorch_dist_mnist:latest",
"name": "pytorch",
"resources": {
"requests": {
"memory": "4Gi",
"cpu": "2000m",
# Uncomment for GPU
# "nvidia.com/gpu": 1,
},
"limits": {
"memory": "4Gi",
"cpu": "2000m",
# Uncomment for GPU
# "nvidia.com/gpu": 1,
},
},
}
]
},
},
}
worker_spec_output = namedtuple(
"MyWorkerOutput", ["worker_spec"]
)
return worker_spec_output(worker)
worker_spec_op = components.func_to_container_op(
create_worker_spec,
base_image="python:slim",
)
@dsl.pipeline(
name="launch-kubeflow-pytorchjob",
description="An example to launch pytorch.",
)
def mnist_train(
namespace: str = get_current_namespace(),
worker_replicas: int = 1,
ttl_seconds_after_finished: int = -1,
job_timeout_minutes: int = 600,
delete_after_done: bool = False,
):
pytorchjob_launcher_op = components.load_component_from_file(
"./component.yaml"
)
master = {
"replicas": 1,
"restartPolicy": "OnFailure",
"template": {
"metadata": {
"annotations": {
# See https://github.com/kubeflow/website/issues/2011
"sidecar.istio.io/inject": "false"
}
},
"spec": {
"containers": [
{
# To override default command
# "command": [
# "python",
# "/opt/mnist/src/mnist.py"
# ],
"args": [
"--backend",
"gloo",
],
# Or, create your own image from
# https://github.com/kubeflow/pytorch-operator/tree/master/examples/mnist
"image": "public.ecr.aws/pytorch-samples/pytorch_dist_mnist:latest",
"name": "pytorch",
"resources": {
"requests": {
"memory": "4Gi",
"cpu": "2000m",
# Uncomment for GPU
# "nvidia.com/gpu": 1,
},
"limits": {
"memory": "4Gi",
"cpu": "2000m",
# Uncomment for GPU
# "nvidia.com/gpu": 1,
},
},
}
],
# If imagePullSecrets required
# "imagePullSecrets": [
# {"name": "image-pull-secret"},
# ],
},
},
}
worker_spec_create = worker_spec_op(
worker_replicas
)
# Launch and monitor the job with the launcher
pytorchjob_launcher_op(
# Note: name needs to be a unique pytorchjob name in the namespace.
# Using RUN_ID_PLACEHOLDER is one way of getting something unique.
name=f"name-{kfp.dsl.RUN_ID_PLACEHOLDER}",
namespace=namespace,
master_spec=master,
# pass worker_spec as a string because the JSON serializer will convert
# the placeholder for worker_replicas (which it sees as a string) into
# a quoted variable (eg a string) instead of an unquoted variable
# (number). If worker_replicas is quoted in the spec, it will break in
# k8s. See https://github.com/kubeflow/pipelines/issues/4776
worker_spec=worker_spec_create.outputs[
"worker_spec"
],
ttl_seconds_after_finished=ttl_seconds_after_finished,
job_timeout_minutes=job_timeout_minutes,
delete_after_done=delete_after_done,
)
if __name__ == "__main__":
|
# # To run:
# client = kfp.Client()
# run = client.create_run_from_pipeline_package(
# pipeline_file,
# arguments={},
# run_name="test pytorchjob run"
# )
# print(f"Created run {run}")
| import kfp.compiler as compiler
pipeline_file = "test.tar.gz"
print(
f"Compiling pipeline as {pipeline_file}"
)
compiler.Compiler().compile(
mnist_train, pipeline_file
) | conditional_block |
urls.py | urlpatterns = patterns('',
url(r'^$', index),
url(r'^joblist$',
JobListView.as_view()),
url(r'^job/(?P<pk>\d+)/$',
DetailView.as_view(
model=Job,
# template_name='tacc_stats/detail.html',
)),
url(r'^job_memused_hist$', job_memused_hist ),
url(r'^job_timespent_hist$', job_timespent_hist ),
url(r'^job_mem_heatmap/(\d+)/$', create_heatmap, {'trait' : 'memory'}),
url(r'^job_files_opened_heatmap/(\d+)/$', create_heatmap, {'trait' : 'files'}),
url(r'^job_flops_heatmap/(\d+)/$', create_heatmap, {'trait' : 'flops'}),
url(r'^search/$', search ),
url(r'^render/jobs/$', render_json),
url(r'^(\w+)/(\d+)/$', get_job ),
url(r'^data/$', data ),
url(r'^hosts/$', list_hosts ),
) | from django.conf.urls.defaults import patterns, url
from django.views.generic import DetailView, ListView
from tacc_stats.models import Job
from tacc_stats.views import index, job_memused_hist, job_timespent_hist, create_heatmap, search, JobListView, render_json, get_job, data, list_hosts
| random_line_split | |
about_tuples.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
from runner.koan import *
class AboutTuples(Koan):
def test_creating_a_tuple(self):
count_of_three = (1, 2, 5)
self.assertEqual(5, count_of_three[2])
def test_tuples_are_immutable_so_item_assignment_is_not_possible(self):
count_of_three = (1, 2, 5)
try:
count_of_three[2] = "three"
except TypeError as ex:
self.assertMatch("'tuple' object does not support item assignment", ex[0])
def test_tuples_are_immutable_so_appending_is_not_possible(self):
count_of_three = (1, 2, 5)
try:
count_of_three.append("boom") | self.assertEqual(AttributeError, type(ex))
# Note, assertMatch() uses regular expression pattern matching,
# so you don't have to copy the whole message.
self.assertMatch("'tuple' object has no attribute 'append'", ex[0])
# Tuples are less flexible than lists, but faster.
def test_tuples_can_only_be_changed_through_replacement(self):
count_of_three = (1, 2, 5)
list_count = list(count_of_three)
list_count.append("boom")
count_of_three = tuple(list_count)
self.assertEqual((1, 2, 5, 'boom'), count_of_three)
def test_tuples_of_one_look_peculiar(self):
self.assertEqual(int, (1).__class__)
self.assertEqual(tuple, (1,).__class__)
self.assertEqual(("Hello comma!", ), ("Hello comma!", ))
def test_tuple_constructor_can_be_surprising(self):
self.assertEqual(('S', 'u', 'r', 'p', 'r', 'i', 's', 'e', '!'), tuple("Surprise!"))
def test_creating_empty_tuples(self):
self.assertEqual((), ())
self.assertEqual((), tuple()) # Sometimes less confusing
def test_tuples_can_be_embedded(self):
lat = (37, 14, 6, 'N')
lon = (115, 48, 40, 'W')
place = ('Area 51', lat, lon)
self.assertEqual(('Area 51', (37, 14, 6, 'N'), (115, 48, 40, 'W')), place)
def test_tuples_are_good_for_representing_records(self):
locations = [
("Illuminati HQ", (38, 52, 15.56, 'N'), (77, 3, 21.46, 'W')),
("Stargate B", (41, 10, 43.92, 'N'), (1, 49, 34.29, 'W')),
]
locations.append(
("Cthulhu", (26, 40, 1, 'N'), (70, 45, 7, 'W'))
)
self.assertEqual("Cthulhu", locations[2][0])
self.assertEqual(15.56, locations[0][1][2]) | except Exception as ex: | random_line_split |
about_tuples.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
from runner.koan import *
class AboutTuples(Koan):
| def test_creating_a_tuple(self):
count_of_three = (1, 2, 5)
self.assertEqual(5, count_of_three[2])
def test_tuples_are_immutable_so_item_assignment_is_not_possible(self):
count_of_three = (1, 2, 5)
try:
count_of_three[2] = "three"
except TypeError as ex:
self.assertMatch("'tuple' object does not support item assignment", ex[0])
def test_tuples_are_immutable_so_appending_is_not_possible(self):
count_of_three = (1, 2, 5)
try:
count_of_three.append("boom")
except Exception as ex:
self.assertEqual(AttributeError, type(ex))
# Note, assertMatch() uses regular expression pattern matching,
# so you don't have to copy the whole message.
self.assertMatch("'tuple' object has no attribute 'append'", ex[0])
# Tuples are less flexible than lists, but faster.
def test_tuples_can_only_be_changed_through_replacement(self):
count_of_three = (1, 2, 5)
list_count = list(count_of_three)
list_count.append("boom")
count_of_three = tuple(list_count)
self.assertEqual((1, 2, 5, 'boom'), count_of_three)
def test_tuples_of_one_look_peculiar(self):
self.assertEqual(int, (1).__class__)
self.assertEqual(tuple, (1,).__class__)
self.assertEqual(("Hello comma!", ), ("Hello comma!", ))
def test_tuple_constructor_can_be_surprising(self):
self.assertEqual(('S', 'u', 'r', 'p', 'r', 'i', 's', 'e', '!'), tuple("Surprise!"))
def test_creating_empty_tuples(self):
self.assertEqual((), ())
self.assertEqual((), tuple()) # Sometimes less confusing
def test_tuples_can_be_embedded(self):
lat = (37, 14, 6, 'N')
lon = (115, 48, 40, 'W')
place = ('Area 51', lat, lon)
self.assertEqual(('Area 51', (37, 14, 6, 'N'), (115, 48, 40, 'W')), place)
def test_tuples_are_good_for_representing_records(self):
locations = [
("Illuminati HQ", (38, 52, 15.56, 'N'), (77, 3, 21.46, 'W')),
("Stargate B", (41, 10, 43.92, 'N'), (1, 49, 34.29, 'W')),
]
locations.append(
("Cthulhu", (26, 40, 1, 'N'), (70, 45, 7, 'W'))
)
self.assertEqual("Cthulhu", locations[2][0])
self.assertEqual(15.56, locations[0][1][2]) | identifier_body | |
about_tuples.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
from runner.koan import *
class AboutTuples(Koan):
def test_creating_a_tuple(self):
count_of_three = (1, 2, 5)
self.assertEqual(5, count_of_three[2])
def test_tuples_are_immutable_so_item_assignment_is_not_possible(self):
count_of_three = (1, 2, 5)
try:
count_of_three[2] = "three"
except TypeError as ex:
self.assertMatch("'tuple' object does not support item assignment", ex[0])
def test_tuples_are_immutable_so_appending_is_not_possible(self):
count_of_three = (1, 2, 5)
try:
count_of_three.append("boom")
except Exception as ex:
self.assertEqual(AttributeError, type(ex))
# Note, assertMatch() uses regular expression pattern matching,
# so you don't have to copy the whole message.
self.assertMatch("'tuple' object has no attribute 'append'", ex[0])
# Tuples are less flexible than lists, but faster.
def test_tuples_can_only_be_changed_through_replacement(self):
count_of_three = (1, 2, 5)
list_count = list(count_of_three)
list_count.append("boom")
count_of_three = tuple(list_count)
self.assertEqual((1, 2, 5, 'boom'), count_of_three)
def test_tuples_of_one_look_peculiar(self):
self.assertEqual(int, (1).__class__)
self.assertEqual(tuple, (1,).__class__)
self.assertEqual(("Hello comma!", ), ("Hello comma!", ))
def test_tuple_constructor_can_be_surprising(self):
self.assertEqual(('S', 'u', 'r', 'p', 'r', 'i', 's', 'e', '!'), tuple("Surprise!"))
def | (self):
self.assertEqual((), ())
self.assertEqual((), tuple()) # Sometimes less confusing
def test_tuples_can_be_embedded(self):
lat = (37, 14, 6, 'N')
lon = (115, 48, 40, 'W')
place = ('Area 51', lat, lon)
self.assertEqual(('Area 51', (37, 14, 6, 'N'), (115, 48, 40, 'W')), place)
def test_tuples_are_good_for_representing_records(self):
locations = [
("Illuminati HQ", (38, 52, 15.56, 'N'), (77, 3, 21.46, 'W')),
("Stargate B", (41, 10, 43.92, 'N'), (1, 49, 34.29, 'W')),
]
locations.append(
("Cthulhu", (26, 40, 1, 'N'), (70, 45, 7, 'W'))
)
self.assertEqual("Cthulhu", locations[2][0])
self.assertEqual(15.56, locations[0][1][2])
| test_creating_empty_tuples | identifier_name |
stats.test.js | const round = require('./round');
const { mean, median, stddev } = require('./stats');
const arr = [
40.73,
80.2,
59.54,
54.91,
93.57,
35.69,
99.44,
98.14,
89.3,
21.7,
54.26,
64.02,
18.05,
0.18,
14.79,
60.44,
47.63,
52.33,
75.62,
65.03,
];
describe('Stats', () => {
describe('mean', () => {
it('should return 0 for an empty array', () => {
const expected = 0;
expect(mean([])).toEqual(expected);
});
it('should return mean for an array', () => {
const expected = 56.2785;
const actual = round(mean(arr), 4);
expect(actual).toEqual(expected);
});
});
describe('median', () => {
it('should return 0 for an empty array', () => {
const expected = 0;
expect(median([])).toEqual(expected);
}); | it('should return median for an array', () => {
const expected = 57.225;
const actual = round(median(arr), 4);
expect(actual).toEqual(expected);
});
});
describe('stddev', () => {
it('should return 0 for an empty array', () => {
const expected = 0;
expect(stddev([])).toEqual(expected);
});
it('should return std for an array', () => {
const expected = 27.834;
const actual = round(stddev(arr), 4);
expect(actual).toEqual(expected);
});
});
}); | random_line_split | |
prefixed_command_runner.py | from __future__ import unicode_literals
import os
import os.path
import subprocess
from pre_commit.util import cmd_output
class PrefixedCommandRunner(object):
"""A PrefixedCommandRunner allows you to run subprocess commands with
comand substitution.
For instance:
PrefixedCommandRunner('/tmp/foo').run(['{prefix}foo.sh', 'bar', 'baz'])
will run ['/tmp/foo/foo.sh', 'bar', 'baz']
"""
def __init__(
self,
prefix_dir,
popen=subprocess.Popen,
makedirs=os.makedirs
):
self.prefix_dir = prefix_dir.rstrip(os.sep) + os.sep
self.__popen = popen
self.__makedirs = makedirs
def _create_path_if_not_exists(self):
if not os.path.exists(self.prefix_dir):
self.__makedirs(self.prefix_dir)
def run(self, cmd, **kwargs):
self._create_path_if_not_exists()
replaced_cmd = [
part.replace('{prefix}', self.prefix_dir) for part in cmd
]
return cmd_output(*replaced_cmd, __popen=self.__popen, **kwargs) | def path(self, *parts):
path = os.path.join(self.prefix_dir, *parts)
return os.path.normpath(path)
def exists(self, *parts):
return os.path.exists(self.path(*parts))
@classmethod
def from_command_runner(cls, command_runner, path_end):
"""Constructs a new command runner from an existing one by appending
`path_end` to the command runner's prefix directory.
"""
return cls(
command_runner.path(path_end),
popen=command_runner.__popen,
makedirs=command_runner.__makedirs,
) | random_line_split | |
prefixed_command_runner.py | from __future__ import unicode_literals
import os
import os.path
import subprocess
from pre_commit.util import cmd_output
class | (object):
"""A PrefixedCommandRunner allows you to run subprocess commands with
comand substitution.
For instance:
PrefixedCommandRunner('/tmp/foo').run(['{prefix}foo.sh', 'bar', 'baz'])
will run ['/tmp/foo/foo.sh', 'bar', 'baz']
"""
def __init__(
self,
prefix_dir,
popen=subprocess.Popen,
makedirs=os.makedirs
):
self.prefix_dir = prefix_dir.rstrip(os.sep) + os.sep
self.__popen = popen
self.__makedirs = makedirs
def _create_path_if_not_exists(self):
if not os.path.exists(self.prefix_dir):
self.__makedirs(self.prefix_dir)
def run(self, cmd, **kwargs):
self._create_path_if_not_exists()
replaced_cmd = [
part.replace('{prefix}', self.prefix_dir) for part in cmd
]
return cmd_output(*replaced_cmd, __popen=self.__popen, **kwargs)
def path(self, *parts):
path = os.path.join(self.prefix_dir, *parts)
return os.path.normpath(path)
def exists(self, *parts):
return os.path.exists(self.path(*parts))
@classmethod
def from_command_runner(cls, command_runner, path_end):
"""Constructs a new command runner from an existing one by appending
`path_end` to the command runner's prefix directory.
"""
return cls(
command_runner.path(path_end),
popen=command_runner.__popen,
makedirs=command_runner.__makedirs,
)
| PrefixedCommandRunner | identifier_name |
prefixed_command_runner.py | from __future__ import unicode_literals
import os
import os.path
import subprocess
from pre_commit.util import cmd_output
class PrefixedCommandRunner(object):
"""A PrefixedCommandRunner allows you to run subprocess commands with
comand substitution.
For instance:
PrefixedCommandRunner('/tmp/foo').run(['{prefix}foo.sh', 'bar', 'baz'])
will run ['/tmp/foo/foo.sh', 'bar', 'baz']
"""
def __init__(
self,
prefix_dir,
popen=subprocess.Popen,
makedirs=os.makedirs
):
self.prefix_dir = prefix_dir.rstrip(os.sep) + os.sep
self.__popen = popen
self.__makedirs = makedirs
def _create_path_if_not_exists(self):
|
def run(self, cmd, **kwargs):
self._create_path_if_not_exists()
replaced_cmd = [
part.replace('{prefix}', self.prefix_dir) for part in cmd
]
return cmd_output(*replaced_cmd, __popen=self.__popen, **kwargs)
def path(self, *parts):
path = os.path.join(self.prefix_dir, *parts)
return os.path.normpath(path)
def exists(self, *parts):
return os.path.exists(self.path(*parts))
@classmethod
def from_command_runner(cls, command_runner, path_end):
"""Constructs a new command runner from an existing one by appending
`path_end` to the command runner's prefix directory.
"""
return cls(
command_runner.path(path_end),
popen=command_runner.__popen,
makedirs=command_runner.__makedirs,
)
| if not os.path.exists(self.prefix_dir):
self.__makedirs(self.prefix_dir) | identifier_body |
prefixed_command_runner.py | from __future__ import unicode_literals
import os
import os.path
import subprocess
from pre_commit.util import cmd_output
class PrefixedCommandRunner(object):
"""A PrefixedCommandRunner allows you to run subprocess commands with
comand substitution.
For instance:
PrefixedCommandRunner('/tmp/foo').run(['{prefix}foo.sh', 'bar', 'baz'])
will run ['/tmp/foo/foo.sh', 'bar', 'baz']
"""
def __init__(
self,
prefix_dir,
popen=subprocess.Popen,
makedirs=os.makedirs
):
self.prefix_dir = prefix_dir.rstrip(os.sep) + os.sep
self.__popen = popen
self.__makedirs = makedirs
def _create_path_if_not_exists(self):
if not os.path.exists(self.prefix_dir):
|
def run(self, cmd, **kwargs):
self._create_path_if_not_exists()
replaced_cmd = [
part.replace('{prefix}', self.prefix_dir) for part in cmd
]
return cmd_output(*replaced_cmd, __popen=self.__popen, **kwargs)
def path(self, *parts):
path = os.path.join(self.prefix_dir, *parts)
return os.path.normpath(path)
def exists(self, *parts):
return os.path.exists(self.path(*parts))
@classmethod
def from_command_runner(cls, command_runner, path_end):
"""Constructs a new command runner from an existing one by appending
`path_end` to the command runner's prefix directory.
"""
return cls(
command_runner.path(path_end),
popen=command_runner.__popen,
makedirs=command_runner.__makedirs,
)
| self.__makedirs(self.prefix_dir) | conditional_block |
mod.rs | // +--------------------------------------------------------------------------+
// | Copyright 2016 Matthew D. Steele <mdsteele@alum.mit.edu> |
// | |
// | This file is part of System Syzygy. |
// | |
// | System Syzygy is free software: you can redistribute it and/or modify it |
// | under the terms of the GNU General Public License as published by the |
// | Free Software Foundation, either version 3 of the License, or (at your |
// | option) any later version. |
// | |
// | System Syzygy 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 details. |
// | |
// | You should have received a copy of the GNU General Public License along |
// | with System Syzygy. If not, see <http://www.gnu.org/licenses/>. |
// +--------------------------------------------------------------------------+
mod action;
mod background;
mod canvas;
mod element;
mod event;
mod font;
mod loader;
mod resources;
mod sound;
mod sprite;
mod window;
pub use self::action::Action;
pub use self::background::Background;
pub use self::canvas::{Align, Canvas};
pub use self::element::Element; | pub use self::window::Window;
pub use sdl2::rect::{Point, Rect};
pub const FRAME_DELAY_MILLIS: u32 = 40;
// ========================================================================= // | pub use self::event::{Event, KeyMod, Keycode};
pub use self::font::Font;
pub use self::resources::Resources;
pub use self::sound::Sound;
pub use self::sprite::Sprite; | random_line_split |
read_handlers.py | ## Copyright 2014 Cognitect. All Rights Reserved.
##
## Licensed under the Apache License, Version 2.0 (the "License");
## you may not use this file except in compliance with the License.
## You may obtain a copy of the License at
##
## http://www.apache.org/licenses/LICENSE-2.0
##
## Unless required by applicable law or agreed to in writing, software
## distributed under the License is distributed on an "AS-IS" BASIS,
## WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
## See the License for the specific language governing permissions and
## limitations under the License.
from transit import pyversion, transit_types
import uuid
import ctypes
import dateutil.parser
import datetime
import dateutil.tz
from transit.helpers import pairs
from decimal import Decimal
## Read handlers are used by the decoder when parsing/reading in Transit
## data and returning Python objects
class DefaultHandler(object):
@staticmethod
def from_rep(t, v):
return transit_types.TaggedValue(t, v)
class NoneHandler(object):
@staticmethod
def from_rep(_):
return None
class KeywordHandler(object):
@staticmethod
def from_rep(v):
return transit_types.Keyword(v)
class SymbolHandler(object):
@staticmethod
def from_rep(v):
return transit_types.Symbol(v)
class BigDecimalHandler(object):
@staticmethod
def from_rep(v):
return Decimal(v)
class BooleanHandler(object):
@staticmethod
def from_rep(x):
return transit_types.true if x == "t" else transit_types.false
class IntHandler(object):
@staticmethod
def from_rep(v):
return int(v)
class FloatHandler(object):
@staticmethod
def from_rep(v):
return float(v)
class UuidHandler(object):
@staticmethod
def from_rep(u):
"""Given a string, return a UUID object."""
if isinstance(u, pyversion.string_types):
return uuid.UUID(u)
# hack to remove signs
a = ctypes.c_ulong(u[0])
b = ctypes.c_ulong(u[1])
combined = a.value << 64 | b.value
return uuid.UUID(int=combined)
class UriHandler(object):
@staticmethod
def from_rep(u):
return transit_types.URI(u)
class DateHandler(object):
@staticmethod
def from_rep(d):
if isinstance(d, pyversion.int_types):
return DateHandler._convert_timestamp(d)
if "T" in d:
return dateutil.parser.parse(d)
return DateHandler._convert_timestamp(pyversion.long_type(d))
@staticmethod
def _convert_timestamp(ms):
"""Given a timestamp in ms, return a DateTime object."""
return datetime.datetime.fromtimestamp(ms/1000.0, dateutil.tz.tzutc())
if pyversion.PY3:
class BigIntegerHandler(object):
@staticmethod
def from_rep(d):
return int(d)
else:
class BigIntegerHandler(object):
@staticmethod
def from_rep(d):
return long(d)
class LinkHandler(object):
@staticmethod
def from_rep(l):
return transit_types.Link(**l)
class ListHandler(object):
@staticmethod
def from_rep(l):
return l
class SetHandler(object):
@staticmethod
def from_rep(s):
return frozenset(s)
class CmapHandler(object):
@staticmethod
def from_rep(cmap):
return transit_types.frozendict(pairs(cmap))
class IdentityHandler(object):
@staticmethod
def from_rep(i):
return i
class SpecialNumbersHandler(object):
@staticmethod
def from_rep(z):
if z == 'NaN':
return float('Nan')
if z == 'INF':
|
if z == '-INF':
return float('-Inf')
raise ValueError("Don't know how to handle: " + str(z) + " as \"z\"")
| return float('Inf') | conditional_block |
read_handlers.py | ## Copyright 2014 Cognitect. All Rights Reserved.
##
## Licensed under the Apache License, Version 2.0 (the "License");
## you may not use this file except in compliance with the License.
## You may obtain a copy of the License at
##
## http://www.apache.org/licenses/LICENSE-2.0
##
## Unless required by applicable law or agreed to in writing, software
## distributed under the License is distributed on an "AS-IS" BASIS,
## WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
## See the License for the specific language governing permissions and
## limitations under the License.
from transit import pyversion, transit_types
import uuid
import ctypes
import dateutil.parser
import datetime
import dateutil.tz
from transit.helpers import pairs
from decimal import Decimal
## Read handlers are used by the decoder when parsing/reading in Transit
## data and returning Python objects
class DefaultHandler(object):
@staticmethod
def from_rep(t, v):
return transit_types.TaggedValue(t, v)
class NoneHandler(object):
@staticmethod
def from_rep(_):
return None
class KeywordHandler(object):
@staticmethod
def from_rep(v):
return transit_types.Keyword(v)
class SymbolHandler(object):
@staticmethod
def from_rep(v):
return transit_types.Symbol(v)
class BigDecimalHandler(object):
@staticmethod
def from_rep(v):
return Decimal(v)
class BooleanHandler(object):
@staticmethod
def from_rep(x):
return transit_types.true if x == "t" else transit_types.false
| @staticmethod
def from_rep(v):
return int(v)
class FloatHandler(object):
@staticmethod
def from_rep(v):
return float(v)
class UuidHandler(object):
@staticmethod
def from_rep(u):
"""Given a string, return a UUID object."""
if isinstance(u, pyversion.string_types):
return uuid.UUID(u)
# hack to remove signs
a = ctypes.c_ulong(u[0])
b = ctypes.c_ulong(u[1])
combined = a.value << 64 | b.value
return uuid.UUID(int=combined)
class UriHandler(object):
@staticmethod
def from_rep(u):
return transit_types.URI(u)
class DateHandler(object):
@staticmethod
def from_rep(d):
if isinstance(d, pyversion.int_types):
return DateHandler._convert_timestamp(d)
if "T" in d:
return dateutil.parser.parse(d)
return DateHandler._convert_timestamp(pyversion.long_type(d))
@staticmethod
def _convert_timestamp(ms):
"""Given a timestamp in ms, return a DateTime object."""
return datetime.datetime.fromtimestamp(ms/1000.0, dateutil.tz.tzutc())
if pyversion.PY3:
class BigIntegerHandler(object):
@staticmethod
def from_rep(d):
return int(d)
else:
class BigIntegerHandler(object):
@staticmethod
def from_rep(d):
return long(d)
class LinkHandler(object):
@staticmethod
def from_rep(l):
return transit_types.Link(**l)
class ListHandler(object):
@staticmethod
def from_rep(l):
return l
class SetHandler(object):
@staticmethod
def from_rep(s):
return frozenset(s)
class CmapHandler(object):
@staticmethod
def from_rep(cmap):
return transit_types.frozendict(pairs(cmap))
class IdentityHandler(object):
@staticmethod
def from_rep(i):
return i
class SpecialNumbersHandler(object):
@staticmethod
def from_rep(z):
if z == 'NaN':
return float('Nan')
if z == 'INF':
return float('Inf')
if z == '-INF':
return float('-Inf')
raise ValueError("Don't know how to handle: " + str(z) + " as \"z\"") |
class IntHandler(object): | random_line_split |
read_handlers.py | ## Copyright 2014 Cognitect. All Rights Reserved.
##
## Licensed under the Apache License, Version 2.0 (the "License");
## you may not use this file except in compliance with the License.
## You may obtain a copy of the License at
##
## http://www.apache.org/licenses/LICENSE-2.0
##
## Unless required by applicable law or agreed to in writing, software
## distributed under the License is distributed on an "AS-IS" BASIS,
## WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
## See the License for the specific language governing permissions and
## limitations under the License.
from transit import pyversion, transit_types
import uuid
import ctypes
import dateutil.parser
import datetime
import dateutil.tz
from transit.helpers import pairs
from decimal import Decimal
## Read handlers are used by the decoder when parsing/reading in Transit
## data and returning Python objects
class DefaultHandler(object):
@staticmethod
def from_rep(t, v):
return transit_types.TaggedValue(t, v)
class NoneHandler(object):
@staticmethod
def from_rep(_):
return None
class KeywordHandler(object):
@staticmethod
def from_rep(v):
return transit_types.Keyword(v)
class SymbolHandler(object):
@staticmethod
def from_rep(v):
return transit_types.Symbol(v)
class BigDecimalHandler(object):
@staticmethod
def from_rep(v):
return Decimal(v)
class BooleanHandler(object):
@staticmethod
def from_rep(x):
return transit_types.true if x == "t" else transit_types.false
class IntHandler(object):
@staticmethod
def from_rep(v):
return int(v)
class FloatHandler(object):
@staticmethod
def from_rep(v):
return float(v)
class UuidHandler(object):
@staticmethod
def from_rep(u):
"""Given a string, return a UUID object."""
if isinstance(u, pyversion.string_types):
return uuid.UUID(u)
# hack to remove signs
a = ctypes.c_ulong(u[0])
b = ctypes.c_ulong(u[1])
combined = a.value << 64 | b.value
return uuid.UUID(int=combined)
class UriHandler(object):
@staticmethod
def from_rep(u):
return transit_types.URI(u)
class DateHandler(object):
@staticmethod
def from_rep(d):
if isinstance(d, pyversion.int_types):
return DateHandler._convert_timestamp(d)
if "T" in d:
return dateutil.parser.parse(d)
return DateHandler._convert_timestamp(pyversion.long_type(d))
@staticmethod
def _convert_timestamp(ms):
"""Given a timestamp in ms, return a DateTime object."""
return datetime.datetime.fromtimestamp(ms/1000.0, dateutil.tz.tzutc())
if pyversion.PY3:
class BigIntegerHandler(object):
|
else:
class BigIntegerHandler(object):
@staticmethod
def from_rep(d):
return long(d)
class LinkHandler(object):
@staticmethod
def from_rep(l):
return transit_types.Link(**l)
class ListHandler(object):
@staticmethod
def from_rep(l):
return l
class SetHandler(object):
@staticmethod
def from_rep(s):
return frozenset(s)
class CmapHandler(object):
@staticmethod
def from_rep(cmap):
return transit_types.frozendict(pairs(cmap))
class IdentityHandler(object):
@staticmethod
def from_rep(i):
return i
class SpecialNumbersHandler(object):
@staticmethod
def from_rep(z):
if z == 'NaN':
return float('Nan')
if z == 'INF':
return float('Inf')
if z == '-INF':
return float('-Inf')
raise ValueError("Don't know how to handle: " + str(z) + " as \"z\"")
| @staticmethod
def from_rep(d):
return int(d) | identifier_body |
read_handlers.py | ## Copyright 2014 Cognitect. All Rights Reserved.
##
## Licensed under the Apache License, Version 2.0 (the "License");
## you may not use this file except in compliance with the License.
## You may obtain a copy of the License at
##
## http://www.apache.org/licenses/LICENSE-2.0
##
## Unless required by applicable law or agreed to in writing, software
## distributed under the License is distributed on an "AS-IS" BASIS,
## WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
## See the License for the specific language governing permissions and
## limitations under the License.
from transit import pyversion, transit_types
import uuid
import ctypes
import dateutil.parser
import datetime
import dateutil.tz
from transit.helpers import pairs
from decimal import Decimal
## Read handlers are used by the decoder when parsing/reading in Transit
## data and returning Python objects
class DefaultHandler(object):
@staticmethod
def from_rep(t, v):
return transit_types.TaggedValue(t, v)
class NoneHandler(object):
@staticmethod
def from_rep(_):
return None
class KeywordHandler(object):
@staticmethod
def from_rep(v):
return transit_types.Keyword(v)
class SymbolHandler(object):
@staticmethod
def from_rep(v):
return transit_types.Symbol(v)
class BigDecimalHandler(object):
@staticmethod
def from_rep(v):
return Decimal(v)
class BooleanHandler(object):
@staticmethod
def from_rep(x):
return transit_types.true if x == "t" else transit_types.false
class IntHandler(object):
@staticmethod
def from_rep(v):
return int(v)
class FloatHandler(object):
@staticmethod
def from_rep(v):
return float(v)
class UuidHandler(object):
@staticmethod
def from_rep(u):
"""Given a string, return a UUID object."""
if isinstance(u, pyversion.string_types):
return uuid.UUID(u)
# hack to remove signs
a = ctypes.c_ulong(u[0])
b = ctypes.c_ulong(u[1])
combined = a.value << 64 | b.value
return uuid.UUID(int=combined)
class UriHandler(object):
@staticmethod
def | (u):
return transit_types.URI(u)
class DateHandler(object):
@staticmethod
def from_rep(d):
if isinstance(d, pyversion.int_types):
return DateHandler._convert_timestamp(d)
if "T" in d:
return dateutil.parser.parse(d)
return DateHandler._convert_timestamp(pyversion.long_type(d))
@staticmethod
def _convert_timestamp(ms):
"""Given a timestamp in ms, return a DateTime object."""
return datetime.datetime.fromtimestamp(ms/1000.0, dateutil.tz.tzutc())
if pyversion.PY3:
class BigIntegerHandler(object):
@staticmethod
def from_rep(d):
return int(d)
else:
class BigIntegerHandler(object):
@staticmethod
def from_rep(d):
return long(d)
class LinkHandler(object):
@staticmethod
def from_rep(l):
return transit_types.Link(**l)
class ListHandler(object):
@staticmethod
def from_rep(l):
return l
class SetHandler(object):
@staticmethod
def from_rep(s):
return frozenset(s)
class CmapHandler(object):
@staticmethod
def from_rep(cmap):
return transit_types.frozendict(pairs(cmap))
class IdentityHandler(object):
@staticmethod
def from_rep(i):
return i
class SpecialNumbersHandler(object):
@staticmethod
def from_rep(z):
if z == 'NaN':
return float('Nan')
if z == 'INF':
return float('Inf')
if z == '-INF':
return float('-Inf')
raise ValueError("Don't know how to handle: " + str(z) + " as \"z\"")
| from_rep | identifier_name |
joiner.rs | use std::os;
use std::str;
use std::io::File;
fn main() {
let args: ~[~str] = os::args();
if args.len() != 3 {
println!("Usage: {:s} <msg.share1> <msg.share2>", args[0]);
} else {
let share1 = args[1].clone();
let share2 = args[2].clone(); |
match (msg1_file, msg2_file) {
(Some(mut msg1), Some(mut msg2)) => {
let msg1_bytes: ~[u8] = msg1.read_to_end();
let msg2_bytes: ~[u8] = msg2.read_to_end();
let result: ~[u8] = xor(msg1_bytes, msg2_bytes);
print!("{:?}", str::from_utf8(result));
} ,
(None, _ ) => fail!("Error opening message file: {:s}", share1),
(_ ,None) => fail!("Error opening message file: {:s}", share2)
}
}
}
fn xor(a: &[u8], b: &[u8]) -> ~[u8] {
let mut ret = ~[];
for i in range(0, a.len()) {
ret.push(a[i] ^ b[i]);
}
ret
} | let path1 = Path::new(share1.clone());
let path2 = Path::new(share2.clone());
let msg1_file = File::open(&path1);
let msg2_file = File::open(&path2); | random_line_split |
joiner.rs | use std::os;
use std::str;
use std::io::File;
fn main() {
let args: ~[~str] = os::args();
if args.len() != 3 {
println!("Usage: {:s} <msg.share1> <msg.share2>", args[0]);
} else |
}
fn xor(a: &[u8], b: &[u8]) -> ~[u8] {
let mut ret = ~[];
for i in range(0, a.len()) {
ret.push(a[i] ^ b[i]);
}
ret
}
| {
let share1 = args[1].clone();
let share2 = args[2].clone();
let path1 = Path::new(share1.clone());
let path2 = Path::new(share2.clone());
let msg1_file = File::open(&path1);
let msg2_file = File::open(&path2);
match (msg1_file, msg2_file) {
(Some(mut msg1), Some(mut msg2)) => {
let msg1_bytes: ~[u8] = msg1.read_to_end();
let msg2_bytes: ~[u8] = msg2.read_to_end();
let result: ~[u8] = xor(msg1_bytes, msg2_bytes);
print!("{:?}", str::from_utf8(result));
} ,
(None, _ ) => fail!("Error opening message file: {:s}", share1),
(_ ,None) => fail!("Error opening message file: {:s}", share2)
}
} | conditional_block |
joiner.rs | use std::os;
use std::str;
use std::io::File;
fn main() {
let args: ~[~str] = os::args();
if args.len() != 3 {
println!("Usage: {:s} <msg.share1> <msg.share2>", args[0]);
} else {
let share1 = args[1].clone();
let share2 = args[2].clone();
let path1 = Path::new(share1.clone());
let path2 = Path::new(share2.clone());
let msg1_file = File::open(&path1);
let msg2_file = File::open(&path2);
match (msg1_file, msg2_file) {
(Some(mut msg1), Some(mut msg2)) => {
let msg1_bytes: ~[u8] = msg1.read_to_end();
let msg2_bytes: ~[u8] = msg2.read_to_end();
let result: ~[u8] = xor(msg1_bytes, msg2_bytes);
print!("{:?}", str::from_utf8(result));
} ,
(None, _ ) => fail!("Error opening message file: {:s}", share1),
(_ ,None) => fail!("Error opening message file: {:s}", share2)
}
}
}
fn | (a: &[u8], b: &[u8]) -> ~[u8] {
let mut ret = ~[];
for i in range(0, a.len()) {
ret.push(a[i] ^ b[i]);
}
ret
}
| xor | identifier_name |
joiner.rs | use std::os;
use std::str;
use std::io::File;
fn main() {
let args: ~[~str] = os::args();
if args.len() != 3 {
println!("Usage: {:s} <msg.share1> <msg.share2>", args[0]);
} else {
let share1 = args[1].clone();
let share2 = args[2].clone();
let path1 = Path::new(share1.clone());
let path2 = Path::new(share2.clone());
let msg1_file = File::open(&path1);
let msg2_file = File::open(&path2);
match (msg1_file, msg2_file) {
(Some(mut msg1), Some(mut msg2)) => {
let msg1_bytes: ~[u8] = msg1.read_to_end();
let msg2_bytes: ~[u8] = msg2.read_to_end();
let result: ~[u8] = xor(msg1_bytes, msg2_bytes);
print!("{:?}", str::from_utf8(result));
} ,
(None, _ ) => fail!("Error opening message file: {:s}", share1),
(_ ,None) => fail!("Error opening message file: {:s}", share2)
}
}
}
fn xor(a: &[u8], b: &[u8]) -> ~[u8] | {
let mut ret = ~[];
for i in range(0, a.len()) {
ret.push(a[i] ^ b[i]);
}
ret
} | identifier_body | |
shelterpro_dbf.py | #!/usr/bin/env python3
import asm, datetime, os
"""
Import script for Shelterpro databases in DBF format
Requires my hack to dbfread to support VFP9 -
copy parseC in FieldParser.py and rename it parseV, then remove
encoding so it's just a binary string that can be ignored.
Requires address.dbf, addrlink.dbf, animal.dbf, incident.dbf, license.dbf, note.dbf, person.dbf, shelter.dbf, vacc.dbf
Will also look in PATH/images/IMAGEKEY.[jpg|JPG] for animal photos if available.
29th December, 2016 - 2nd April 2020
"""
PATH = "/home/robin/tmp/asm3_import_data/shelterpro_bc2243"
START_ID = 100
INCIDENT_IMPORT = False
LICENCE_IMPORT = False
PICTURE_IMPORT = True
VACCINATION_IMPORT = True
NOTE_IMPORT = True
SHELTER_IMPORT = True
SEPARATE_ADDRESS_TABLE = True
IMPORT_ANIMALS_WITH_NO_NAME = True
""" when faced with a field type it doesn't understand, dbfread can produce an error
'Unknown field type xx'. This parser returns anything unrecognised as binary data """
class ExtraFieldParser(dbfread.FieldParser):
def parse(self, field, data):
try:
return dbfread.FieldParser.parse(self, field, data)
except ValueError:
return data
def open_dbf(name):
return asm.read_dbf(name)
def gettype(animaldes):
spmap = {
"DOG": 2,
"CAT": 11
}
species = animaldes.split(" ")[0]
if species in spmap:
return spmap[species]
else:
return 2
def gettypeletter(aid):
tmap = {
2: "D",
10: "A",
11: "U",
12: "S"
}
return tmap[aid]
def getsize(size):
if size == "VERY":
return 0
elif size == "LARGE":
return 1
elif size == "MEDIUM":
return 2
else:
return 3
def getdateage(age, arrivaldate):
""" Returns a date adjusted for age. Age can be one of
ADULT, PUPPY, KITTEN, SENIOR """
d = arrivaldate
if d == None: d = datetime.datetime.today()
if age == "ADULT":
d = d - datetime.timedelta(days = 365 * 2)
if age == "SENIOR":
d = d - datetime.timedelta(days = 365 * 7)
if age == "KITTEN":
d = d - datetime.timedelta(days = 60)
if age == "PUPPY":
d = d - datetime.timedelta(days = 60)
return d
owners = []
ownerlicences = []
logs = []
movements = []
animals = []
animalvaccinations = []
animalcontrol = []
animalcontrolanimals = []
ppa = {}
ppo = {}
ppi = {}
addresses = {}
addrlink = {}
notes = {}
asm.setid("adoption", START_ID)
asm.setid("animal", START_ID)
asm.setid("animalcontrol", START_ID)
asm.setid("log", START_ID)
asm.setid("owner", START_ID)
if VACCINATION_IMPORT: asm.setid("animalvaccination", START_ID)
if LICENCE_IMPORT: asm.setid("ownerlicence", START_ID)
if PICTURE_IMPORT: asm.setid("media", START_ID)
if PICTURE_IMPORT: asm.setid("dbfs", START_ID)
# Remove existing
print("\\set ON_ERROR_STOP\nBEGIN;")
print("DELETE FROM adoption WHERE ID >= %d AND CreatedBy = 'conversion';" % START_ID)
print("DELETE FROM animal WHERE ID >= %d AND CreatedBy = 'conversion';" % START_ID)
print("DELETE FROM owner WHERE ID >= %d AND CreatedBy = 'conversion';" % START_ID)
if INCIDENT_IMPORT: print("DELETE FROM animalcontrol WHERE ID >= %d AND CreatedBy = 'conversion';" % START_ID)
if VACCINATION_IMPORT: print("DELETE FROM animalvaccination WHERE ID >= %d AND CreatedBy = 'conversion';" % START_ID)
if LICENCE_IMPORT: print("DELETE FROM ownerlicence WHERE ID >= %d AND CreatedBy = 'conversion';" % START_ID)
if PICTURE_IMPORT: print("DELETE FROM media WHERE ID >= %d;" % START_ID)
if PICTURE_IMPORT: print("DELETE FROM dbfs WHERE ID >= %d;" % START_ID)
# Create a transfer owner
to = asm.Owner()
owners.append(to)
to.OwnerSurname = "Other Shelter"
to.OwnerName = to.OwnerSurname
# Create an unknown owner
uo = asm.Owner()
owners.append(uo)
uo.OwnerSurname = "Unknown Owner"
uo.OwnerName = uo.OwnerSurname
# Load up data files
if SEPARATE_ADDRESS_TABLE:
caddress = open_dbf("address")
caddrlink = open_dbf("addrlink")
canimal = open_dbf("animal")
if LICENCE_IMPORT: clicense = open_dbf("license")
cperson = open_dbf("person")
if SHELTER_IMPORT: cshelter = open_dbf("shelter")
if VACCINATION_IMPORT: cvacc = open_dbf("vacc")
if INCIDENT_IMPORT: cincident = open_dbf("incident")
if NOTE_IMPORT: cnote = open_dbf("note")
if PICTURE_IMPORT: cimage = open_dbf("image")
# Addresses if we have a separate file
if SEPARATE_ADDRESS_TABLE:
for row in caddress:
addresses[row["ADDRESSKEY"]] = {
"address": asm.strip(row["ADDRESSSTR"]) + " " + asm.strip(row["ADDRESSST2"]) + " " + asm.strip(row["ADDRESSST3"]),
"city": asm.strip(row["ADDRESSCIT"]),
"state": asm.strip(row["ADDRESSSTA"]),
"zip": asm.strip(row["ADDRESSPOS"])
}
# The link between addresses and people
for row in caddrlink:
addrlink[row["EVENTKEY"]] = row["ADDRLINKAD"]
# People
for row in cperson:
o = asm.Owner()
owners.append(o)
personkey = 0
# Sometimes called UNIQUE
if "PERSONKEY" in row: personkey = row["PERSONKEY"]
elif "UNIQUE" in row: personkey = row["UNIQUE"]
ppo[personkey] = o
o.OwnerForeNames = asm.strip(row["FNAME"])
o.OwnerSurname = asm.strip(row["LNAME"])
o.OwnerName = o.OwnerTitle + " " + o.OwnerForeNames + " " + o.OwnerSurname
# Find the address if it's in a separate table
if SEPARATE_ADDRESS_TABLE:
if personkey in addrlink:
addrkey = addrlink[personkey]
if addrkey in addresses:
add = addresses[addrkey]
o.OwnerAddress = add["address"]
o.OwnerTown = add["city"]
o.OwnerCounty = add["state"]
o.OwnerPostcode = add["zip"]
else:
# Otherwise, address fields are in the person table
o.OwnerAddress = row["ADDR1"].encode("ascii", "xmlcharrefreplace") + "\n" + row["ADDR2"].encode("ascii", "xmlcharrefreplace")
o.OwnerTown = row["CITY"]
o.OwnerCounty = row["STATE"]
o.OwnerPostcode = row["POSTAL_ID"]
if asm.strip(row["EMAIL"]) != "(": o.EmailAddress = asm.strip(row["EMAIL"])
if row["HOME_PH"] != 0: o.HomeTelephone = asm.strip(row["HOME_PH"])
if row["WORK_PH"] != 0: o.WorkTelephone = asm.strip(row["WORK_PH"])
if row["THIRD_PH"] != 0: o.MobileTelephone = asm.strip(row["THIRD_PH"])
o.IsACO = asm.cint(row["ACO_IND"])
o.IsStaff = asm.cint(row["STAFF_IND"])
o.IsVolunteer = asm.cint(row["VOL_IND"])
o.IsDonor = asm.cint(row["DONOR_IND"])
o.IsMember = asm.cint(row["MEMBER_IND"])
o.IsBanned = asm.cint(row["NOADOPT"] == "T" and "1" or "0")
if "FOSTERS" in row: o.IsFosterer = asm.cint(row["FOSTERS"])
# o.ExcludeFromBulkEmail = asm.cint(row["MAILINGSAM"]) # Not sure this is correct
# Animals
for row in canimal:
if not IMPORT_ANIMALS_WITH_NO_NAME and row["PETNAME"].strip() == "": continue
a = asm.Animal()
animals.append(a)
ppa[row["ANIMALKEY"]] = a
a.AnimalTypeID = gettype(row["ANIMLDES"])
a.SpeciesID = asm.species_id_for_name(row["ANIMLDES"].split(" ")[0])
a.AnimalName = asm.strip(row["PETNAME"]).title()
if a.AnimalName.strip() == "":
a.AnimalName = "(unknown)"
age = row["AGE"].split(" ")[0]
added = asm.now()
if "ADDEDDATET" in row and row["ADDEDDATET"] is not None: added = row["ADDEDDATET"]
if "DOB" in row: a.DateOfBirth = row["DOB"]
if a.DateOfBirth is None: a.DateOfBirth = getdateage(age, added)
a.DateBroughtIn = added
a.LastChangedDate = a.DateBroughtIn
a.CreatedDate = a.DateBroughtIn
a.EntryReasonID = 4
a.generateCode(gettypeletter(a.AnimalTypeID))
a.ShortCode = row["ANIMALKEY"]
a.Neutered = asm.cint(row["FIX"])
a.Declawed = asm.cint(row["DECLAWED"])
a.IsNotAvailableForAdoption = 0
a.ShelterLocation = 1
a.Sex = asm.getsex_mf(asm.strip(row["GENDER"]))
a.Size = getsize(asm.strip(row["WEIGHT"]))
a.BaseColourID = asm.colour_id_for_names(asm.strip(row["FURCOLR1"]), asm.strip(row["FURCOLR2"]))
a.IdentichipNumber = asm.strip(row["MICROCHIP"])
if a.IdentichipNumber <> "": a.Identichipped = 1
comments = "Original breed: " + asm.strip(row["BREED1"]) + "/" + asm.strip(row["CROSSBREED"]) + ", age: " + age
comments += ",Color: " + asm.strip(row["FURCOLR1"]) + "/" + asm.strip(row["FURCOLR2"])
comments += ", Coat: " + asm.strip(row["COAT"])
comments += ", Collar: " + asm.strip(row["COLLRTYP"])
a.BreedID = asm.breed_id_for_name(asm.strip(row["BREED1"]))
a.Breed2ID = a.BreedID
a.BreedName = asm.breed_name_for_id(a.BreedID)
if row["PUREBRED"] == "0":
a.Breed2ID = asm.breed_id_for_name(asm.strip(row["CROSSBREED"]))
if a.Breed2ID == 1: a.Breed2ID = 442
a.BreedName = "%s / %s" % ( asm.breed_name_for_id(a.BreedID), asm.breed_name_for_id(a.Breed2ID) )
a.HiddenAnimalDetails = comments
# Make everything non-shelter until it's in the shelter file
a.NonShelterAnimal = 1
a.Archived = 1
# If the row has an original owner
if row["PERSOWNR"] in ppo:
o = ppo[row["PERSOWNR"]]
a.OriginalOwnerID = o.ID
# Shelterpro records Deceased as Status == 2 as far as we can tell
if row["STATUS"] == 2:
a.DeceasedDate = a.DateBroughtIn
a.PTSReasonID = 2 # Died
# Vaccinations
if VACCINATION_IMPORT:
for row in cvacc:
if not row["ANIMALKEY"] in ppa: continue
a = ppa[row["ANIMALKEY"]]
# Each row contains a vaccination
av = asm.AnimalVaccination()
animalvaccinations.append(av)
vaccdate = row["VACCEFFECT"]
if vaccdate is None:
vaccdate = a.DateBroughtIn
av.AnimalID = a.ID
av.VaccinationID = 8
if row["VACCTYPE"].find("DHLPP") != -1: av.VaccinationID = 8
if row["VACCTYPE"].find("BORDETELLA") != -1: av.VaccinationID = 6
if row["VACCTYPE"].find("RABIES") != -1: av.VaccinationID = 4
av.DateRequired = vaccdate
av.DateOfVaccination = vaccdate
av.DateExpires = row["VACCEXPIRA"]
av.Manufacturer = row["VACCMANUFA"]
av.BatchNumber = row["VACCSERIAL"]
av.Comments = "Name: %s, Issue: %s" % (row["VACCDRUGNA"], row["VACCISSUED"])
# Run through the shelter file and create any movements/euthanisation info
if SHELTER_IMPORT:
for row in cshelter:
a = None
if row["ANIMALKEY"] in ppa:
a = ppa[row["ANIMALKEY"]]
arivdate = row["ARIVDATE"]
a.ShortCode = asm.strip(row["ANIMALKEY"])
a.ShelterLocationUnit = asm.strip(row["KENNEL"])
a.NonShelterAnimal = 0
if arivdate is not None:
a.DateBroughtIn = arivdate
a.LastChangedDate = a.DateBroughtIn
a.CreatedDate = a.DateBroughtIn
a.generateCode(gettypeletter(a.AnimalTypeID))
a.ShortCode = asm.strip(row["ANIMALKEY"])
else:
# Couldn't find an animal record, bail
continue
o = None
if row["OWNERATDIS"] in ppo:
o = ppo[row["OWNERATDIS"]]
dispmeth = asm.strip(row["DISPMETH"])
dispdate = row["DISPDATE"]
# Apply other fields
if row["ARIVREAS"] == "QUARANTINE":
a.IsQuarantine = 1
elif row["ARIVREAS"] == "STRAY":
if a.AnimalTypeID == 2: a.AnimalTypeID = 10
if a.AnimalTypeID == 11: a.AnimalTypeID = 12
a.EntryReasonID = 7
# Adoptions
if dispmeth == "ADOPTED":
if a is None or o is None: continue
m = asm.Movement()
m.AnimalID = a.ID
m.OwnerID = o.ID
m.MovementType = 1
m.MovementDate = dispdate
a.Archived = 1
a.ActiveMovementID = m.ID
a.ActiveMovementDate = m.MovementDate
a.ActiveMovementType = 1
movements.append(m)
# Reclaims
elif dispmeth == "RETURN TO OWNER":
if a is None or o is None: continue
m = asm.Movement()
m.AnimalID = a.ID
m.OwnerID = o.ID
m.MovementType = 5
m.MovementDate = dispdate
a.Archived = 1
a.ActiveMovementID = m.ID
a.ActiveMovementDate = m.MovementDate
a.ActiveMovementType = 5
movements.append(m)
# Released or Other
elif dispmeth == "RELEASED" or dispmeth == "OTHER":
if a is None or o is None: continue
m = asm.Movement()
m.AnimalID = a.ID
m.OwnerID = 0
m.MovementType = 7
m.MovementDate = dispdate
m.Comments = dispmeth
a.Archived = 1
a.ActiveMovementDate = m.MovementDate
a.ActiveMovementID = m.ID
a.ActiveMovementType = 7
movements.append(m)
# Holding
elif dispmeth == "" and row["ANIMSTAT"] == "HOLDING":
a.IsHold = 1
a.Archived = 0
# Deceased
elif dispmeth == "DECEASED":
a.DeceasedDate = dispdate
a.PTSReasonID = 2 # Died
a.Archived = 1
# Euthanized
elif dispmeth == "EUTHANIZED": | # If the outcome is blank, it's on the shelter
elif dispmeth == "":
a.Archived = 0
# It's the name of an organisation that received the animal
else:
if a is None: continue
m = asm.Movement()
m.AnimalID = a.ID
m.OwnerID = to.ID
m.MovementType = 3
m.MovementDate = dispdate
m.Comments = dispmeth
a.Archived = 1
a.ActiveMovementID = m.ID
a.ActiveMovementType = 3
movements.append(m)
if LICENCE_IMPORT:
for row in clicense:
a = None
if row["ANIMALKEY"] in ppa:
a = ppa[row["ANIMALKEY"]]
o = None
if row["LICENSEOWN"] in ppo:
o = ppo[row["LICENSEOWN"]]
if a is not None and o is not None:
if row["LICENSEEFF"] is None:
continue
ol = asm.OwnerLicence()
ownerlicences.append(ol)
ol.AnimalID = a.ID
ol.OwnerID = o.ID
ol.IssueDate = row["LICENSEEFF"]
ol.ExpiryDate = row["LICENSEEXP"]
if ol.ExpiryDate is None: ol.ExpiryDate = ol.IssueDate
ol.LicenceNumber = asm.strip(row["LICENSE"])
ol.LicenceTypeID = 2 # Unaltered dog
if a.Neutered == 1:
ol.LicenceTypeID = 1 # Altered dog
if PICTURE_IMPORT:
for row in cimage:
a = None
if not row["ANIMALKEY"] in ppa:
continue
a = ppa[row["ANIMALKEY"]]
imdata = None
if os.path.exists(PATH + "/images/%s.jpg" % row["IMAGEKEY"]):
f = open(PATH + "/images/%s.jpg" % row["IMAGEKEY"], "rb")
imdata = f.read()
f.close()
if imdata is not None:
asm.animal_image(a.ID, imdata)
# Incidents
if INCIDENT_IMPORT:
for row in cincident:
ac = asm.AnimalControl()
animalcontrol.append(ac)
calldate = row["DATETIMEAS"]
if calldate is None: calldate = row["DATETIMEOR"]
if calldate is None: calldate = asm.now()
ac.CallDateTime = calldate
ac.IncidentDateTime = calldate
ac.DispatchDateTime = calldate
ac.CompletedDate = row["DATETIMEOU"]
if ac.CompletedDate is None: ac.CompletedDate = calldate
if row["CITIZENMAK"] in ppo:
ac.CallerID = ppo[row["CITIZENMAK"]].ID
if row["OWNERATORI"] in ppo:
ac.OwnerID = ppo[row["OWNERATORI"]].ID
ac.IncidentCompletedID = 2
if row["FINALOUTCO"] == "ANIMAL PICKED UP":
ac.IncidentCompletedID = 2
elif row["FINALOUTCO"] == "OTHER":
ac.IncidentCompletedID = 6 # Does not exist in default data
ac.IncidentTypeID = 1
incidentkey = 0
if "INCIDENTKE" in row: incidentkey = row["INCIDENTKE"]
elif "KEY" in row: incidentkey = row["KEY"]
comments = "case: %s\n" % incidentkey
comments += "outcome: %s\n" % asm.strip(row["FINALOUTCO"])
comments += "precinct: %s\n" % asm.strip(row["PRECINCT"])
ac.CallNotes = comments
ac.Sex = 2
if "ANIMALKEY" in row:
if row["ANIMALKEY"] in ppa:
a = ppa[row["ANIMALKEY"]]
animalcontrolanimals.append("INSERT INTO animalcontrolanimal (AnimalControlID, AnimalID) VALUES (%s, %s);" % (ac.ID, a.ID))
# Notes as log entries
if NOTE_IMPORT:
for row in cnote:
eventtype = row["EVENTTYPE"]
eventkey = row["EVENTKEY"]
notedate = row["NOTEDATE"]
memo = row["NOTEMEMO"]
if eventtype in [ 1, 3 ]: # animal/intake or case notes
if not eventkey in ppa: continue
linkid = ppa[eventkey].ID
ppa[eventkey].HiddenAnimalDetails += "\n" + memo
l = asm.Log()
logs.append(l)
l.LogTypeID = 3
l.LinkID = linkid
l.LinkType = 0
l.Date = notedate
if l.Date is None:
l.Date = asm.now()
l.Comments = memo
elif eventtype in [ 2, 5, 10 ]: # person, case and incident notes
if not eventkey in ppi: continue
linkid = ppi[eventkey].ID
ppi[eventkey].CallNotes += "\n" + memo
l = asm.Log()
logs.append(l)
l.LogTypeID = 3
l.LinkID = linkid
l.LinkType = 6
l.Date = notedate
if l.Date is None:
l.Date = asm.now()
l.Comments = memo
# Run back through the animals, if we have any that are still
# on shelter after 2 years, add an adoption to an unknown owner
#asm.adopt_older_than(animals, movements, uo.ID, 365*2)
# Now that everything else is done, output stored records
for a in animals:
print(a)
for av in animalvaccinations:
print(av)
for o in owners:
print(o)
for l in logs:
print(l)
for m in movements:
print(m)
for ol in ownerlicences:
print(ol)
for ac in animalcontrol:
print(ac)
for aca in animalcontrolanimals:
print(aca)
asm.stderr_summary(animals=animals, animalvaccinations=animalvaccinations, logs=logs, owners=owners, movements=movements, ownerlicences=ownerlicences, animalcontrol=animalcontrol)
print("DELETE FROM configuration WHERE ItemName LIKE 'DBView%';")
print("COMMIT;") | a.DeceasedDate = dispdate
a.PutToSleep = 1
a.PTSReasonID = 4 # Sick/Injured
a.Archived = 1
| random_line_split |
shelterpro_dbf.py | #!/usr/bin/env python3
import asm, datetime, os
"""
Import script for Shelterpro databases in DBF format
Requires my hack to dbfread to support VFP9 -
copy parseC in FieldParser.py and rename it parseV, then remove
encoding so it's just a binary string that can be ignored.
Requires address.dbf, addrlink.dbf, animal.dbf, incident.dbf, license.dbf, note.dbf, person.dbf, shelter.dbf, vacc.dbf
Will also look in PATH/images/IMAGEKEY.[jpg|JPG] for animal photos if available.
29th December, 2016 - 2nd April 2020
"""
PATH = "/home/robin/tmp/asm3_import_data/shelterpro_bc2243"
START_ID = 100
INCIDENT_IMPORT = False
LICENCE_IMPORT = False
PICTURE_IMPORT = True
VACCINATION_IMPORT = True
NOTE_IMPORT = True
SHELTER_IMPORT = True
SEPARATE_ADDRESS_TABLE = True
IMPORT_ANIMALS_WITH_NO_NAME = True
""" when faced with a field type it doesn't understand, dbfread can produce an error
'Unknown field type xx'. This parser returns anything unrecognised as binary data """
class ExtraFieldParser(dbfread.FieldParser):
def parse(self, field, data):
try:
return dbfread.FieldParser.parse(self, field, data)
except ValueError:
return data
def open_dbf(name):
return asm.read_dbf(name)
def gettype(animaldes):
spmap = {
"DOG": 2,
"CAT": 11
}
species = animaldes.split(" ")[0]
if species in spmap:
return spmap[species]
else:
return 2
def gettypeletter(aid):
tmap = {
2: "D",
10: "A",
11: "U",
12: "S"
}
return tmap[aid]
def getsize(size):
if size == "VERY":
return 0
elif size == "LARGE":
return 1
elif size == "MEDIUM":
return 2
else:
return 3
def getdateage(age, arrivaldate):
""" Returns a date adjusted for age. Age can be one of
ADULT, PUPPY, KITTEN, SENIOR """
d = arrivaldate
if d == None: d = datetime.datetime.today()
if age == "ADULT":
d = d - datetime.timedelta(days = 365 * 2)
if age == "SENIOR":
d = d - datetime.timedelta(days = 365 * 7)
if age == "KITTEN":
d = d - datetime.timedelta(days = 60)
if age == "PUPPY":
d = d - datetime.timedelta(days = 60)
return d
owners = []
ownerlicences = []
logs = []
movements = []
animals = []
animalvaccinations = []
animalcontrol = []
animalcontrolanimals = []
ppa = {}
ppo = {}
ppi = {}
addresses = {}
addrlink = {}
notes = {}
asm.setid("adoption", START_ID)
asm.setid("animal", START_ID)
asm.setid("animalcontrol", START_ID)
asm.setid("log", START_ID)
asm.setid("owner", START_ID)
if VACCINATION_IMPORT: asm.setid("animalvaccination", START_ID)
if LICENCE_IMPORT: asm.setid("ownerlicence", START_ID)
if PICTURE_IMPORT: asm.setid("media", START_ID)
if PICTURE_IMPORT: asm.setid("dbfs", START_ID)
# Remove existing
print("\\set ON_ERROR_STOP\nBEGIN;")
print("DELETE FROM adoption WHERE ID >= %d AND CreatedBy = 'conversion';" % START_ID)
print("DELETE FROM animal WHERE ID >= %d AND CreatedBy = 'conversion';" % START_ID)
print("DELETE FROM owner WHERE ID >= %d AND CreatedBy = 'conversion';" % START_ID)
if INCIDENT_IMPORT: print("DELETE FROM animalcontrol WHERE ID >= %d AND CreatedBy = 'conversion';" % START_ID)
if VACCINATION_IMPORT: print("DELETE FROM animalvaccination WHERE ID >= %d AND CreatedBy = 'conversion';" % START_ID)
if LICENCE_IMPORT: print("DELETE FROM ownerlicence WHERE ID >= %d AND CreatedBy = 'conversion';" % START_ID)
if PICTURE_IMPORT: print("DELETE FROM media WHERE ID >= %d;" % START_ID)
if PICTURE_IMPORT: print("DELETE FROM dbfs WHERE ID >= %d;" % START_ID)
# Create a transfer owner
to = asm.Owner()
owners.append(to)
to.OwnerSurname = "Other Shelter"
to.OwnerName = to.OwnerSurname
# Create an unknown owner
uo = asm.Owner()
owners.append(uo)
uo.OwnerSurname = "Unknown Owner"
uo.OwnerName = uo.OwnerSurname
# Load up data files
if SEPARATE_ADDRESS_TABLE:
caddress = open_dbf("address")
caddrlink = open_dbf("addrlink")
canimal = open_dbf("animal")
if LICENCE_IMPORT: clicense = open_dbf("license")
cperson = open_dbf("person")
if SHELTER_IMPORT: cshelter = open_dbf("shelter")
if VACCINATION_IMPORT: cvacc = open_dbf("vacc")
if INCIDENT_IMPORT: cincident = open_dbf("incident")
if NOTE_IMPORT: cnote = open_dbf("note")
if PICTURE_IMPORT: cimage = open_dbf("image")
# Addresses if we have a separate file
if SEPARATE_ADDRESS_TABLE:
for row in caddress:
addresses[row["ADDRESSKEY"]] = {
"address": asm.strip(row["ADDRESSSTR"]) + " " + asm.strip(row["ADDRESSST2"]) + " " + asm.strip(row["ADDRESSST3"]),
"city": asm.strip(row["ADDRESSCIT"]),
"state": asm.strip(row["ADDRESSSTA"]),
"zip": asm.strip(row["ADDRESSPOS"])
}
# The link between addresses and people
for row in caddrlink:
addrlink[row["EVENTKEY"]] = row["ADDRLINKAD"]
# People
for row in cperson:
o = asm.Owner()
owners.append(o)
personkey = 0
# Sometimes called UNIQUE
if "PERSONKEY" in row: personkey = row["PERSONKEY"]
elif "UNIQUE" in row: personkey = row["UNIQUE"]
ppo[personkey] = o
o.OwnerForeNames = asm.strip(row["FNAME"])
o.OwnerSurname = asm.strip(row["LNAME"])
o.OwnerName = o.OwnerTitle + " " + o.OwnerForeNames + " " + o.OwnerSurname
# Find the address if it's in a separate table
if SEPARATE_ADDRESS_TABLE:
if personkey in addrlink:
addrkey = addrlink[personkey]
if addrkey in addresses:
add = addresses[addrkey]
o.OwnerAddress = add["address"]
o.OwnerTown = add["city"]
o.OwnerCounty = add["state"]
o.OwnerPostcode = add["zip"]
else:
# Otherwise, address fields are in the person table
o.OwnerAddress = row["ADDR1"].encode("ascii", "xmlcharrefreplace") + "\n" + row["ADDR2"].encode("ascii", "xmlcharrefreplace")
o.OwnerTown = row["CITY"]
o.OwnerCounty = row["STATE"]
o.OwnerPostcode = row["POSTAL_ID"]
if asm.strip(row["EMAIL"]) != "(": o.EmailAddress = asm.strip(row["EMAIL"])
if row["HOME_PH"] != 0: o.HomeTelephone = asm.strip(row["HOME_PH"])
if row["WORK_PH"] != 0: o.WorkTelephone = asm.strip(row["WORK_PH"])
if row["THIRD_PH"] != 0: o.MobileTelephone = asm.strip(row["THIRD_PH"])
o.IsACO = asm.cint(row["ACO_IND"])
o.IsStaff = asm.cint(row["STAFF_IND"])
o.IsVolunteer = asm.cint(row["VOL_IND"])
o.IsDonor = asm.cint(row["DONOR_IND"])
o.IsMember = asm.cint(row["MEMBER_IND"])
o.IsBanned = asm.cint(row["NOADOPT"] == "T" and "1" or "0")
if "FOSTERS" in row: o.IsFosterer = asm.cint(row["FOSTERS"])
# o.ExcludeFromBulkEmail = asm.cint(row["MAILINGSAM"]) # Not sure this is correct
# Animals
for row in canimal:
if not IMPORT_ANIMALS_WITH_NO_NAME and row["PETNAME"].strip() == "": continue
a = asm.Animal()
animals.append(a)
ppa[row["ANIMALKEY"]] = a
a.AnimalTypeID = gettype(row["ANIMLDES"])
a.SpeciesID = asm.species_id_for_name(row["ANIMLDES"].split(" ")[0])
a.AnimalName = asm.strip(row["PETNAME"]).title()
if a.AnimalName.strip() == "":
a.AnimalName = "(unknown)"
age = row["AGE"].split(" ")[0]
added = asm.now()
if "ADDEDDATET" in row and row["ADDEDDATET"] is not None: added = row["ADDEDDATET"]
if "DOB" in row: a.DateOfBirth = row["DOB"]
if a.DateOfBirth is None: a.DateOfBirth = getdateage(age, added)
a.DateBroughtIn = added
a.LastChangedDate = a.DateBroughtIn
a.CreatedDate = a.DateBroughtIn
a.EntryReasonID = 4
a.generateCode(gettypeletter(a.AnimalTypeID))
a.ShortCode = row["ANIMALKEY"]
a.Neutered = asm.cint(row["FIX"])
a.Declawed = asm.cint(row["DECLAWED"])
a.IsNotAvailableForAdoption = 0
a.ShelterLocation = 1
a.Sex = asm.getsex_mf(asm.strip(row["GENDER"]))
a.Size = getsize(asm.strip(row["WEIGHT"]))
a.BaseColourID = asm.colour_id_for_names(asm.strip(row["FURCOLR1"]), asm.strip(row["FURCOLR2"]))
a.IdentichipNumber = asm.strip(row["MICROCHIP"])
if a.IdentichipNumber <> "": a.Identichipped = 1
comments = "Original breed: " + asm.strip(row["BREED1"]) + "/" + asm.strip(row["CROSSBREED"]) + ", age: " + age
comments += ",Color: " + asm.strip(row["FURCOLR1"]) + "/" + asm.strip(row["FURCOLR2"])
comments += ", Coat: " + asm.strip(row["COAT"])
comments += ", Collar: " + asm.strip(row["COLLRTYP"])
a.BreedID = asm.breed_id_for_name(asm.strip(row["BREED1"]))
a.Breed2ID = a.BreedID
a.BreedName = asm.breed_name_for_id(a.BreedID)
if row["PUREBRED"] == "0":
a.Breed2ID = asm.breed_id_for_name(asm.strip(row["CROSSBREED"]))
if a.Breed2ID == 1: a.Breed2ID = 442
a.BreedName = "%s / %s" % ( asm.breed_name_for_id(a.BreedID), asm.breed_name_for_id(a.Breed2ID) )
a.HiddenAnimalDetails = comments
# Make everything non-shelter until it's in the shelter file
a.NonShelterAnimal = 1
a.Archived = 1
# If the row has an original owner
if row["PERSOWNR"] in ppo:
o = ppo[row["PERSOWNR"]]
a.OriginalOwnerID = o.ID
# Shelterpro records Deceased as Status == 2 as far as we can tell
if row["STATUS"] == 2:
a.DeceasedDate = a.DateBroughtIn
a.PTSReasonID = 2 # Died
# Vaccinations
if VACCINATION_IMPORT:
for row in cvacc:
if not row["ANIMALKEY"] in ppa: continue
a = ppa[row["ANIMALKEY"]]
# Each row contains a vaccination
av = asm.AnimalVaccination()
animalvaccinations.append(av)
vaccdate = row["VACCEFFECT"]
if vaccdate is None:
vaccdate = a.DateBroughtIn
av.AnimalID = a.ID
av.VaccinationID = 8
if row["VACCTYPE"].find("DHLPP") != -1: av.VaccinationID = 8
if row["VACCTYPE"].find("BORDETELLA") != -1: av.VaccinationID = 6
if row["VACCTYPE"].find("RABIES") != -1: av.VaccinationID = 4
av.DateRequired = vaccdate
av.DateOfVaccination = vaccdate
av.DateExpires = row["VACCEXPIRA"]
av.Manufacturer = row["VACCMANUFA"]
av.BatchNumber = row["VACCSERIAL"]
av.Comments = "Name: %s, Issue: %s" % (row["VACCDRUGNA"], row["VACCISSUED"])
# Run through the shelter file and create any movements/euthanisation info
if SHELTER_IMPORT:
for row in cshelter:
a = None
if row["ANIMALKEY"] in ppa:
a = ppa[row["ANIMALKEY"]]
arivdate = row["ARIVDATE"]
a.ShortCode = asm.strip(row["ANIMALKEY"])
a.ShelterLocationUnit = asm.strip(row["KENNEL"])
a.NonShelterAnimal = 0
if arivdate is not None:
a.DateBroughtIn = arivdate
a.LastChangedDate = a.DateBroughtIn
a.CreatedDate = a.DateBroughtIn
a.generateCode(gettypeletter(a.AnimalTypeID))
a.ShortCode = asm.strip(row["ANIMALKEY"])
else:
# Couldn't find an animal record, bail
continue
o = None
if row["OWNERATDIS"] in ppo:
o = ppo[row["OWNERATDIS"]]
dispmeth = asm.strip(row["DISPMETH"])
dispdate = row["DISPDATE"]
# Apply other fields
if row["ARIVREAS"] == "QUARANTINE":
a.IsQuarantine = 1
elif row["ARIVREAS"] == "STRAY":
if a.AnimalTypeID == 2: a.AnimalTypeID = 10
if a.AnimalTypeID == 11: a.AnimalTypeID = 12
a.EntryReasonID = 7
# Adoptions
if dispmeth == "ADOPTED":
if a is None or o is None: continue
m = asm.Movement()
m.AnimalID = a.ID
m.OwnerID = o.ID
m.MovementType = 1
m.MovementDate = dispdate
a.Archived = 1
a.ActiveMovementID = m.ID
a.ActiveMovementDate = m.MovementDate
a.ActiveMovementType = 1
movements.append(m)
# Reclaims
elif dispmeth == "RETURN TO OWNER":
if a is None or o is None: continue
m = asm.Movement()
m.AnimalID = a.ID
m.OwnerID = o.ID
m.MovementType = 5
m.MovementDate = dispdate
a.Archived = 1
a.ActiveMovementID = m.ID
a.ActiveMovementDate = m.MovementDate
a.ActiveMovementType = 5
movements.append(m)
# Released or Other
elif dispmeth == "RELEASED" or dispmeth == "OTHER":
if a is None or o is None: continue
m = asm.Movement()
m.AnimalID = a.ID
m.OwnerID = 0
m.MovementType = 7
m.MovementDate = dispdate
m.Comments = dispmeth
a.Archived = 1
a.ActiveMovementDate = m.MovementDate
a.ActiveMovementID = m.ID
a.ActiveMovementType = 7
movements.append(m)
# Holding
elif dispmeth == "" and row["ANIMSTAT"] == "HOLDING":
a.IsHold = 1
a.Archived = 0
# Deceased
elif dispmeth == "DECEASED":
a.DeceasedDate = dispdate
a.PTSReasonID = 2 # Died
a.Archived = 1
# Euthanized
elif dispmeth == "EUTHANIZED":
a.DeceasedDate = dispdate
a.PutToSleep = 1
a.PTSReasonID = 4 # Sick/Injured
a.Archived = 1
# If the outcome is blank, it's on the shelter
elif dispmeth == "":
a.Archived = 0
# It's the name of an organisation that received the animal
else:
|
if LICENCE_IMPORT:
for row in clicense:
a = None
if row["ANIMALKEY"] in ppa:
a = ppa[row["ANIMALKEY"]]
o = None
if row["LICENSEOWN"] in ppo:
o = ppo[row["LICENSEOWN"]]
if a is not None and o is not None:
if row["LICENSEEFF"] is None:
continue
ol = asm.OwnerLicence()
ownerlicences.append(ol)
ol.AnimalID = a.ID
ol.OwnerID = o.ID
ol.IssueDate = row["LICENSEEFF"]
ol.ExpiryDate = row["LICENSEEXP"]
if ol.ExpiryDate is None: ol.ExpiryDate = ol.IssueDate
ol.LicenceNumber = asm.strip(row["LICENSE"])
ol.LicenceTypeID = 2 # Unaltered dog
if a.Neutered == 1:
ol.LicenceTypeID = 1 # Altered dog
if PICTURE_IMPORT:
for row in cimage:
a = None
if not row["ANIMALKEY"] in ppa:
continue
a = ppa[row["ANIMALKEY"]]
imdata = None
if os.path.exists(PATH + "/images/%s.jpg" % row["IMAGEKEY"]):
f = open(PATH + "/images/%s.jpg" % row["IMAGEKEY"], "rb")
imdata = f.read()
f.close()
if imdata is not None:
asm.animal_image(a.ID, imdata)
# Incidents
if INCIDENT_IMPORT:
for row in cincident:
ac = asm.AnimalControl()
animalcontrol.append(ac)
calldate = row["DATETIMEAS"]
if calldate is None: calldate = row["DATETIMEOR"]
if calldate is None: calldate = asm.now()
ac.CallDateTime = calldate
ac.IncidentDateTime = calldate
ac.DispatchDateTime = calldate
ac.CompletedDate = row["DATETIMEOU"]
if ac.CompletedDate is None: ac.CompletedDate = calldate
if row["CITIZENMAK"] in ppo:
ac.CallerID = ppo[row["CITIZENMAK"]].ID
if row["OWNERATORI"] in ppo:
ac.OwnerID = ppo[row["OWNERATORI"]].ID
ac.IncidentCompletedID = 2
if row["FINALOUTCO"] == "ANIMAL PICKED UP":
ac.IncidentCompletedID = 2
elif row["FINALOUTCO"] == "OTHER":
ac.IncidentCompletedID = 6 # Does not exist in default data
ac.IncidentTypeID = 1
incidentkey = 0
if "INCIDENTKE" in row: incidentkey = row["INCIDENTKE"]
elif "KEY" in row: incidentkey = row["KEY"]
comments = "case: %s\n" % incidentkey
comments += "outcome: %s\n" % asm.strip(row["FINALOUTCO"])
comments += "precinct: %s\n" % asm.strip(row["PRECINCT"])
ac.CallNotes = comments
ac.Sex = 2
if "ANIMALKEY" in row:
if row["ANIMALKEY"] in ppa:
a = ppa[row["ANIMALKEY"]]
animalcontrolanimals.append("INSERT INTO animalcontrolanimal (AnimalControlID, AnimalID) VALUES (%s, %s);" % (ac.ID, a.ID))
# Notes as log entries
if NOTE_IMPORT:
for row in cnote:
eventtype = row["EVENTTYPE"]
eventkey = row["EVENTKEY"]
notedate = row["NOTEDATE"]
memo = row["NOTEMEMO"]
if eventtype in [ 1, 3 ]: # animal/intake or case notes
if not eventkey in ppa: continue
linkid = ppa[eventkey].ID
ppa[eventkey].HiddenAnimalDetails += "\n" + memo
l = asm.Log()
logs.append(l)
l.LogTypeID = 3
l.LinkID = linkid
l.LinkType = 0
l.Date = notedate
if l.Date is None:
l.Date = asm.now()
l.Comments = memo
elif eventtype in [ 2, 5, 10 ]: # person, case and incident notes
if not eventkey in ppi: continue
linkid = ppi[eventkey].ID
ppi[eventkey].CallNotes += "\n" + memo
l = asm.Log()
logs.append(l)
l.LogTypeID = 3
l.LinkID = linkid
l.LinkType = 6
l.Date = notedate
if l.Date is None:
l.Date = asm.now()
l.Comments = memo
# Run back through the animals, if we have any that are still
# on shelter after 2 years, add an adoption to an unknown owner
#asm.adopt_older_than(animals, movements, uo.ID, 365*2)
# Now that everything else is done, output stored records
for a in animals:
print(a)
for av in animalvaccinations:
print(av)
for o in owners:
print(o)
for l in logs:
print(l)
for m in movements:
print(m)
for ol in ownerlicences:
print(ol)
for ac in animalcontrol:
print(ac)
for aca in animalcontrolanimals:
print(aca)
asm.stderr_summary(animals=animals, animalvaccinations=animalvaccinations, logs=logs, owners=owners, movements=movements, ownerlicences=ownerlicences, animalcontrol=animalcontrol)
print("DELETE FROM configuration WHERE ItemName LIKE 'DBView%';")
print("COMMIT;")
| if a is None: continue
m = asm.Movement()
m.AnimalID = a.ID
m.OwnerID = to.ID
m.MovementType = 3
m.MovementDate = dispdate
m.Comments = dispmeth
a.Archived = 1
a.ActiveMovementID = m.ID
a.ActiveMovementType = 3
movements.append(m) | conditional_block |
shelterpro_dbf.py | #!/usr/bin/env python3
import asm, datetime, os
"""
Import script for Shelterpro databases in DBF format
Requires my hack to dbfread to support VFP9 -
copy parseC in FieldParser.py and rename it parseV, then remove
encoding so it's just a binary string that can be ignored.
Requires address.dbf, addrlink.dbf, animal.dbf, incident.dbf, license.dbf, note.dbf, person.dbf, shelter.dbf, vacc.dbf
Will also look in PATH/images/IMAGEKEY.[jpg|JPG] for animal photos if available.
29th December, 2016 - 2nd April 2020
"""
PATH = "/home/robin/tmp/asm3_import_data/shelterpro_bc2243"
START_ID = 100
INCIDENT_IMPORT = False
LICENCE_IMPORT = False
PICTURE_IMPORT = True
VACCINATION_IMPORT = True
NOTE_IMPORT = True
SHELTER_IMPORT = True
SEPARATE_ADDRESS_TABLE = True
IMPORT_ANIMALS_WITH_NO_NAME = True
""" when faced with a field type it doesn't understand, dbfread can produce an error
'Unknown field type xx'. This parser returns anything unrecognised as binary data """
class ExtraFieldParser(dbfread.FieldParser):
def parse(self, field, data):
try:
return dbfread.FieldParser.parse(self, field, data)
except ValueError:
return data
def | (name):
return asm.read_dbf(name)
def gettype(animaldes):
spmap = {
"DOG": 2,
"CAT": 11
}
species = animaldes.split(" ")[0]
if species in spmap:
return spmap[species]
else:
return 2
def gettypeletter(aid):
tmap = {
2: "D",
10: "A",
11: "U",
12: "S"
}
return tmap[aid]
def getsize(size):
if size == "VERY":
return 0
elif size == "LARGE":
return 1
elif size == "MEDIUM":
return 2
else:
return 3
def getdateage(age, arrivaldate):
""" Returns a date adjusted for age. Age can be one of
ADULT, PUPPY, KITTEN, SENIOR """
d = arrivaldate
if d == None: d = datetime.datetime.today()
if age == "ADULT":
d = d - datetime.timedelta(days = 365 * 2)
if age == "SENIOR":
d = d - datetime.timedelta(days = 365 * 7)
if age == "KITTEN":
d = d - datetime.timedelta(days = 60)
if age == "PUPPY":
d = d - datetime.timedelta(days = 60)
return d
owners = []
ownerlicences = []
logs = []
movements = []
animals = []
animalvaccinations = []
animalcontrol = []
animalcontrolanimals = []
ppa = {}
ppo = {}
ppi = {}
addresses = {}
addrlink = {}
notes = {}
asm.setid("adoption", START_ID)
asm.setid("animal", START_ID)
asm.setid("animalcontrol", START_ID)
asm.setid("log", START_ID)
asm.setid("owner", START_ID)
if VACCINATION_IMPORT: asm.setid("animalvaccination", START_ID)
if LICENCE_IMPORT: asm.setid("ownerlicence", START_ID)
if PICTURE_IMPORT: asm.setid("media", START_ID)
if PICTURE_IMPORT: asm.setid("dbfs", START_ID)
# Remove existing
print("\\set ON_ERROR_STOP\nBEGIN;")
print("DELETE FROM adoption WHERE ID >= %d AND CreatedBy = 'conversion';" % START_ID)
print("DELETE FROM animal WHERE ID >= %d AND CreatedBy = 'conversion';" % START_ID)
print("DELETE FROM owner WHERE ID >= %d AND CreatedBy = 'conversion';" % START_ID)
if INCIDENT_IMPORT: print("DELETE FROM animalcontrol WHERE ID >= %d AND CreatedBy = 'conversion';" % START_ID)
if VACCINATION_IMPORT: print("DELETE FROM animalvaccination WHERE ID >= %d AND CreatedBy = 'conversion';" % START_ID)
if LICENCE_IMPORT: print("DELETE FROM ownerlicence WHERE ID >= %d AND CreatedBy = 'conversion';" % START_ID)
if PICTURE_IMPORT: print("DELETE FROM media WHERE ID >= %d;" % START_ID)
if PICTURE_IMPORT: print("DELETE FROM dbfs WHERE ID >= %d;" % START_ID)
# Create a transfer owner
to = asm.Owner()
owners.append(to)
to.OwnerSurname = "Other Shelter"
to.OwnerName = to.OwnerSurname
# Create an unknown owner
uo = asm.Owner()
owners.append(uo)
uo.OwnerSurname = "Unknown Owner"
uo.OwnerName = uo.OwnerSurname
# Load up data files
if SEPARATE_ADDRESS_TABLE:
caddress = open_dbf("address")
caddrlink = open_dbf("addrlink")
canimal = open_dbf("animal")
if LICENCE_IMPORT: clicense = open_dbf("license")
cperson = open_dbf("person")
if SHELTER_IMPORT: cshelter = open_dbf("shelter")
if VACCINATION_IMPORT: cvacc = open_dbf("vacc")
if INCIDENT_IMPORT: cincident = open_dbf("incident")
if NOTE_IMPORT: cnote = open_dbf("note")
if PICTURE_IMPORT: cimage = open_dbf("image")
# Addresses if we have a separate file
if SEPARATE_ADDRESS_TABLE:
for row in caddress:
addresses[row["ADDRESSKEY"]] = {
"address": asm.strip(row["ADDRESSSTR"]) + " " + asm.strip(row["ADDRESSST2"]) + " " + asm.strip(row["ADDRESSST3"]),
"city": asm.strip(row["ADDRESSCIT"]),
"state": asm.strip(row["ADDRESSSTA"]),
"zip": asm.strip(row["ADDRESSPOS"])
}
# The link between addresses and people
for row in caddrlink:
addrlink[row["EVENTKEY"]] = row["ADDRLINKAD"]
# People
for row in cperson:
o = asm.Owner()
owners.append(o)
personkey = 0
# Sometimes called UNIQUE
if "PERSONKEY" in row: personkey = row["PERSONKEY"]
elif "UNIQUE" in row: personkey = row["UNIQUE"]
ppo[personkey] = o
o.OwnerForeNames = asm.strip(row["FNAME"])
o.OwnerSurname = asm.strip(row["LNAME"])
o.OwnerName = o.OwnerTitle + " " + o.OwnerForeNames + " " + o.OwnerSurname
# Find the address if it's in a separate table
if SEPARATE_ADDRESS_TABLE:
if personkey in addrlink:
addrkey = addrlink[personkey]
if addrkey in addresses:
add = addresses[addrkey]
o.OwnerAddress = add["address"]
o.OwnerTown = add["city"]
o.OwnerCounty = add["state"]
o.OwnerPostcode = add["zip"]
else:
# Otherwise, address fields are in the person table
o.OwnerAddress = row["ADDR1"].encode("ascii", "xmlcharrefreplace") + "\n" + row["ADDR2"].encode("ascii", "xmlcharrefreplace")
o.OwnerTown = row["CITY"]
o.OwnerCounty = row["STATE"]
o.OwnerPostcode = row["POSTAL_ID"]
if asm.strip(row["EMAIL"]) != "(": o.EmailAddress = asm.strip(row["EMAIL"])
if row["HOME_PH"] != 0: o.HomeTelephone = asm.strip(row["HOME_PH"])
if row["WORK_PH"] != 0: o.WorkTelephone = asm.strip(row["WORK_PH"])
if row["THIRD_PH"] != 0: o.MobileTelephone = asm.strip(row["THIRD_PH"])
o.IsACO = asm.cint(row["ACO_IND"])
o.IsStaff = asm.cint(row["STAFF_IND"])
o.IsVolunteer = asm.cint(row["VOL_IND"])
o.IsDonor = asm.cint(row["DONOR_IND"])
o.IsMember = asm.cint(row["MEMBER_IND"])
o.IsBanned = asm.cint(row["NOADOPT"] == "T" and "1" or "0")
if "FOSTERS" in row: o.IsFosterer = asm.cint(row["FOSTERS"])
# o.ExcludeFromBulkEmail = asm.cint(row["MAILINGSAM"]) # Not sure this is correct
# Animals
for row in canimal:
if not IMPORT_ANIMALS_WITH_NO_NAME and row["PETNAME"].strip() == "": continue
a = asm.Animal()
animals.append(a)
ppa[row["ANIMALKEY"]] = a
a.AnimalTypeID = gettype(row["ANIMLDES"])
a.SpeciesID = asm.species_id_for_name(row["ANIMLDES"].split(" ")[0])
a.AnimalName = asm.strip(row["PETNAME"]).title()
if a.AnimalName.strip() == "":
a.AnimalName = "(unknown)"
age = row["AGE"].split(" ")[0]
added = asm.now()
if "ADDEDDATET" in row and row["ADDEDDATET"] is not None: added = row["ADDEDDATET"]
if "DOB" in row: a.DateOfBirth = row["DOB"]
if a.DateOfBirth is None: a.DateOfBirth = getdateage(age, added)
a.DateBroughtIn = added
a.LastChangedDate = a.DateBroughtIn
a.CreatedDate = a.DateBroughtIn
a.EntryReasonID = 4
a.generateCode(gettypeletter(a.AnimalTypeID))
a.ShortCode = row["ANIMALKEY"]
a.Neutered = asm.cint(row["FIX"])
a.Declawed = asm.cint(row["DECLAWED"])
a.IsNotAvailableForAdoption = 0
a.ShelterLocation = 1
a.Sex = asm.getsex_mf(asm.strip(row["GENDER"]))
a.Size = getsize(asm.strip(row["WEIGHT"]))
a.BaseColourID = asm.colour_id_for_names(asm.strip(row["FURCOLR1"]), asm.strip(row["FURCOLR2"]))
a.IdentichipNumber = asm.strip(row["MICROCHIP"])
if a.IdentichipNumber <> "": a.Identichipped = 1
comments = "Original breed: " + asm.strip(row["BREED1"]) + "/" + asm.strip(row["CROSSBREED"]) + ", age: " + age
comments += ",Color: " + asm.strip(row["FURCOLR1"]) + "/" + asm.strip(row["FURCOLR2"])
comments += ", Coat: " + asm.strip(row["COAT"])
comments += ", Collar: " + asm.strip(row["COLLRTYP"])
a.BreedID = asm.breed_id_for_name(asm.strip(row["BREED1"]))
a.Breed2ID = a.BreedID
a.BreedName = asm.breed_name_for_id(a.BreedID)
if row["PUREBRED"] == "0":
a.Breed2ID = asm.breed_id_for_name(asm.strip(row["CROSSBREED"]))
if a.Breed2ID == 1: a.Breed2ID = 442
a.BreedName = "%s / %s" % ( asm.breed_name_for_id(a.BreedID), asm.breed_name_for_id(a.Breed2ID) )
a.HiddenAnimalDetails = comments
# Make everything non-shelter until it's in the shelter file
a.NonShelterAnimal = 1
a.Archived = 1
# If the row has an original owner
if row["PERSOWNR"] in ppo:
o = ppo[row["PERSOWNR"]]
a.OriginalOwnerID = o.ID
# Shelterpro records Deceased as Status == 2 as far as we can tell
if row["STATUS"] == 2:
a.DeceasedDate = a.DateBroughtIn
a.PTSReasonID = 2 # Died
# Vaccinations
if VACCINATION_IMPORT:
for row in cvacc:
if not row["ANIMALKEY"] in ppa: continue
a = ppa[row["ANIMALKEY"]]
# Each row contains a vaccination
av = asm.AnimalVaccination()
animalvaccinations.append(av)
vaccdate = row["VACCEFFECT"]
if vaccdate is None:
vaccdate = a.DateBroughtIn
av.AnimalID = a.ID
av.VaccinationID = 8
if row["VACCTYPE"].find("DHLPP") != -1: av.VaccinationID = 8
if row["VACCTYPE"].find("BORDETELLA") != -1: av.VaccinationID = 6
if row["VACCTYPE"].find("RABIES") != -1: av.VaccinationID = 4
av.DateRequired = vaccdate
av.DateOfVaccination = vaccdate
av.DateExpires = row["VACCEXPIRA"]
av.Manufacturer = row["VACCMANUFA"]
av.BatchNumber = row["VACCSERIAL"]
av.Comments = "Name: %s, Issue: %s" % (row["VACCDRUGNA"], row["VACCISSUED"])
# Run through the shelter file and create any movements/euthanisation info
if SHELTER_IMPORT:
for row in cshelter:
a = None
if row["ANIMALKEY"] in ppa:
a = ppa[row["ANIMALKEY"]]
arivdate = row["ARIVDATE"]
a.ShortCode = asm.strip(row["ANIMALKEY"])
a.ShelterLocationUnit = asm.strip(row["KENNEL"])
a.NonShelterAnimal = 0
if arivdate is not None:
a.DateBroughtIn = arivdate
a.LastChangedDate = a.DateBroughtIn
a.CreatedDate = a.DateBroughtIn
a.generateCode(gettypeletter(a.AnimalTypeID))
a.ShortCode = asm.strip(row["ANIMALKEY"])
else:
# Couldn't find an animal record, bail
continue
o = None
if row["OWNERATDIS"] in ppo:
o = ppo[row["OWNERATDIS"]]
dispmeth = asm.strip(row["DISPMETH"])
dispdate = row["DISPDATE"]
# Apply other fields
if row["ARIVREAS"] == "QUARANTINE":
a.IsQuarantine = 1
elif row["ARIVREAS"] == "STRAY":
if a.AnimalTypeID == 2: a.AnimalTypeID = 10
if a.AnimalTypeID == 11: a.AnimalTypeID = 12
a.EntryReasonID = 7
# Adoptions
if dispmeth == "ADOPTED":
if a is None or o is None: continue
m = asm.Movement()
m.AnimalID = a.ID
m.OwnerID = o.ID
m.MovementType = 1
m.MovementDate = dispdate
a.Archived = 1
a.ActiveMovementID = m.ID
a.ActiveMovementDate = m.MovementDate
a.ActiveMovementType = 1
movements.append(m)
# Reclaims
elif dispmeth == "RETURN TO OWNER":
if a is None or o is None: continue
m = asm.Movement()
m.AnimalID = a.ID
m.OwnerID = o.ID
m.MovementType = 5
m.MovementDate = dispdate
a.Archived = 1
a.ActiveMovementID = m.ID
a.ActiveMovementDate = m.MovementDate
a.ActiveMovementType = 5
movements.append(m)
# Released or Other
elif dispmeth == "RELEASED" or dispmeth == "OTHER":
if a is None or o is None: continue
m = asm.Movement()
m.AnimalID = a.ID
m.OwnerID = 0
m.MovementType = 7
m.MovementDate = dispdate
m.Comments = dispmeth
a.Archived = 1
a.ActiveMovementDate = m.MovementDate
a.ActiveMovementID = m.ID
a.ActiveMovementType = 7
movements.append(m)
# Holding
elif dispmeth == "" and row["ANIMSTAT"] == "HOLDING":
a.IsHold = 1
a.Archived = 0
# Deceased
elif dispmeth == "DECEASED":
a.DeceasedDate = dispdate
a.PTSReasonID = 2 # Died
a.Archived = 1
# Euthanized
elif dispmeth == "EUTHANIZED":
a.DeceasedDate = dispdate
a.PutToSleep = 1
a.PTSReasonID = 4 # Sick/Injured
a.Archived = 1
# If the outcome is blank, it's on the shelter
elif dispmeth == "":
a.Archived = 0
# It's the name of an organisation that received the animal
else:
if a is None: continue
m = asm.Movement()
m.AnimalID = a.ID
m.OwnerID = to.ID
m.MovementType = 3
m.MovementDate = dispdate
m.Comments = dispmeth
a.Archived = 1
a.ActiveMovementID = m.ID
a.ActiveMovementType = 3
movements.append(m)
if LICENCE_IMPORT:
for row in clicense:
a = None
if row["ANIMALKEY"] in ppa:
a = ppa[row["ANIMALKEY"]]
o = None
if row["LICENSEOWN"] in ppo:
o = ppo[row["LICENSEOWN"]]
if a is not None and o is not None:
if row["LICENSEEFF"] is None:
continue
ol = asm.OwnerLicence()
ownerlicences.append(ol)
ol.AnimalID = a.ID
ol.OwnerID = o.ID
ol.IssueDate = row["LICENSEEFF"]
ol.ExpiryDate = row["LICENSEEXP"]
if ol.ExpiryDate is None: ol.ExpiryDate = ol.IssueDate
ol.LicenceNumber = asm.strip(row["LICENSE"])
ol.LicenceTypeID = 2 # Unaltered dog
if a.Neutered == 1:
ol.LicenceTypeID = 1 # Altered dog
if PICTURE_IMPORT:
for row in cimage:
a = None
if not row["ANIMALKEY"] in ppa:
continue
a = ppa[row["ANIMALKEY"]]
imdata = None
if os.path.exists(PATH + "/images/%s.jpg" % row["IMAGEKEY"]):
f = open(PATH + "/images/%s.jpg" % row["IMAGEKEY"], "rb")
imdata = f.read()
f.close()
if imdata is not None:
asm.animal_image(a.ID, imdata)
# Incidents
if INCIDENT_IMPORT:
for row in cincident:
ac = asm.AnimalControl()
animalcontrol.append(ac)
calldate = row["DATETIMEAS"]
if calldate is None: calldate = row["DATETIMEOR"]
if calldate is None: calldate = asm.now()
ac.CallDateTime = calldate
ac.IncidentDateTime = calldate
ac.DispatchDateTime = calldate
ac.CompletedDate = row["DATETIMEOU"]
if ac.CompletedDate is None: ac.CompletedDate = calldate
if row["CITIZENMAK"] in ppo:
ac.CallerID = ppo[row["CITIZENMAK"]].ID
if row["OWNERATORI"] in ppo:
ac.OwnerID = ppo[row["OWNERATORI"]].ID
ac.IncidentCompletedID = 2
if row["FINALOUTCO"] == "ANIMAL PICKED UP":
ac.IncidentCompletedID = 2
elif row["FINALOUTCO"] == "OTHER":
ac.IncidentCompletedID = 6 # Does not exist in default data
ac.IncidentTypeID = 1
incidentkey = 0
if "INCIDENTKE" in row: incidentkey = row["INCIDENTKE"]
elif "KEY" in row: incidentkey = row["KEY"]
comments = "case: %s\n" % incidentkey
comments += "outcome: %s\n" % asm.strip(row["FINALOUTCO"])
comments += "precinct: %s\n" % asm.strip(row["PRECINCT"])
ac.CallNotes = comments
ac.Sex = 2
if "ANIMALKEY" in row:
if row["ANIMALKEY"] in ppa:
a = ppa[row["ANIMALKEY"]]
animalcontrolanimals.append("INSERT INTO animalcontrolanimal (AnimalControlID, AnimalID) VALUES (%s, %s);" % (ac.ID, a.ID))
# Notes as log entries
if NOTE_IMPORT:
for row in cnote:
eventtype = row["EVENTTYPE"]
eventkey = row["EVENTKEY"]
notedate = row["NOTEDATE"]
memo = row["NOTEMEMO"]
if eventtype in [ 1, 3 ]: # animal/intake or case notes
if not eventkey in ppa: continue
linkid = ppa[eventkey].ID
ppa[eventkey].HiddenAnimalDetails += "\n" + memo
l = asm.Log()
logs.append(l)
l.LogTypeID = 3
l.LinkID = linkid
l.LinkType = 0
l.Date = notedate
if l.Date is None:
l.Date = asm.now()
l.Comments = memo
elif eventtype in [ 2, 5, 10 ]: # person, case and incident notes
if not eventkey in ppi: continue
linkid = ppi[eventkey].ID
ppi[eventkey].CallNotes += "\n" + memo
l = asm.Log()
logs.append(l)
l.LogTypeID = 3
l.LinkID = linkid
l.LinkType = 6
l.Date = notedate
if l.Date is None:
l.Date = asm.now()
l.Comments = memo
# Run back through the animals, if we have any that are still
# on shelter after 2 years, add an adoption to an unknown owner
#asm.adopt_older_than(animals, movements, uo.ID, 365*2)
# Now that everything else is done, output stored records
for a in animals:
print(a)
for av in animalvaccinations:
print(av)
for o in owners:
print(o)
for l in logs:
print(l)
for m in movements:
print(m)
for ol in ownerlicences:
print(ol)
for ac in animalcontrol:
print(ac)
for aca in animalcontrolanimals:
print(aca)
asm.stderr_summary(animals=animals, animalvaccinations=animalvaccinations, logs=logs, owners=owners, movements=movements, ownerlicences=ownerlicences, animalcontrol=animalcontrol)
print("DELETE FROM configuration WHERE ItemName LIKE 'DBView%';")
print("COMMIT;")
| open_dbf | identifier_name |
shelterpro_dbf.py | #!/usr/bin/env python3
import asm, datetime, os
"""
Import script for Shelterpro databases in DBF format
Requires my hack to dbfread to support VFP9 -
copy parseC in FieldParser.py and rename it parseV, then remove
encoding so it's just a binary string that can be ignored.
Requires address.dbf, addrlink.dbf, animal.dbf, incident.dbf, license.dbf, note.dbf, person.dbf, shelter.dbf, vacc.dbf
Will also look in PATH/images/IMAGEKEY.[jpg|JPG] for animal photos if available.
29th December, 2016 - 2nd April 2020
"""
PATH = "/home/robin/tmp/asm3_import_data/shelterpro_bc2243"
START_ID = 100
INCIDENT_IMPORT = False
LICENCE_IMPORT = False
PICTURE_IMPORT = True
VACCINATION_IMPORT = True
NOTE_IMPORT = True
SHELTER_IMPORT = True
SEPARATE_ADDRESS_TABLE = True
IMPORT_ANIMALS_WITH_NO_NAME = True
""" when faced with a field type it doesn't understand, dbfread can produce an error
'Unknown field type xx'. This parser returns anything unrecognised as binary data """
class ExtraFieldParser(dbfread.FieldParser):
def parse(self, field, data):
try:
return dbfread.FieldParser.parse(self, field, data)
except ValueError:
return data
def open_dbf(name):
|
def gettype(animaldes):
spmap = {
"DOG": 2,
"CAT": 11
}
species = animaldes.split(" ")[0]
if species in spmap:
return spmap[species]
else:
return 2
def gettypeletter(aid):
tmap = {
2: "D",
10: "A",
11: "U",
12: "S"
}
return tmap[aid]
def getsize(size):
if size == "VERY":
return 0
elif size == "LARGE":
return 1
elif size == "MEDIUM":
return 2
else:
return 3
def getdateage(age, arrivaldate):
""" Returns a date adjusted for age. Age can be one of
ADULT, PUPPY, KITTEN, SENIOR """
d = arrivaldate
if d == None: d = datetime.datetime.today()
if age == "ADULT":
d = d - datetime.timedelta(days = 365 * 2)
if age == "SENIOR":
d = d - datetime.timedelta(days = 365 * 7)
if age == "KITTEN":
d = d - datetime.timedelta(days = 60)
if age == "PUPPY":
d = d - datetime.timedelta(days = 60)
return d
owners = []
ownerlicences = []
logs = []
movements = []
animals = []
animalvaccinations = []
animalcontrol = []
animalcontrolanimals = []
ppa = {}
ppo = {}
ppi = {}
addresses = {}
addrlink = {}
notes = {}
asm.setid("adoption", START_ID)
asm.setid("animal", START_ID)
asm.setid("animalcontrol", START_ID)
asm.setid("log", START_ID)
asm.setid("owner", START_ID)
if VACCINATION_IMPORT: asm.setid("animalvaccination", START_ID)
if LICENCE_IMPORT: asm.setid("ownerlicence", START_ID)
if PICTURE_IMPORT: asm.setid("media", START_ID)
if PICTURE_IMPORT: asm.setid("dbfs", START_ID)
# Remove existing
print("\\set ON_ERROR_STOP\nBEGIN;")
print("DELETE FROM adoption WHERE ID >= %d AND CreatedBy = 'conversion';" % START_ID)
print("DELETE FROM animal WHERE ID >= %d AND CreatedBy = 'conversion';" % START_ID)
print("DELETE FROM owner WHERE ID >= %d AND CreatedBy = 'conversion';" % START_ID)
if INCIDENT_IMPORT: print("DELETE FROM animalcontrol WHERE ID >= %d AND CreatedBy = 'conversion';" % START_ID)
if VACCINATION_IMPORT: print("DELETE FROM animalvaccination WHERE ID >= %d AND CreatedBy = 'conversion';" % START_ID)
if LICENCE_IMPORT: print("DELETE FROM ownerlicence WHERE ID >= %d AND CreatedBy = 'conversion';" % START_ID)
if PICTURE_IMPORT: print("DELETE FROM media WHERE ID >= %d;" % START_ID)
if PICTURE_IMPORT: print("DELETE FROM dbfs WHERE ID >= %d;" % START_ID)
# Create a transfer owner
to = asm.Owner()
owners.append(to)
to.OwnerSurname = "Other Shelter"
to.OwnerName = to.OwnerSurname
# Create an unknown owner
uo = asm.Owner()
owners.append(uo)
uo.OwnerSurname = "Unknown Owner"
uo.OwnerName = uo.OwnerSurname
# Load up data files
if SEPARATE_ADDRESS_TABLE:
caddress = open_dbf("address")
caddrlink = open_dbf("addrlink")
canimal = open_dbf("animal")
if LICENCE_IMPORT: clicense = open_dbf("license")
cperson = open_dbf("person")
if SHELTER_IMPORT: cshelter = open_dbf("shelter")
if VACCINATION_IMPORT: cvacc = open_dbf("vacc")
if INCIDENT_IMPORT: cincident = open_dbf("incident")
if NOTE_IMPORT: cnote = open_dbf("note")
if PICTURE_IMPORT: cimage = open_dbf("image")
# Addresses if we have a separate file
if SEPARATE_ADDRESS_TABLE:
for row in caddress:
addresses[row["ADDRESSKEY"]] = {
"address": asm.strip(row["ADDRESSSTR"]) + " " + asm.strip(row["ADDRESSST2"]) + " " + asm.strip(row["ADDRESSST3"]),
"city": asm.strip(row["ADDRESSCIT"]),
"state": asm.strip(row["ADDRESSSTA"]),
"zip": asm.strip(row["ADDRESSPOS"])
}
# The link between addresses and people
for row in caddrlink:
addrlink[row["EVENTKEY"]] = row["ADDRLINKAD"]
# People
for row in cperson:
o = asm.Owner()
owners.append(o)
personkey = 0
# Sometimes called UNIQUE
if "PERSONKEY" in row: personkey = row["PERSONKEY"]
elif "UNIQUE" in row: personkey = row["UNIQUE"]
ppo[personkey] = o
o.OwnerForeNames = asm.strip(row["FNAME"])
o.OwnerSurname = asm.strip(row["LNAME"])
o.OwnerName = o.OwnerTitle + " " + o.OwnerForeNames + " " + o.OwnerSurname
# Find the address if it's in a separate table
if SEPARATE_ADDRESS_TABLE:
if personkey in addrlink:
addrkey = addrlink[personkey]
if addrkey in addresses:
add = addresses[addrkey]
o.OwnerAddress = add["address"]
o.OwnerTown = add["city"]
o.OwnerCounty = add["state"]
o.OwnerPostcode = add["zip"]
else:
# Otherwise, address fields are in the person table
o.OwnerAddress = row["ADDR1"].encode("ascii", "xmlcharrefreplace") + "\n" + row["ADDR2"].encode("ascii", "xmlcharrefreplace")
o.OwnerTown = row["CITY"]
o.OwnerCounty = row["STATE"]
o.OwnerPostcode = row["POSTAL_ID"]
if asm.strip(row["EMAIL"]) != "(": o.EmailAddress = asm.strip(row["EMAIL"])
if row["HOME_PH"] != 0: o.HomeTelephone = asm.strip(row["HOME_PH"])
if row["WORK_PH"] != 0: o.WorkTelephone = asm.strip(row["WORK_PH"])
if row["THIRD_PH"] != 0: o.MobileTelephone = asm.strip(row["THIRD_PH"])
o.IsACO = asm.cint(row["ACO_IND"])
o.IsStaff = asm.cint(row["STAFF_IND"])
o.IsVolunteer = asm.cint(row["VOL_IND"])
o.IsDonor = asm.cint(row["DONOR_IND"])
o.IsMember = asm.cint(row["MEMBER_IND"])
o.IsBanned = asm.cint(row["NOADOPT"] == "T" and "1" or "0")
if "FOSTERS" in row: o.IsFosterer = asm.cint(row["FOSTERS"])
# o.ExcludeFromBulkEmail = asm.cint(row["MAILINGSAM"]) # Not sure this is correct
# Animals
for row in canimal:
if not IMPORT_ANIMALS_WITH_NO_NAME and row["PETNAME"].strip() == "": continue
a = asm.Animal()
animals.append(a)
ppa[row["ANIMALKEY"]] = a
a.AnimalTypeID = gettype(row["ANIMLDES"])
a.SpeciesID = asm.species_id_for_name(row["ANIMLDES"].split(" ")[0])
a.AnimalName = asm.strip(row["PETNAME"]).title()
if a.AnimalName.strip() == "":
a.AnimalName = "(unknown)"
age = row["AGE"].split(" ")[0]
added = asm.now()
if "ADDEDDATET" in row and row["ADDEDDATET"] is not None: added = row["ADDEDDATET"]
if "DOB" in row: a.DateOfBirth = row["DOB"]
if a.DateOfBirth is None: a.DateOfBirth = getdateage(age, added)
a.DateBroughtIn = added
a.LastChangedDate = a.DateBroughtIn
a.CreatedDate = a.DateBroughtIn
a.EntryReasonID = 4
a.generateCode(gettypeletter(a.AnimalTypeID))
a.ShortCode = row["ANIMALKEY"]
a.Neutered = asm.cint(row["FIX"])
a.Declawed = asm.cint(row["DECLAWED"])
a.IsNotAvailableForAdoption = 0
a.ShelterLocation = 1
a.Sex = asm.getsex_mf(asm.strip(row["GENDER"]))
a.Size = getsize(asm.strip(row["WEIGHT"]))
a.BaseColourID = asm.colour_id_for_names(asm.strip(row["FURCOLR1"]), asm.strip(row["FURCOLR2"]))
a.IdentichipNumber = asm.strip(row["MICROCHIP"])
if a.IdentichipNumber <> "": a.Identichipped = 1
comments = "Original breed: " + asm.strip(row["BREED1"]) + "/" + asm.strip(row["CROSSBREED"]) + ", age: " + age
comments += ",Color: " + asm.strip(row["FURCOLR1"]) + "/" + asm.strip(row["FURCOLR2"])
comments += ", Coat: " + asm.strip(row["COAT"])
comments += ", Collar: " + asm.strip(row["COLLRTYP"])
a.BreedID = asm.breed_id_for_name(asm.strip(row["BREED1"]))
a.Breed2ID = a.BreedID
a.BreedName = asm.breed_name_for_id(a.BreedID)
if row["PUREBRED"] == "0":
a.Breed2ID = asm.breed_id_for_name(asm.strip(row["CROSSBREED"]))
if a.Breed2ID == 1: a.Breed2ID = 442
a.BreedName = "%s / %s" % ( asm.breed_name_for_id(a.BreedID), asm.breed_name_for_id(a.Breed2ID) )
a.HiddenAnimalDetails = comments
# Make everything non-shelter until it's in the shelter file
a.NonShelterAnimal = 1
a.Archived = 1
# If the row has an original owner
if row["PERSOWNR"] in ppo:
o = ppo[row["PERSOWNR"]]
a.OriginalOwnerID = o.ID
# Shelterpro records Deceased as Status == 2 as far as we can tell
if row["STATUS"] == 2:
a.DeceasedDate = a.DateBroughtIn
a.PTSReasonID = 2 # Died
# Vaccinations
if VACCINATION_IMPORT:
for row in cvacc:
if not row["ANIMALKEY"] in ppa: continue
a = ppa[row["ANIMALKEY"]]
# Each row contains a vaccination
av = asm.AnimalVaccination()
animalvaccinations.append(av)
vaccdate = row["VACCEFFECT"]
if vaccdate is None:
vaccdate = a.DateBroughtIn
av.AnimalID = a.ID
av.VaccinationID = 8
if row["VACCTYPE"].find("DHLPP") != -1: av.VaccinationID = 8
if row["VACCTYPE"].find("BORDETELLA") != -1: av.VaccinationID = 6
if row["VACCTYPE"].find("RABIES") != -1: av.VaccinationID = 4
av.DateRequired = vaccdate
av.DateOfVaccination = vaccdate
av.DateExpires = row["VACCEXPIRA"]
av.Manufacturer = row["VACCMANUFA"]
av.BatchNumber = row["VACCSERIAL"]
av.Comments = "Name: %s, Issue: %s" % (row["VACCDRUGNA"], row["VACCISSUED"])
# Run through the shelter file and create any movements/euthanisation info
if SHELTER_IMPORT:
for row in cshelter:
a = None
if row["ANIMALKEY"] in ppa:
a = ppa[row["ANIMALKEY"]]
arivdate = row["ARIVDATE"]
a.ShortCode = asm.strip(row["ANIMALKEY"])
a.ShelterLocationUnit = asm.strip(row["KENNEL"])
a.NonShelterAnimal = 0
if arivdate is not None:
a.DateBroughtIn = arivdate
a.LastChangedDate = a.DateBroughtIn
a.CreatedDate = a.DateBroughtIn
a.generateCode(gettypeletter(a.AnimalTypeID))
a.ShortCode = asm.strip(row["ANIMALKEY"])
else:
# Couldn't find an animal record, bail
continue
o = None
if row["OWNERATDIS"] in ppo:
o = ppo[row["OWNERATDIS"]]
dispmeth = asm.strip(row["DISPMETH"])
dispdate = row["DISPDATE"]
# Apply other fields
if row["ARIVREAS"] == "QUARANTINE":
a.IsQuarantine = 1
elif row["ARIVREAS"] == "STRAY":
if a.AnimalTypeID == 2: a.AnimalTypeID = 10
if a.AnimalTypeID == 11: a.AnimalTypeID = 12
a.EntryReasonID = 7
# Adoptions
if dispmeth == "ADOPTED":
if a is None or o is None: continue
m = asm.Movement()
m.AnimalID = a.ID
m.OwnerID = o.ID
m.MovementType = 1
m.MovementDate = dispdate
a.Archived = 1
a.ActiveMovementID = m.ID
a.ActiveMovementDate = m.MovementDate
a.ActiveMovementType = 1
movements.append(m)
# Reclaims
elif dispmeth == "RETURN TO OWNER":
if a is None or o is None: continue
m = asm.Movement()
m.AnimalID = a.ID
m.OwnerID = o.ID
m.MovementType = 5
m.MovementDate = dispdate
a.Archived = 1
a.ActiveMovementID = m.ID
a.ActiveMovementDate = m.MovementDate
a.ActiveMovementType = 5
movements.append(m)
# Released or Other
elif dispmeth == "RELEASED" or dispmeth == "OTHER":
if a is None or o is None: continue
m = asm.Movement()
m.AnimalID = a.ID
m.OwnerID = 0
m.MovementType = 7
m.MovementDate = dispdate
m.Comments = dispmeth
a.Archived = 1
a.ActiveMovementDate = m.MovementDate
a.ActiveMovementID = m.ID
a.ActiveMovementType = 7
movements.append(m)
# Holding
elif dispmeth == "" and row["ANIMSTAT"] == "HOLDING":
a.IsHold = 1
a.Archived = 0
# Deceased
elif dispmeth == "DECEASED":
a.DeceasedDate = dispdate
a.PTSReasonID = 2 # Died
a.Archived = 1
# Euthanized
elif dispmeth == "EUTHANIZED":
a.DeceasedDate = dispdate
a.PutToSleep = 1
a.PTSReasonID = 4 # Sick/Injured
a.Archived = 1
# If the outcome is blank, it's on the shelter
elif dispmeth == "":
a.Archived = 0
# It's the name of an organisation that received the animal
else:
if a is None: continue
m = asm.Movement()
m.AnimalID = a.ID
m.OwnerID = to.ID
m.MovementType = 3
m.MovementDate = dispdate
m.Comments = dispmeth
a.Archived = 1
a.ActiveMovementID = m.ID
a.ActiveMovementType = 3
movements.append(m)
if LICENCE_IMPORT:
for row in clicense:
a = None
if row["ANIMALKEY"] in ppa:
a = ppa[row["ANIMALKEY"]]
o = None
if row["LICENSEOWN"] in ppo:
o = ppo[row["LICENSEOWN"]]
if a is not None and o is not None:
if row["LICENSEEFF"] is None:
continue
ol = asm.OwnerLicence()
ownerlicences.append(ol)
ol.AnimalID = a.ID
ol.OwnerID = o.ID
ol.IssueDate = row["LICENSEEFF"]
ol.ExpiryDate = row["LICENSEEXP"]
if ol.ExpiryDate is None: ol.ExpiryDate = ol.IssueDate
ol.LicenceNumber = asm.strip(row["LICENSE"])
ol.LicenceTypeID = 2 # Unaltered dog
if a.Neutered == 1:
ol.LicenceTypeID = 1 # Altered dog
if PICTURE_IMPORT:
for row in cimage:
a = None
if not row["ANIMALKEY"] in ppa:
continue
a = ppa[row["ANIMALKEY"]]
imdata = None
if os.path.exists(PATH + "/images/%s.jpg" % row["IMAGEKEY"]):
f = open(PATH + "/images/%s.jpg" % row["IMAGEKEY"], "rb")
imdata = f.read()
f.close()
if imdata is not None:
asm.animal_image(a.ID, imdata)
# Incidents
if INCIDENT_IMPORT:
for row in cincident:
ac = asm.AnimalControl()
animalcontrol.append(ac)
calldate = row["DATETIMEAS"]
if calldate is None: calldate = row["DATETIMEOR"]
if calldate is None: calldate = asm.now()
ac.CallDateTime = calldate
ac.IncidentDateTime = calldate
ac.DispatchDateTime = calldate
ac.CompletedDate = row["DATETIMEOU"]
if ac.CompletedDate is None: ac.CompletedDate = calldate
if row["CITIZENMAK"] in ppo:
ac.CallerID = ppo[row["CITIZENMAK"]].ID
if row["OWNERATORI"] in ppo:
ac.OwnerID = ppo[row["OWNERATORI"]].ID
ac.IncidentCompletedID = 2
if row["FINALOUTCO"] == "ANIMAL PICKED UP":
ac.IncidentCompletedID = 2
elif row["FINALOUTCO"] == "OTHER":
ac.IncidentCompletedID = 6 # Does not exist in default data
ac.IncidentTypeID = 1
incidentkey = 0
if "INCIDENTKE" in row: incidentkey = row["INCIDENTKE"]
elif "KEY" in row: incidentkey = row["KEY"]
comments = "case: %s\n" % incidentkey
comments += "outcome: %s\n" % asm.strip(row["FINALOUTCO"])
comments += "precinct: %s\n" % asm.strip(row["PRECINCT"])
ac.CallNotes = comments
ac.Sex = 2
if "ANIMALKEY" in row:
if row["ANIMALKEY"] in ppa:
a = ppa[row["ANIMALKEY"]]
animalcontrolanimals.append("INSERT INTO animalcontrolanimal (AnimalControlID, AnimalID) VALUES (%s, %s);" % (ac.ID, a.ID))
# Notes as log entries
if NOTE_IMPORT:
for row in cnote:
eventtype = row["EVENTTYPE"]
eventkey = row["EVENTKEY"]
notedate = row["NOTEDATE"]
memo = row["NOTEMEMO"]
if eventtype in [ 1, 3 ]: # animal/intake or case notes
if not eventkey in ppa: continue
linkid = ppa[eventkey].ID
ppa[eventkey].HiddenAnimalDetails += "\n" + memo
l = asm.Log()
logs.append(l)
l.LogTypeID = 3
l.LinkID = linkid
l.LinkType = 0
l.Date = notedate
if l.Date is None:
l.Date = asm.now()
l.Comments = memo
elif eventtype in [ 2, 5, 10 ]: # person, case and incident notes
if not eventkey in ppi: continue
linkid = ppi[eventkey].ID
ppi[eventkey].CallNotes += "\n" + memo
l = asm.Log()
logs.append(l)
l.LogTypeID = 3
l.LinkID = linkid
l.LinkType = 6
l.Date = notedate
if l.Date is None:
l.Date = asm.now()
l.Comments = memo
# Run back through the animals, if we have any that are still
# on shelter after 2 years, add an adoption to an unknown owner
#asm.adopt_older_than(animals, movements, uo.ID, 365*2)
# Now that everything else is done, output stored records
for a in animals:
print(a)
for av in animalvaccinations:
print(av)
for o in owners:
print(o)
for l in logs:
print(l)
for m in movements:
print(m)
for ol in ownerlicences:
print(ol)
for ac in animalcontrol:
print(ac)
for aca in animalcontrolanimals:
print(aca)
asm.stderr_summary(animals=animals, animalvaccinations=animalvaccinations, logs=logs, owners=owners, movements=movements, ownerlicences=ownerlicences, animalcontrol=animalcontrol)
print("DELETE FROM configuration WHERE ItemName LIKE 'DBView%';")
print("COMMIT;")
| return asm.read_dbf(name) | identifier_body |
cabi_mips.rs | // Copyright 2012-2013 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
#![allow(non_uppercase_pattern_statics)]
use libc::c_uint;
use std::cmp;
use llvm;
use llvm::{Integer, Pointer, Float, Double, Struct, Array};
use llvm::{StructRetAttribute, ZExtAttribute};
use middle::trans::cabi::{ArgType, FnType};
use middle::trans::context::CrateContext;
use middle::trans::type_::Type;
fn align_up_to(off: uint, a: uint) -> uint {
return (off + a - 1u) / a * a;
}
fn align(off: uint, ty: Type) -> uint {
let a = ty_align(ty);
return align_up_to(off, a);
}
fn ty_align(ty: Type) -> uint |
fn ty_size(ty: Type) -> uint {
match ty.kind() {
Integer => {
unsafe {
((llvm::LLVMGetIntTypeWidth(ty.to_ref()) as uint) + 7) / 8
}
}
Pointer => 4,
Float => 4,
Double => 8,
Struct => {
if ty.is_packed() {
let str_tys = ty.field_types();
str_tys.iter().fold(0, |s, t| s + ty_size(*t))
} else {
let str_tys = ty.field_types();
let size = str_tys.iter().fold(0, |s, t| align(s, *t) + ty_size(*t));
align(size, ty)
}
}
Array => {
let len = ty.array_length();
let elt = ty.element_type();
let eltsz = ty_size(elt);
len * eltsz
}
_ => fail!("ty_size: unhandled type")
}
}
fn classify_ret_ty(ccx: &CrateContext, ty: Type) -> ArgType {
if is_reg_ty(ty) {
let attr = if ty == Type::i1(ccx) { Some(ZExtAttribute) } else { None };
ArgType::direct(ty, None, None, attr)
} else {
ArgType::indirect(ty, Some(StructRetAttribute))
}
}
fn classify_arg_ty(ccx: &CrateContext, ty: Type, offset: &mut uint) -> ArgType {
let orig_offset = *offset;
let size = ty_size(ty) * 8;
let mut align = ty_align(ty);
align = cmp::min(cmp::max(align, 4), 8);
*offset = align_up_to(*offset, align);
*offset += align_up_to(size, align * 8) / 8;
if is_reg_ty(ty) {
let attr = if ty == Type::i1(ccx) { Some(ZExtAttribute) } else { None };
ArgType::direct(ty, None, None, attr)
} else {
ArgType::direct(
ty,
Some(struct_ty(ccx, ty)),
padding_ty(ccx, align, orig_offset),
None
)
}
}
fn is_reg_ty(ty: Type) -> bool {
return match ty.kind() {
Integer
| Pointer
| Float
| Double => true,
_ => false
};
}
fn padding_ty(ccx: &CrateContext, align: uint, offset: uint) -> Option<Type> {
if ((align - 1 ) & offset) > 0 {
Some(Type::i32(ccx))
} else {
None
}
}
fn coerce_to_int(ccx: &CrateContext, size: uint) -> Vec<Type> {
let int_ty = Type::i32(ccx);
let mut args = Vec::new();
let mut n = size / 32;
while n > 0 {
args.push(int_ty);
n -= 1;
}
let r = size % 32;
if r > 0 {
unsafe {
args.push(Type::from_ref(llvm::LLVMIntTypeInContext(ccx.llcx, r as c_uint)));
}
}
args
}
fn struct_ty(ccx: &CrateContext, ty: Type) -> Type {
let size = ty_size(ty) * 8;
Type::struct_(ccx, coerce_to_int(ccx, size).as_slice(), false)
}
pub fn compute_abi_info(ccx: &CrateContext,
atys: &[Type],
rty: Type,
ret_def: bool) -> FnType {
let ret_ty = if ret_def {
classify_ret_ty(ccx, rty)
} else {
ArgType::direct(Type::void(ccx), None, None, None)
};
let sret = ret_ty.is_indirect();
let mut arg_tys = Vec::new();
let mut offset = if sret { 4 } else { 0 };
for aty in atys.iter() {
let ty = classify_arg_ty(ccx, *aty, &mut offset);
arg_tys.push(ty);
};
return FnType {
arg_tys: arg_tys,
ret_ty: ret_ty,
};
}
| {
match ty.kind() {
Integer => {
unsafe {
((llvm::LLVMGetIntTypeWidth(ty.to_ref()) as uint) + 7) / 8
}
}
Pointer => 4,
Float => 4,
Double => 8,
Struct => {
if ty.is_packed() {
1
} else {
let str_tys = ty.field_types();
str_tys.iter().fold(1, |a, t| cmp::max(a, ty_align(*t)))
}
}
Array => {
let elt = ty.element_type();
ty_align(elt)
}
_ => fail!("ty_size: unhandled type")
}
} | identifier_body |
cabi_mips.rs | // Copyright 2012-2013 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
#![allow(non_uppercase_pattern_statics)]
use libc::c_uint;
use std::cmp;
use llvm;
use llvm::{Integer, Pointer, Float, Double, Struct, Array};
use llvm::{StructRetAttribute, ZExtAttribute};
use middle::trans::cabi::{ArgType, FnType};
use middle::trans::context::CrateContext;
use middle::trans::type_::Type;
fn align_up_to(off: uint, a: uint) -> uint {
return (off + a - 1u) / a * a;
}
fn align(off: uint, ty: Type) -> uint {
let a = ty_align(ty);
return align_up_to(off, a); | unsafe {
((llvm::LLVMGetIntTypeWidth(ty.to_ref()) as uint) + 7) / 8
}
}
Pointer => 4,
Float => 4,
Double => 8,
Struct => {
if ty.is_packed() {
1
} else {
let str_tys = ty.field_types();
str_tys.iter().fold(1, |a, t| cmp::max(a, ty_align(*t)))
}
}
Array => {
let elt = ty.element_type();
ty_align(elt)
}
_ => fail!("ty_size: unhandled type")
}
}
fn ty_size(ty: Type) -> uint {
match ty.kind() {
Integer => {
unsafe {
((llvm::LLVMGetIntTypeWidth(ty.to_ref()) as uint) + 7) / 8
}
}
Pointer => 4,
Float => 4,
Double => 8,
Struct => {
if ty.is_packed() {
let str_tys = ty.field_types();
str_tys.iter().fold(0, |s, t| s + ty_size(*t))
} else {
let str_tys = ty.field_types();
let size = str_tys.iter().fold(0, |s, t| align(s, *t) + ty_size(*t));
align(size, ty)
}
}
Array => {
let len = ty.array_length();
let elt = ty.element_type();
let eltsz = ty_size(elt);
len * eltsz
}
_ => fail!("ty_size: unhandled type")
}
}
fn classify_ret_ty(ccx: &CrateContext, ty: Type) -> ArgType {
if is_reg_ty(ty) {
let attr = if ty == Type::i1(ccx) { Some(ZExtAttribute) } else { None };
ArgType::direct(ty, None, None, attr)
} else {
ArgType::indirect(ty, Some(StructRetAttribute))
}
}
fn classify_arg_ty(ccx: &CrateContext, ty: Type, offset: &mut uint) -> ArgType {
let orig_offset = *offset;
let size = ty_size(ty) * 8;
let mut align = ty_align(ty);
align = cmp::min(cmp::max(align, 4), 8);
*offset = align_up_to(*offset, align);
*offset += align_up_to(size, align * 8) / 8;
if is_reg_ty(ty) {
let attr = if ty == Type::i1(ccx) { Some(ZExtAttribute) } else { None };
ArgType::direct(ty, None, None, attr)
} else {
ArgType::direct(
ty,
Some(struct_ty(ccx, ty)),
padding_ty(ccx, align, orig_offset),
None
)
}
}
fn is_reg_ty(ty: Type) -> bool {
return match ty.kind() {
Integer
| Pointer
| Float
| Double => true,
_ => false
};
}
fn padding_ty(ccx: &CrateContext, align: uint, offset: uint) -> Option<Type> {
if ((align - 1 ) & offset) > 0 {
Some(Type::i32(ccx))
} else {
None
}
}
fn coerce_to_int(ccx: &CrateContext, size: uint) -> Vec<Type> {
let int_ty = Type::i32(ccx);
let mut args = Vec::new();
let mut n = size / 32;
while n > 0 {
args.push(int_ty);
n -= 1;
}
let r = size % 32;
if r > 0 {
unsafe {
args.push(Type::from_ref(llvm::LLVMIntTypeInContext(ccx.llcx, r as c_uint)));
}
}
args
}
fn struct_ty(ccx: &CrateContext, ty: Type) -> Type {
let size = ty_size(ty) * 8;
Type::struct_(ccx, coerce_to_int(ccx, size).as_slice(), false)
}
pub fn compute_abi_info(ccx: &CrateContext,
atys: &[Type],
rty: Type,
ret_def: bool) -> FnType {
let ret_ty = if ret_def {
classify_ret_ty(ccx, rty)
} else {
ArgType::direct(Type::void(ccx), None, None, None)
};
let sret = ret_ty.is_indirect();
let mut arg_tys = Vec::new();
let mut offset = if sret { 4 } else { 0 };
for aty in atys.iter() {
let ty = classify_arg_ty(ccx, *aty, &mut offset);
arg_tys.push(ty);
};
return FnType {
arg_tys: arg_tys,
ret_ty: ret_ty,
};
} | }
fn ty_align(ty: Type) -> uint {
match ty.kind() {
Integer => { | random_line_split |
cabi_mips.rs | // Copyright 2012-2013 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
#![allow(non_uppercase_pattern_statics)]
use libc::c_uint;
use std::cmp;
use llvm;
use llvm::{Integer, Pointer, Float, Double, Struct, Array};
use llvm::{StructRetAttribute, ZExtAttribute};
use middle::trans::cabi::{ArgType, FnType};
use middle::trans::context::CrateContext;
use middle::trans::type_::Type;
fn align_up_to(off: uint, a: uint) -> uint {
return (off + a - 1u) / a * a;
}
fn align(off: uint, ty: Type) -> uint {
let a = ty_align(ty);
return align_up_to(off, a);
}
fn ty_align(ty: Type) -> uint {
match ty.kind() {
Integer => {
unsafe {
((llvm::LLVMGetIntTypeWidth(ty.to_ref()) as uint) + 7) / 8
}
}
Pointer => 4,
Float => 4,
Double => 8,
Struct => {
if ty.is_packed() {
1
} else {
let str_tys = ty.field_types();
str_tys.iter().fold(1, |a, t| cmp::max(a, ty_align(*t)))
}
}
Array => {
let elt = ty.element_type();
ty_align(elt)
}
_ => fail!("ty_size: unhandled type")
}
}
fn ty_size(ty: Type) -> uint {
match ty.kind() {
Integer => {
unsafe {
((llvm::LLVMGetIntTypeWidth(ty.to_ref()) as uint) + 7) / 8
}
}
Pointer => 4,
Float => 4,
Double => 8,
Struct => {
if ty.is_packed() {
let str_tys = ty.field_types();
str_tys.iter().fold(0, |s, t| s + ty_size(*t))
} else {
let str_tys = ty.field_types();
let size = str_tys.iter().fold(0, |s, t| align(s, *t) + ty_size(*t));
align(size, ty)
}
}
Array => {
let len = ty.array_length();
let elt = ty.element_type();
let eltsz = ty_size(elt);
len * eltsz
}
_ => fail!("ty_size: unhandled type")
}
}
fn classify_ret_ty(ccx: &CrateContext, ty: Type) -> ArgType {
if is_reg_ty(ty) {
let attr = if ty == Type::i1(ccx) { Some(ZExtAttribute) } else { None };
ArgType::direct(ty, None, None, attr)
} else {
ArgType::indirect(ty, Some(StructRetAttribute))
}
}
fn classify_arg_ty(ccx: &CrateContext, ty: Type, offset: &mut uint) -> ArgType {
let orig_offset = *offset;
let size = ty_size(ty) * 8;
let mut align = ty_align(ty);
align = cmp::min(cmp::max(align, 4), 8);
*offset = align_up_to(*offset, align);
*offset += align_up_to(size, align * 8) / 8;
if is_reg_ty(ty) {
let attr = if ty == Type::i1(ccx) { Some(ZExtAttribute) } else { None };
ArgType::direct(ty, None, None, attr)
} else {
ArgType::direct(
ty,
Some(struct_ty(ccx, ty)),
padding_ty(ccx, align, orig_offset),
None
)
}
}
fn is_reg_ty(ty: Type) -> bool {
return match ty.kind() {
Integer
| Pointer
| Float
| Double => true,
_ => false
};
}
fn padding_ty(ccx: &CrateContext, align: uint, offset: uint) -> Option<Type> {
if ((align - 1 ) & offset) > 0 {
Some(Type::i32(ccx))
} else {
None
}
}
fn coerce_to_int(ccx: &CrateContext, size: uint) -> Vec<Type> {
let int_ty = Type::i32(ccx);
let mut args = Vec::new();
let mut n = size / 32;
while n > 0 {
args.push(int_ty);
n -= 1;
}
let r = size % 32;
if r > 0 {
unsafe {
args.push(Type::from_ref(llvm::LLVMIntTypeInContext(ccx.llcx, r as c_uint)));
}
}
args
}
fn | (ccx: &CrateContext, ty: Type) -> Type {
let size = ty_size(ty) * 8;
Type::struct_(ccx, coerce_to_int(ccx, size).as_slice(), false)
}
pub fn compute_abi_info(ccx: &CrateContext,
atys: &[Type],
rty: Type,
ret_def: bool) -> FnType {
let ret_ty = if ret_def {
classify_ret_ty(ccx, rty)
} else {
ArgType::direct(Type::void(ccx), None, None, None)
};
let sret = ret_ty.is_indirect();
let mut arg_tys = Vec::new();
let mut offset = if sret { 4 } else { 0 };
for aty in atys.iter() {
let ty = classify_arg_ty(ccx, *aty, &mut offset);
arg_tys.push(ty);
};
return FnType {
arg_tys: arg_tys,
ret_ty: ret_ty,
};
}
| struct_ty | identifier_name |
evaluate-senna-hash-2-pos-chunk-128-64-rmsprop5.py | '''
evaluate result
'''
from keras.models import load_model
from keras.utils import np_utils
import numpy as np
import os
import sys
# add path
sys.path.append('../')
sys.path.append('../tools')
from tools import conf
from tools import load_data
from tools import prepare
# input sentence dimensions
step_length = conf.ner_step_length
pos_length = conf.ner_pos_length
chunk_length = conf.ner_chunk_length
# gazetteer_length = conf.gazetteer_length
IOB = conf.ner_BIOES_decode
data = sys.argv[1]
best_epoch = sys.argv[2]
if data=="dev":
test_data = load_data.load_ner(dataset='eng.testa', form='BIOES')
elif data == "test":
test_data = load_data.load_ner(dataset='eng.testb', form='BIOES')
tokens = [len(x[0]) for x in test_data]
print(sum(tokens))
print('%s shape:'%data, len(test_data))
model_name = os.path.basename(__file__)[9:-3]
folder_path = './model/%s'%model_name
model_path = '%s/model_epoch_%s.h5'%(folder_path, best_epoch)
result = open('%s/predict.txt'%folder_path, 'w')
def convert(chunktags):
# convert BIOES to BIO
|
print('loading model...')
model = load_model(model_path)
print('loading model finished.')
for each in test_data:
embed_index, hash_index, pos, chunk, label, length, sentence = prepare.prepare_ner(batch=[each], gram='bi', form='BIOES')
pos = np.array([(np.concatenate([np_utils.to_categorical(p, pos_length), np.zeros((step_length-length[l], pos_length))])) for l,p in enumerate(pos)])
chunk = np.array([(np.concatenate([np_utils.to_categorical(c, chunk_length), np.zeros((step_length-length[l], chunk_length))])) for l,c in enumerate(chunk)])
prob = model.predict_on_batch([embed_index, hash_index, pos, chunk])
for i, l in enumerate(length):
predict_label = np_utils.categorical_probas_to_classes(prob[i])
chunktags = [IOB[j] for j in predict_label][:l]
word_pos_chunk = list(zip(*each))
# convert
word_pos_chunk = list(zip(*word_pos_chunk))
word_pos_chunk = [list(x) for x in word_pos_chunk]
# if data == "test":
# word_pos_chunk[3] = convert(word_pos_chunk[3])
word_pos_chunk = list(zip(*word_pos_chunk))
#convert
# if data == "test":
# chunktags = convert(chunktags)
# chunktags = prepare.gazetteer_lookup(each[0], chunktags, data)
for ind, chunktag in enumerate(chunktags):
result.write(' '.join(word_pos_chunk[ind])+' '+chunktag+'\n')
result.write('\n')
result.close()
print('epoch %s predict over !'%best_epoch)
os.system('../tools/conlleval < %s/predict.txt'%folder_path)
| for p, q in enumerate(chunktags):
if q.startswith("E-"):
chunktags[p] = "I-" + q[2:]
elif q.startswith("S-"):
if p==0:
chunktags[p] = "I-" + q[2:]
elif q[2:]==chunktags[p-1][2:]:
chunktags[p] = "B-" + q[2:]
elif q[2:]!=chunktags[p-1][2:]:
chunktags[p] = "I-" + q[2:]
elif q.startswith("B-"):
if p==0:
chunktags[p] = "I-" + q[2:]
else:
if q[2:]!=chunktags[p-1][2:]:
chunktags[p] = "I-" + q[2:]
return chunktags | identifier_body |
evaluate-senna-hash-2-pos-chunk-128-64-rmsprop5.py | '''
evaluate result
'''
from keras.models import load_model
from keras.utils import np_utils
import numpy as np
import os
import sys
# add path
sys.path.append('../')
sys.path.append('../tools')
from tools import conf
from tools import load_data
from tools import prepare
# input sentence dimensions
step_length = conf.ner_step_length
pos_length = conf.ner_pos_length
chunk_length = conf.ner_chunk_length
# gazetteer_length = conf.gazetteer_length
IOB = conf.ner_BIOES_decode
data = sys.argv[1]
best_epoch = sys.argv[2]
if data=="dev":
test_data = load_data.load_ner(dataset='eng.testa', form='BIOES')
elif data == "test":
test_data = load_data.load_ner(dataset='eng.testb', form='BIOES')
tokens = [len(x[0]) for x in test_data]
print(sum(tokens))
print('%s shape:'%data, len(test_data))
model_name = os.path.basename(__file__)[9:-3]
folder_path = './model/%s'%model_name
model_path = '%s/model_epoch_%s.h5'%(folder_path, best_epoch)
result = open('%s/predict.txt'%folder_path, 'w')
def | (chunktags):
# convert BIOES to BIO
for p, q in enumerate(chunktags):
if q.startswith("E-"):
chunktags[p] = "I-" + q[2:]
elif q.startswith("S-"):
if p==0:
chunktags[p] = "I-" + q[2:]
elif q[2:]==chunktags[p-1][2:]:
chunktags[p] = "B-" + q[2:]
elif q[2:]!=chunktags[p-1][2:]:
chunktags[p] = "I-" + q[2:]
elif q.startswith("B-"):
if p==0:
chunktags[p] = "I-" + q[2:]
else:
if q[2:]!=chunktags[p-1][2:]:
chunktags[p] = "I-" + q[2:]
return chunktags
print('loading model...')
model = load_model(model_path)
print('loading model finished.')
for each in test_data:
embed_index, hash_index, pos, chunk, label, length, sentence = prepare.prepare_ner(batch=[each], gram='bi', form='BIOES')
pos = np.array([(np.concatenate([np_utils.to_categorical(p, pos_length), np.zeros((step_length-length[l], pos_length))])) for l,p in enumerate(pos)])
chunk = np.array([(np.concatenate([np_utils.to_categorical(c, chunk_length), np.zeros((step_length-length[l], chunk_length))])) for l,c in enumerate(chunk)])
prob = model.predict_on_batch([embed_index, hash_index, pos, chunk])
for i, l in enumerate(length):
predict_label = np_utils.categorical_probas_to_classes(prob[i])
chunktags = [IOB[j] for j in predict_label][:l]
word_pos_chunk = list(zip(*each))
# convert
word_pos_chunk = list(zip(*word_pos_chunk))
word_pos_chunk = [list(x) for x in word_pos_chunk]
# if data == "test":
# word_pos_chunk[3] = convert(word_pos_chunk[3])
word_pos_chunk = list(zip(*word_pos_chunk))
#convert
# if data == "test":
# chunktags = convert(chunktags)
# chunktags = prepare.gazetteer_lookup(each[0], chunktags, data)
for ind, chunktag in enumerate(chunktags):
result.write(' '.join(word_pos_chunk[ind])+' '+chunktag+'\n')
result.write('\n')
result.close()
print('epoch %s predict over !'%best_epoch)
os.system('../tools/conlleval < %s/predict.txt'%folder_path)
| convert | identifier_name |
evaluate-senna-hash-2-pos-chunk-128-64-rmsprop5.py | '''
evaluate result
'''
from keras.models import load_model
from keras.utils import np_utils
import numpy as np
import os
import sys
# add path
sys.path.append('../')
sys.path.append('../tools')
from tools import conf
from tools import load_data
from tools import prepare
# input sentence dimensions
step_length = conf.ner_step_length
pos_length = conf.ner_pos_length | data = sys.argv[1]
best_epoch = sys.argv[2]
if data=="dev":
test_data = load_data.load_ner(dataset='eng.testa', form='BIOES')
elif data == "test":
test_data = load_data.load_ner(dataset='eng.testb', form='BIOES')
tokens = [len(x[0]) for x in test_data]
print(sum(tokens))
print('%s shape:'%data, len(test_data))
model_name = os.path.basename(__file__)[9:-3]
folder_path = './model/%s'%model_name
model_path = '%s/model_epoch_%s.h5'%(folder_path, best_epoch)
result = open('%s/predict.txt'%folder_path, 'w')
def convert(chunktags):
# convert BIOES to BIO
for p, q in enumerate(chunktags):
if q.startswith("E-"):
chunktags[p] = "I-" + q[2:]
elif q.startswith("S-"):
if p==0:
chunktags[p] = "I-" + q[2:]
elif q[2:]==chunktags[p-1][2:]:
chunktags[p] = "B-" + q[2:]
elif q[2:]!=chunktags[p-1][2:]:
chunktags[p] = "I-" + q[2:]
elif q.startswith("B-"):
if p==0:
chunktags[p] = "I-" + q[2:]
else:
if q[2:]!=chunktags[p-1][2:]:
chunktags[p] = "I-" + q[2:]
return chunktags
print('loading model...')
model = load_model(model_path)
print('loading model finished.')
for each in test_data:
embed_index, hash_index, pos, chunk, label, length, sentence = prepare.prepare_ner(batch=[each], gram='bi', form='BIOES')
pos = np.array([(np.concatenate([np_utils.to_categorical(p, pos_length), np.zeros((step_length-length[l], pos_length))])) for l,p in enumerate(pos)])
chunk = np.array([(np.concatenate([np_utils.to_categorical(c, chunk_length), np.zeros((step_length-length[l], chunk_length))])) for l,c in enumerate(chunk)])
prob = model.predict_on_batch([embed_index, hash_index, pos, chunk])
for i, l in enumerate(length):
predict_label = np_utils.categorical_probas_to_classes(prob[i])
chunktags = [IOB[j] for j in predict_label][:l]
word_pos_chunk = list(zip(*each))
# convert
word_pos_chunk = list(zip(*word_pos_chunk))
word_pos_chunk = [list(x) for x in word_pos_chunk]
# if data == "test":
# word_pos_chunk[3] = convert(word_pos_chunk[3])
word_pos_chunk = list(zip(*word_pos_chunk))
#convert
# if data == "test":
# chunktags = convert(chunktags)
# chunktags = prepare.gazetteer_lookup(each[0], chunktags, data)
for ind, chunktag in enumerate(chunktags):
result.write(' '.join(word_pos_chunk[ind])+' '+chunktag+'\n')
result.write('\n')
result.close()
print('epoch %s predict over !'%best_epoch)
os.system('../tools/conlleval < %s/predict.txt'%folder_path) | chunk_length = conf.ner_chunk_length
# gazetteer_length = conf.gazetteer_length
IOB = conf.ner_BIOES_decode
| random_line_split |
evaluate-senna-hash-2-pos-chunk-128-64-rmsprop5.py | '''
evaluate result
'''
from keras.models import load_model
from keras.utils import np_utils
import numpy as np
import os
import sys
# add path
sys.path.append('../')
sys.path.append('../tools')
from tools import conf
from tools import load_data
from tools import prepare
# input sentence dimensions
step_length = conf.ner_step_length
pos_length = conf.ner_pos_length
chunk_length = conf.ner_chunk_length
# gazetteer_length = conf.gazetteer_length
IOB = conf.ner_BIOES_decode
data = sys.argv[1]
best_epoch = sys.argv[2]
if data=="dev":
test_data = load_data.load_ner(dataset='eng.testa', form='BIOES')
elif data == "test":
test_data = load_data.load_ner(dataset='eng.testb', form='BIOES')
tokens = [len(x[0]) for x in test_data]
print(sum(tokens))
print('%s shape:'%data, len(test_data))
model_name = os.path.basename(__file__)[9:-3]
folder_path = './model/%s'%model_name
model_path = '%s/model_epoch_%s.h5'%(folder_path, best_epoch)
result = open('%s/predict.txt'%folder_path, 'w')
def convert(chunktags):
# convert BIOES to BIO
for p, q in enumerate(chunktags):
if q.startswith("E-"):
chunktags[p] = "I-" + q[2:]
elif q.startswith("S-"):
if p==0:
chunktags[p] = "I-" + q[2:]
elif q[2:]==chunktags[p-1][2:]:
chunktags[p] = "B-" + q[2:]
elif q[2:]!=chunktags[p-1][2:]:
chunktags[p] = "I-" + q[2:]
elif q.startswith("B-"):
if p==0:
chunktags[p] = "I-" + q[2:]
else:
if q[2:]!=chunktags[p-1][2:]:
chunktags[p] = "I-" + q[2:]
return chunktags
print('loading model...')
model = load_model(model_path)
print('loading model finished.')
for each in test_data:
|
result.close()
print('epoch %s predict over !'%best_epoch)
os.system('../tools/conlleval < %s/predict.txt'%folder_path)
| embed_index, hash_index, pos, chunk, label, length, sentence = prepare.prepare_ner(batch=[each], gram='bi', form='BIOES')
pos = np.array([(np.concatenate([np_utils.to_categorical(p, pos_length), np.zeros((step_length-length[l], pos_length))])) for l,p in enumerate(pos)])
chunk = np.array([(np.concatenate([np_utils.to_categorical(c, chunk_length), np.zeros((step_length-length[l], chunk_length))])) for l,c in enumerate(chunk)])
prob = model.predict_on_batch([embed_index, hash_index, pos, chunk])
for i, l in enumerate(length):
predict_label = np_utils.categorical_probas_to_classes(prob[i])
chunktags = [IOB[j] for j in predict_label][:l]
word_pos_chunk = list(zip(*each))
# convert
word_pos_chunk = list(zip(*word_pos_chunk))
word_pos_chunk = [list(x) for x in word_pos_chunk]
# if data == "test":
# word_pos_chunk[3] = convert(word_pos_chunk[3])
word_pos_chunk = list(zip(*word_pos_chunk))
#convert
# if data == "test":
# chunktags = convert(chunktags)
# chunktags = prepare.gazetteer_lookup(each[0], chunktags, data)
for ind, chunktag in enumerate(chunktags):
result.write(' '.join(word_pos_chunk[ind])+' '+chunktag+'\n')
result.write('\n') | conditional_block |
part14.rs | // Rust-101, Part 14: Slices, Arrays, External Dependencies
// ========================================================
// ## Slices
pub fn sort<T: PartialOrd>(data: &mut [T]) {
if data.len() < 2 { return; }
// We decide that the element at 0 is our pivot, and then we move our cursors through the rest of the slice,
// making sure that everything on the left is no larger than the pivot, and everything on the right is no smaller.
let mut lpos = 1;
let mut rpos = data.len();
/* Invariant: pivot is data[0]; everything with index (0,lpos) is <= pivot;
[rpos,len) is >= pivot; lpos < rpos */
loop {
// **Exercise 14.1**: Complete this Quicksort loop. You can use `swap` on slices to swap two elements. Write a
// test function for `sort`.
unimplemented!()
}
// Once our cursors met, we need to put the pivot in the right place.
data.swap(0, lpos-1);
// Finally, we split our slice to sort the two halves. The nice part about slices is that splitting them is cheap:
let (part1, part2) = data.split_at_mut(lpos);
unimplemented!()
}
// **Exercise 14.2**: Since `String` implements `PartialEq`, you can now change the function `output_lines` in the previous part
// to call the sort function above. If you did exercise 13.1, you will have slightly more work. Make sure you sort by the matched line
// only, not by filename or line number!
// Now, we can sort, e.g., an vector of numbers.
fn sort_nums(data: &mut Vec<i32>) {
sort(&mut data[..]);
}
// ## Arrays
fn sort_array() {
let mut array_of_data: [f64; 5] = [1.0, 3.4, 12.7, -9.12, 0.1];
sort(&mut array_of_data);
}
// ## External Dependencies
// I disabled the following module (using a rather bad hack), because it only compiles if `docopt` is linked.
// Remove the attribute of the `rgrep` module to enable compilation.
#[cfg(feature = "disabled")]
pub mod rgrep {
// Now that `docopt` is linked, we can first add it to the namespace with `extern crate` and then import shorter names with `use`.
// We also import some other pieces that we will need.
extern crate docopt;
use self::docopt::Docopt;
use part13::{run, Options, OutputMode};
use std::process;
// The `USAGE` string documents how the program is to be called. It's written in a format that `docopt` can parse.
static USAGE: &'static str = "
Usage: rgrep [-c] [-s] <pattern> <file>...
Options:
-c, --count Count number of matching lines (rather than printing them).
-s, --sort Sort the lines before printing.
";
// This function extracts the rgrep options from the command-line arguments.
fn get_options() -> Options {
// This parses `argv` and exit the program with an error message if it fails. The code is taken from the [`docopt` documentation](http://burntsushi.net/rustdoc/docopt/). <br/>
let args = Docopt::new(USAGE).and_then(|d| d.parse()).unwrap_or_else(|e| e.exit());
// Now we can get all the values out.
let count = args.get_bool("-c");
let sort = args.get_bool("-s");
let pattern = args.get_str("<pattern>");
let files = args.get_vec("<file>");
if count && sort {
println!("Setting both '-c' and '-s' at the same time does not make any sense.");
process::exit(1);
}
// We need to make the strings owned to construct the `Options` instance.
let mode = if count {
OutputMode::Count
} else if sort | else {
OutputMode::Print
};
Options {
files: files.iter().map(|file| file.to_string()).collect(),
pattern: pattern.to_string(),
output_mode: mode,
}
}
// Finally, we can call the `run` function from the previous part on the options extracted using `get_options`. Edit `main.rs` to call this function.
// You can now use `cargo run -- <pattern> <files>` to call your program, and see the argument parser and the threads we wrote previously in action!
pub fn main() {
unimplemented!()
}
}
// **Exercise 14.3**: Wouldn't it be nice if rgrep supported regular expressions? There's already a crate that does all the parsing and matching on regular
// expression, it's called [regex](https://crates.io/crates/regex). Add this crate to the dependencies of your workspace, add an option ("-r") to switch
// the pattern to regular-expression mode, and change `filter_lines` to honor this option. The documentation of regex is available from its crates.io site.
// (You won't be able to use the `regex!` macro if you are on the stable or beta channel of Rust. But it wouldn't help for our use-case anyway.)
| {
OutputMode::SortAndPrint
} | conditional_block |
part14.rs | // Rust-101, Part 14: Slices, Arrays, External Dependencies
// ========================================================
// ## Slices
pub fn sort<T: PartialOrd>(data: &mut [T]) {
if data.len() < 2 { return; }
// We decide that the element at 0 is our pivot, and then we move our cursors through the rest of the slice,
// making sure that everything on the left is no larger than the pivot, and everything on the right is no smaller.
let mut lpos = 1;
let mut rpos = data.len();
/* Invariant: pivot is data[0]; everything with index (0,lpos) is <= pivot;
[rpos,len) is >= pivot; lpos < rpos */
loop {
// **Exercise 14.1**: Complete this Quicksort loop. You can use `swap` on slices to swap two elements. Write a
// test function for `sort`.
unimplemented!()
}
// Once our cursors met, we need to put the pivot in the right place.
data.swap(0, lpos-1);
// Finally, we split our slice to sort the two halves. The nice part about slices is that splitting them is cheap:
let (part1, part2) = data.split_at_mut(lpos);
unimplemented!()
}
// **Exercise 14.2**: Since `String` implements `PartialEq`, you can now change the function `output_lines` in the previous part
// to call the sort function above. If you did exercise 13.1, you will have slightly more work. Make sure you sort by the matched line
// only, not by filename or line number!
// Now, we can sort, e.g., an vector of numbers.
fn sort_nums(data: &mut Vec<i32>) {
sort(&mut data[..]);
}
// ## Arrays
fn sort_array() {
let mut array_of_data: [f64; 5] = [1.0, 3.4, 12.7, -9.12, 0.1];
sort(&mut array_of_data);
}
// ## External Dependencies
// I disabled the following module (using a rather bad hack), because it only compiles if `docopt` is linked.
// Remove the attribute of the `rgrep` module to enable compilation.
#[cfg(feature = "disabled")]
pub mod rgrep {
// Now that `docopt` is linked, we can first add it to the namespace with `extern crate` and then import shorter names with `use`.
// We also import some other pieces that we will need.
extern crate docopt;
use self::docopt::Docopt;
use part13::{run, Options, OutputMode};
use std::process;
// The `USAGE` string documents how the program is to be called. It's written in a format that `docopt` can parse.
static USAGE: &'static str = "
Usage: rgrep [-c] [-s] <pattern> <file>...
Options:
-c, --count Count number of matching lines (rather than printing them).
-s, --sort Sort the lines before printing.
";
// This function extracts the rgrep options from the command-line arguments.
fn get_options() -> Options {
// This parses `argv` and exit the program with an error message if it fails. The code is taken from the [`docopt` documentation](http://burntsushi.net/rustdoc/docopt/). <br/>
let args = Docopt::new(USAGE).and_then(|d| d.parse()).unwrap_or_else(|e| e.exit());
// Now we can get all the values out.
let count = args.get_bool("-c");
let sort = args.get_bool("-s");
let pattern = args.get_str("<pattern>");
let files = args.get_vec("<file>");
if count && sort {
println!("Setting both '-c' and '-s' at the same time does not make any sense.");
process::exit(1);
}
// We need to make the strings owned to construct the `Options` instance.
let mode = if count {
OutputMode::Count
} else if sort {
OutputMode::SortAndPrint
} else {
OutputMode::Print
};
Options {
files: files.iter().map(|file| file.to_string()).collect(),
pattern: pattern.to_string(),
output_mode: mode,
}
}
// Finally, we can call the `run` function from the previous part on the options extracted using `get_options`. Edit `main.rs` to call this function.
// You can now use `cargo run -- <pattern> <files>` to call your program, and see the argument parser and the threads we wrote previously in action!
pub fn main() |
}
// **Exercise 14.3**: Wouldn't it be nice if rgrep supported regular expressions? There's already a crate that does all the parsing and matching on regular
// expression, it's called [regex](https://crates.io/crates/regex). Add this crate to the dependencies of your workspace, add an option ("-r") to switch
// the pattern to regular-expression mode, and change `filter_lines` to honor this option. The documentation of regex is available from its crates.io site.
// (You won't be able to use the `regex!` macro if you are on the stable or beta channel of Rust. But it wouldn't help for our use-case anyway.)
| {
unimplemented!()
} | identifier_body |
part14.rs | // Rust-101, Part 14: Slices, Arrays, External Dependencies
// ========================================================
// ## Slices
pub fn sort<T: PartialOrd>(data: &mut [T]) {
if data.len() < 2 { return; }
// We decide that the element at 0 is our pivot, and then we move our cursors through the rest of the slice,
// making sure that everything on the left is no larger than the pivot, and everything on the right is no smaller.
let mut lpos = 1;
let mut rpos = data.len();
/* Invariant: pivot is data[0]; everything with index (0,lpos) is <= pivot;
[rpos,len) is >= pivot; lpos < rpos */
loop {
// **Exercise 14.1**: Complete this Quicksort loop. You can use `swap` on slices to swap two elements. Write a
// test function for `sort`.
unimplemented!()
}
// Once our cursors met, we need to put the pivot in the right place.
data.swap(0, lpos-1);
// Finally, we split our slice to sort the two halves. The nice part about slices is that splitting them is cheap:
let (part1, part2) = data.split_at_mut(lpos);
unimplemented!()
}
// **Exercise 14.2**: Since `String` implements `PartialEq`, you can now change the function `output_lines` in the previous part
// to call the sort function above. If you did exercise 13.1, you will have slightly more work. Make sure you sort by the matched line
// only, not by filename or line number!
// Now, we can sort, e.g., an vector of numbers.
fn sort_nums(data: &mut Vec<i32>) {
sort(&mut data[..]);
}
// ## Arrays
fn sort_array() {
let mut array_of_data: [f64; 5] = [1.0, 3.4, 12.7, -9.12, 0.1];
sort(&mut array_of_data);
}
// ## External Dependencies
// I disabled the following module (using a rather bad hack), because it only compiles if `docopt` is linked.
// Remove the attribute of the `rgrep` module to enable compilation.
#[cfg(feature = "disabled")]
pub mod rgrep {
// Now that `docopt` is linked, we can first add it to the namespace with `extern crate` and then import shorter names with `use`.
// We also import some other pieces that we will need.
extern crate docopt;
use self::docopt::Docopt;
use part13::{run, Options, OutputMode};
use std::process;
// The `USAGE` string documents how the program is to be called. It's written in a format that `docopt` can parse.
static USAGE: &'static str = "
Usage: rgrep [-c] [-s] <pattern> <file>...
Options:
-c, --count Count number of matching lines (rather than printing them).
-s, --sort Sort the lines before printing.
";
// This function extracts the rgrep options from the command-line arguments.
fn get_options() -> Options {
// This parses `argv` and exit the program with an error message if it fails. The code is taken from the [`docopt` documentation](http://burntsushi.net/rustdoc/docopt/). <br/>
let args = Docopt::new(USAGE).and_then(|d| d.parse()).unwrap_or_else(|e| e.exit());
// Now we can get all the values out.
let count = args.get_bool("-c");
let sort = args.get_bool("-s");
let pattern = args.get_str("<pattern>");
let files = args.get_vec("<file>");
if count && sort {
println!("Setting both '-c' and '-s' at the same time does not make any sense.");
process::exit(1);
}
| let mode = if count {
OutputMode::Count
} else if sort {
OutputMode::SortAndPrint
} else {
OutputMode::Print
};
Options {
files: files.iter().map(|file| file.to_string()).collect(),
pattern: pattern.to_string(),
output_mode: mode,
}
}
// Finally, we can call the `run` function from the previous part on the options extracted using `get_options`. Edit `main.rs` to call this function.
// You can now use `cargo run -- <pattern> <files>` to call your program, and see the argument parser and the threads we wrote previously in action!
pub fn main() {
unimplemented!()
}
}
// **Exercise 14.3**: Wouldn't it be nice if rgrep supported regular expressions? There's already a crate that does all the parsing and matching on regular
// expression, it's called [regex](https://crates.io/crates/regex). Add this crate to the dependencies of your workspace, add an option ("-r") to switch
// the pattern to regular-expression mode, and change `filter_lines` to honor this option. The documentation of regex is available from its crates.io site.
// (You won't be able to use the `regex!` macro if you are on the stable or beta channel of Rust. But it wouldn't help for our use-case anyway.) | // We need to make the strings owned to construct the `Options` instance. | random_line_split |
part14.rs | // Rust-101, Part 14: Slices, Arrays, External Dependencies
// ========================================================
// ## Slices
pub fn sort<T: PartialOrd>(data: &mut [T]) {
if data.len() < 2 { return; }
// We decide that the element at 0 is our pivot, and then we move our cursors through the rest of the slice,
// making sure that everything on the left is no larger than the pivot, and everything on the right is no smaller.
let mut lpos = 1;
let mut rpos = data.len();
/* Invariant: pivot is data[0]; everything with index (0,lpos) is <= pivot;
[rpos,len) is >= pivot; lpos < rpos */
loop {
// **Exercise 14.1**: Complete this Quicksort loop. You can use `swap` on slices to swap two elements. Write a
// test function for `sort`.
unimplemented!()
}
// Once our cursors met, we need to put the pivot in the right place.
data.swap(0, lpos-1);
// Finally, we split our slice to sort the two halves. The nice part about slices is that splitting them is cheap:
let (part1, part2) = data.split_at_mut(lpos);
unimplemented!()
}
// **Exercise 14.2**: Since `String` implements `PartialEq`, you can now change the function `output_lines` in the previous part
// to call the sort function above. If you did exercise 13.1, you will have slightly more work. Make sure you sort by the matched line
// only, not by filename or line number!
// Now, we can sort, e.g., an vector of numbers.
fn sort_nums(data: &mut Vec<i32>) {
sort(&mut data[..]);
}
// ## Arrays
fn | () {
let mut array_of_data: [f64; 5] = [1.0, 3.4, 12.7, -9.12, 0.1];
sort(&mut array_of_data);
}
// ## External Dependencies
// I disabled the following module (using a rather bad hack), because it only compiles if `docopt` is linked.
// Remove the attribute of the `rgrep` module to enable compilation.
#[cfg(feature = "disabled")]
pub mod rgrep {
// Now that `docopt` is linked, we can first add it to the namespace with `extern crate` and then import shorter names with `use`.
// We also import some other pieces that we will need.
extern crate docopt;
use self::docopt::Docopt;
use part13::{run, Options, OutputMode};
use std::process;
// The `USAGE` string documents how the program is to be called. It's written in a format that `docopt` can parse.
static USAGE: &'static str = "
Usage: rgrep [-c] [-s] <pattern> <file>...
Options:
-c, --count Count number of matching lines (rather than printing them).
-s, --sort Sort the lines before printing.
";
// This function extracts the rgrep options from the command-line arguments.
fn get_options() -> Options {
// This parses `argv` and exit the program with an error message if it fails. The code is taken from the [`docopt` documentation](http://burntsushi.net/rustdoc/docopt/). <br/>
let args = Docopt::new(USAGE).and_then(|d| d.parse()).unwrap_or_else(|e| e.exit());
// Now we can get all the values out.
let count = args.get_bool("-c");
let sort = args.get_bool("-s");
let pattern = args.get_str("<pattern>");
let files = args.get_vec("<file>");
if count && sort {
println!("Setting both '-c' and '-s' at the same time does not make any sense.");
process::exit(1);
}
// We need to make the strings owned to construct the `Options` instance.
let mode = if count {
OutputMode::Count
} else if sort {
OutputMode::SortAndPrint
} else {
OutputMode::Print
};
Options {
files: files.iter().map(|file| file.to_string()).collect(),
pattern: pattern.to_string(),
output_mode: mode,
}
}
// Finally, we can call the `run` function from the previous part on the options extracted using `get_options`. Edit `main.rs` to call this function.
// You can now use `cargo run -- <pattern> <files>` to call your program, and see the argument parser and the threads we wrote previously in action!
pub fn main() {
unimplemented!()
}
}
// **Exercise 14.3**: Wouldn't it be nice if rgrep supported regular expressions? There's already a crate that does all the parsing and matching on regular
// expression, it's called [regex](https://crates.io/crates/regex). Add this crate to the dependencies of your workspace, add an option ("-r") to switch
// the pattern to regular-expression mode, and change `filter_lines` to honor this option. The documentation of regex is available from its crates.io site.
// (You won't be able to use the `regex!` macro if you are on the stable or beta channel of Rust. But it wouldn't help for our use-case anyway.)
| sort_array | identifier_name |
TwitterWebPart.ts | import { Version } from '@microsoft/sp-core-library';
import {
BaseClientSideWebPart,
IPropertyPaneConfiguration,
PropertyPaneTextField
} from '@microsoft/sp-webpart-base';
import { escape } from '@microsoft/sp-lodash-subset';
import styles from './TwitterWebPart.module.scss';
import * as strings from 'TwitterWebPartStrings';
import { SPComponentLoader } from '@microsoft/sp-loader';
export interface ITwitterWebPartProps {
screenname: string;
}
export default class TwitterWebPartWebPart extends BaseClientSideWebPart<ITwitterWebPartProps> {
public constructor() {
super();
SPComponentLoader.loadScript("/scripts/widgets.js");
}
public render(): void {
this.domElement.innerHTML = `
<div class="${styles.twitter}">
<div class="${styles.container}">
<div class="ms-Grid-row ms-bgColor-themeDark ms-fontColor-white ${styles.row}">
<div class="ms-Grid-col ms-lg10 ms-xl8 ms-xlPush2 ms-lgPush1">
<a class="twitter-timeline"
href="https://twitter.com/${escape(this.properties.screenname)}">
Tweets by @${escape(this.properties.screenname)}
</a>
</div>
</div>
</div>
</div>`;
}
protected get dataVersion(): Version |
protected getPropertyPaneConfiguration(): IPropertyPaneConfiguration {
return {
pages: [
{
header: {
description: strings.PropertyPaneDescription
},
groups: [
{
groupName: strings.BasicGroupName,
groupFields: [
PropertyPaneTextField('screenname', {
label: 'Screenname'
})
]
}
]
}
]
};
}
}
| {
return Version.parse('1.0');
} | identifier_body |
TwitterWebPart.ts | import { Version } from '@microsoft/sp-core-library';
import {
BaseClientSideWebPart,
IPropertyPaneConfiguration,
PropertyPaneTextField
} from '@microsoft/sp-webpart-base';
import { escape } from '@microsoft/sp-lodash-subset';
import styles from './TwitterWebPart.module.scss';
import * as strings from 'TwitterWebPartStrings';
import { SPComponentLoader } from '@microsoft/sp-loader';
export interface ITwitterWebPartProps {
screenname: string;
}
export default class TwitterWebPartWebPart extends BaseClientSideWebPart<ITwitterWebPartProps> {
public constructor() {
super();
SPComponentLoader.loadScript("/scripts/widgets.js");
}
| public render(): void {
this.domElement.innerHTML = `
<div class="${styles.twitter}">
<div class="${styles.container}">
<div class="ms-Grid-row ms-bgColor-themeDark ms-fontColor-white ${styles.row}">
<div class="ms-Grid-col ms-lg10 ms-xl8 ms-xlPush2 ms-lgPush1">
<a class="twitter-timeline"
href="https://twitter.com/${escape(this.properties.screenname)}">
Tweets by @${escape(this.properties.screenname)}
</a>
</div>
</div>
</div>
</div>`;
}
protected get dataVersion(): Version {
return Version.parse('1.0');
}
protected getPropertyPaneConfiguration(): IPropertyPaneConfiguration {
return {
pages: [
{
header: {
description: strings.PropertyPaneDescription
},
groups: [
{
groupName: strings.BasicGroupName,
groupFields: [
PropertyPaneTextField('screenname', {
label: 'Screenname'
})
]
}
]
}
]
};
}
} | random_line_split | |
TwitterWebPart.ts | import { Version } from '@microsoft/sp-core-library';
import {
BaseClientSideWebPart,
IPropertyPaneConfiguration,
PropertyPaneTextField
} from '@microsoft/sp-webpart-base';
import { escape } from '@microsoft/sp-lodash-subset';
import styles from './TwitterWebPart.module.scss';
import * as strings from 'TwitterWebPartStrings';
import { SPComponentLoader } from '@microsoft/sp-loader';
export interface ITwitterWebPartProps {
screenname: string;
}
export default class TwitterWebPartWebPart extends BaseClientSideWebPart<ITwitterWebPartProps> {
public constructor() {
super();
SPComponentLoader.loadScript("/scripts/widgets.js");
}
public render(): void {
this.domElement.innerHTML = `
<div class="${styles.twitter}">
<div class="${styles.container}">
<div class="ms-Grid-row ms-bgColor-themeDark ms-fontColor-white ${styles.row}">
<div class="ms-Grid-col ms-lg10 ms-xl8 ms-xlPush2 ms-lgPush1">
<a class="twitter-timeline"
href="https://twitter.com/${escape(this.properties.screenname)}">
Tweets by @${escape(this.properties.screenname)}
</a>
</div>
</div>
</div>
</div>`;
}
protected get | (): Version {
return Version.parse('1.0');
}
protected getPropertyPaneConfiguration(): IPropertyPaneConfiguration {
return {
pages: [
{
header: {
description: strings.PropertyPaneDescription
},
groups: [
{
groupName: strings.BasicGroupName,
groupFields: [
PropertyPaneTextField('screenname', {
label: 'Screenname'
})
]
}
]
}
]
};
}
}
| dataVersion | identifier_name |
php.js | define(["exports"], function (_exports) {
"use strict";
Object.defineProperty(_exports, "__esModule", {
value: true
});
_exports.phpLang = phpLang;
function phpLang(hljs) {
var VARIABLE = {
begin: "\\$+[a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]*"
};
var PREPROCESSOR = {
className: "meta",
begin: /<\?(php)?|\?>/
};
var STRING = {
className: "string",
contains: [hljs.BACKSLASH_ESCAPE, PREPROCESSOR],
variants: [{
begin: 'b"',
end: '"'
}, {
begin: "b'", | illegal: null
})]
};
var NUMBER = {
variants: [hljs.BINARY_NUMBER_MODE, hljs.C_NUMBER_MODE]
};
return {
aliases: ["php", "php3", "php4", "php5", "php6", "php7"],
case_insensitive: true,
keywords: "and include_once list abstract global private echo interface as static endswitch " + "array null if endwhile or const for endforeach self var while isset public " + "protected exit foreach throw elseif include __FILE__ empty require_once do xor " + "return parent clone use __CLASS__ __LINE__ else break print eval new " + "catch __METHOD__ case exception default die require __FUNCTION__ " + "enddeclare final try switch continue endfor endif declare unset true false " + "trait goto instanceof insteadof __DIR__ __NAMESPACE__ " + "yield finally",
contains: [hljs.HASH_COMMENT_MODE, hljs.COMMENT("//", "$", {
contains: [PREPROCESSOR]
}), hljs.COMMENT("/\\*", "\\*/", {
contains: [{
className: "doctag",
begin: "@[A-Za-z]+"
}]
}), hljs.COMMENT("__halt_compiler.+?;", false, {
endsWithParent: true,
keywords: "__halt_compiler",
lexemes: hljs.UNDERSCORE_IDENT_RE
}), {
className: "string",
begin: /<<<['"]?\w+['"]?$/,
end: /^\w+;?$/,
contains: [hljs.BACKSLASH_ESCAPE, {
className: "subst",
variants: [{
begin: /\$\w+/
}, {
begin: /\{\$/,
end: /\}/
}]
}]
}, PREPROCESSOR, {
className: "keyword",
begin: /\$this\b/
}, VARIABLE, {
// swallow composed identifiers to avoid parsing them as keywords
begin: /(::|->)+[a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]*/
}, {
className: "function",
beginKeywords: "function",
end: /[;{]/,
excludeEnd: true,
illegal: "\\$|\\[|%",
contains: [hljs.UNDERSCORE_TITLE_MODE, {
className: "params",
begin: "\\(",
end: "\\)",
contains: ["self", VARIABLE, hljs.C_BLOCK_COMMENT_MODE, STRING, NUMBER]
}]
}, {
className: "class",
beginKeywords: "class interface",
end: "{",
excludeEnd: true,
illegal: /[:\(\$"]/,
contains: [{
beginKeywords: "extends implements"
}, hljs.UNDERSCORE_TITLE_MODE]
}, {
beginKeywords: "namespace",
end: ";",
illegal: /[\.']/,
contains: [hljs.UNDERSCORE_TITLE_MODE]
}, {
beginKeywords: "use",
end: ";",
contains: [hljs.UNDERSCORE_TITLE_MODE]
}, {
begin: "=>" // No markup, just a relevance booster
}, STRING, NUMBER]
};
}
}); | end: "'"
}, hljs.inherit(hljs.APOS_STRING_MODE, {
illegal: null
}), hljs.inherit(hljs.QUOTE_STRING_MODE, { | random_line_split |
php.js | define(["exports"], function (_exports) {
"use strict";
Object.defineProperty(_exports, "__esModule", {
value: true
});
_exports.phpLang = phpLang;
function | (hljs) {
var VARIABLE = {
begin: "\\$+[a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]*"
};
var PREPROCESSOR = {
className: "meta",
begin: /<\?(php)?|\?>/
};
var STRING = {
className: "string",
contains: [hljs.BACKSLASH_ESCAPE, PREPROCESSOR],
variants: [{
begin: 'b"',
end: '"'
}, {
begin: "b'",
end: "'"
}, hljs.inherit(hljs.APOS_STRING_MODE, {
illegal: null
}), hljs.inherit(hljs.QUOTE_STRING_MODE, {
illegal: null
})]
};
var NUMBER = {
variants: [hljs.BINARY_NUMBER_MODE, hljs.C_NUMBER_MODE]
};
return {
aliases: ["php", "php3", "php4", "php5", "php6", "php7"],
case_insensitive: true,
keywords: "and include_once list abstract global private echo interface as static endswitch " + "array null if endwhile or const for endforeach self var while isset public " + "protected exit foreach throw elseif include __FILE__ empty require_once do xor " + "return parent clone use __CLASS__ __LINE__ else break print eval new " + "catch __METHOD__ case exception default die require __FUNCTION__ " + "enddeclare final try switch continue endfor endif declare unset true false " + "trait goto instanceof insteadof __DIR__ __NAMESPACE__ " + "yield finally",
contains: [hljs.HASH_COMMENT_MODE, hljs.COMMENT("//", "$", {
contains: [PREPROCESSOR]
}), hljs.COMMENT("/\\*", "\\*/", {
contains: [{
className: "doctag",
begin: "@[A-Za-z]+"
}]
}), hljs.COMMENT("__halt_compiler.+?;", false, {
endsWithParent: true,
keywords: "__halt_compiler",
lexemes: hljs.UNDERSCORE_IDENT_RE
}), {
className: "string",
begin: /<<<['"]?\w+['"]?$/,
end: /^\w+;?$/,
contains: [hljs.BACKSLASH_ESCAPE, {
className: "subst",
variants: [{
begin: /\$\w+/
}, {
begin: /\{\$/,
end: /\}/
}]
}]
}, PREPROCESSOR, {
className: "keyword",
begin: /\$this\b/
}, VARIABLE, {
// swallow composed identifiers to avoid parsing them as keywords
begin: /(::|->)+[a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]*/
}, {
className: "function",
beginKeywords: "function",
end: /[;{]/,
excludeEnd: true,
illegal: "\\$|\\[|%",
contains: [hljs.UNDERSCORE_TITLE_MODE, {
className: "params",
begin: "\\(",
end: "\\)",
contains: ["self", VARIABLE, hljs.C_BLOCK_COMMENT_MODE, STRING, NUMBER]
}]
}, {
className: "class",
beginKeywords: "class interface",
end: "{",
excludeEnd: true,
illegal: /[:\(\$"]/,
contains: [{
beginKeywords: "extends implements"
}, hljs.UNDERSCORE_TITLE_MODE]
}, {
beginKeywords: "namespace",
end: ";",
illegal: /[\.']/,
contains: [hljs.UNDERSCORE_TITLE_MODE]
}, {
beginKeywords: "use",
end: ";",
contains: [hljs.UNDERSCORE_TITLE_MODE]
}, {
begin: "=>" // No markup, just a relevance booster
}, STRING, NUMBER]
};
}
}); | phpLang | identifier_name |
php.js | define(["exports"], function (_exports) {
"use strict";
Object.defineProperty(_exports, "__esModule", {
value: true
});
_exports.phpLang = phpLang;
function phpLang(hljs) |
}); | {
var VARIABLE = {
begin: "\\$+[a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]*"
};
var PREPROCESSOR = {
className: "meta",
begin: /<\?(php)?|\?>/
};
var STRING = {
className: "string",
contains: [hljs.BACKSLASH_ESCAPE, PREPROCESSOR],
variants: [{
begin: 'b"',
end: '"'
}, {
begin: "b'",
end: "'"
}, hljs.inherit(hljs.APOS_STRING_MODE, {
illegal: null
}), hljs.inherit(hljs.QUOTE_STRING_MODE, {
illegal: null
})]
};
var NUMBER = {
variants: [hljs.BINARY_NUMBER_MODE, hljs.C_NUMBER_MODE]
};
return {
aliases: ["php", "php3", "php4", "php5", "php6", "php7"],
case_insensitive: true,
keywords: "and include_once list abstract global private echo interface as static endswitch " + "array null if endwhile or const for endforeach self var while isset public " + "protected exit foreach throw elseif include __FILE__ empty require_once do xor " + "return parent clone use __CLASS__ __LINE__ else break print eval new " + "catch __METHOD__ case exception default die require __FUNCTION__ " + "enddeclare final try switch continue endfor endif declare unset true false " + "trait goto instanceof insteadof __DIR__ __NAMESPACE__ " + "yield finally",
contains: [hljs.HASH_COMMENT_MODE, hljs.COMMENT("//", "$", {
contains: [PREPROCESSOR]
}), hljs.COMMENT("/\\*", "\\*/", {
contains: [{
className: "doctag",
begin: "@[A-Za-z]+"
}]
}), hljs.COMMENT("__halt_compiler.+?;", false, {
endsWithParent: true,
keywords: "__halt_compiler",
lexemes: hljs.UNDERSCORE_IDENT_RE
}), {
className: "string",
begin: /<<<['"]?\w+['"]?$/,
end: /^\w+;?$/,
contains: [hljs.BACKSLASH_ESCAPE, {
className: "subst",
variants: [{
begin: /\$\w+/
}, {
begin: /\{\$/,
end: /\}/
}]
}]
}, PREPROCESSOR, {
className: "keyword",
begin: /\$this\b/
}, VARIABLE, {
// swallow composed identifiers to avoid parsing them as keywords
begin: /(::|->)+[a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]*/
}, {
className: "function",
beginKeywords: "function",
end: /[;{]/,
excludeEnd: true,
illegal: "\\$|\\[|%",
contains: [hljs.UNDERSCORE_TITLE_MODE, {
className: "params",
begin: "\\(",
end: "\\)",
contains: ["self", VARIABLE, hljs.C_BLOCK_COMMENT_MODE, STRING, NUMBER]
}]
}, {
className: "class",
beginKeywords: "class interface",
end: "{",
excludeEnd: true,
illegal: /[:\(\$"]/,
contains: [{
beginKeywords: "extends implements"
}, hljs.UNDERSCORE_TITLE_MODE]
}, {
beginKeywords: "namespace",
end: ";",
illegal: /[\.']/,
contains: [hljs.UNDERSCORE_TITLE_MODE]
}, {
beginKeywords: "use",
end: ";",
contains: [hljs.UNDERSCORE_TITLE_MODE]
}, {
begin: "=>" // No markup, just a relevance booster
}, STRING, NUMBER]
};
} | identifier_body |
tests.js | /* global describe, beforeEach, it */
import { expect } from "chai";
import { shouldOpenInNewTab } from "./utils";
describe("app/lib/utils:shouldOpenInNewTab", () => {
let mockClickEvent;
beforeEach(() => {
mockClickEvent = { | });
it("should default to false", () => {
expect(shouldOpenInNewTab(mockClickEvent)).to.be.false;
});
it("should return true when ctrl-clicked", () => {
mockClickEvent.ctrlKey = true;
expect(shouldOpenInNewTab(mockClickEvent)).to.be.true;
});
it("should return true when cmd-clicked", () => {
mockClickEvent.metaKey = true;
expect(shouldOpenInNewTab(mockClickEvent)).to.be.true;
});
it("should return false for non-click events", () => {
mockClickEvent.type = "keypress";
expect(shouldOpenInNewTab(mockClickEvent)).to.be.false;
});
it("should return true for middle clicks", () => {
mockClickEvent.button = 1;
expect(shouldOpenInNewTab(mockClickEvent)).to.be.true;
});
it("should return false for right clicks", () => {
mockClickEvent.button = 2;
expect(shouldOpenInNewTab(mockClickEvent)).to.be.false;
});
}); | ctrlKey: false,
metaKey: false,
type: "click",
button: 0
}; | random_line_split |
edl-split.js | function convertEdl() {
var join = document.getElementById("join").checked;
var stills = document.getElementById("stills").checked;
var crop = document.getElementById("crop").checked;
var input = document.getElementById("input").value;
var frames = [];
var pat = /C +(\d+)/g;
var match = pat.exec(input);
while (match != null) {
frames.push(match[1]);
match = pat.exec(input);
}
var output = "";
for (var i = 0; i < frames.length; i++) {
if (join) {
output += "c" + i + "=";
} else {
output += "#~ ";
}
output += "Trim(" + frames[i] + ", ";
if (stills) {
output += "-1)";
} else if (i < (frames.length - 1)) {
output += frames[i + 1] + "-1)";
} else {
output += "0)";
}
if (crop) {
output += ".crop(0,0,0,0)";
}
output += "\n";
}
if (join) {
output += "\n";
for (var i = 0; i < frames.length; i++) {
if (i % 10 === 0 && i !== 0) { | output += "c" + i;
} else {
output += "+c" + i;
}
}
}
document.getElementById("output").value = output;
} | output += "\n\\";
}
if (i === 0) { | random_line_split |
edl-split.js | function convertEdl() | {
var join = document.getElementById("join").checked;
var stills = document.getElementById("stills").checked;
var crop = document.getElementById("crop").checked;
var input = document.getElementById("input").value;
var frames = [];
var pat = /C +(\d+)/g;
var match = pat.exec(input);
while (match != null) {
frames.push(match[1]);
match = pat.exec(input);
}
var output = "";
for (var i = 0; i < frames.length; i++) {
if (join) {
output += "c" + i + "=";
} else {
output += "#~ ";
}
output += "Trim(" + frames[i] + ", ";
if (stills) {
output += "-1)";
} else if (i < (frames.length - 1)) {
output += frames[i + 1] + "-1)";
} else {
output += "0)";
}
if (crop) {
output += ".crop(0,0,0,0)";
}
output += "\n";
}
if (join) {
output += "\n";
for (var i = 0; i < frames.length; i++) {
if (i % 10 === 0 && i !== 0) {
output += "\n\\";
}
if (i === 0) {
output += "c" + i;
} else {
output += "+c" + i;
}
}
}
document.getElementById("output").value = output;
} | identifier_body | |
edl-split.js | function convertEdl() {
var join = document.getElementById("join").checked;
var stills = document.getElementById("stills").checked;
var crop = document.getElementById("crop").checked;
var input = document.getElementById("input").value;
var frames = [];
var pat = /C +(\d+)/g;
var match = pat.exec(input);
while (match != null) {
frames.push(match[1]);
match = pat.exec(input);
}
var output = "";
for (var i = 0; i < frames.length; i++) {
if (join) {
output += "c" + i + "=";
} else {
output += "#~ ";
}
output += "Trim(" + frames[i] + ", ";
if (stills) {
output += "-1)";
} else if (i < (frames.length - 1)) {
output += frames[i + 1] + "-1)";
} else {
output += "0)";
}
if (crop) {
output += ".crop(0,0,0,0)";
}
output += "\n";
}
if (join) {
output += "\n";
for (var i = 0; i < frames.length; i++) {
if (i % 10 === 0 && i !== 0) {
output += "\n\\";
}
if (i === 0) {
output += "c" + i;
} else |
}
}
document.getElementById("output").value = output;
}
| {
output += "+c" + i;
} | conditional_block |
edl-split.js | function | () {
var join = document.getElementById("join").checked;
var stills = document.getElementById("stills").checked;
var crop = document.getElementById("crop").checked;
var input = document.getElementById("input").value;
var frames = [];
var pat = /C +(\d+)/g;
var match = pat.exec(input);
while (match != null) {
frames.push(match[1]);
match = pat.exec(input);
}
var output = "";
for (var i = 0; i < frames.length; i++) {
if (join) {
output += "c" + i + "=";
} else {
output += "#~ ";
}
output += "Trim(" + frames[i] + ", ";
if (stills) {
output += "-1)";
} else if (i < (frames.length - 1)) {
output += frames[i + 1] + "-1)";
} else {
output += "0)";
}
if (crop) {
output += ".crop(0,0,0,0)";
}
output += "\n";
}
if (join) {
output += "\n";
for (var i = 0; i < frames.length; i++) {
if (i % 10 === 0 && i !== 0) {
output += "\n\\";
}
if (i === 0) {
output += "c" + i;
} else {
output += "+c" + i;
}
}
}
document.getElementById("output").value = output;
}
| convertEdl | identifier_name |
head-let-destructuring.js | // Copyright (C) 2016 the V8 project authors. All rights reserved.
// This code is governed by the BSD license found in the LICENSE file.
/*---
esid: sec-iteration-statements
es6id: 13.7
description: >
The token sequence `let [`is interpreted as the beginning of a destructuring
binding pattern
info: |
Syntax
IterationStatement[Yield, Return]:
for ( [lookahead ∉ { let [ } ] LeftHandSideExpression[?Yield] in
Expression[+In, ?Yield] ) Statement[?Yield, ?Return]
for ( ForDeclaration[?Yield] in Expression[+In, ?Yield] )
Statement[?Yield, ?Return]
---*/
var obj = Object.create(null); |
for ( let[x] in obj ) {
value = x;
}
assert.sameValue(typeof x, 'undefined', 'binding is block-scoped');
assert.sameValue(value, 'k'); | var value;
obj.key = 1; | random_line_split |
index.d.ts | // Type definitions for non-npm package DiskQuotaTypeLibrary 1.0
// Project: https://msdn.microsoft.com/en-us/library/windows/desktop/bb773938(v=vs.85).aspx
// Definitions by: Zev Spitz <https://github.com/zspitz>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
// TypeScript Version: 2.6
| dqAcctDeleted = 2,
dqAcctInvalid = 3,
dqAcctResolved = 0,
dqAcctUnavailable = 1,
dqAcctUnknown = 4,
dqAcctUnresolved = 5,
}
// tslint:disable-next-line no-const-enum
const enum QuotaStateConstants {
dqStateDisable = 0,
dqStateEnforce = 2,
dqStateTrack = 1,
}
// tslint:disable-next-line no-const-enum
const enum UserNameResolutionConstants {
dqResolveAsync = 2,
dqResolveNone = 0,
dqResolveSync = 1,
}
/** Automation interface for DiskQuotaUser */
class DIDiskQuotaUser {
private 'DiskQuotaTypeLibrary.DIDiskQuotaUser_typekey': DIDiskQuotaUser;
private constructor();
/** Name of user's account container */
readonly AccountContainerName: string;
/** Status of user's account */
readonly AccountStatus: AccountStatusConstants;
/** User's display name */
readonly DisplayName: string;
/** Unique ID number */
readonly ID: number;
/** Invalidate data cached in user object */
Invalidate(): void;
/** User's logon account name */
readonly LogonName: string;
/** User's quota limit (bytes) */
QuotaLimit: number;
/** User's quota limit (text) */
readonly QuotaLimitText: string;
/** User's quota warning threshold (bytes) */
QuotaThreshold: number;
/** User's quota warning threshold (text) */
readonly QuotaThresholdText: string;
/** Quota charged to user (bytes) */
readonly QuotaUsed: number;
/** Quota charged to user (text) */
readonly QuotaUsedText: string;
}
/** Microsoft Disk Quota */
class DiskQuotaControl {
private 'DiskQuotaTypeLibrary.DiskQuotaControl_typekey': DiskQuotaControl;
private constructor();
/** Add a user quota entry by Name */
AddUser(LogonName: string): DIDiskQuotaUser;
/** Default quota limit applied to new volume users (byte value) */
DefaultQuotaLimit: number;
/** Default quota limit applied to new volume users (text string) */
readonly DefaultQuotaLimitText: string;
/** Default warning threshold applied to new volume users (byte value) */
DefaultQuotaThreshold: number;
/** Default warning threshold applied to new volume users (text string) */
readonly DefaultQuotaThresholdText: string;
/** Delete a user quota entry */
DeleteUser(pUser: DIDiskQuotaUser): void;
/** Find a user quota entry by Name */
FindUser(LogonName: string): DIDiskQuotaUser;
/** Promote a user quota entry to the head of the name resolution queue */
GiveUserNameResolutionPriority(pUser: DIDiskQuotaUser): void;
/** Initialize the quota control object for a specified volume */
Initialize(path: string, bReadWrite: boolean): void;
/** Invalidate the cache of user name information */
InvalidateSidNameCache(): void;
/** Write event log entry when user exceeds quota limit */
LogQuotaLimit: boolean;
/** Write event log entry when user exceeds quota warning threshold */
LogQuotaThreshold: boolean;
/** Indicates if quota information is out of date */
readonly QuotaFileIncomplete: boolean;
/** Indicates if quota information is being rebuilt */
readonly QuotaFileRebuilding: boolean;
/** State of the volume's disk quota system */
QuotaState: QuotaStateConstants;
/** Terminate the user name resolution thread */
ShutdownNameResolution(): void;
/** Translates a user logon name to a security ID */
TranslateLogonNameToSID(LogonName: string): string;
/** Control the resolution of user Security IDs to user Names */
UserNameResolution: UserNameResolutionConstants;
}
}
interface ActiveXObject {
on(
obj: DiskQuotaTypeLibrary.DiskQuotaControl, event: 'OnUserNameChanged', argNames: ['pUser'], handler: (
this: DiskQuotaTypeLibrary.DiskQuotaControl, parameter: {readonly pUser: DiskQuotaTypeLibrary.DIDiskQuotaUser}) => void): void;
}
interface ActiveXObjectNameMap {
'Microsoft.DiskQuota': DiskQuotaTypeLibrary.DiskQuotaControl;
}
interface EnumeratorConstructor {
new(col: DiskQuotaTypeLibrary.DiskQuotaControl): Enumerator<DiskQuotaTypeLibrary.DIDiskQuotaUser>;
} | /// <reference types="activex-interop" />
declare namespace DiskQuotaTypeLibrary {
// tslint:disable-next-line no-const-enum
const enum AccountStatusConstants { | random_line_split |
index.d.ts | // Type definitions for non-npm package DiskQuotaTypeLibrary 1.0
// Project: https://msdn.microsoft.com/en-us/library/windows/desktop/bb773938(v=vs.85).aspx
// Definitions by: Zev Spitz <https://github.com/zspitz>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
// TypeScript Version: 2.6
/// <reference types="activex-interop" />
declare namespace DiskQuotaTypeLibrary {
// tslint:disable-next-line no-const-enum
const enum AccountStatusConstants {
dqAcctDeleted = 2,
dqAcctInvalid = 3,
dqAcctResolved = 0,
dqAcctUnavailable = 1,
dqAcctUnknown = 4,
dqAcctUnresolved = 5,
}
// tslint:disable-next-line no-const-enum
const enum QuotaStateConstants {
dqStateDisable = 0,
dqStateEnforce = 2,
dqStateTrack = 1,
}
// tslint:disable-next-line no-const-enum
const enum UserNameResolutionConstants {
dqResolveAsync = 2,
dqResolveNone = 0,
dqResolveSync = 1,
}
/** Automation interface for DiskQuotaUser */
class DIDiskQuotaUser {
private 'DiskQuotaTypeLibrary.DIDiskQuotaUser_typekey': DIDiskQuotaUser;
private constructor();
/** Name of user's account container */
readonly AccountContainerName: string;
/** Status of user's account */
readonly AccountStatus: AccountStatusConstants;
/** User's display name */
readonly DisplayName: string;
/** Unique ID number */
readonly ID: number;
/** Invalidate data cached in user object */
Invalidate(): void;
/** User's logon account name */
readonly LogonName: string;
/** User's quota limit (bytes) */
QuotaLimit: number;
/** User's quota limit (text) */
readonly QuotaLimitText: string;
/** User's quota warning threshold (bytes) */
QuotaThreshold: number;
/** User's quota warning threshold (text) */
readonly QuotaThresholdText: string;
/** Quota charged to user (bytes) */
readonly QuotaUsed: number;
/** Quota charged to user (text) */
readonly QuotaUsedText: string;
}
/** Microsoft Disk Quota */
class | {
private 'DiskQuotaTypeLibrary.DiskQuotaControl_typekey': DiskQuotaControl;
private constructor();
/** Add a user quota entry by Name */
AddUser(LogonName: string): DIDiskQuotaUser;
/** Default quota limit applied to new volume users (byte value) */
DefaultQuotaLimit: number;
/** Default quota limit applied to new volume users (text string) */
readonly DefaultQuotaLimitText: string;
/** Default warning threshold applied to new volume users (byte value) */
DefaultQuotaThreshold: number;
/** Default warning threshold applied to new volume users (text string) */
readonly DefaultQuotaThresholdText: string;
/** Delete a user quota entry */
DeleteUser(pUser: DIDiskQuotaUser): void;
/** Find a user quota entry by Name */
FindUser(LogonName: string): DIDiskQuotaUser;
/** Promote a user quota entry to the head of the name resolution queue */
GiveUserNameResolutionPriority(pUser: DIDiskQuotaUser): void;
/** Initialize the quota control object for a specified volume */
Initialize(path: string, bReadWrite: boolean): void;
/** Invalidate the cache of user name information */
InvalidateSidNameCache(): void;
/** Write event log entry when user exceeds quota limit */
LogQuotaLimit: boolean;
/** Write event log entry when user exceeds quota warning threshold */
LogQuotaThreshold: boolean;
/** Indicates if quota information is out of date */
readonly QuotaFileIncomplete: boolean;
/** Indicates if quota information is being rebuilt */
readonly QuotaFileRebuilding: boolean;
/** State of the volume's disk quota system */
QuotaState: QuotaStateConstants;
/** Terminate the user name resolution thread */
ShutdownNameResolution(): void;
/** Translates a user logon name to a security ID */
TranslateLogonNameToSID(LogonName: string): string;
/** Control the resolution of user Security IDs to user Names */
UserNameResolution: UserNameResolutionConstants;
}
}
interface ActiveXObject {
on(
obj: DiskQuotaTypeLibrary.DiskQuotaControl, event: 'OnUserNameChanged', argNames: ['pUser'], handler: (
this: DiskQuotaTypeLibrary.DiskQuotaControl, parameter: {readonly pUser: DiskQuotaTypeLibrary.DIDiskQuotaUser}) => void): void;
}
interface ActiveXObjectNameMap {
'Microsoft.DiskQuota': DiskQuotaTypeLibrary.DiskQuotaControl;
}
interface EnumeratorConstructor {
new(col: DiskQuotaTypeLibrary.DiskQuotaControl): Enumerator<DiskQuotaTypeLibrary.DIDiskQuotaUser>;
}
| DiskQuotaControl | identifier_name |
run_combined.py | import os
import csv
import pickle
from indra.literature import id_lookup
from indra.sources import trips, reach, index_cards
from assembly_eval import have_file, run_assembly
if __name__ == '__main__':
pmc_ids = [s.strip() for s in open('pmcids.txt', 'rt').readlines()]
# Load the REACH reading output
with open('reach/reach_stmts_batch_4_eval.pkl') as f:
reach_stmts = pickle.load(f)
# Load the PMID to PMCID map
pmcid_to_pmid = {}
with open('pmc_batch_4_id_map.txt') as f:
csvreader = csv.reader(f, delimiter='\t')
for row in csvreader:
pmcid_to_pmid[row[0]] = row[1]
for pmcid in pmc_ids:
print 'Processing %s...' % pmcid
# Process TRIPS
trips_fname = 'trips/' + pmcid + '.ekb'
tp = trips.process_xml(open(trips_fname).read())
# Get REACH statements
reach_stmts_for_pmcid = reach_stmts.get(pmcid_to_pmid[pmcid], [])
if not reach_stmts_for_pmcid:
print "No REACH statements for %s" % pmcid
# Get NACTEM/ISI statements
fname = 'nactem/' + pmcid + '.cards'
if not os.path.exists(fname):
nactem_stmts = []
else:
|
# Combine all statements
all_statements = tp.statements + reach_stmts_for_pmcid + nactem_stmts
# Run assembly
run_assembly(all_statements, 'combined', pmcid)
| icp = index_cards.process_json_file(fname, 'nactem')
nactem_stmts = icp.statements | conditional_block |
run_combined.py | import os
import csv
import pickle
from indra.literature import id_lookup
from indra.sources import trips, reach, index_cards
from assembly_eval import have_file, run_assembly
if __name__ == '__main__':
pmc_ids = [s.strip() for s in open('pmcids.txt', 'rt').readlines()]
# Load the REACH reading output |
# Load the PMID to PMCID map
pmcid_to_pmid = {}
with open('pmc_batch_4_id_map.txt') as f:
csvreader = csv.reader(f, delimiter='\t')
for row in csvreader:
pmcid_to_pmid[row[0]] = row[1]
for pmcid in pmc_ids:
print 'Processing %s...' % pmcid
# Process TRIPS
trips_fname = 'trips/' + pmcid + '.ekb'
tp = trips.process_xml(open(trips_fname).read())
# Get REACH statements
reach_stmts_for_pmcid = reach_stmts.get(pmcid_to_pmid[pmcid], [])
if not reach_stmts_for_pmcid:
print "No REACH statements for %s" % pmcid
# Get NACTEM/ISI statements
fname = 'nactem/' + pmcid + '.cards'
if not os.path.exists(fname):
nactem_stmts = []
else:
icp = index_cards.process_json_file(fname, 'nactem')
nactem_stmts = icp.statements
# Combine all statements
all_statements = tp.statements + reach_stmts_for_pmcid + nactem_stmts
# Run assembly
run_assembly(all_statements, 'combined', pmcid) | with open('reach/reach_stmts_batch_4_eval.pkl') as f:
reach_stmts = pickle.load(f) | random_line_split |
MemberBio.tsx | import React from 'react'
import { Link } from 'gatsby'
import styled from 'styled-components'
import { IMember } from '../../types'
import { TEAM_MEMBER_ROUTE } from '../../constants/routes'
import { Card, Flex, H4, LinkChevronRightIcon, Fade } from '../../shared'
import {
BORDER_RADIUS_LG,
minWidth,
PHONE,
M1,
maxWidth,
M2,
} from '../../constants/measurements'
const Thumbnail = styled.img`
min-height: 4rem;
border-radius: ${BORDER_RADIUS_LG};
margin-bottom: 0;
max-height: 10rem;
margin-right: 1rem;
${minWidth(PHONE)} {
min-height: 10rem;
}
${maxWidth(PHONE)} {
height: 3rem;
width: 3rem;
border-radius: 50%;
min-height: 0;
max-height: none;
}
${maxWidth('400px')} {
height: 2.5rem;
width: 2.5rem;
margin-right: ${M2}; | const CenteredFlex = styled(Flex)`
align-items: center;
`
interface IMemberBioProps {
author: IMember
}
const Bio = styled.div`
font-size: 80%;
line-height: 1.375;
p {
margin-bottom: ${M2};
}
`
const StyledCenteredFlex = styled(CenteredFlex)`
${maxWidth(PHONE)} {
align-items: start;
}
`
const MemberBio = ({
author: { pennkey, localImage, bio = '', name },
}: IMemberBioProps): React.ReactElement => (
<Fade distance={M1}>
<Card shaded>
<StyledCenteredFlex>
<Thumbnail src={localImage.childImageSharp.fluid.src} />
<div>
<H4 mb2>{name}</H4>
<Bio dangerouslySetInnerHTML={{ __html: bio }} />
<div style={{ transform: 'scale(0.8)', transformOrigin: 'top left' }}>
<Link to={TEAM_MEMBER_ROUTE(pennkey)}>
Learn more <LinkChevronRightIcon />
</Link>
</div>
</div>
</StyledCenteredFlex>
</Card>
</Fade>
)
export default MemberBio | }
`
| random_line_split |
regions-trait-1.rs | // Copyright 2012 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
#![feature(box_syntax)]
struct ctxt { v: uint }
trait get_ctxt {
// Here the `&` is bound in the method definition:
fn get_ctxt(&self) -> &ctxt;
}
struct | <'a> { c: &'a ctxt }
impl<'a> get_ctxt for has_ctxt<'a> {
// Here an error occurs because we used `&self` but
// the definition used `&`:
fn get_ctxt(&self) -> &'a ctxt { //~ ERROR method `get_ctxt` has an incompatible type
self.c
}
}
fn get_v(gc: Box<get_ctxt>) -> uint {
gc.get_ctxt().v
}
fn main() {
let ctxt = ctxt { v: 22u };
let hc = has_ctxt { c: &ctxt };
assert_eq!(get_v(box hc as Box<get_ctxt>), 22u);
}
| has_ctxt | identifier_name |
regions-trait-1.rs | // Copyright 2012 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
#![feature(box_syntax)]
struct ctxt { v: uint }
trait get_ctxt {
// Here the `&` is bound in the method definition:
fn get_ctxt(&self) -> &ctxt;
}
struct has_ctxt<'a> { c: &'a ctxt }
impl<'a> get_ctxt for has_ctxt<'a> {
// Here an error occurs because we used `&self` but
// the definition used `&`: |
}
fn get_v(gc: Box<get_ctxt>) -> uint {
gc.get_ctxt().v
}
fn main() {
let ctxt = ctxt { v: 22u };
let hc = has_ctxt { c: &ctxt };
assert_eq!(get_v(box hc as Box<get_ctxt>), 22u);
} | fn get_ctxt(&self) -> &'a ctxt { //~ ERROR method `get_ctxt` has an incompatible type
self.c
} | random_line_split |
filesearch.rs | // Copyright 2012-2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
#![allow(non_camel_case_types)]
pub use self::FileMatch::*;
use std::collections::HashSet;
use std::io::fs::PathExtensions;
use std::io::fs;
use std::os;
use util::fs as myfs;
use session::search_paths::{SearchPaths, PathKind};
#[derive(Copy)]
pub enum FileMatch {
FileMatches,
FileDoesntMatch,
}
// A module for searching for libraries
// FIXME (#2658): I'm not happy how this module turned out. Should
// probably just be folded into cstore.
pub struct FileSearch<'a> {
pub sysroot: &'a Path,
pub search_paths: &'a SearchPaths,
pub triple: &'a str,
pub kind: PathKind,
}
impl<'a> FileSearch<'a> {
pub fn for_each_lib_search_path<F>(&self, mut f: F) where
F: FnMut(&Path) -> FileMatch,
{
let mut visited_dirs = HashSet::new();
let mut found = false;
for path in self.search_paths.iter(self.kind) {
match f(path) {
FileMatches => found = true,
FileDoesntMatch => ()
}
visited_dirs.insert(path.as_vec().to_vec());
}
debug!("filesearch: searching lib path");
let tlib_path = make_target_lib_path(self.sysroot,
self.triple);
if !visited_dirs.contains(tlib_path.as_vec()) {
match f(&tlib_path) {
FileMatches => found = true,
FileDoesntMatch => ()
}
}
visited_dirs.insert(tlib_path.as_vec().to_vec());
// Try RUST_PATH
if !found {
let rustpath = rust_path();
for path in rustpath.iter() {
let tlib_path = make_rustpkg_lib_path(
self.sysroot, path, self.triple);
debug!("is {} in visited_dirs? {}", tlib_path.display(),
visited_dirs.contains(&tlib_path.as_vec().to_vec()));
if !visited_dirs.contains(tlib_path.as_vec()) {
visited_dirs.insert(tlib_path.as_vec().to_vec());
// Don't keep searching the RUST_PATH if one match turns up --
// if we did, we'd get a "multiple matching crates" error
match f(&tlib_path) {
FileMatches => {
break;
}
FileDoesntMatch => ()
}
}
}
}
}
pub fn get_lib_path(&self) -> Path {
make_target_lib_path(self.sysroot, self.triple)
}
pub fn search<F>(&self, mut pick: F) where F: FnMut(&Path) -> FileMatch {
self.for_each_lib_search_path(|lib_search_path| {
debug!("searching {}", lib_search_path.display());
match fs::readdir(lib_search_path) {
Ok(files) => {
let mut rslt = FileDoesntMatch;
fn is_rlib(p: & &Path) -> bool {
p.extension_str() == Some("rlib")
}
// Reading metadata out of rlibs is faster, and if we find both
// an rlib and a dylib we only read one of the files of
// metadata, so in the name of speed, bring all rlib files to
// the front of the search list.
let files1 = files.iter().filter(|p| is_rlib(p));
let files2 = files.iter().filter(|p| !is_rlib(p));
for path in files1.chain(files2) {
debug!("testing {}", path.display());
let maybe_picked = pick(path);
match maybe_picked {
FileMatches => {
debug!("picked {}", path.display()); | FileDoesntMatch => {
debug!("rejected {}", path.display());
}
}
}
rslt
}
Err(..) => FileDoesntMatch,
}
});
}
pub fn new(sysroot: &'a Path,
triple: &'a str,
search_paths: &'a SearchPaths,
kind: PathKind) -> FileSearch<'a> {
debug!("using sysroot = {}, triple = {}", sysroot.display(), triple);
FileSearch {
sysroot: sysroot,
search_paths: search_paths,
triple: triple,
kind: kind,
}
}
// Returns a list of directories where target-specific dylibs might be located.
pub fn get_dylib_search_paths(&self) -> Vec<Path> {
let mut paths = Vec::new();
self.for_each_lib_search_path(|lib_search_path| {
paths.push(lib_search_path.clone());
FileDoesntMatch
});
paths
}
// Returns a list of directories where target-specific tool binaries are located.
pub fn get_tools_search_paths(&self) -> Vec<Path> {
let mut p = Path::new(self.sysroot);
p.push(find_libdir(self.sysroot));
p.push(rustlibdir());
p.push(self.triple);
p.push("bin");
vec![p]
}
}
pub fn relative_target_lib_path(sysroot: &Path, target_triple: &str) -> Path {
let mut p = Path::new(find_libdir(sysroot));
assert!(p.is_relative());
p.push(rustlibdir());
p.push(target_triple);
p.push("lib");
p
}
fn make_target_lib_path(sysroot: &Path,
target_triple: &str) -> Path {
sysroot.join(&relative_target_lib_path(sysroot, target_triple))
}
fn make_rustpkg_lib_path(sysroot: &Path,
dir: &Path,
triple: &str) -> Path {
let mut p = dir.join(find_libdir(sysroot));
p.push(triple);
p
}
pub fn get_or_default_sysroot() -> Path {
// Follow symlinks. If the resolved path is relative, make it absolute.
fn canonicalize(path: Option<Path>) -> Option<Path> {
path.and_then(|path|
match myfs::realpath(&path) {
Ok(canon) => Some(canon),
Err(e) => panic!("failed to get realpath: {}", e),
})
}
match canonicalize(os::self_exe_name()) {
Some(mut p) => { p.pop(); p.pop(); p }
None => panic!("can't determine value for sysroot")
}
}
#[cfg(windows)]
static PATH_ENTRY_SEPARATOR: &'static str = ";";
#[cfg(not(windows))]
static PATH_ENTRY_SEPARATOR: &'static str = ":";
/// Returns RUST_PATH as a string, without default paths added
pub fn get_rust_path() -> Option<String> {
os::getenv("RUST_PATH").map(|x| x.to_string())
}
/// Returns the value of RUST_PATH, as a list
/// of Paths. Includes default entries for, if they exist:
/// $HOME/.rust
/// DIR/.rust for any DIR that's the current working directory
/// or an ancestor of it
pub fn rust_path() -> Vec<Path> {
let mut env_rust_path: Vec<Path> = match get_rust_path() {
Some(env_path) => {
let env_path_components =
env_path.split_str(PATH_ENTRY_SEPARATOR);
env_path_components.map(|s| Path::new(s)).collect()
}
None => Vec::new()
};
let mut cwd = os::getcwd().unwrap();
// now add in default entries
let cwd_dot_rust = cwd.join(".rust");
if !env_rust_path.contains(&cwd_dot_rust) {
env_rust_path.push(cwd_dot_rust);
}
if !env_rust_path.contains(&cwd) {
env_rust_path.push(cwd.clone());
}
loop {
if { let f = cwd.filename(); f.is_none() || f.unwrap() == b".." } {
break
}
cwd.set_filename(".rust");
if !env_rust_path.contains(&cwd) && cwd.exists() {
env_rust_path.push(cwd.clone());
}
cwd.pop();
}
let h = os::homedir();
for h in h.iter() {
let p = h.join(".rust");
if !env_rust_path.contains(&p) && p.exists() {
env_rust_path.push(p);
}
}
env_rust_path
}
// The name of the directory rustc expects libraries to be located.
// On Unix should be "lib", on windows "bin"
#[cfg(unix)]
fn find_libdir(sysroot: &Path) -> String {
// FIXME: This is a quick hack to make the rustc binary able to locate
// Rust libraries in Linux environments where libraries might be installed
// to lib64/lib32. This would be more foolproof by basing the sysroot off
// of the directory where librustc is located, rather than where the rustc
// binary is.
//If --libdir is set during configuration to the value other than
// "lib" (i.e. non-default), this value is used (see issue #16552).
match option_env!("CFG_LIBDIR_RELATIVE") {
Some(libdir) if libdir != "lib" => return libdir.to_string(),
_ => if sysroot.join(primary_libdir_name()).join(rustlibdir()).exists() {
return primary_libdir_name();
} else {
return secondary_libdir_name();
}
}
#[cfg(any(all(stage0, target_word_size = "64"), all(not(stage0), target_pointer_width = "64")))]
fn primary_libdir_name() -> String {
"lib64".to_string()
}
#[cfg(any(all(stage0, target_word_size = "32"), all(not(stage0), target_pointer_width = "32")))]
fn primary_libdir_name() -> String {
"lib32".to_string()
}
fn secondary_libdir_name() -> String {
"lib".to_string()
}
}
#[cfg(windows)]
fn find_libdir(_sysroot: &Path) -> String {
"bin".to_string()
}
// The name of rustc's own place to organize libraries.
// Used to be "rustc", now the default is "rustlib"
pub fn rustlibdir() -> String {
"rustlib".to_string()
} | rslt = FileMatches;
} | random_line_split |
filesearch.rs | // Copyright 2012-2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
#![allow(non_camel_case_types)]
pub use self::FileMatch::*;
use std::collections::HashSet;
use std::io::fs::PathExtensions;
use std::io::fs;
use std::os;
use util::fs as myfs;
use session::search_paths::{SearchPaths, PathKind};
#[derive(Copy)]
pub enum FileMatch {
FileMatches,
FileDoesntMatch,
}
// A module for searching for libraries
// FIXME (#2658): I'm not happy how this module turned out. Should
// probably just be folded into cstore.
pub struct FileSearch<'a> {
pub sysroot: &'a Path,
pub search_paths: &'a SearchPaths,
pub triple: &'a str,
pub kind: PathKind,
}
impl<'a> FileSearch<'a> {
pub fn for_each_lib_search_path<F>(&self, mut f: F) where
F: FnMut(&Path) -> FileMatch,
|
pub fn get_lib_path(&self) -> Path {
make_target_lib_path(self.sysroot, self.triple)
}
pub fn search<F>(&self, mut pick: F) where F: FnMut(&Path) -> FileMatch {
self.for_each_lib_search_path(|lib_search_path| {
debug!("searching {}", lib_search_path.display());
match fs::readdir(lib_search_path) {
Ok(files) => {
let mut rslt = FileDoesntMatch;
fn is_rlib(p: & &Path) -> bool {
p.extension_str() == Some("rlib")
}
// Reading metadata out of rlibs is faster, and if we find both
// an rlib and a dylib we only read one of the files of
// metadata, so in the name of speed, bring all rlib files to
// the front of the search list.
let files1 = files.iter().filter(|p| is_rlib(p));
let files2 = files.iter().filter(|p| !is_rlib(p));
for path in files1.chain(files2) {
debug!("testing {}", path.display());
let maybe_picked = pick(path);
match maybe_picked {
FileMatches => {
debug!("picked {}", path.display());
rslt = FileMatches;
}
FileDoesntMatch => {
debug!("rejected {}", path.display());
}
}
}
rslt
}
Err(..) => FileDoesntMatch,
}
});
}
pub fn new(sysroot: &'a Path,
triple: &'a str,
search_paths: &'a SearchPaths,
kind: PathKind) -> FileSearch<'a> {
debug!("using sysroot = {}, triple = {}", sysroot.display(), triple);
FileSearch {
sysroot: sysroot,
search_paths: search_paths,
triple: triple,
kind: kind,
}
}
// Returns a list of directories where target-specific dylibs might be located.
pub fn get_dylib_search_paths(&self) -> Vec<Path> {
let mut paths = Vec::new();
self.for_each_lib_search_path(|lib_search_path| {
paths.push(lib_search_path.clone());
FileDoesntMatch
});
paths
}
// Returns a list of directories where target-specific tool binaries are located.
pub fn get_tools_search_paths(&self) -> Vec<Path> {
let mut p = Path::new(self.sysroot);
p.push(find_libdir(self.sysroot));
p.push(rustlibdir());
p.push(self.triple);
p.push("bin");
vec![p]
}
}
pub fn relative_target_lib_path(sysroot: &Path, target_triple: &str) -> Path {
let mut p = Path::new(find_libdir(sysroot));
assert!(p.is_relative());
p.push(rustlibdir());
p.push(target_triple);
p.push("lib");
p
}
fn make_target_lib_path(sysroot: &Path,
target_triple: &str) -> Path {
sysroot.join(&relative_target_lib_path(sysroot, target_triple))
}
fn make_rustpkg_lib_path(sysroot: &Path,
dir: &Path,
triple: &str) -> Path {
let mut p = dir.join(find_libdir(sysroot));
p.push(triple);
p
}
pub fn get_or_default_sysroot() -> Path {
// Follow symlinks. If the resolved path is relative, make it absolute.
fn canonicalize(path: Option<Path>) -> Option<Path> {
path.and_then(|path|
match myfs::realpath(&path) {
Ok(canon) => Some(canon),
Err(e) => panic!("failed to get realpath: {}", e),
})
}
match canonicalize(os::self_exe_name()) {
Some(mut p) => { p.pop(); p.pop(); p }
None => panic!("can't determine value for sysroot")
}
}
#[cfg(windows)]
static PATH_ENTRY_SEPARATOR: &'static str = ";";
#[cfg(not(windows))]
static PATH_ENTRY_SEPARATOR: &'static str = ":";
/// Returns RUST_PATH as a string, without default paths added
pub fn get_rust_path() -> Option<String> {
os::getenv("RUST_PATH").map(|x| x.to_string())
}
/// Returns the value of RUST_PATH, as a list
/// of Paths. Includes default entries for, if they exist:
/// $HOME/.rust
/// DIR/.rust for any DIR that's the current working directory
/// or an ancestor of it
pub fn rust_path() -> Vec<Path> {
let mut env_rust_path: Vec<Path> = match get_rust_path() {
Some(env_path) => {
let env_path_components =
env_path.split_str(PATH_ENTRY_SEPARATOR);
env_path_components.map(|s| Path::new(s)).collect()
}
None => Vec::new()
};
let mut cwd = os::getcwd().unwrap();
// now add in default entries
let cwd_dot_rust = cwd.join(".rust");
if !env_rust_path.contains(&cwd_dot_rust) {
env_rust_path.push(cwd_dot_rust);
}
if !env_rust_path.contains(&cwd) {
env_rust_path.push(cwd.clone());
}
loop {
if { let f = cwd.filename(); f.is_none() || f.unwrap() == b".." } {
break
}
cwd.set_filename(".rust");
if !env_rust_path.contains(&cwd) && cwd.exists() {
env_rust_path.push(cwd.clone());
}
cwd.pop();
}
let h = os::homedir();
for h in h.iter() {
let p = h.join(".rust");
if !env_rust_path.contains(&p) && p.exists() {
env_rust_path.push(p);
}
}
env_rust_path
}
// The name of the directory rustc expects libraries to be located.
// On Unix should be "lib", on windows "bin"
#[cfg(unix)]
fn find_libdir(sysroot: &Path) -> String {
// FIXME: This is a quick hack to make the rustc binary able to locate
// Rust libraries in Linux environments where libraries might be installed
// to lib64/lib32. This would be more foolproof by basing the sysroot off
// of the directory where librustc is located, rather than where the rustc
// binary is.
//If --libdir is set during configuration to the value other than
// "lib" (i.e. non-default), this value is used (see issue #16552).
match option_env!("CFG_LIBDIR_RELATIVE") {
Some(libdir) if libdir != "lib" => return libdir.to_string(),
_ => if sysroot.join(primary_libdir_name()).join(rustlibdir()).exists() {
return primary_libdir_name();
} else {
return secondary_libdir_name();
}
}
#[cfg(any(all(stage0, target_word_size = "64"), all(not(stage0), target_pointer_width = "64")))]
fn primary_libdir_name() -> String {
"lib64".to_string()
}
#[cfg(any(all(stage0, target_word_size = "32"), all(not(stage0), target_pointer_width = "32")))]
fn primary_libdir_name() -> String {
"lib32".to_string()
}
fn secondary_libdir_name() -> String {
"lib".to_string()
}
}
#[cfg(windows)]
fn find_libdir(_sysroot: &Path) -> String {
"bin".to_string()
}
// The name of rustc's own place to organize libraries.
// Used to be "rustc", now the default is "rustlib"
pub fn rustlibdir() -> String {
"rustlib".to_string()
}
| {
let mut visited_dirs = HashSet::new();
let mut found = false;
for path in self.search_paths.iter(self.kind) {
match f(path) {
FileMatches => found = true,
FileDoesntMatch => ()
}
visited_dirs.insert(path.as_vec().to_vec());
}
debug!("filesearch: searching lib path");
let tlib_path = make_target_lib_path(self.sysroot,
self.triple);
if !visited_dirs.contains(tlib_path.as_vec()) {
match f(&tlib_path) {
FileMatches => found = true,
FileDoesntMatch => ()
}
}
visited_dirs.insert(tlib_path.as_vec().to_vec());
// Try RUST_PATH
if !found {
let rustpath = rust_path();
for path in rustpath.iter() {
let tlib_path = make_rustpkg_lib_path(
self.sysroot, path, self.triple);
debug!("is {} in visited_dirs? {}", tlib_path.display(),
visited_dirs.contains(&tlib_path.as_vec().to_vec()));
if !visited_dirs.contains(tlib_path.as_vec()) {
visited_dirs.insert(tlib_path.as_vec().to_vec());
// Don't keep searching the RUST_PATH if one match turns up --
// if we did, we'd get a "multiple matching crates" error
match f(&tlib_path) {
FileMatches => {
break;
}
FileDoesntMatch => ()
}
}
}
}
} | identifier_body |
filesearch.rs | // Copyright 2012-2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
#![allow(non_camel_case_types)]
pub use self::FileMatch::*;
use std::collections::HashSet;
use std::io::fs::PathExtensions;
use std::io::fs;
use std::os;
use util::fs as myfs;
use session::search_paths::{SearchPaths, PathKind};
#[derive(Copy)]
pub enum FileMatch {
FileMatches,
FileDoesntMatch,
}
// A module for searching for libraries
// FIXME (#2658): I'm not happy how this module turned out. Should
// probably just be folded into cstore.
pub struct FileSearch<'a> {
pub sysroot: &'a Path,
pub search_paths: &'a SearchPaths,
pub triple: &'a str,
pub kind: PathKind,
}
impl<'a> FileSearch<'a> {
pub fn for_each_lib_search_path<F>(&self, mut f: F) where
F: FnMut(&Path) -> FileMatch,
{
let mut visited_dirs = HashSet::new();
let mut found = false;
for path in self.search_paths.iter(self.kind) {
match f(path) {
FileMatches => found = true,
FileDoesntMatch => ()
}
visited_dirs.insert(path.as_vec().to_vec());
}
debug!("filesearch: searching lib path");
let tlib_path = make_target_lib_path(self.sysroot,
self.triple);
if !visited_dirs.contains(tlib_path.as_vec()) {
match f(&tlib_path) {
FileMatches => found = true,
FileDoesntMatch => ()
}
}
visited_dirs.insert(tlib_path.as_vec().to_vec());
// Try RUST_PATH
if !found {
let rustpath = rust_path();
for path in rustpath.iter() {
let tlib_path = make_rustpkg_lib_path(
self.sysroot, path, self.triple);
debug!("is {} in visited_dirs? {}", tlib_path.display(),
visited_dirs.contains(&tlib_path.as_vec().to_vec()));
if !visited_dirs.contains(tlib_path.as_vec()) {
visited_dirs.insert(tlib_path.as_vec().to_vec());
// Don't keep searching the RUST_PATH if one match turns up --
// if we did, we'd get a "multiple matching crates" error
match f(&tlib_path) {
FileMatches => {
break;
}
FileDoesntMatch => ()
}
}
}
}
}
pub fn get_lib_path(&self) -> Path {
make_target_lib_path(self.sysroot, self.triple)
}
pub fn | <F>(&self, mut pick: F) where F: FnMut(&Path) -> FileMatch {
self.for_each_lib_search_path(|lib_search_path| {
debug!("searching {}", lib_search_path.display());
match fs::readdir(lib_search_path) {
Ok(files) => {
let mut rslt = FileDoesntMatch;
fn is_rlib(p: & &Path) -> bool {
p.extension_str() == Some("rlib")
}
// Reading metadata out of rlibs is faster, and if we find both
// an rlib and a dylib we only read one of the files of
// metadata, so in the name of speed, bring all rlib files to
// the front of the search list.
let files1 = files.iter().filter(|p| is_rlib(p));
let files2 = files.iter().filter(|p| !is_rlib(p));
for path in files1.chain(files2) {
debug!("testing {}", path.display());
let maybe_picked = pick(path);
match maybe_picked {
FileMatches => {
debug!("picked {}", path.display());
rslt = FileMatches;
}
FileDoesntMatch => {
debug!("rejected {}", path.display());
}
}
}
rslt
}
Err(..) => FileDoesntMatch,
}
});
}
pub fn new(sysroot: &'a Path,
triple: &'a str,
search_paths: &'a SearchPaths,
kind: PathKind) -> FileSearch<'a> {
debug!("using sysroot = {}, triple = {}", sysroot.display(), triple);
FileSearch {
sysroot: sysroot,
search_paths: search_paths,
triple: triple,
kind: kind,
}
}
// Returns a list of directories where target-specific dylibs might be located.
pub fn get_dylib_search_paths(&self) -> Vec<Path> {
let mut paths = Vec::new();
self.for_each_lib_search_path(|lib_search_path| {
paths.push(lib_search_path.clone());
FileDoesntMatch
});
paths
}
// Returns a list of directories where target-specific tool binaries are located.
pub fn get_tools_search_paths(&self) -> Vec<Path> {
let mut p = Path::new(self.sysroot);
p.push(find_libdir(self.sysroot));
p.push(rustlibdir());
p.push(self.triple);
p.push("bin");
vec![p]
}
}
pub fn relative_target_lib_path(sysroot: &Path, target_triple: &str) -> Path {
let mut p = Path::new(find_libdir(sysroot));
assert!(p.is_relative());
p.push(rustlibdir());
p.push(target_triple);
p.push("lib");
p
}
fn make_target_lib_path(sysroot: &Path,
target_triple: &str) -> Path {
sysroot.join(&relative_target_lib_path(sysroot, target_triple))
}
fn make_rustpkg_lib_path(sysroot: &Path,
dir: &Path,
triple: &str) -> Path {
let mut p = dir.join(find_libdir(sysroot));
p.push(triple);
p
}
pub fn get_or_default_sysroot() -> Path {
// Follow symlinks. If the resolved path is relative, make it absolute.
fn canonicalize(path: Option<Path>) -> Option<Path> {
path.and_then(|path|
match myfs::realpath(&path) {
Ok(canon) => Some(canon),
Err(e) => panic!("failed to get realpath: {}", e),
})
}
match canonicalize(os::self_exe_name()) {
Some(mut p) => { p.pop(); p.pop(); p }
None => panic!("can't determine value for sysroot")
}
}
#[cfg(windows)]
static PATH_ENTRY_SEPARATOR: &'static str = ";";
#[cfg(not(windows))]
static PATH_ENTRY_SEPARATOR: &'static str = ":";
/// Returns RUST_PATH as a string, without default paths added
pub fn get_rust_path() -> Option<String> {
os::getenv("RUST_PATH").map(|x| x.to_string())
}
/// Returns the value of RUST_PATH, as a list
/// of Paths. Includes default entries for, if they exist:
/// $HOME/.rust
/// DIR/.rust for any DIR that's the current working directory
/// or an ancestor of it
pub fn rust_path() -> Vec<Path> {
let mut env_rust_path: Vec<Path> = match get_rust_path() {
Some(env_path) => {
let env_path_components =
env_path.split_str(PATH_ENTRY_SEPARATOR);
env_path_components.map(|s| Path::new(s)).collect()
}
None => Vec::new()
};
let mut cwd = os::getcwd().unwrap();
// now add in default entries
let cwd_dot_rust = cwd.join(".rust");
if !env_rust_path.contains(&cwd_dot_rust) {
env_rust_path.push(cwd_dot_rust);
}
if !env_rust_path.contains(&cwd) {
env_rust_path.push(cwd.clone());
}
loop {
if { let f = cwd.filename(); f.is_none() || f.unwrap() == b".." } {
break
}
cwd.set_filename(".rust");
if !env_rust_path.contains(&cwd) && cwd.exists() {
env_rust_path.push(cwd.clone());
}
cwd.pop();
}
let h = os::homedir();
for h in h.iter() {
let p = h.join(".rust");
if !env_rust_path.contains(&p) && p.exists() {
env_rust_path.push(p);
}
}
env_rust_path
}
// The name of the directory rustc expects libraries to be located.
// On Unix should be "lib", on windows "bin"
#[cfg(unix)]
fn find_libdir(sysroot: &Path) -> String {
// FIXME: This is a quick hack to make the rustc binary able to locate
// Rust libraries in Linux environments where libraries might be installed
// to lib64/lib32. This would be more foolproof by basing the sysroot off
// of the directory where librustc is located, rather than where the rustc
// binary is.
//If --libdir is set during configuration to the value other than
// "lib" (i.e. non-default), this value is used (see issue #16552).
match option_env!("CFG_LIBDIR_RELATIVE") {
Some(libdir) if libdir != "lib" => return libdir.to_string(),
_ => if sysroot.join(primary_libdir_name()).join(rustlibdir()).exists() {
return primary_libdir_name();
} else {
return secondary_libdir_name();
}
}
#[cfg(any(all(stage0, target_word_size = "64"), all(not(stage0), target_pointer_width = "64")))]
fn primary_libdir_name() -> String {
"lib64".to_string()
}
#[cfg(any(all(stage0, target_word_size = "32"), all(not(stage0), target_pointer_width = "32")))]
fn primary_libdir_name() -> String {
"lib32".to_string()
}
fn secondary_libdir_name() -> String {
"lib".to_string()
}
}
#[cfg(windows)]
fn find_libdir(_sysroot: &Path) -> String {
"bin".to_string()
}
// The name of rustc's own place to organize libraries.
// Used to be "rustc", now the default is "rustlib"
pub fn rustlibdir() -> String {
"rustlib".to_string()
}
| search | identifier_name |
mod.rs | // Copyright 2020 The Tink-Rust Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
////////////////////////////////////////////////////////////////////////////////
//! Provide methods to generate, read, write or validate keysets.
mod binary_io;
pub use binary_io::*;
mod handle;
pub use handle::*;
#[cfg(feature = "json")]
#[cfg_attr(docsrs, doc(cfg(feature = "json")))]
mod json_io;
#[cfg(feature = "json")]
pub use json_io::*; | pub use reader::*;
mod validation;
pub use validation::*;
mod writer;
pub use writer::*;
#[cfg(feature = "insecure")]
#[cfg_attr(docsrs, doc(cfg(feature = "insecure")))]
pub mod insecure; | mod manager;
pub use manager::*;
mod mem_io;
pub use mem_io::*;
mod reader; | random_line_split |
test_product_tmpl_image.py | # Copyright 2019 Rafis Bikbov <https://it-projects.info/team/RafiZz>
# Copyright 2019 Alexandr Kolushov <https://it-projects.info/team/KolushovAlexandr>
# Copyright 2019 Eugene Molotov <https://it-projects.info/team/em230418>
# License LGPL-3.0 or later (http://www.gnu.org/licenses/lgpl.html).
import logging
from odoo import api, conf
from odoo.tests.common import HttpCase, tagged
_logger = logging.getLogger(__name__)
@tagged("post_install", "-at_install")
class TestProductTmplImage(HttpCase):
def | (self, px=1024):
return "https://upload.wikimedia.org/wikipedia/commons/thumb/1/1e/Gullfoss%2C_an_iconic_waterfall_of_Iceland.jpg/{}px-Gullfoss%2C_an_iconic_waterfall_of_Iceland.jpg".format(
px
)
def _get_odoo_image_url(self, model, record_id, field):
return "/web/image?model={}&id={}&field={}".format(model, record_id, field)
def test_getting_product_variant_image_fields_urls(self):
assert (
"ir_attachment_url" in conf.server_wide_modules
), "ir_attachment_url is not in server_wide_modules. Please add it via --load parameter"
env = api.Environment(self.registry.test_cr, self.uid, {})
env["ir.config_parameter"].set_param("ir_attachment_url.storage", "url")
product_tmpl = env["product.template"].create(
{
"name": "Test template",
"image": self._get_original_image_url(1024),
"image_medium": self._get_original_image_url(128),
"image_small": self._get_original_image_url(64),
}
)
product_product = env["product.product"].create(
{
"name": "Test product",
"image": False,
"image_medium": False,
"image_small": False,
"product_tmpl_id": product_tmpl.id,
}
)
odoo_image_url = self._get_odoo_image_url(
"product.product", product_product.id, "image"
)
odoo_image_medium_url = self._get_odoo_image_url(
"product.product", product_product.id, "image_medium"
)
odoo_image_small_url = self._get_odoo_image_url(
"product.product", product_product.id, "image_small"
)
product_tmpl_image_attachment = env["ir.http"].find_field_attachment(
env, "product.template", "image", product_tmpl
)
product_tmpl_image_medium_attachment = env["ir.http"].find_field_attachment(
env, "product.template", "image_medium", product_tmpl
)
product_tmpl_image_small_attachment = env["ir.http"].find_field_attachment(
env, "product.template", "image_small", product_tmpl
)
self.assertTrue(product_tmpl_image_attachment)
self.assertTrue(product_tmpl_image_medium_attachment)
self.assertTrue(product_tmpl_image_small_attachment)
self.authenticate("demo", "demo")
self.assertEqual(
self.url_open(odoo_image_url).url, product_tmpl_image_attachment.url
)
self.assertEqual(
self.url_open(odoo_image_medium_url).url,
product_tmpl_image_medium_attachment.url,
)
self.assertEqual(
self.url_open(odoo_image_small_url).url,
product_tmpl_image_small_attachment.url,
)
| _get_original_image_url | identifier_name |
test_product_tmpl_image.py | # Copyright 2019 Rafis Bikbov <https://it-projects.info/team/RafiZz>
# Copyright 2019 Alexandr Kolushov <https://it-projects.info/team/KolushovAlexandr>
# Copyright 2019 Eugene Molotov <https://it-projects.info/team/em230418>
# License LGPL-3.0 or later (http://www.gnu.org/licenses/lgpl.html).
import logging
from odoo import api, conf
from odoo.tests.common import HttpCase, tagged
_logger = logging.getLogger(__name__)
@tagged("post_install", "-at_install")
class TestProductTmplImage(HttpCase):
def _get_original_image_url(self, px=1024):
return "https://upload.wikimedia.org/wikipedia/commons/thumb/1/1e/Gullfoss%2C_an_iconic_waterfall_of_Iceland.jpg/{}px-Gullfoss%2C_an_iconic_waterfall_of_Iceland.jpg".format(
px
)
def _get_odoo_image_url(self, model, record_id, field):
return "/web/image?model={}&id={}&field={}".format(model, record_id, field)
def test_getting_product_variant_image_fields_urls(self):
assert (
"ir_attachment_url" in conf.server_wide_modules
), "ir_attachment_url is not in server_wide_modules. Please add it via --load parameter"
env = api.Environment(self.registry.test_cr, self.uid, {})
env["ir.config_parameter"].set_param("ir_attachment_url.storage", "url")
product_tmpl = env["product.template"].create(
{
"name": "Test template",
"image": self._get_original_image_url(1024),
"image_medium": self._get_original_image_url(128),
"image_small": self._get_original_image_url(64),
}
)
product_product = env["product.product"].create(
{
"name": "Test product",
"image": False,
"image_medium": False,
"image_small": False,
"product_tmpl_id": product_tmpl.id, | }
)
odoo_image_url = self._get_odoo_image_url(
"product.product", product_product.id, "image"
)
odoo_image_medium_url = self._get_odoo_image_url(
"product.product", product_product.id, "image_medium"
)
odoo_image_small_url = self._get_odoo_image_url(
"product.product", product_product.id, "image_small"
)
product_tmpl_image_attachment = env["ir.http"].find_field_attachment(
env, "product.template", "image", product_tmpl
)
product_tmpl_image_medium_attachment = env["ir.http"].find_field_attachment(
env, "product.template", "image_medium", product_tmpl
)
product_tmpl_image_small_attachment = env["ir.http"].find_field_attachment(
env, "product.template", "image_small", product_tmpl
)
self.assertTrue(product_tmpl_image_attachment)
self.assertTrue(product_tmpl_image_medium_attachment)
self.assertTrue(product_tmpl_image_small_attachment)
self.authenticate("demo", "demo")
self.assertEqual(
self.url_open(odoo_image_url).url, product_tmpl_image_attachment.url
)
self.assertEqual(
self.url_open(odoo_image_medium_url).url,
product_tmpl_image_medium_attachment.url,
)
self.assertEqual(
self.url_open(odoo_image_small_url).url,
product_tmpl_image_small_attachment.url,
) | random_line_split | |
test_product_tmpl_image.py | # Copyright 2019 Rafis Bikbov <https://it-projects.info/team/RafiZz>
# Copyright 2019 Alexandr Kolushov <https://it-projects.info/team/KolushovAlexandr>
# Copyright 2019 Eugene Molotov <https://it-projects.info/team/em230418>
# License LGPL-3.0 or later (http://www.gnu.org/licenses/lgpl.html).
import logging
from odoo import api, conf
from odoo.tests.common import HttpCase, tagged
_logger = logging.getLogger(__name__)
@tagged("post_install", "-at_install")
class TestProductTmplImage(HttpCase):
| def _get_original_image_url(self, px=1024):
return "https://upload.wikimedia.org/wikipedia/commons/thumb/1/1e/Gullfoss%2C_an_iconic_waterfall_of_Iceland.jpg/{}px-Gullfoss%2C_an_iconic_waterfall_of_Iceland.jpg".format(
px
)
def _get_odoo_image_url(self, model, record_id, field):
return "/web/image?model={}&id={}&field={}".format(model, record_id, field)
def test_getting_product_variant_image_fields_urls(self):
assert (
"ir_attachment_url" in conf.server_wide_modules
), "ir_attachment_url is not in server_wide_modules. Please add it via --load parameter"
env = api.Environment(self.registry.test_cr, self.uid, {})
env["ir.config_parameter"].set_param("ir_attachment_url.storage", "url")
product_tmpl = env["product.template"].create(
{
"name": "Test template",
"image": self._get_original_image_url(1024),
"image_medium": self._get_original_image_url(128),
"image_small": self._get_original_image_url(64),
}
)
product_product = env["product.product"].create(
{
"name": "Test product",
"image": False,
"image_medium": False,
"image_small": False,
"product_tmpl_id": product_tmpl.id,
}
)
odoo_image_url = self._get_odoo_image_url(
"product.product", product_product.id, "image"
)
odoo_image_medium_url = self._get_odoo_image_url(
"product.product", product_product.id, "image_medium"
)
odoo_image_small_url = self._get_odoo_image_url(
"product.product", product_product.id, "image_small"
)
product_tmpl_image_attachment = env["ir.http"].find_field_attachment(
env, "product.template", "image", product_tmpl
)
product_tmpl_image_medium_attachment = env["ir.http"].find_field_attachment(
env, "product.template", "image_medium", product_tmpl
)
product_tmpl_image_small_attachment = env["ir.http"].find_field_attachment(
env, "product.template", "image_small", product_tmpl
)
self.assertTrue(product_tmpl_image_attachment)
self.assertTrue(product_tmpl_image_medium_attachment)
self.assertTrue(product_tmpl_image_small_attachment)
self.authenticate("demo", "demo")
self.assertEqual(
self.url_open(odoo_image_url).url, product_tmpl_image_attachment.url
)
self.assertEqual(
self.url_open(odoo_image_medium_url).url,
product_tmpl_image_medium_attachment.url,
)
self.assertEqual(
self.url_open(odoo_image_small_url).url,
product_tmpl_image_small_attachment.url,
) | identifier_body | |
ecosystem.config.js | module.exports = {
apps: [{
name: 'URL-ShortenerAPI',
script: './source/server.js',
env: {
watch: 'source',
ignore_watch : 'source/gui',
NODE_ENV: 'development',
MONGO_PORT: 28017,
API_PORT: 8000
},
env_production: {
watch: false,
NODE_ENV: 'production',
HOOK_PORT: 8813,
MONGO_PORT: 27017,
API_PORT: 8080
}
}],
deploy: { | 'ref': 'origin/master',
'repo': 'git@github.com:taxnuke/url-shortener.git',
'path': '/var/www/short.taxnuke.ru',
'post-deploy':
'npm i && npm run build && pm2 startOrReload ecosystem.config.js \
--update-env --env production'
}
}
} | production: {
'user': 'adminus',
'host': '138.68.183.160', | random_line_split |
tweets.py | # -*- coding: utf-8 -*-
'''
script.matchcenter - Football information for Kodi
A program addon that can be mapped to a key on your remote to display football information.
Livescores, Event details, Line-ups, League tables, next and previous matches by team. Follow what
others are saying about the match in twitter.
Copyright (C) 2016 enen92
| the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
'''
import xbmcgui
import xbmc
import datetime
import json
import mainmenu
import os
from resources.lib.utilities import tweet
from resources.lib.utilities.addonfileio import FileIO
from resources.lib.utilities import ssutils
from resources.lib.utilities.common_addon import *
class TwitterDialog(xbmcgui.WindowXMLDialog):
def __init__( self, *args, **kwargs ):
self.isRunning = True
self.hash = kwargs["hash"]
self.standalone = kwargs["standalone"]
self.teamObjs = {}
def onInit(self):
xbmc.log(msg="[Match Center] Twitter cycle started", level=xbmc.LOGDEBUG)
self.getControl(32540).setImage(os.path.join(addon_path,"resources","img","goal.png"))
xbmc.executebuiltin("SetProperty(loading-script-matchcenter-twitter,1,home)")
self.getTweets()
xbmc.executebuiltin("ClearProperty(loading-script-matchcenter-twitter,Home)")
i=0
while self.isRunning:
if (float(i*200)/(twitter_update_time*60*1000)).is_integer() and ((i*200)/(3*60*1000)) != 0:
self.getTweets()
xbmc.sleep(200)
i += 1
xbmc.log(msg="[Match Center] Twitter cycle stopped", level=xbmc.LOGDEBUG)
def getTweets(self):
self.getControl(32500).setLabel("#"+self.hash)
self.getControl(32503).setImage(os.path.join(addon_path,"resources","img","twitter_sm.png"))
tweetitems = []
tweets = tweet.get_hashtag_tweets(self.hash)
if tweets:
for _tweet in tweets:
td = ssutils.get_timedelta_string(datetime.datetime.utcnow() - _tweet["date"])
item = xbmcgui.ListItem(_tweet["text"].replace("\n",""))
item.setProperty("profilepic",_tweet["profilepic"])
item.setProperty("author","[B]" +"@" + _tweet["author"] + "[/B]")
item.setProperty("timedelta", td)
tweetitems.append(item)
self.getControl(32501).reset()
self.getControl(32501).addItems(tweetitems)
if tweetitems:
self.setFocusId(32501)
return
def reset(self):
if os.path.exists(tweet_file):
os.remove(tweet_file)
xbmcgui.Dialog().ok(translate(32000), translate(32045))
return
def stopRunning(self):
self.isRunning = False
self.close()
if not self.standalone:
mainmenu.start()
def onAction(self,action):
if action.getId() == 92 or action.getId() == 10:
self.stopRunning()
def onClick(self,controlId):
if controlId == 32501:
teamid = self.getControl(controlId).getSelectedItem().getProperty("teamid")
matchhistory.start(teamid)
elif controlId == 32514:
self.reset()
def start(twitterhash=None, standalone=False):
if not twitterhash:
userInput = True
if os.path.exists(tweet_file):
twitter_data = json.loads(FileIO.fileread(tweet_file))
twitterhash = twitter_data["hash"]
twitter_mediafile = twitter_data["file"]
if twitter_mediafile == xbmc.getInfoLabel('Player.Filenameandpath'):
userInput = False
else:
userInput = False
if userInput:
dialog = xbmcgui.Dialog()
twitterhash = dialog.input(translate(32046), type=xbmcgui.INPUT_ALPHANUM)
if len(twitterhash) != 0:
twitterhash = twitterhash.replace("#","")
else:
xbmcgui.Dialog().ok(translate(32000), translate(32047))
mainmenu.start()
if twitterhash:
#Save twitter hashtag
if twitter_history_enabled == 'true':
tweet.add_hashtag_to_twitter_history(twitterhash)
if xbmc.getCondVisibility("Player.HasMedia") and save_hashes_during_playback == 'true':
tweet.savecurrenthash(twitterhash)
main = TwitterDialog('script-matchcenter-Twitter.xml', addon_path, getskinfolder(), '', hash=twitterhash, standalone=standalone)
main.doModal()
del main | 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 | random_line_split |
tweets.py | # -*- coding: utf-8 -*-
'''
script.matchcenter - Football information for Kodi
A program addon that can be mapped to a key on your remote to display football information.
Livescores, Event details, Line-ups, League tables, next and previous matches by team. Follow what
others are saying about the match in twitter.
Copyright (C) 2016 enen92
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
'''
import xbmcgui
import xbmc
import datetime
import json
import mainmenu
import os
from resources.lib.utilities import tweet
from resources.lib.utilities.addonfileio import FileIO
from resources.lib.utilities import ssutils
from resources.lib.utilities.common_addon import *
class TwitterDialog(xbmcgui.WindowXMLDialog):
def __init__( self, *args, **kwargs ):
self.isRunning = True
self.hash = kwargs["hash"]
self.standalone = kwargs["standalone"]
self.teamObjs = {}
def onInit(self):
xbmc.log(msg="[Match Center] Twitter cycle started", level=xbmc.LOGDEBUG)
self.getControl(32540).setImage(os.path.join(addon_path,"resources","img","goal.png"))
xbmc.executebuiltin("SetProperty(loading-script-matchcenter-twitter,1,home)")
self.getTweets()
xbmc.executebuiltin("ClearProperty(loading-script-matchcenter-twitter,Home)")
i=0
while self.isRunning:
if (float(i*200)/(twitter_update_time*60*1000)).is_integer() and ((i*200)/(3*60*1000)) != 0:
self.getTweets()
xbmc.sleep(200)
i += 1
xbmc.log(msg="[Match Center] Twitter cycle stopped", level=xbmc.LOGDEBUG)
def getTweets(self):
self.getControl(32500).setLabel("#"+self.hash)
self.getControl(32503).setImage(os.path.join(addon_path,"resources","img","twitter_sm.png"))
tweetitems = []
tweets = tweet.get_hashtag_tweets(self.hash)
if tweets:
for _tweet in tweets:
td = ssutils.get_timedelta_string(datetime.datetime.utcnow() - _tweet["date"])
item = xbmcgui.ListItem(_tweet["text"].replace("\n",""))
item.setProperty("profilepic",_tweet["profilepic"])
item.setProperty("author","[B]" +"@" + _tweet["author"] + "[/B]")
item.setProperty("timedelta", td)
tweetitems.append(item)
self.getControl(32501).reset()
self.getControl(32501).addItems(tweetitems)
if tweetitems:
self.setFocusId(32501)
return
def reset(self):
if os.path.exists(tweet_file):
os.remove(tweet_file)
xbmcgui.Dialog().ok(translate(32000), translate(32045))
return
def stopRunning(self):
self.isRunning = False
self.close()
if not self.standalone:
mainmenu.start()
def onAction(self,action):
if action.getId() == 92 or action.getId() == 10:
self.stopRunning()
def onClick(self,controlId):
if controlId == 32501:
teamid = self.getControl(controlId).getSelectedItem().getProperty("teamid")
matchhistory.start(teamid)
elif controlId == 32514:
self.reset()
def | (twitterhash=None, standalone=False):
if not twitterhash:
userInput = True
if os.path.exists(tweet_file):
twitter_data = json.loads(FileIO.fileread(tweet_file))
twitterhash = twitter_data["hash"]
twitter_mediafile = twitter_data["file"]
if twitter_mediafile == xbmc.getInfoLabel('Player.Filenameandpath'):
userInput = False
else:
userInput = False
if userInput:
dialog = xbmcgui.Dialog()
twitterhash = dialog.input(translate(32046), type=xbmcgui.INPUT_ALPHANUM)
if len(twitterhash) != 0:
twitterhash = twitterhash.replace("#","")
else:
xbmcgui.Dialog().ok(translate(32000), translate(32047))
mainmenu.start()
if twitterhash:
#Save twitter hashtag
if twitter_history_enabled == 'true':
tweet.add_hashtag_to_twitter_history(twitterhash)
if xbmc.getCondVisibility("Player.HasMedia") and save_hashes_during_playback == 'true':
tweet.savecurrenthash(twitterhash)
main = TwitterDialog('script-matchcenter-Twitter.xml', addon_path, getskinfolder(), '', hash=twitterhash, standalone=standalone)
main.doModal()
del main
| start | identifier_name |
tweets.py | # -*- coding: utf-8 -*-
'''
script.matchcenter - Football information for Kodi
A program addon that can be mapped to a key on your remote to display football information.
Livescores, Event details, Line-ups, League tables, next and previous matches by team. Follow what
others are saying about the match in twitter.
Copyright (C) 2016 enen92
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
'''
import xbmcgui
import xbmc
import datetime
import json
import mainmenu
import os
from resources.lib.utilities import tweet
from resources.lib.utilities.addonfileio import FileIO
from resources.lib.utilities import ssutils
from resources.lib.utilities.common_addon import *
class TwitterDialog(xbmcgui.WindowXMLDialog):
|
def start(twitterhash=None, standalone=False):
if not twitterhash:
userInput = True
if os.path.exists(tweet_file):
twitter_data = json.loads(FileIO.fileread(tweet_file))
twitterhash = twitter_data["hash"]
twitter_mediafile = twitter_data["file"]
if twitter_mediafile == xbmc.getInfoLabel('Player.Filenameandpath'):
userInput = False
else:
userInput = False
if userInput:
dialog = xbmcgui.Dialog()
twitterhash = dialog.input(translate(32046), type=xbmcgui.INPUT_ALPHANUM)
if len(twitterhash) != 0:
twitterhash = twitterhash.replace("#","")
else:
xbmcgui.Dialog().ok(translate(32000), translate(32047))
mainmenu.start()
if twitterhash:
#Save twitter hashtag
if twitter_history_enabled == 'true':
tweet.add_hashtag_to_twitter_history(twitterhash)
if xbmc.getCondVisibility("Player.HasMedia") and save_hashes_during_playback == 'true':
tweet.savecurrenthash(twitterhash)
main = TwitterDialog('script-matchcenter-Twitter.xml', addon_path, getskinfolder(), '', hash=twitterhash, standalone=standalone)
main.doModal()
del main
| def __init__( self, *args, **kwargs ):
self.isRunning = True
self.hash = kwargs["hash"]
self.standalone = kwargs["standalone"]
self.teamObjs = {}
def onInit(self):
xbmc.log(msg="[Match Center] Twitter cycle started", level=xbmc.LOGDEBUG)
self.getControl(32540).setImage(os.path.join(addon_path,"resources","img","goal.png"))
xbmc.executebuiltin("SetProperty(loading-script-matchcenter-twitter,1,home)")
self.getTweets()
xbmc.executebuiltin("ClearProperty(loading-script-matchcenter-twitter,Home)")
i=0
while self.isRunning:
if (float(i*200)/(twitter_update_time*60*1000)).is_integer() and ((i*200)/(3*60*1000)) != 0:
self.getTweets()
xbmc.sleep(200)
i += 1
xbmc.log(msg="[Match Center] Twitter cycle stopped", level=xbmc.LOGDEBUG)
def getTweets(self):
self.getControl(32500).setLabel("#"+self.hash)
self.getControl(32503).setImage(os.path.join(addon_path,"resources","img","twitter_sm.png"))
tweetitems = []
tweets = tweet.get_hashtag_tweets(self.hash)
if tweets:
for _tweet in tweets:
td = ssutils.get_timedelta_string(datetime.datetime.utcnow() - _tweet["date"])
item = xbmcgui.ListItem(_tweet["text"].replace("\n",""))
item.setProperty("profilepic",_tweet["profilepic"])
item.setProperty("author","[B]" +"@" + _tweet["author"] + "[/B]")
item.setProperty("timedelta", td)
tweetitems.append(item)
self.getControl(32501).reset()
self.getControl(32501).addItems(tweetitems)
if tweetitems:
self.setFocusId(32501)
return
def reset(self):
if os.path.exists(tweet_file):
os.remove(tweet_file)
xbmcgui.Dialog().ok(translate(32000), translate(32045))
return
def stopRunning(self):
self.isRunning = False
self.close()
if not self.standalone:
mainmenu.start()
def onAction(self,action):
if action.getId() == 92 or action.getId() == 10:
self.stopRunning()
def onClick(self,controlId):
if controlId == 32501:
teamid = self.getControl(controlId).getSelectedItem().getProperty("teamid")
matchhistory.start(teamid)
elif controlId == 32514:
self.reset() | identifier_body |
tweets.py | # -*- coding: utf-8 -*-
'''
script.matchcenter - Football information for Kodi
A program addon that can be mapped to a key on your remote to display football information.
Livescores, Event details, Line-ups, League tables, next and previous matches by team. Follow what
others are saying about the match in twitter.
Copyright (C) 2016 enen92
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
'''
import xbmcgui
import xbmc
import datetime
import json
import mainmenu
import os
from resources.lib.utilities import tweet
from resources.lib.utilities.addonfileio import FileIO
from resources.lib.utilities import ssutils
from resources.lib.utilities.common_addon import *
class TwitterDialog(xbmcgui.WindowXMLDialog):
def __init__( self, *args, **kwargs ):
self.isRunning = True
self.hash = kwargs["hash"]
self.standalone = kwargs["standalone"]
self.teamObjs = {}
def onInit(self):
xbmc.log(msg="[Match Center] Twitter cycle started", level=xbmc.LOGDEBUG)
self.getControl(32540).setImage(os.path.join(addon_path,"resources","img","goal.png"))
xbmc.executebuiltin("SetProperty(loading-script-matchcenter-twitter,1,home)")
self.getTweets()
xbmc.executebuiltin("ClearProperty(loading-script-matchcenter-twitter,Home)")
i=0
while self.isRunning:
if (float(i*200)/(twitter_update_time*60*1000)).is_integer() and ((i*200)/(3*60*1000)) != 0:
self.getTweets()
xbmc.sleep(200)
i += 1
xbmc.log(msg="[Match Center] Twitter cycle stopped", level=xbmc.LOGDEBUG)
def getTweets(self):
self.getControl(32500).setLabel("#"+self.hash)
self.getControl(32503).setImage(os.path.join(addon_path,"resources","img","twitter_sm.png"))
tweetitems = []
tweets = tweet.get_hashtag_tweets(self.hash)
if tweets:
for _tweet in tweets:
td = ssutils.get_timedelta_string(datetime.datetime.utcnow() - _tweet["date"])
item = xbmcgui.ListItem(_tweet["text"].replace("\n",""))
item.setProperty("profilepic",_tweet["profilepic"])
item.setProperty("author","[B]" +"@" + _tweet["author"] + "[/B]")
item.setProperty("timedelta", td)
tweetitems.append(item)
self.getControl(32501).reset()
self.getControl(32501).addItems(tweetitems)
if tweetitems:
self.setFocusId(32501)
return
def reset(self):
if os.path.exists(tweet_file):
os.remove(tweet_file)
xbmcgui.Dialog().ok(translate(32000), translate(32045))
return
def stopRunning(self):
self.isRunning = False
self.close()
if not self.standalone:
mainmenu.start()
def onAction(self,action):
if action.getId() == 92 or action.getId() == 10:
self.stopRunning()
def onClick(self,controlId):
if controlId == 32501:
teamid = self.getControl(controlId).getSelectedItem().getProperty("teamid")
matchhistory.start(teamid)
elif controlId == 32514:
self.reset()
def start(twitterhash=None, standalone=False):
if not twitterhash:
userInput = True
if os.path.exists(tweet_file):
twitter_data = json.loads(FileIO.fileread(tweet_file))
twitterhash = twitter_data["hash"]
twitter_mediafile = twitter_data["file"]
if twitter_mediafile == xbmc.getInfoLabel('Player.Filenameandpath'):
userInput = False
else:
userInput = False
if userInput:
|
if twitterhash:
#Save twitter hashtag
if twitter_history_enabled == 'true':
tweet.add_hashtag_to_twitter_history(twitterhash)
if xbmc.getCondVisibility("Player.HasMedia") and save_hashes_during_playback == 'true':
tweet.savecurrenthash(twitterhash)
main = TwitterDialog('script-matchcenter-Twitter.xml', addon_path, getskinfolder(), '', hash=twitterhash, standalone=standalone)
main.doModal()
del main
| dialog = xbmcgui.Dialog()
twitterhash = dialog.input(translate(32046), type=xbmcgui.INPUT_ALPHANUM)
if len(twitterhash) != 0:
twitterhash = twitterhash.replace("#","")
else:
xbmcgui.Dialog().ok(translate(32000), translate(32047))
mainmenu.start() | conditional_block |
os.rs | // Copyright 2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
// FIXME: move various extern bindings from here into liblibc or
// something similar |
use libc;
use libc::{c_int, c_char, c_void};
use prelude::*;
use io::{IoResult, IoError};
use sys::fs::FileDesc;
use ptr;
use os::TMPBUF_SZ;
pub fn errno() -> uint {
use libc::types::os::arch::extra::DWORD;
#[link_name = "kernel32"]
extern "system" {
fn GetLastError() -> DWORD;
}
unsafe {
GetLastError() as uint
}
}
/// Get a detailed string description for the given error number
pub fn error_string(errnum: i32) -> String {
use libc::types::os::arch::extra::DWORD;
use libc::types::os::arch::extra::LPWSTR;
use libc::types::os::arch::extra::LPVOID;
use libc::types::os::arch::extra::WCHAR;
#[link_name = "kernel32"]
extern "system" {
fn FormatMessageW(flags: DWORD,
lpSrc: LPVOID,
msgId: DWORD,
langId: DWORD,
buf: LPWSTR,
nsize: DWORD,
args: *const c_void)
-> DWORD;
}
static FORMAT_MESSAGE_FROM_SYSTEM: DWORD = 0x00001000;
static FORMAT_MESSAGE_IGNORE_INSERTS: DWORD = 0x00000200;
// This value is calculated from the macro
// MAKELANGID(LANG_SYSTEM_DEFAULT, SUBLANG_SYS_DEFAULT)
let langId = 0x0800 as DWORD;
let mut buf = [0 as WCHAR, ..TMPBUF_SZ];
unsafe {
let res = FormatMessageW(FORMAT_MESSAGE_FROM_SYSTEM |
FORMAT_MESSAGE_IGNORE_INSERTS,
ptr::null_mut(),
errnum as DWORD,
langId,
buf.as_mut_ptr(),
buf.len() as DWORD,
ptr::null());
if res == 0 {
// Sometimes FormatMessageW can fail e.g. system doesn't like langId,
let fm_err = errno();
return format!("OS Error {} (FormatMessageW() returned error {})", errnum, fm_err);
}
let msg = String::from_utf16(::str::truncate_utf16_at_nul(buf));
match msg {
Some(msg) => format!("OS Error {}: {}", errnum, msg),
None => format!("OS Error {} (FormatMessageW() returned invalid UTF-16)", errnum),
}
}
}
pub unsafe fn pipe() -> IoResult<(FileDesc, FileDesc)> {
// Windows pipes work subtly differently than unix pipes, and their
// inheritance has to be handled in a different way that I do not
// fully understand. Here we explicitly make the pipe non-inheritable,
// which means to pass it to a subprocess they need to be duplicated
// first, as in std::run.
let mut fds = [0, ..2];
match libc::pipe(fds.as_mut_ptr(), 1024 as ::libc::c_uint,
(libc::O_BINARY | libc::O_NOINHERIT) as c_int) {
0 => {
assert!(fds[0] != -1 && fds[0] != 0);
assert!(fds[1] != -1 && fds[1] != 0);
Ok((FileDesc::new(fds[0], true), FileDesc::new(fds[1], true)))
}
_ => Err(IoError::last_error()),
}
} | random_line_split | |
os.rs | // Copyright 2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
// FIXME: move various extern bindings from here into liblibc or
// something similar
use libc;
use libc::{c_int, c_char, c_void};
use prelude::*;
use io::{IoResult, IoError};
use sys::fs::FileDesc;
use ptr;
use os::TMPBUF_SZ;
pub fn errno() -> uint {
use libc::types::os::arch::extra::DWORD;
#[link_name = "kernel32"]
extern "system" {
fn GetLastError() -> DWORD;
}
unsafe {
GetLastError() as uint
}
}
/// Get a detailed string description for the given error number
pub fn error_string(errnum: i32) -> String {
use libc::types::os::arch::extra::DWORD;
use libc::types::os::arch::extra::LPWSTR;
use libc::types::os::arch::extra::LPVOID;
use libc::types::os::arch::extra::WCHAR;
#[link_name = "kernel32"]
extern "system" {
fn FormatMessageW(flags: DWORD,
lpSrc: LPVOID,
msgId: DWORD,
langId: DWORD,
buf: LPWSTR,
nsize: DWORD,
args: *const c_void)
-> DWORD;
}
static FORMAT_MESSAGE_FROM_SYSTEM: DWORD = 0x00001000;
static FORMAT_MESSAGE_IGNORE_INSERTS: DWORD = 0x00000200;
// This value is calculated from the macro
// MAKELANGID(LANG_SYSTEM_DEFAULT, SUBLANG_SYS_DEFAULT)
let langId = 0x0800 as DWORD;
let mut buf = [0 as WCHAR, ..TMPBUF_SZ];
unsafe {
let res = FormatMessageW(FORMAT_MESSAGE_FROM_SYSTEM |
FORMAT_MESSAGE_IGNORE_INSERTS,
ptr::null_mut(),
errnum as DWORD,
langId,
buf.as_mut_ptr(),
buf.len() as DWORD,
ptr::null());
if res == 0 {
// Sometimes FormatMessageW can fail e.g. system doesn't like langId,
let fm_err = errno();
return format!("OS Error {} (FormatMessageW() returned error {})", errnum, fm_err);
}
let msg = String::from_utf16(::str::truncate_utf16_at_nul(buf));
match msg {
Some(msg) => format!("OS Error {}: {}", errnum, msg),
None => format!("OS Error {} (FormatMessageW() returned invalid UTF-16)", errnum),
}
}
}
pub unsafe fn pipe() -> IoResult<(FileDesc, FileDesc)> | {
// Windows pipes work subtly differently than unix pipes, and their
// inheritance has to be handled in a different way that I do not
// fully understand. Here we explicitly make the pipe non-inheritable,
// which means to pass it to a subprocess they need to be duplicated
// first, as in std::run.
let mut fds = [0, ..2];
match libc::pipe(fds.as_mut_ptr(), 1024 as ::libc::c_uint,
(libc::O_BINARY | libc::O_NOINHERIT) as c_int) {
0 => {
assert!(fds[0] != -1 && fds[0] != 0);
assert!(fds[1] != -1 && fds[1] != 0);
Ok((FileDesc::new(fds[0], true), FileDesc::new(fds[1], true)))
}
_ => Err(IoError::last_error()),
}
} | identifier_body | |
os.rs | // Copyright 2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
// FIXME: move various extern bindings from here into liblibc or
// something similar
use libc;
use libc::{c_int, c_char, c_void};
use prelude::*;
use io::{IoResult, IoError};
use sys::fs::FileDesc;
use ptr;
use os::TMPBUF_SZ;
pub fn errno() -> uint {
use libc::types::os::arch::extra::DWORD;
#[link_name = "kernel32"]
extern "system" {
fn GetLastError() -> DWORD;
}
unsafe {
GetLastError() as uint
}
}
/// Get a detailed string description for the given error number
pub fn error_string(errnum: i32) -> String {
use libc::types::os::arch::extra::DWORD;
use libc::types::os::arch::extra::LPWSTR;
use libc::types::os::arch::extra::LPVOID;
use libc::types::os::arch::extra::WCHAR;
#[link_name = "kernel32"]
extern "system" {
fn FormatMessageW(flags: DWORD,
lpSrc: LPVOID,
msgId: DWORD,
langId: DWORD,
buf: LPWSTR,
nsize: DWORD,
args: *const c_void)
-> DWORD;
}
static FORMAT_MESSAGE_FROM_SYSTEM: DWORD = 0x00001000;
static FORMAT_MESSAGE_IGNORE_INSERTS: DWORD = 0x00000200;
// This value is calculated from the macro
// MAKELANGID(LANG_SYSTEM_DEFAULT, SUBLANG_SYS_DEFAULT)
let langId = 0x0800 as DWORD;
let mut buf = [0 as WCHAR, ..TMPBUF_SZ];
unsafe {
let res = FormatMessageW(FORMAT_MESSAGE_FROM_SYSTEM |
FORMAT_MESSAGE_IGNORE_INSERTS,
ptr::null_mut(),
errnum as DWORD,
langId,
buf.as_mut_ptr(),
buf.len() as DWORD,
ptr::null());
if res == 0 |
let msg = String::from_utf16(::str::truncate_utf16_at_nul(buf));
match msg {
Some(msg) => format!("OS Error {}: {}", errnum, msg),
None => format!("OS Error {} (FormatMessageW() returned invalid UTF-16)", errnum),
}
}
}
pub unsafe fn pipe() -> IoResult<(FileDesc, FileDesc)> {
// Windows pipes work subtly differently than unix pipes, and their
// inheritance has to be handled in a different way that I do not
// fully understand. Here we explicitly make the pipe non-inheritable,
// which means to pass it to a subprocess they need to be duplicated
// first, as in std::run.
let mut fds = [0, ..2];
match libc::pipe(fds.as_mut_ptr(), 1024 as ::libc::c_uint,
(libc::O_BINARY | libc::O_NOINHERIT) as c_int) {
0 => {
assert!(fds[0] != -1 && fds[0] != 0);
assert!(fds[1] != -1 && fds[1] != 0);
Ok((FileDesc::new(fds[0], true), FileDesc::new(fds[1], true)))
}
_ => Err(IoError::last_error()),
}
}
| {
// Sometimes FormatMessageW can fail e.g. system doesn't like langId,
let fm_err = errno();
return format!("OS Error {} (FormatMessageW() returned error {})", errnum, fm_err);
} | conditional_block |
os.rs | // Copyright 2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
// FIXME: move various extern bindings from here into liblibc or
// something similar
use libc;
use libc::{c_int, c_char, c_void};
use prelude::*;
use io::{IoResult, IoError};
use sys::fs::FileDesc;
use ptr;
use os::TMPBUF_SZ;
pub fn | () -> uint {
use libc::types::os::arch::extra::DWORD;
#[link_name = "kernel32"]
extern "system" {
fn GetLastError() -> DWORD;
}
unsafe {
GetLastError() as uint
}
}
/// Get a detailed string description for the given error number
pub fn error_string(errnum: i32) -> String {
use libc::types::os::arch::extra::DWORD;
use libc::types::os::arch::extra::LPWSTR;
use libc::types::os::arch::extra::LPVOID;
use libc::types::os::arch::extra::WCHAR;
#[link_name = "kernel32"]
extern "system" {
fn FormatMessageW(flags: DWORD,
lpSrc: LPVOID,
msgId: DWORD,
langId: DWORD,
buf: LPWSTR,
nsize: DWORD,
args: *const c_void)
-> DWORD;
}
static FORMAT_MESSAGE_FROM_SYSTEM: DWORD = 0x00001000;
static FORMAT_MESSAGE_IGNORE_INSERTS: DWORD = 0x00000200;
// This value is calculated from the macro
// MAKELANGID(LANG_SYSTEM_DEFAULT, SUBLANG_SYS_DEFAULT)
let langId = 0x0800 as DWORD;
let mut buf = [0 as WCHAR, ..TMPBUF_SZ];
unsafe {
let res = FormatMessageW(FORMAT_MESSAGE_FROM_SYSTEM |
FORMAT_MESSAGE_IGNORE_INSERTS,
ptr::null_mut(),
errnum as DWORD,
langId,
buf.as_mut_ptr(),
buf.len() as DWORD,
ptr::null());
if res == 0 {
// Sometimes FormatMessageW can fail e.g. system doesn't like langId,
let fm_err = errno();
return format!("OS Error {} (FormatMessageW() returned error {})", errnum, fm_err);
}
let msg = String::from_utf16(::str::truncate_utf16_at_nul(buf));
match msg {
Some(msg) => format!("OS Error {}: {}", errnum, msg),
None => format!("OS Error {} (FormatMessageW() returned invalid UTF-16)", errnum),
}
}
}
pub unsafe fn pipe() -> IoResult<(FileDesc, FileDesc)> {
// Windows pipes work subtly differently than unix pipes, and their
// inheritance has to be handled in a different way that I do not
// fully understand. Here we explicitly make the pipe non-inheritable,
// which means to pass it to a subprocess they need to be duplicated
// first, as in std::run.
let mut fds = [0, ..2];
match libc::pipe(fds.as_mut_ptr(), 1024 as ::libc::c_uint,
(libc::O_BINARY | libc::O_NOINHERIT) as c_int) {
0 => {
assert!(fds[0] != -1 && fds[0] != 0);
assert!(fds[1] != -1 && fds[1] != 0);
Ok((FileDesc::new(fds[0], true), FileDesc::new(fds[1], true)))
}
_ => Err(IoError::last_error()),
}
}
| errno | identifier_name |
cisco_constants.py | # Copyright 2011 Cisco Systems, Inc. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations | # Attachment attributes
INSTANCE_ID = 'instance_id'
TENANT_ID = 'tenant_id'
TENANT_NAME = 'tenant_name'
HOST_NAME = 'host_name'
# Network attributes
NET_ID = 'id'
NET_NAME = 'name'
NET_VLAN_ID = 'vlan_id'
NET_VLAN_NAME = 'vlan_name'
NET_PORTS = 'ports'
CREDENTIAL_ID = 'credential_id'
CREDENTIAL_NAME = 'credential_name'
CREDENTIAL_USERNAME = 'user_name'
CREDENTIAL_PASSWORD = 'password'
CREDENTIAL_TYPE = 'type'
MASKED_PASSWORD = '********'
USERNAME = 'username'
PASSWORD = 'password'
LOGGER_COMPONENT_NAME = "cisco_plugin"
NEXUS_PLUGIN = 'nexus_plugin'
VSWITCH_PLUGIN = 'vswitch_plugin'
DEVICE_IP = 'device_ip'
NETWORK_ADMIN = 'network_admin'
NETWORK = 'network'
PORT = 'port'
BASE_PLUGIN_REF = 'base_plugin_ref'
CONTEXT = 'context'
SUBNET = 'subnet'
#### N1Kv CONSTANTS
# Special vlan_id value in n1kv_vlan_allocations table indicating flat network
FLAT_VLAN_ID = -1
# Topic for tunnel notifications between the plugin and agent
TUNNEL = 'tunnel'
# Maximum VXLAN range configurable for one network profile.
MAX_VXLAN_RANGE = 1000000
# Values for network_type
NETWORK_TYPE_FLAT = 'flat'
NETWORK_TYPE_VLAN = 'vlan'
NETWORK_TYPE_VXLAN = 'vxlan'
NETWORK_TYPE_LOCAL = 'local'
NETWORK_TYPE_NONE = 'none'
NETWORK_TYPE_TRUNK = 'trunk'
NETWORK_TYPE_MULTI_SEGMENT = 'multi-segment'
# Values for network sub_type
NETWORK_TYPE_OVERLAY = 'overlay'
NETWORK_SUBTYPE_NATIVE_VXLAN = 'native_vxlan'
NETWORK_SUBTYPE_TRUNK_VLAN = NETWORK_TYPE_VLAN
NETWORK_SUBTYPE_TRUNK_VXLAN = NETWORK_TYPE_OVERLAY
# Prefix for VM Network name
VM_NETWORK_NAME_PREFIX = 'vmn_'
DEFAULT_HTTP_TIMEOUT = 15
SET = 'set'
INSTANCE = 'instance'
PROPERTIES = 'properties'
NAME = 'name'
ID = 'id'
POLICY = 'policy'
TENANT_ID_NOT_SET = 'TENANT_ID_NOT_SET'
ENCAPSULATIONS = 'encapsulations'
STATE = 'state'
ONLINE = 'online'
MAPPINGS = 'mappings'
MAPPING = 'mapping'
SEGMENTS = 'segments'
SEGMENT = 'segment'
BRIDGE_DOMAIN_SUFFIX = '_bd'
LOGICAL_NETWORK_SUFFIX = '_log_net'
ENCAPSULATION_PROFILE_SUFFIX = '_profile'
UUID_LENGTH = 36
# Nexus vlan and vxlan segment range
NEXUS_VLAN_RESERVED_MIN = 3968
NEXUS_VLAN_RESERVED_MAX = 4047
NEXUS_VXLAN_MIN = 4096
NEXUS_VXLAN_MAX = 16000000 | # under the License.
#
# @author: Sumit Naiksatam, Cisco Systems, Inc.
| random_line_split |
Npc.js | import Objects from './'
import Character from './Character'
import Actions from '../actions'
import Attacks from '../actions/Attacks'
import Dash from '../actions/Dash'
const addMoveAnimations = function () {
Object.keys(this.directions).map(
(direction) => this.atlasAnimations.add({
action: Actions.move,
direction,
speed: 8
})
)
}
const addAtkAnimations = function () {
Object.keys(this.directions).map(
(direction) => this.atlasAnimations.add({
action: Actions.atk,
direction,
speed: 13
})
)
}
export default class extends Character {
constructor ({
game, x, y, name
}) {
super({
game,
x,
y,
name,
type: Objects.npc,
firstSprite: `${name}-move-down-1`
})
this.setActions([
new Attacks({
character: this,
attacks: [{id: 0, type: 'normal', time: 24, speed: 13, cooldown: 15}]
}),
new Dash({
character: this,
dash: {time: 15, speed: 300, cooldown: 15}
})
])
this.speed = 140
addMoveAnimations.call(this)
addAtkAnimations.call(this)
}
| () {
super.update()
}
}
| update | identifier_name |
Npc.js | import Objects from './'
import Character from './Character'
import Actions from '../actions'
import Attacks from '../actions/Attacks'
import Dash from '../actions/Dash'
const addMoveAnimations = function () {
Object.keys(this.directions).map(
(direction) => this.atlasAnimations.add({
action: Actions.move,
direction,
speed: 8
})
)
}
const addAtkAnimations = function () {
Object.keys(this.directions).map(
(direction) => this.atlasAnimations.add({
action: Actions.atk,
direction,
speed: 13
})
) | }) {
super({
game,
x,
y,
name,
type: Objects.npc,
firstSprite: `${name}-move-down-1`
})
this.setActions([
new Attacks({
character: this,
attacks: [{id: 0, type: 'normal', time: 24, speed: 13, cooldown: 15}]
}),
new Dash({
character: this,
dash: {time: 15, speed: 300, cooldown: 15}
})
])
this.speed = 140
addMoveAnimations.call(this)
addAtkAnimations.call(this)
}
update () {
super.update()
}
} | }
export default class extends Character {
constructor ({
game, x, y, name | random_line_split |
Npc.js | import Objects from './'
import Character from './Character'
import Actions from '../actions'
import Attacks from '../actions/Attacks'
import Dash from '../actions/Dash'
const addMoveAnimations = function () {
Object.keys(this.directions).map(
(direction) => this.atlasAnimations.add({
action: Actions.move,
direction,
speed: 8
})
)
}
const addAtkAnimations = function () {
Object.keys(this.directions).map(
(direction) => this.atlasAnimations.add({
action: Actions.atk,
direction,
speed: 13
})
)
}
export default class extends Character {
constructor ({
game, x, y, name
}) |
update () {
super.update()
}
}
| {
super({
game,
x,
y,
name,
type: Objects.npc,
firstSprite: `${name}-move-down-1`
})
this.setActions([
new Attacks({
character: this,
attacks: [{id: 0, type: 'normal', time: 24, speed: 13, cooldown: 15}]
}),
new Dash({
character: this,
dash: {time: 15, speed: 300, cooldown: 15}
})
])
this.speed = 140
addMoveAnimations.call(this)
addAtkAnimations.call(this)
} | identifier_body |
formatagesource0.rs | use std::fmt::{self, Formatter, Display};
struct City {
name: &'static str,
// Latitude
lat: f32,
// Longitude
lon: f32,
}
impl Display for City {
// `f` est un tampon, cette méthode écrit la chaîne de caractères
// formattée à l'intérieur de ce dernier.
fn fmt(&se | f: &mut Formatter) -> fmt::Result {
let lat_c = if self.lat >= 0.0 { 'N' } else { 'S' };
let lon_c = if self.lon >= 0.0 { 'E' } else { 'W' };
// `write!` est équivalente à `format!`, à l'exception qu'elle écrira
// la chaîne de caractères formatée dans un tampon (le premier argument).
write!(f, "{}: {:.3}°{} {:.3}°{}",
self.name, self.lat.abs(), lat_c, self.lon.abs(), lon_c)
}
}
#[derive(Debug)]
struct Color {
red: u8,
green: u8,
blue: u8,
}
fn main() {
for city in [
City { name: "Dublin", lat: 53.347778, lon: -6.259722 },
City { name: "Oslo", lat: 59.95, lon: 10.75 },
City { name: "Vancouver", lat: 49.25, lon: -123.1 },
].iter() {
println!("{}", *city);
}
for color in [
Color { red: 128, green: 255, blue: 90 },
Color { red: 0, green: 3, blue: 254 },
Color { red: 0, green: 0, blue: 0 },
].iter() {
// Utilisez le marqueur `{}` une fois que vous aurez implémenté
// le trait fmt::Display.
println!("{:?}", *color)
}
} | lf, | identifier_name |
formatagesource0.rs | use std::fmt::{self, Formatter, Display};
struct City {
name: &'static str,
// Latitude
lat: f32,
// Longitude
lon: f32,
}
impl Display for City {
// `f` est un tampon, cette méthode écrit la chaîne de caractères
// formattée à l'intérieur de ce dernier.
fn fmt(&self, f: &mut Formatter) -> fmt::Result {
let lat_c = if self.lat >= 0.0 { 'N' } else { 'S' };
let lon_c = if self.lon >= 0.0 { 'E' } else { 'W' };
// `write!` est équivalente à `format!`, à l'exception qu'elle écrira
// la chaîne de caractères formatée dans un tampon (le premier argument).
write!(f, "{}: {:.3}°{} {:.3}°{}",
self.name, self.lat.abs(), lat_c, self.lon.abs(), lon_c)
}
}
#[derive(Debug)]
struct Color {
red: u8,
green: u8,
blue: u8,
}
fn main() {
for city in [
City { name: "Dublin", lat: 53.347778, lon: -6.259722 },
City { name: "Oslo", lat: 59.95, lon: 10.75 },
City { name: "Vancouver", lat: 49.25, lon: -123.1 },
].iter() {
println!("{}", *city);
}
for color in [
Color { red: 128, green: 255, blue: 90 }, | // le trait fmt::Display.
println!("{:?}", *color)
}
} | Color { red: 0, green: 3, blue: 254 },
Color { red: 0, green: 0, blue: 0 },
].iter() {
// Utilisez le marqueur `{}` une fois que vous aurez implémenté | random_line_split |
formatagesource0.rs | use std::fmt::{self, Formatter, Display};
struct City {
name: &'static str,
// Latitude
lat: f32,
// Longitude
lon: f32,
}
impl Display for City {
// `f` est un tampon, cette méthode écrit la chaîne de caractères
// formattée à l'intérieur de ce dernier.
fn fmt(&self, f: &mut Formatter) -> fmt::Result {
let lat_c = if self.lat >= 0.0 { 'N' } else { 'S' } | let lon_c = if self.lon >= 0.0 { 'E' } else { 'W' };
// `write!` est équivalente à `format!`, à l'exception qu'elle écrira
// la chaîne de caractères formatée dans un tampon (le premier argument).
write!(f, "{}: {:.3}°{} {:.3}°{}",
self.name, self.lat.abs(), lat_c, self.lon.abs(), lon_c)
}
}
#[derive(Debug)]
struct Color {
red: u8,
green: u8,
blue: u8,
}
fn main() {
for city in [
City { name: "Dublin", lat: 53.347778, lon: -6.259722 },
City { name: "Oslo", lat: 59.95, lon: 10.75 },
City { name: "Vancouver", lat: 49.25, lon: -123.1 },
].iter() {
println!("{}", *city);
}
for color in [
Color { red: 128, green: 255, blue: 90 },
Color { red: 0, green: 3, blue: 254 },
Color { red: 0, green: 0, blue: 0 },
].iter() {
// Utilisez le marqueur `{}` une fois que vous aurez implémenté
// le trait fmt::Display.
println!("{:?}", *color)
}
} | ;
| conditional_block |
models.py | from django.db import models
# Create your models here.
MEASUREMENT = (
('c', 'cups'),
('tsp', 'teaspoons'),
('tbsp', 'tablespoons'),
('item', 'item'),
)
class Step(models.Model):
"""A step in a recipe"""
order = models.IntegerField()
directions = models.TextField()
recipe = models.ForeignKey('Recipe')
class Tag(models.Model):
"""A tag to identify a recipe"""
name = models.CharField(max_length=50)
recipes = models.ManyToManyField('Recipe')
def __str__(self):
return self.name
class RecipeIngredient(models.Model):
ingredient = models.ForeignKey('Ingredient')
recipe = models.ForeignKey('Recipe')
quantity = models.FloatField()
unit = models.CharField(choices=MEASUREMENT, max_length=10)
description = models.CharField(max_length=100)
notes = models.TextField()
class Ingredient(models.Model):
name = models.CharField(max_length=100)
def __str__(self):
return self.name
| class Recipe(models.Model):
name = models.CharField(max_length=100)
def __str__(self):
return self.name | random_line_split | |
models.py | from django.db import models
# Create your models here.
MEASUREMENT = (
('c', 'cups'),
('tsp', 'teaspoons'),
('tbsp', 'tablespoons'),
('item', 'item'),
)
class Step(models.Model):
"""A step in a recipe"""
order = models.IntegerField()
directions = models.TextField()
recipe = models.ForeignKey('Recipe')
class Tag(models.Model):
"""A tag to identify a recipe"""
name = models.CharField(max_length=50)
recipes = models.ManyToManyField('Recipe')
def __str__(self):
return self.name
class RecipeIngredient(models.Model):
ingredient = models.ForeignKey('Ingredient')
recipe = models.ForeignKey('Recipe')
quantity = models.FloatField()
unit = models.CharField(choices=MEASUREMENT, max_length=10)
description = models.CharField(max_length=100)
notes = models.TextField()
class Ingredient(models.Model):
name = models.CharField(max_length=100)
def __str__(self):
return self.name
class Recipe(models.Model):
| name = models.CharField(max_length=100)
def __str__(self):
return self.name | identifier_body | |
models.py | from django.db import models
# Create your models here.
MEASUREMENT = (
('c', 'cups'),
('tsp', 'teaspoons'),
('tbsp', 'tablespoons'),
('item', 'item'),
)
class Step(models.Model):
"""A step in a recipe"""
order = models.IntegerField()
directions = models.TextField()
recipe = models.ForeignKey('Recipe')
class Tag(models.Model):
"""A tag to identify a recipe"""
name = models.CharField(max_length=50)
recipes = models.ManyToManyField('Recipe')
def | (self):
return self.name
class RecipeIngredient(models.Model):
ingredient = models.ForeignKey('Ingredient')
recipe = models.ForeignKey('Recipe')
quantity = models.FloatField()
unit = models.CharField(choices=MEASUREMENT, max_length=10)
description = models.CharField(max_length=100)
notes = models.TextField()
class Ingredient(models.Model):
name = models.CharField(max_length=100)
def __str__(self):
return self.name
class Recipe(models.Model):
name = models.CharField(max_length=100)
def __str__(self):
return self.name
| __str__ | identifier_name |
zeroconf.py | """
This module exposes Home Assistant via Zeroconf.
For more details about this component, please refer to the documentation at
https://home-assistant.io/components/zeroconf/
"""
import logging
import socket
import voluptuous as vol
from homeassistant import util | DOMAIN = 'zeroconf'
REQUIREMENTS = ['zeroconf==0.19.1']
ZEROCONF_TYPE = '_home-assistant._tcp.local.'
CONFIG_SCHEMA = vol.Schema({
DOMAIN: vol.Schema({}),
}, extra=vol.ALLOW_EXTRA)
def setup(hass, config):
"""Set up Zeroconf and make Home Assistant discoverable."""
from zeroconf import Zeroconf, ServiceInfo
zeroconf = Zeroconf()
zeroconf_name = '{}.{}'.format(hass.config.location_name, ZEROCONF_TYPE)
requires_api_password = hass.config.api.api_password is not None
params = {
'version': __version__,
'base_url': hass.config.api.base_url,
'requires_api_password': requires_api_password,
}
host_ip = util.get_local_ip()
try:
host_ip_pton = socket.inet_pton(socket.AF_INET, host_ip)
except socket.error:
host_ip_pton = socket.inet_pton(socket.AF_INET6, host_ip)
info = ServiceInfo(ZEROCONF_TYPE, zeroconf_name, host_ip_pton,
hass.http.server_port, 0, 0, params)
zeroconf.register_service(info)
def stop_zeroconf(event):
"""Stop Zeroconf."""
zeroconf.unregister_service(info)
zeroconf.close()
hass.bus.listen_once(EVENT_HOMEASSISTANT_STOP, stop_zeroconf)
return True | from homeassistant.const import (EVENT_HOMEASSISTANT_STOP, __version__)
_LOGGER = logging.getLogger(__name__)
DEPENDENCIES = ['api'] | random_line_split |
zeroconf.py | """
This module exposes Home Assistant via Zeroconf.
For more details about this component, please refer to the documentation at
https://home-assistant.io/components/zeroconf/
"""
import logging
import socket
import voluptuous as vol
from homeassistant import util
from homeassistant.const import (EVENT_HOMEASSISTANT_STOP, __version__)
_LOGGER = logging.getLogger(__name__)
DEPENDENCIES = ['api']
DOMAIN = 'zeroconf'
REQUIREMENTS = ['zeroconf==0.19.1']
ZEROCONF_TYPE = '_home-assistant._tcp.local.'
CONFIG_SCHEMA = vol.Schema({
DOMAIN: vol.Schema({}),
}, extra=vol.ALLOW_EXTRA)
def setup(hass, config):
"""Set up Zeroconf and make Home Assistant discoverable."""
from zeroconf import Zeroconf, ServiceInfo
zeroconf = Zeroconf()
zeroconf_name = '{}.{}'.format(hass.config.location_name, ZEROCONF_TYPE)
requires_api_password = hass.config.api.api_password is not None
params = {
'version': __version__,
'base_url': hass.config.api.base_url,
'requires_api_password': requires_api_password,
}
host_ip = util.get_local_ip()
try:
host_ip_pton = socket.inet_pton(socket.AF_INET, host_ip)
except socket.error:
host_ip_pton = socket.inet_pton(socket.AF_INET6, host_ip)
info = ServiceInfo(ZEROCONF_TYPE, zeroconf_name, host_ip_pton,
hass.http.server_port, 0, 0, params)
zeroconf.register_service(info)
def | (event):
"""Stop Zeroconf."""
zeroconf.unregister_service(info)
zeroconf.close()
hass.bus.listen_once(EVENT_HOMEASSISTANT_STOP, stop_zeroconf)
return True
| stop_zeroconf | identifier_name |
zeroconf.py | """
This module exposes Home Assistant via Zeroconf.
For more details about this component, please refer to the documentation at
https://home-assistant.io/components/zeroconf/
"""
import logging
import socket
import voluptuous as vol
from homeassistant import util
from homeassistant.const import (EVENT_HOMEASSISTANT_STOP, __version__)
_LOGGER = logging.getLogger(__name__)
DEPENDENCIES = ['api']
DOMAIN = 'zeroconf'
REQUIREMENTS = ['zeroconf==0.19.1']
ZEROCONF_TYPE = '_home-assistant._tcp.local.'
CONFIG_SCHEMA = vol.Schema({
DOMAIN: vol.Schema({}),
}, extra=vol.ALLOW_EXTRA)
def setup(hass, config):
| """Set up Zeroconf and make Home Assistant discoverable."""
from zeroconf import Zeroconf, ServiceInfo
zeroconf = Zeroconf()
zeroconf_name = '{}.{}'.format(hass.config.location_name, ZEROCONF_TYPE)
requires_api_password = hass.config.api.api_password is not None
params = {
'version': __version__,
'base_url': hass.config.api.base_url,
'requires_api_password': requires_api_password,
}
host_ip = util.get_local_ip()
try:
host_ip_pton = socket.inet_pton(socket.AF_INET, host_ip)
except socket.error:
host_ip_pton = socket.inet_pton(socket.AF_INET6, host_ip)
info = ServiceInfo(ZEROCONF_TYPE, zeroconf_name, host_ip_pton,
hass.http.server_port, 0, 0, params)
zeroconf.register_service(info)
def stop_zeroconf(event):
"""Stop Zeroconf."""
zeroconf.unregister_service(info)
zeroconf.close()
hass.bus.listen_once(EVENT_HOMEASSISTANT_STOP, stop_zeroconf)
return True | identifier_body | |
reverse_lookup.js | describe("domain landing page", () => {
beforeEach(() => {
cy.elektraLogin(
Cypress.env("TEST_DOMAIN"),
Cypress.env("TEST_USER"),
Cypress.env("TEST_PASSWORD")
)
})
| cy.visit(`/${Cypress.env("TEST_DOMAIN")}/lookup/reverselookup`)
cy.contains('[data-test=page-title]','Find Project')
cy.get('#reverseLookupValue').type('elektra-test-vm (do not delete){enter}')
cy.contains('Could not load object (Request failed with status code 404)')
cy.get('#reverseLookupValue').type('{selectall}df628236-e1a5-4dcd-9715-e204e184fe71{enter}')
cy.contains('elektra-test-vm (do not delete)')
})
}) | it("open reverse lookup page and search for elektra test vm", () => { | random_line_split |
data.py | import itertools
import os
import zipfile
import numpy as np
import requests
import scipy.sparse as sp
def _get_movielens_path():
"""
Get path to the movielens dataset file.
"""
return os.path.join(os.path.dirname(os.path.abspath(__file__)),
'movielens.zip')
def _download_movielens(dest_path):
"""
Download the dataset.
"""
url = 'http://files.grouplens.org/datasets/movielens/ml-100k.zip'
req = requests.get(url, stream=True)
with open(dest_path, 'wb') as fd:
for chunk in req.iter_content():
fd.write(chunk)
def _get_raw_movielens_data():
"""
Return the raw lines of the train and test files.
"""
path = _get_movielens_path()
if not os.path.isfile(path):
_download_movielens(path)
with zipfile.ZipFile(path) as datafile:
return (datafile.read('ml-100k/ua.base').decode().split('\n'),
datafile.read('ml-100k/ua.test').decode().split('\n'))
def _parse(data):
"""
Parse movielens dataset lines.
"""
for line in data:
if not line:
continue
uid, iid, rating, timestamp = [int(x) for x in line.split('\t')]
yield uid, iid, rating, timestamp
def | (rows, cols, data):
"""
Build the training matrix (no_users, no_items),
with ratings >= 4.0 being marked as positive and
the rest as negative.
"""
mat = sp.lil_matrix((rows, cols), dtype=np.int32)
for uid, iid, rating, timestamp in data:
if rating >= 4.0:
mat[uid, iid] = 1.0
else:
mat[uid, iid] = -1.0
return mat.tocoo()
def _get_movie_raw_metadata():
"""
Get raw lines of the genre file.
"""
path = _get_movielens_path()
if not os.path.isfile(path):
_download_movielens(path)
with zipfile.ZipFile(path) as datafile:
return datafile.read('ml-100k/u.item').decode(errors='ignore').split('\n')
def get_movielens_item_metadata(use_item_ids):
"""
Build a matrix of genre features (no_items, no_features).
If use_item_ids is True, per-item features will also be used.
"""
features = {}
genre_set = set()
for line in _get_movie_raw_metadata():
if not line:
continue
splt = line.split('|')
item_id = int(splt[0])
genres = [idx for idx, val in
zip(range(len(splt[5:])), splt[5:])
if int(val) > 0]
if use_item_ids:
# Add item-specific features too
genres.append(item_id)
for genre_id in genres:
genre_set.add(genre_id)
features[item_id] = genres
mat = sp.lil_matrix((len(features) + 1,
len(genre_set)),
dtype=np.int32)
for item_id, genre_ids in features.items():
for genre_id in genre_ids:
mat[item_id, genre_id] = 1
return mat
def get_movielens_data():
"""
Return (train_interactions, test_interactions).
"""
train_data, test_data = _get_raw_movielens_data()
uids = set()
iids = set()
for uid, iid, rating, timestamp in itertools.chain(_parse(train_data),
_parse(test_data)):
uids.add(uid)
iids.add(iid)
rows = max(uids) + 1
cols = max(iids) + 1
return (_build_interaction_matrix(rows, cols, _parse(train_data)),
_build_interaction_matrix(rows, cols, _parse(test_data)))
| _build_interaction_matrix | identifier_name |
data.py | import itertools
import os
import zipfile
import numpy as np
import requests
import scipy.sparse as sp
def _get_movielens_path():
"""
Get path to the movielens dataset file.
"""
return os.path.join(os.path.dirname(os.path.abspath(__file__)),
'movielens.zip')
def _download_movielens(dest_path):
"""
Download the dataset.
"""
url = 'http://files.grouplens.org/datasets/movielens/ml-100k.zip'
req = requests.get(url, stream=True)
with open(dest_path, 'wb') as fd:
for chunk in req.iter_content():
fd.write(chunk)
def _get_raw_movielens_data():
"""
Return the raw lines of the train and test files.
"""
path = _get_movielens_path()
if not os.path.isfile(path):
_download_movielens(path)
with zipfile.ZipFile(path) as datafile:
return (datafile.read('ml-100k/ua.base').decode().split('\n'),
datafile.read('ml-100k/ua.test').decode().split('\n'))
def _parse(data):
"""
Parse movielens dataset lines.
"""
for line in data:
if not line:
continue
uid, iid, rating, timestamp = [int(x) for x in line.split('\t')]
yield uid, iid, rating, timestamp
def _build_interaction_matrix(rows, cols, data):
"""
Build the training matrix (no_users, no_items),
with ratings >= 4.0 being marked as positive and
the rest as negative.
"""
mat = sp.lil_matrix((rows, cols), dtype=np.int32)
for uid, iid, rating, timestamp in data:
|
return mat.tocoo()
def _get_movie_raw_metadata():
"""
Get raw lines of the genre file.
"""
path = _get_movielens_path()
if not os.path.isfile(path):
_download_movielens(path)
with zipfile.ZipFile(path) as datafile:
return datafile.read('ml-100k/u.item').decode(errors='ignore').split('\n')
def get_movielens_item_metadata(use_item_ids):
"""
Build a matrix of genre features (no_items, no_features).
If use_item_ids is True, per-item features will also be used.
"""
features = {}
genre_set = set()
for line in _get_movie_raw_metadata():
if not line:
continue
splt = line.split('|')
item_id = int(splt[0])
genres = [idx for idx, val in
zip(range(len(splt[5:])), splt[5:])
if int(val) > 0]
if use_item_ids:
# Add item-specific features too
genres.append(item_id)
for genre_id in genres:
genre_set.add(genre_id)
features[item_id] = genres
mat = sp.lil_matrix((len(features) + 1,
len(genre_set)),
dtype=np.int32)
for item_id, genre_ids in features.items():
for genre_id in genre_ids:
mat[item_id, genre_id] = 1
return mat
def get_movielens_data():
"""
Return (train_interactions, test_interactions).
"""
train_data, test_data = _get_raw_movielens_data()
uids = set()
iids = set()
for uid, iid, rating, timestamp in itertools.chain(_parse(train_data),
_parse(test_data)):
uids.add(uid)
iids.add(iid)
rows = max(uids) + 1
cols = max(iids) + 1
return (_build_interaction_matrix(rows, cols, _parse(train_data)),
_build_interaction_matrix(rows, cols, _parse(test_data)))
| if rating >= 4.0:
mat[uid, iid] = 1.0
else:
mat[uid, iid] = -1.0 | conditional_block |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.