text:
extern crate tokio_reactor;
extern crate tokio_uds;

extern crate libc;

use futures;
use futures::stream::Stream;
use std;
use std::io::Result as IoResult;
use std::io::{Read, Write};
use tokio_io::{AsyncRead, AsyncWrite};

use std::cell::RefCell;
use std::rc::Rc;

use std::path::{Path, PathBuf};

use self::tokio_uds::{UnixDatagram, UnixListener, UnixStream};

//#[cfg_attr(feature="cargo-clippy",allow(unused_imports))]
#[allow(unused_imports)]
use super::simple_err;
use super::{box_up_err, peer_err_s, util::peer_err_sb, BoxedNewPeerFuture, BoxedNewPeerStream, Peer};
use super::{multi, once, ConstructParams, Options, PeerConstructor, Specifier};

#[derive(Debug, Clone)]
pub struct UnixConnect(pub PathBuf);
impl Specifier for UnixConnect {
    fn construct(&self, _: ConstructParams) -> PeerConstructor {
        once(unix_connect_peer(&self.0))
    }
    specifier_boilerplate!(noglobalstate singleconnect no_subspec);
}
specifier_class!(
    name = UnixConnectClass,
    target = UnixConnect,
    prefixes = [
        "unix:",
        "unix-connect:",
        "connect-unix:",
        "unix-c:",
        "c-unix:"
    ],
    arg_handling = into,
    overlay = false,
    StreamOriented,
    SingleConnect,
    help = r#"
Connect to UNIX socket. Argument is filesystem path. [A]

Example: forward connections from websockets to a UNIX stream socket

    websocat ws-l:127.0.0.1:8088 unix:the_socket
"#
);

#[derive(Debug, Clone)]
pub struct UnixListen(pub PathBuf);
impl Specifier for UnixListen {
    fn construct(&self, p: ConstructParams) -> PeerConstructor {
        multi(unix_listen_peer(&self.0, &p.program_options))
    }
    specifier_boilerplate!(noglobalstate multiconnect no_subspec);
}
specifier_class!(
    name = UnixListenClass,
    target = UnixListen,
    prefixes = ["unix-listen:", "listen-unix:", "unix-l:", "l-unix:"],
    arg_handling = into,
    overlay = false,
    StreamOriented,
    MultiConnect,
    help = r#"
Listen for connections on a specified UNIX socket [A]

Example: forward connections from a UNIX socket to a WebSocket

    websocat --unlink unix-l:the_socket ws://127.0.0.1:8089

Example: Accept forwarded WebSocket connections from Nginx

    umask 0000
    websocat --unlink -b -E ws-u:unix-l:/tmp/wstest tcp:[::]:22

Nginx config:

    location /ws {
        proxy_read_timeout 7d;
        proxy_send_timeout 7d;
        #proxy_pass http://localhost:3012;
        proxy_pass http://unix:/tmp/wstest;
        proxy_http_version 1.1;
        proxy_set_header Upgrade $http_upgrade;
        proxy_set_header Connection \"upgrade\";
    }

This configuration allows to make Nginx responsible for
SSL and also it can choose which connections to forward
to websocat based on URLs.

Obviously, Nginx can also redirect to TCP-listening
websocat just as well - UNIX sockets are not a requirement for this feature.

See `moreexamples.md` for SystemD usage (untested).

TODO: --chmod option?
"#
);

#[derive(Debug, Clone)]
pub struct UnixDgram(pub PathBuf, pub PathBuf);
impl Specifier for UnixDgram {
    fn construct(&self, p: ConstructParams) -> PeerConstructor {
        once(dgram_peer(&self.0, &self.1, &p.program_options))
    }
    specifier_boilerplate!(noglobalstate singleconnect no_subspec);
}
specifier_class!(
    name = UnixDgramClass,
    target = UnixDgram,
    prefixes = ["unix-dgram:"],
    arg_handling = {
        fn construct(self: &UnixDgramClass, just_arg: &str) -> super::Result<Rc<dyn Specifier>> {
            let splits: Vec<&str> = just_arg.split(':').collect();
            if splits.len() != 2 {
                Err("Expected two colon-separated paths")?;
            }
            Ok(Rc::new(UnixDgram(splits[0].into(), splits[1].into())))
        }
        fn construct_overlay(
            self: &UnixDgramClass,
            _inner: Rc<dyn Specifier>,
        ) -> super::Result<Rc<dyn Specifier>> {
            panic!("Error: construct_overlay called on non-overlay specifier class")
        }
    },
    overlay = false,
    MessageOriented,
    SingleConnect,
    help = r#"
Send packets to one path, receive from the other. [A]
A socket for sending must be already opened.

I don't know if this mode has any use, it is here just for completeness.

Example:

    socat unix-recv:./sender -&
    websocat - unix-dgram:./receiver:./sender
"#
);

fn to_abstract(x: &str) -> PathBuf {
    format!("\x00{}", x).into()
}

#[derive(Debug, Clone)]
pub struct AbstractConnect(pub String);
impl Specifier for AbstractConnect {
    fn construct(&self, _: ConstructParams) -> PeerConstructor {
        once(unix_connect_peer(&to_abstract(&self.0)))
    }
    specifier_boilerplate!(noglobalstate singleconnect no_subspec);
}
specifier_class!(
    name = AbstractConnectClass,
    target = AbstractConnect,
    prefixes = [
        "abstract:",
        "abstract-connect:",
        "connect-abstract:",
        "abstract-c:",
        "c-abstract:"
    ],
    arg_handling = into,
    overlay = false,
    StreamOriented,
    SingleConnect,
    help = r#"
Connect to UNIX abstract-namespaced socket. Argument is some string used as address. [A]

Too long addresses may be silently chopped off.

Example: forward connections from websockets to an abstract stream socket

    websocat ws-l:127.0.0.1:8088 abstract:the_socket

Note that abstract-namespaced Linux sockets may not be normally supported by Rust,
so non-prebuilt versions may have problems with them.
"#
);

#[derive(Debug, Clone)]
pub struct AbstractListen(pub String);
impl Specifier for AbstractListen {
    fn construct(&self, cp: ConstructParams) -> PeerConstructor {
        multi(unix_listen_peer(
            &to_abstract(&self.0),
            &cp.program_options,
        ))
    }
    specifier_boilerplate!(noglobalstate multiconnect no_subspec);
}
specifier_class!(
    name = AbstractListenClass,
    target = AbstractListen,
    prefixes = [
        "abstract-listen:",
        "listen-abstract:",
        "abstract-l:",
        "l-abstract:"
    ],
    arg_handling = into,
    overlay = false,
    StreamOriented,
    MultiConnect,
    help = r#"
Listen for connections on a specified abstract UNIX socket [A]

Example: forward connections from an abstract UNIX socket to a WebSocket

    websocat abstract-l:the_socket ws://127.0.0.1:8089

Note that abstract-namespaced Linux sockets may not be normally supported by Rust,
so non-prebuilt versions may have problems with them.
"#
);

#[derive(Debug, Clone)]
pub struct AbstractDgram(pub String, pub String);
impl Specifier for AbstractDgram {
    fn construct(&self, p: ConstructParams) -> PeerConstructor {
        #[cfg(not(all(target_os = "linux", feature = "workaround1")))]
        {
            once(dgram_peer(
                &to_abstract(&self.0),
                &to_abstract(&self.1),
                &p.program_options,
            ))
        }
        #[cfg(all(target_os = "linux", feature = "workaround1"))]
        {
            once(dgram_peer_workaround(
                &to_abstract(&self.0),
                &to_abstract(&self.1),
                &p.program_options,
            ))
        }
    }
    specifier_boilerplate!(noglobalstate singleconnect no_subspec);
}
specifier_class!(
    name = AbstractDgramClass,
    target = AbstractDgram,
    prefixes = ["abstract-dgram:"],
    arg_handling = {
        fn construct(self: &AbstractDgramClass, just_arg: &str) -> super::Result<Rc<dyn Specifier>> {
            let splits: Vec<&str> = just_arg.split(':').collect();
            if splits.len() != 2 {
                Err("Expected two colon-separated addresses")?;
            }
            Ok(Rc::new(UnixDgram(splits[0].into(), splits[1].into())))
        }
        fn construct_overlay(
            self: &AbstractDgramClass,
            _inner: Rc<dyn Specifier>,
        ) -> super::Result<Rc<dyn Specifier>> {
            panic!("Error: construct_overlay called on non-overlay specifier class")
        }
    },
    overlay = false,
    MessageOriented,
    SingleConnect,
    help = r#"
Send packets to one address, receive from the other. [A]
A socket for sending must be already opened.

I don't know if this mode has any use, it is here just for completeness.

Example (untested):

    websocat - abstract-dgram:receiver_addr:sender_addr

Note that abstract-namespaced Linux sockets may not be normally supported by Rust,
so non-prebuilt versions may have problems with them. In particular, this mode
may fail to work without `workaround1` Cargo feature.
"#
);

#[cfg(all(target_os = "linux", feature = "seqpacket"))]
#[path = "unix_seqpacket_peer.rs"]
pub mod unix_seqpacket_peer;

// based on https://github.com/tokio-rs/tokio-core/blob/master/examples/proxy.rs
#[derive(Clone)]
struct MyUnixStream(Rc<UnixStream>, bool);

impl Read for MyUnixStream {
    fn read(&mut self, buf: &mut [u8]) -> IoResult<usize> {
        (&*self.0).read(buf)
    }
}

impl Write for MyUnixStream {
    fn write(&mut self, buf: &[u8]) -> IoResult<usize> {
        (&*self.0).write(buf)
    }

    fn flush(&mut self) -> IoResult<()> {
        Ok(())
    }
}

impl AsyncRead for MyUnixStream {}

impl AsyncWrite for MyUnixStream {
    fn shutdown(&mut self) -> futures::Poll<(), std::io::Error> {
        self.0.shutdown(std::net::Shutdown::Write)?;
        Ok(().into())
    }
}

impl Drop for MyUnixStream {
    fn drop(&mut self) {
        let i_am_read_part = self.1;
        if i_am_read_part {
            let _ = self.0.shutdown(std::net::Shutdown::Read);
        }
    }
}

pub fn unix_connect_peer(addr: &Path) -> BoxedNewPeerFuture {
    use futures::Future;
    Box::new(
        UnixStream::connect(&addr)
            .map(|x| {
                info!("Connected to a unix socket");
                let x = Rc::new(x);
                Peer::new(
                    MyUnixStream(x.clone(), true),
                    MyUnixStream(x.clone(), false),
                    None /* TODO */,
                )
            })
            .map_err(box_up_err),
    ) as BoxedNewPeerFuture
}

pub fn unix_listen_peer(addr: &Path, opts: &Rc<Options>) -> BoxedNewPeerStream {
    let bound = if opts.unix_socket_accept_from_fd {
        // Special mode for SystemD (untested yet)
        let fdnum: libc::c_int = match addr.to_str().map(|x|x.parse()) {
            Some(Ok(x)) => x,
            _ => {
                let e: Box<dyn std::error::Error> = From::from("Specify numeric argument instead of path in --accept-from-fd mode");
                return peer_err_sb(e);
            }
        };
        use std::os::unix::io::FromRawFd;
        let l = unsafe { std::os::unix::net::UnixListener::from_raw_fd(fdnum) } ;
        let _ = l.set_nonblocking(true);
        let bound =
        UnixListener::from_std(l, &tokio_reactor::Handle::default());
        bound
    } else {
        if opts.unlink_unix_socket {
            let _ = ::std::fs::remove_file(addr);
        };
        let bound = UnixListener::bind(&addr);
        if opts.announce_listens {
            let poss = addr.as_os_str();
            use std::os::unix::ffi::OsStrExt;
            if !poss.is_empty() && poss.as_bytes()[0] == b'\0' {
                println!("LISTEN proto=abstract,path_hex={}", hex::encode(&poss.as_bytes()[1..]));
            } else {
                println!("LISTEN proto=unix,path={:?}", addr);
            }
        }
        bound
    };
    let bound = match bound {
        Ok(x) => x,
        Err(e) => return peer_err_s(e),
    };
    debug!("UNIX listening socket should be ready");
    // TODO: chmod
    use tk_listen::ListenExt;
    Box::new(
        bound
            .incoming()
            .sleep_on_error(::std::time::Duration::from_millis(500))
            .map(|x| {
                info!("Incoming unix socket connection");
                let x = Rc::new(x);
                Peer::new(
                    MyUnixStream(x.clone(), true),
                    MyUnixStream(x.clone(), false),
                    None /* TODO */,
                )
            })
            .map_err(|()| crate::simple_err2("unreachable error?")),
    ) as BoxedNewPeerStream
}

struct DgramPeer {
    s: UnixDatagram,
    #[allow(unused)]
    oneshot_mode: bool, // TODO
}

#[derive(Clone)]
struct DgramPeerHandle(Rc<RefCell<DgramPeer>>);

pub fn dgram_peer(bindaddr: &Path, connectaddr: &Path, opts: &Rc<Options>) -> BoxedNewPeerFuture {
    Box::new(futures::future::result(
        UnixDatagram::bind(bindaddr)
            .and_then(|x| {
                x.connect(connectaddr)?;

                let h1 = DgramPeerHandle(Rc::new(RefCell::new(DgramPeer {
                    s: x,
                    oneshot_mode: opts.udp_oneshot_mode,
                })));
                let h2 = h1.clone();
                Ok(Peer::new(h1, h2, None))
            })
            .map_err(box_up_err),
    )) as BoxedNewPeerFuture
}

#[cfg(all(target_os = "linux", feature = "workaround1"))]
pub fn dgram_peer_workaround(
    bindaddr: &Path,
    connectaddr: &Path,
    opts: &Rc<Options>,
) -> BoxedNewPeerFuture {
    info!("Workaround method for getting abstract datagram socket");
    fn getfd(bindaddr: &Path, connectaddr: &Path) -> Option<i32> {
        use self::libc::{
            bind, c_char, close, connect, sa_family_t, sockaddr_un, socket, socklen_t, AF_UNIX,
            SOCK_DGRAM,
        };
        use std::mem::size_of;
        use std::os::unix::ffi::OsStrExt;
        unsafe {
            let s = socket(AF_UNIX, SOCK_DGRAM, 0);
            if s == -1 {
                return None;
            }
            {
                let mut sa = sockaddr_un {
                    sun_family: AF_UNIX as sa_family_t,
                    sun_path: [0; 108],
                };
                let bp: &[c_char] =
                    &*(bindaddr.as_os_str().as_bytes() as *const [u8] as *const [c_char]);
                let l = 108.min(bp.len());
                sa.sun_path[..l].copy_from_slice(&bp[..l]);
                let sa_len = l + size_of::<sa_family_t>();
                let sa_ = &sa as *const self::libc::sockaddr_un as *const self::libc::sockaddr;
                let ret = bind(s, sa_, sa_len as socklen_t);
                if ret == -1 {
                    close(s);
                    return None;
                }
            }
            {
                let mut sa = sockaddr_un {
                    sun_family: AF_UNIX as sa_family_t,
                    sun_path: [0; 108],
                };
                let bp: &[c_char] =
                    &*(connectaddr.as_os_str().as_bytes() as *const [u8] as *const [c_char]);
                let l = 108.min(bp.len());
                sa.sun_path[..l].copy_from_slice(&bp[..l]);
                let sa_len = l + size_of::<sa_family_t>();
                let sa_ = &sa as *const self::libc::sockaddr_un as *const self::libc::sockaddr;
                let ret = connect(s, sa_, sa_len as socklen_t);
                if ret == -1 {
                    close(s);
                    return None;
                }
            }
            Some(s)
        }
    }
    fn getpeer(
        bindaddr: &Path,
        connectaddr: &Path,
        opts: &Rc<Options>,
    ) -> Result<Peer, Box<dyn (::std::error::Error)>> {
        if let Some(fd) = getfd(bindaddr, connectaddr) {
            let s: ::std::os::unix::net::UnixDatagram =
                unsafe { ::std::os::unix::io::FromRawFd::from_raw_fd(fd) };
            let ss = UnixDatagram::from_std(s, &tokio_reactor::Handle::default())?;
            let h1 = DgramPeerHandle(Rc::new(RefCell::new(DgramPeer {
                s: ss,
                oneshot_mode: opts.udp_oneshot_mode,
            })));
            let h2 = h1.clone();
            Ok(Peer::new(h1, h2, None))
        } else {
            Err("Failed to get, bind or connect socket")?
        }
    }
    Box::new(futures::future::result({
        getpeer(bindaddr, connectaddr, opts)
    })) as BoxedNewPeerFuture
}

impl Read for DgramPeerHandle {
    fn read(&mut self, buf: &mut [u8]) -> IoResult<usize> {
        let p = self.0.borrow_mut();
        p.s.recv(buf)
    }
}

impl Write for DgramPeerHandle {
    fn write(&mut self, buf: &[u8]) -> IoResult<usize> {
        let p = self.0.borrow_mut();
        p.s.send(buf)
    }

    fn flush(&mut self) -> IoResult<()> {
        Ok(())
    }
}

impl AsyncRead for DgramPeerHandle {}

impl AsyncWrite for DgramPeerHandle {
    fn shutdown(&mut self) -> futures::Poll<(), std::io::Error> {
        Ok(().into())
    }
}

trait HacksForMigratingFromTokioCore {
    fn recv(&self, buf: &mut [u8]) -> std::io::Result<usize>;
    fn send(&self, buf: &[u8]) -> std::io::Result<usize>;
}

impl HacksForMigratingFromTokioCore for UnixDatagram {
    fn recv(&self, buf: &mut [u8]) -> std::io::Result<usize> {
        match self.poll_recv(buf)? {
            futures::Async::Ready(n) => Ok(n),
            futures::Async::NotReady => Err(std::io::ErrorKind::WouldBlock.into()),
        }
    }

    fn send(&self, buf: &[u8]) -> std::io::Result<usize> {
        match self.poll_send(buf)? {
            futures::Async::Ready(n) => Ok(n),
            futures::Async::NotReady => Err(std::io::ErrorKind::WouldBlock.into()),
        }
    }
}


text:
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
// Code generated by Microsoft (R) AutoRest Code Generator.

package com.azure.resourcemanager.signalr.models;

import com.azure.core.annotation.Fluent;
import com.fasterxml.jackson.annotation.JsonProperty;
import java.util.List;

/** Network ACL. */
@Fluent
public class NetworkAcl {
    /*
     * Allowed request types. The value can be one or more of: ClientConnection, ServerConnection, RESTAPI.
     */
    @JsonProperty(value = "allow")
    private List<SignalRRequestType> allow;

    /*
     * Denied request types. The value can be one or more of: ClientConnection, ServerConnection, RESTAPI.
     */
    @JsonProperty(value = "deny")
    private List<SignalRRequestType> deny;

    /** Creates an instance of NetworkAcl class. */
    public NetworkAcl() {
    }

    /**
     * Get the allow property: Allowed request types. The value can be one or more of: ClientConnection,
     * ServerConnection, RESTAPI.
     *
     * @return the allow value.
     */
    public List<SignalRRequestType> allow() {
        return this.allow;
    }

    /**
     * Set the allow property: Allowed request types. The value can be one or more of: ClientConnection,
     * ServerConnection, RESTAPI.
     *
     * @param allow the allow value to set.
     * @return the NetworkAcl object itself.
     */
    public NetworkAcl withAllow(List<SignalRRequestType> allow) {
        this.allow = allow;
        return this;
    }

    /**
     * Get the deny property: Denied request types. The value can be one or more of: ClientConnection, ServerConnection,
     * RESTAPI.
     *
     * @return the deny value.
     */
    public List<SignalRRequestType> deny() {
        return this.deny;
    }

    /**
     * Set the deny property: Denied request types. The value can be one or more of: ClientConnection, ServerConnection,
     * RESTAPI.
     *
     * @param deny the deny value to set.
     * @return the NetworkAcl object itself.
     */
    public NetworkAcl withDeny(List<SignalRRequestType> deny) {
        this.deny = deny;
        return this;
    }

    /**
     * Validates the instance.
     *
     * @throws IllegalArgumentException thrown if the instance is not valid.
     */
    public void validate() {
    }
}

redpajama_set_name: RedPajamaGithub


text:
require 'securerandom'

hospitals = [{:id => 1, :name => 'Sankara Rural Eye Hospital', :surgeries => 15000, :city => "Krishnankoil", :state => "Tamil Nadu", :building_status => "Completed", :contact => "info@giftofvision.org", :story => "This is the story of The Sankara Rural Eye Hospital", :lat => 9.565389, :lng =>77.688760, :status => true},
            {:id => 2, :name => 'Sankara Eye Hospital', :surgeries => 10000, :city => "Ludhiana", :state => "Punjab", :building_status => "Completed", :contact => "info@giftofvision.org", :story => "This is the story of The Sankara Eye Hospital", :lat =>30.861098, :lng => 75.704154, :status => true},
            {:id => 3, :name => 'Bangalore Hospital', :surgeries => 134546, :city => "Bengaluru", :state => "Karnataka", :building_status => "Completed", :contact => "info@giftofvision.org", :story => "This is the story of The Bangalore Hospitall", :lat => 12.957378, :lng => 77.712852, :status => true},
            {:id => 4, :name => 'Sankara Eye Hospital, Guntur', :surgeries => 25000, :city => "Guntur", :state => "Andhra Pradesh", :building_status => "Completed", :contact => "vmaddipati@gmail.com", :story => "This is the story of The Sankara Eye Hospital, Guntur", :lat => 16.350630, :lng => 80.49328, :status => true},
            {:id => 5, :name => 'Shimoga Hospital', :surgeries => 89307, :city => "Shimoga", :state => "Karnataka", :building_status => "Completed", :contact => "info@giftofvision.org", :story => "This is the story of The Shimoga Hospital", :lat => 13.904054, :lng => 75.560752, :status => true}
  ]

hospitals.each do |hospital|
  if not Hospital.exists?(hospital[:id])
    Hospital.create!(hospital)
  elsif Hospital.find(hospital[:id]).status.nil?
    h = Hospital.find(hospital[:id])
    h.update(status: hospital[:status])
  end
end

donors = [{:id => 1, :first_name => 'Aaron', :last_name => 'Rowell', :email => 'AaronERowell@teleworm.us', :phone => '806-278-5037', :status => true},
        {:id => 2, :first_name => 'Mary', :last_name => 'Wilson', :email => 'MaryTWilson@dayrep.com', :phone => '847-509-8591', :status => true},
        {:id => 3, :first_name => 'Richard', :last_name => 'Krantz', :email => 'RichardMKrantz@rhyta.com', :phone => '503-616-7352', :status => true},
        {:id => 4, :first_name => 'Sandra', :last_name => 'Railey', :email => 'SandraDRailey@dayrep.com', :phone => '510-992-1438', :status => true},
        {:id => 5, :first_name => 'Ilana', :last_name => 'Miranda', :email => 'IlanaJMiranda@armyspy.com', :phone => '206-234-2513', :status => true},
        {:id => 6, :first_name => 'Teresa', :last_name => 'Bahr', :email => 'TeresaDBahr@teleworm.us', :phone => '773-718-0267', :status => true},
        {:id => 7, :first_name => 'Dennis', :last_name => 'Gain', :email => 'DennisAGain@teleworm.us', :phone => '630-922-7498', :status => true},
        {:id => 8, :first_name => 'Grace', :last_name => 'Wright', :email => 'GraceJWright@dayrep.com', :phone => '502-301-1405', :status => true},
        {:id => 9, :first_name => 'Kevin', :last_name => 'Curry', :email => 'Kcurry739@gmail.com', :phone => '415-338-8924', :status => true},
        {:id => 10, :first_name => 'Kobe', :last_name => 'James', :email => 'KobeBJ@yahoo.com', :phone => '639-671-3451', :status => true}
  	 ]

donors.each do |donor|
  donor[:secret] = SecureRandom.urlsafe_base64
  if not Donor.exists?(donor[:id])
    Donor.create!(donor)
  elsif Donor.find(donor[:id]).status.nil?
    d = Donor.find(donor[:id])
    d.update(status: donor[:status])
  elsif Donor.find(donor[:id]).secret.nil?
    d = Donor.find(donor[:id])
    d.update(secret: donor[:secret])
  end
end

dedications = [{:id => 1, :dedication => 'No more blindness!', :status => true, :hospital_id => 2, :donor_id => 6, :tier => 'Gold', :published => true},
            {:id => 2, :dedication => 'For the kids', :status => true, :hospital_id => 2, :donor_id => 1, :tier => 'Platinum', :published => true},
            {:id => 3, :dedication => 'Dedicated to my family', :status => true, :hospital_id => 2, :donor_id => 3, :tier => 'Silver', :published => true},
            {:id => 4, :dedication => 'Keep up the good work', :status => true, :hospital_id => 1, :donor_id => 2, :tier => 'Gold', :published => true},
            {:id => 5, :dedication => '20/20 for all', :status => true, :hospital_id => 1, :donor_id => 4, :tier => 'Gold', :published => true},
            {:id => 6, :dedication => 'Go Sankara!', :status => true, :hospital_id => 3, :donor_id => 5, :tier => "Platinum", :published => false},
            {:id => 7, :dedication => 'Keep it up!', :status => true, :hospital_id => 3, :donor_id => 1, :tier => "Silver", :published => true},
            {:id => 8, :dedication => 'My favorite charity!', :status => true, :hospital_id => 4, :donor_id => 7, :tier => "Gold", :published => true},
            {:id => 9, :dedication => 'Happy to help a great cause', :status => true, :hospital_id => 5, :donor_id => 8, :tier => "Platinum", :published => true},
            {:id => 10, :dedication => 'Keep funding', :status => true, :hospital_id => 4, :donor_id => 9, :tier => "Silver", :published => false},
            {:id => 11, :dedication => 'I love Sankara', :status => false, :hospital_id => 1, :donor_id => 8, :tier => "Platinum", :published => true},
            {:id => 12, :dedication => 'I hate blindness!', :status => true, :hospital_id => 5, :donor_id => 10, :tier => "Gold", :published => true},
            {:id => 13, :hospital_id => 1, :donor_id => 2, :tier => "Silver", :published => false},
            {:id => 14, :hospital_id => 1, :donor_id => 3, :tier => "Silver", :published => false}
  	 ]

dedications.each do |dedication|
  if not Dedication.exists?(dedication[:id])
    Dedication.create!(dedication)
  elsif Dedication.find(dedication[:id]).status.nil?
    d = Dedication.find(dedication[:id])
    d.update(status: dedication[:status])
  elsif Dedication.find(dedication[:id]).published.nil?
    d = Dedication.find(dedication[:id])
    d.update(published: dedication[:published])
  end
end

users = [{:id => 1, :email => 'admin@admin.com', :password => 'password', :admin => true},
         {:id => 2, :email => 'user@user.com', :password => 'password', :admin => false}
  ]

users.each do |user|
  if not User.exists?(user[:id])
    User.create!(user)
  end
end


text:
<!DOCTYPE html>

    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no" />

    <title>loginProviders Fragment</title>
    <link href="../../static/css/cas.css" rel="stylesheet" th:remove="tag" />

                    External Identity Providers

                            <form method="post" th:id="${'form' + entry.name}" th:action="@{/login}">
                                <button class="mdc-button mdc-button--raised me-2 btn btn-primary d-block w-100"
                                        name="submitButton"
                                        id="submitButton"
                                        type="submit"
                                        th:attr="autoRedirectType=${#strings.toLowerCase(entry.autoRedirectType)},redirectUrl=@{${entry.redirectUrl}}"
                                        th:title="${entry.name + ' ' + entry.type}"
                                        th:id="${entry.name}"
                                        th:classappend="'mdc-button-' + ${entry.type}"
                                        accesskey="s">
                                    [[${#strings.defaultString(entry.title,entry.name)}]]
                                </button>

                                <input type="hidden" name="client_name" th:value="${entry.name}" />
                                <input type="hidden" name="_eventId" value="delegatedAuthenticationRedirect" />
                                <input type="hidden" name="execution" th:value="${flowExecutionKey}" />
                            </form>

Login with:

                                    [[${entry.name}]]


text:
import { basename, dirname } from "path";
import { RequestType2, NotificationType2, NotificationType4, MessageConnection } from "vscode-jsonrpc";
import { AutorestExtensionLogger } from "./extension-logger";
import { Mapping, Message, RawSourceMap, Channel } from "./types";

namespace IAutoRestPluginInitiatorTypes {
  export const ReadFile = new RequestType2<string, string, string, Error, void>("ReadFile");
  export const GetValue = new RequestType2<string, string, any, Error, void>("GetValue");
  export const ListInputs = new RequestType2<string, string | undefined, Array<string>, Error, void>("ListInputs");
  export const ProtectFiles = new NotificationType2<string, string, void>("ProtectFiles");
  export const WriteFile = new NotificationType4<
    string,
    string,
    string,
    Array<Mapping> | RawSourceMap | undefined,
    void
  >("WriteFile");
  export const Message = new NotificationType2<string, Message, void>("Message");
}

/**
 * Sepecify that the source file and current file is a 1:1 mapping.
 */
export interface IdentitySourceMap {
  type: "identity";

  /**1
   * Name of the file that this file is mapping to.
   */
  source: string;
}

export interface WriteFileOptions {
  /**
   * @param filename Name of the file.
   */
  filename: string;

  /**
   * @param content Content of the file.
   */
  content: string;

  /**
   * @param sourceMap Source map that can be used to trace back source position in case of error.
   */
  sourceMap?: Mapping[] | RawSourceMap | IdentitySourceMap;

  /**
   * @param artifactType Artifact type
   */
  artifactType?: string;
}

export interface AutorestExtensionHost {
  logger: AutorestExtensionLogger;

  protectFiles(path: string): Promise<void>;
  readFile(filename: string): Promise<string>;
  getValue<T>(key: string): Promise<T | undefined>;
  listInputs(artifactType?: string): Promise<Array<string>>;
  writeFile({ filename, content, sourceMap, artifactType }: WriteFileOptions): void;
  message(message: Message): void;

  /**
   * @deprecated
   */
  UpdateConfigurationFile(filename: string, content: string): void;

  /**
   * @deprecated
   */
  GetConfigurationFile(filename: string): Promise<string>;

  /**
   * @deprecated use #writeFile
   */
  WriteFile(filename: string, content: string): void;

  /**
   * @deprecated use #getValue
   */
  GetValue(key: string): any;

  /**
   * @deprecated use #message
   */
  Message(message: Message): any;
}

export class AutorestExtensionRpcHost implements AutorestExtensionHost {
  public logger: AutorestExtensionLogger;

  public constructor(private channel: MessageConnection, private sessionId: string) {
    this.logger = new AutorestExtensionLogger((x) => this.message(x));
  }
  /**
   * Protect files that will not be cleared when using clear-output-folder.
   * @param path Path to the file/folder to protect.
   */
  public async protectFiles(path: string): Promise<void> {
    this.channel.sendNotification(IAutoRestPluginInitiatorTypes.ProtectFiles, this.sessionId, path);
  }

  public async readFile(filename: string): Promise<string> {
    return await this.channel.sendRequest(IAutoRestPluginInitiatorTypes.ReadFile, this.sessionId, filename);
  }

  /**
   * Get a configuration key form the resolved configuration.
   * @param key Path to the configuration entry. (Keys dot seperated)
   * @returns Value of the configuration.
   */
  public async getValue<T>(key: string): Promise<T | undefined> {
    return await this.channel.sendRequest(IAutoRestPluginInitiatorTypes.GetValue, this.sessionId, key);
  }

  /**
   * List inputs
   * @param artifactType @optional Filter by artifact type.
   * @returns name of the input files.
   */
  public async listInputs(artifactType?: string): Promise<Array<string>> {
    return await this.channel.sendRequest(IAutoRestPluginInitiatorTypes.ListInputs, this.sessionId, artifactType);
  }

  /**
   * Write a file.
   */
  public writeFile({ filename, content, sourceMap, artifactType }: WriteFileOptions): void {
    if (artifactType) {
      this.channel.sendNotification(IAutoRestPluginInitiatorTypes.Message, this.sessionId, {
        Channel: Channel.File,
        Details: {
          content: content,
          type: artifactType,
          uri: filename,
          sourceMap: sourceMap,
        },
        Text: content,
        Key: [artifactType, filename],
      });
    } else {
      this.channel.sendNotification(
        IAutoRestPluginInitiatorTypes.WriteFile,
        this.sessionId,
        filename,
        content,
        sourceMap,
      );
    }
  }

  /**
   * Send a message.
   * @param message Message to send.
   */
  public message(message: Message): void {
    this.channel.sendNotification(IAutoRestPluginInitiatorTypes.Message, this.sessionId, message);
  }

  /**
   * @deprecated
   */
  public WriteFile(filename: string, content: string) {
    return this.writeFile({ filename, content });
  }

  /**
   * @deprecated
   */
  public GetValue(key: string) {
    return this.getValue(key);
  }

  /**
   * @deprecated
   */
  public Message(message: Message) {
    return this.message(message);
  }

  /**
   * @deprecated
   */
  public UpdateConfigurationFile(filename: string, content: string): void {
    this.channel.sendNotification(IAutoRestPluginInitiatorTypes.Message, this.sessionId, {
      Channel: Channel.Configuration,
      Key: [filename],
      Text: content,
    });
  }

  /**
   * @deprecated
   */
  public async GetConfigurationFile(filename: string): Promise<string> {
    const configurations = await this.channel.sendRequest(
      IAutoRestPluginInitiatorTypes.GetValue,
      this.sessionId,
      "configurationFiles",
    );

    const filenames = Object.getOwnPropertyNames(configurations);
    if (filenames.length > 0) {
      const basePath = dirname(filenames[0]);
      for (const configFile of filenames) {
        if (configFile.startsWith(basePath) && filename === basename(configFile)) {
          return configurations[configFile];
        }
      }
    }
    return "";
  }
}


text:
import constants
import subprocess

def screenshot(url, fname=None, width=1024, height=600, delay=0):
  name_fmt = "" if fname is None else " --filename={0}".format(fname)
  cmd = "python vendor/webkit2png/webkit2png {0} -W {1} -H {2} --fullsize --delay={3}{4} --dir={5}".format(url, width, height, delay, name_fmt, constants.DATA_PATH_SCREENSHOT)
  subprocess.call(cmd, shell=True)

if __name__=="__main__":
  screenshot("http://www.google.jp", "google.jp")


text:
package com.twelvemonkeys.imageio.metadata.psd;

import com.twelvemonkeys.imageio.metadata.Directory;
import com.twelvemonkeys.imageio.metadata.DirectoryAbstractTest;
import com.twelvemonkeys.imageio.metadata.Entry;

import java.util.Collection;

/**
 * PhotoshopDirectoryTest
 *
 * @author Harald Kuhr
 * @author last modified by $Author: haraldk$
 * @version $Id: PhotoshopDirectoryTest.java,v 1.0 04.01.12 12:01 haraldk Exp$
 */
public class PSDDirectoryTest extends DirectoryAbstractTest {
    @Override
    protected Directory createDirectory(final Collection<Entry> entries) {
        return new PSDDirectory(entries);
    }
}


text:
<?php

namespace app\models;

use Yii;

/**
 * This is the model class for table "categories".
 *
 * @property string $id
 * @property string $category_id
 * @property string $id_area
 * @property string $name
 * @property string $description
 * @property integer $service_level_agreement_asignment
 * @property integer $service_level_agreement_completion
 *
 * @property Category $category
 * @property Category[] $categories
 * @property Area $idArea
 * @property CategoryRequest[] $categoryRequests
 * @property Request[] $requests
 */
class Category extends \yii\db\ActiveRecord
{
    /**
     * @inheritdoc
     */
    public static function tableName()
    {
        return 'categories';
    }

    /**
     * @inheritdoc
     */
    public function rules()
    {
        return [
            [['category_id', 'id_area', 'service_level_agreement_asignment', 'service_level_agreement_completion'], 'integer'],
            [['id_area', 'name'], 'required'],
            [['name'], 'string', 'max' => 100],
            [['description'], 'string', 'max' => 150]
        ];
    }

    /**
     * @inheritdoc
     */
    public function attributeLabels()
    {
        return [
            'id' => Yii::t('app', 'ID'),
            'category_id' => Yii::t('app', 'Father Category'),
            'id_area' => Yii::t('app', 'Area'),
            'name' => Yii::t('app', 'Name'),
            'description' => Yii::t('app', 'Description'),
            'service_level_agreement_asignment' => Yii::t('app', 'Service Level Agreement Asignment'),
            'service_level_agreement_completion' => Yii::t('app', 'Service Level Agreement Completion'),
        ];
    }

    /**
     * @return \yii\db\ActiveQuery
     */
    public function getCategory()
    {
        return $this->hasOne(Category::className(), ['id' => 'category_id']);
    }

    /**
     * @return \yii\db\ActiveQuery
     */
    public function getCategories()
    {
        return $this->hasMany(Category::className(), ['category_id' => 'id']);
    }

    /**
     * @return \yii\db\ActiveQuery
     */
    public function getIdArea()
    {
        return $this->hasOne(Area::className(), ['id' => 'id_area']);
    }

    /**
     * @return \yii\db\ActiveQuery
     */
    public function getCategoryRequests()
    {
        return $this->hasMany(CategoryRequest::className(), ['category_id' => 'id']);
    }

    /**
     * @return \yii\db\ActiveQuery
     */
    public function getRequests()
    {
        return $this->hasMany(Request::className(), ['id' => 'request_id'])->viaTable('category_request', ['category_id' => 'id']);
    }

    /**
     * @inheritdoc
     * @return CategoriesQuery the active query used by this AR class.
     */
    public static function find()
    {
        return new CategoriesQuery(get_called_class());
    }
}


text:
Point p = new Point(520.4606f, 3885.672f, 190.2297f);

/*if(nManager.Wow.Helpers.Quest.GetLogQuestIsComplete(9410) || nManager.Wow.Helpers.Quest.GetQuestCompleted(9410))
	return true;*/

if(ObjectManager.Me.Position.DistanceTo(p) >= 10)
	return false;

return true;


text:
<?php

/*

Jappix - An open social platform
This is the Jappix microblog file attaching script

-------------------------------------------------

License: AGPL
Author: Valérian Saliou
Last revision: 27/05/11

*/

// PHP base
define('JAPPIX_BASE', '..');

// Get the needed files
require_once('./functions.php');
require_once('./read-main.php');
require_once('./read-hosts.php');

// Optimize the page rendering
hideErrors();
compressThis();

// Not allowed for a special node
if(isStatic() || isUpload())
	exit;

// Set a special XML header
header('Content-Type: text/xml; charset=utf-8');

// Everything is okay
if((isset($_FILES['file']) && !empty($_FILES['file'])) && (isset($_POST['user']) && !empty($_POST['user'])) && (isset($_POST['location']) && !empty($_POST['location']))) {
	// Get the user name
	$user = $_POST['user'];

	// Get the file name
	$tmp_filename = $_FILES['file']['tmp_name'];
	$filename = $_FILES['file']['name'];

	// Get the location
	if(HOST_UPLOAD)
		$location = HOST_UPLOAD;
	else
		$location = $_POST['location'];

	// Forbidden file?
	if(!isSafe($filename)) {
		exit(
'<jappix xmlns=\'jappix:file:post\'>
	<error>forbidden-type</error>
</jappix>'
		);
	}

	// Get the file new name
	$ext = getFileExt($filename);
	$new_name = preg_replace('/(^)(.+)(\.)(.+)($)/i', '$2', $filename);

	// Define some vars
	$content_dir = JAPPIX_BASE.'/store/share/'.$user;
	$security_file = $content_dir.'/index.html';
	$name = sha1(time().$filename);
	$path = $content_dir.'/'.$name.'.'.$ext;
	$thumb_xml = '';

	// Create the user directory
	if(!is_dir($content_dir)) {
		mkdir($content_dir, 0777, true);
		chmod($content_dir, 0777);
	}

	// Create (or re-create) the security file
	if(!file_exists($security_file))
		file_put_contents($security_file, securityHTML());

	// File upload error?
	if(!is_uploaded_file($tmp_filename) || !move_uploaded_file($tmp_filename, $path)) {
		exit(
'<jappix xmlns=\'jappix:file:post\'>
	<error>move-error</error>
</jappix>'
		);
	}

	// Resize and compress if this is a JPEG file
	if(preg_match('/^(jpg|jpeg|png|gif)$/i', $ext)) {
		// Resize the image
		resizeImage($path, $ext, 1024, 1024);

		// Copy the image
		$thumb = $content_dir.'/'.$name.'_thumb.'.$ext;
		copy($path, $thumb);

		// Create the thumbnail
		if(resizeImage($thumb, $ext, 140, 105))
			$thumb_xml = '<thumb>'.htmlspecialchars($location.'store/share/'.$user.'/'.$name.'_thumb.'.$ext).'</thumb>';
	}

	// Return the path to the file
	exit(
'<jappix xmlns=\'jappix:file:post\'>
	<href>'.htmlspecialchars($location.'store/share/'.$user.'/'.$name.'.'.$ext).'</href>
	<title>'.htmlspecialchars($new_name).'</title>
	<type>'.htmlspecialchars(getFileMIME($path)).'</type>
	<length>'.htmlspecialchars(filesize($path)).'</length>
	'.$thumb_xml.'
</jappix>'
	);
}

// Bad request error!
exit(
'<jappix xmlns=\'jappix:file:post\'>
	<error>bad-request</error>
</jappix>'
);

?>


text:
using UnityEngine;
using System.Collections;

public class Item_Master : MonoBehaviour {

	void OnEnable()
	{
		SetInitialReferences();
	}

	void OnDisable()
	{

	}

	void Update ()
	{

	}

	void SetInitialReferences()
	{

	}
}


text:
	#include <camkes.h>
	#include <inttypes.h>
#elif __TB_OS_ECHRONOS__
	#include <debug.h>
#endif
#include "tb_receiver.h"
#include <inttypes.h>
#ifndef __TB_OS_ECHRONOS
#include <stdio.h>
#endif

void receiver_periodic_ping(const int64_t * periodic_1000_ms) {
	printf("receiver: periodic dispatch received at time: %d", (int32_t)*periodic_1000_ms);

	bool result = true;
	while (result) {
		result = read_input1();
		if (result) {
   			printf("receiver: event consumed\n");
   		} else {
   			printf("receiver: queue emptied.\n");
   		}
   	}
}


text:
<?php

namespace app\models;

use Yii;

/**
 * This is the model class for table "D_STATUSES".
 *
 * @property integer $ID_STATUS
 * @property string $NAME_STATUS
 * @property integer $IS_FINAL
 *
 * @property Tickets[] $Tickets
 */
class Statuses extends \yii\db\ActiveRecord
{
    /**
     * @inheritdoc
     */
    public static function tableName()
    {
        return 'D_STATUSES';
    }

    /**
     * @inheritdoc
     */
    public function rules()
    {
        return [
            [['NAME_STATUS', 'IS_FINAL'], 'required'],
            [['IS_FINAL'], 'integer'],
            [['NAME_STATUS'], 'string', 'max' => 255]
        ];
    }

    /**
     * @inheritdoc
     */
    public function attributeLabels()
    {
        return [
            'ID_STATUS' => 'Код статуса',
            'NAME_STATUS' => 'Статус',
            'IS_FINAL' => 'Флаг конечного статуса',
        ];
    }

    /**
     * @return \yii\db\ActiveQuery
     */
    public function getTickets()
    {
        return $this->hasMany(TICKETS::className(), ['FID_CATEGORY' => 'ID_CATEGORY']);
    }
}


text:
@class NumberJumpLabel;
@interface ScoreViewController : UIViewController
@property (weak, nonatomic) IBOutlet NumberJumpLabel *scoreLabel;
@property (weak, nonatomic) IBOutlet UIView *albumView;
@property (weak, nonatomic) IBOutlet UIView *containerView;
@property (weak, nonatomic) IBOutlet UIView *scoreView;
@property (weak, nonatomic) IBOutlet UIImageView *scoreImageView;
@property (weak, nonatomic) IBOutlet UIImageView *albumImageView;
@property (weak, nonatomic) IBOutlet UIView *albumContainerView;

@property (weak, nonatomic) IBOutlet UIImageView *albumCoverImageView;
@property (weak, nonatomic) IBOutlet UILabel *albumScoreLabel;
@property (weak, nonatomic) IBOutlet UILabel *albumNameLabel;

@property (weak, nonatomic) IBOutlet UIButton *albumPlayBtn;

- (void)score;
@end


text:
__author__ = 'Mael Beuget, Pierre Monnin & Thibaut Smith'

import os

import webapp2
import jinja2

from model.Accounts import *
from frtz import *

template_dir = os.path.join(os.path.dirname(__file__), '../templates')
jinja_env = jinja2.Environment(loader=jinja2.FileSystemLoader(template_dir), autoescape=True)

class BaseHandler(webapp2.RequestHandler):
    page_name = "home"
    date_details = datetime.datetime.now(frtz())
    date_details = date_details.replace(tzinfo=frtz())

    def is_connected(self):
        if self.request.cookies.get('user_id'):
            user_id = str(self.request.cookies.get('user_id'))

            if user_id and user_id != "":
                return check_cookie(user_id)
            else:
                return False

        else:
            return False

    @staticmethod
    def render_str(template, **params):
        t = jinja_env.get_template(template)
        return t.render(params)

    def render(self, template, **kw):
        if self.is_connected():
            user_id = self.request.cookies.get('user_id').split('|')[0]
            username = get_username_from_id(user_id)
            is_teacher = get_is_teacher_from_id(user_id)
            is_admin = get_is_admin_from_id(user_id)

            self.write(self.render_str(template, connected=True, username=username, is_teacher=is_teacher,
                                       is_admin=is_admin, pageName=self.page_name, **kw))
        else:
            self.write(self.render_str(template, connected=False, pageName=self.page_name, **kw))

    def write(self, *a, **kw):
        self.response.out.write(*a, **kw)


text:
<?php

namespace Oro\Bundle\SearchBundle\Extension;

use Symfony\Component\Config\Definition\Exception\InvalidConfigurationException;
use Symfony\Component\Security\Core\Util\ClassUtils;

use Oro\Bundle\DataGridBundle\Datasource\ResultRecordInterface;
use Oro\Bundle\DataGridBundle\Extension\Formatter\Property\TwigTemplateProperty;
use Oro\Bundle\SearchBundle\Provider\SearchMappingProvider;

class SearchResultProperty extends TwigTemplateProperty
{
    /**  @var SearchMappingProvider */
    protected $mappingProvider;

    /**
     * @var array
     * @deprecated since 1.8 Please use mappingProvider for mapping config
     */
    protected $entitiesConfig;

    public function __construct(\Twig_Environment $environment, $config)
    {
        parent::__construct($environment);

        $this->entitiesConfig = $config;
    }

    /**
     * @param SearchMappingProvider $mappingProvider
     */
    public function setMappingProvider(SearchMappingProvider $mappingProvider)
    {
        $this->mappingProvider = $mappingProvider;
    }

    /**
     * {@inheritdoc}
     */
    public function getValue(ResultRecordInterface $record)
    {
        $entity = $record->getValue('entity');
        $entityClass = ClassUtils::getRealClass($entity);

        if (!$this->mappingProvider->isClassSupported($entityClass)) {
            throw new InvalidConfigurationException(
                sprintf('Unknown entity type %s, unable to find search configuration', $entityClass)
            );
        } else {
            $searchTemplate = $this->mappingProvider->getMappingConfig()[$entityClass]['search_template'];
        }

        if (!$this->params->offsetGetOr('template', false)) {
            $this->params->offsetSet('template', $searchTemplate);
        }

        return $this->getTemplate()->render(
            [
                'indexer_item' => $record->getValue('indexer_item'),
                'entity'       => $record->getValue('entity'),
            ]
        );
    }

    /**
     * @param array $configArray
     */
    public function setEntitiesConfig(array $configArray)
    {
        $this->entitiesConfig = $configArray;
    }
}


text:
package neo4j.sample02;

import java.net.*;
import com.sun.jersey.api.client.*;
import javax.ws.rs.core.MediaType;

public class RestApi01
{
	private static final String SERVER_ROOT_URI = "http://localhost:7474/db/data/";

    public static void main( String[] args ) throws URISyntaxException
    {
        checkDatabaseIsRunning();

        // START SNIPPET: nodesAndProps
        URI firstNode = createNode();
        addProperty( firstNode, "name", "Joe Strummer" );
        URI secondNode = createNode();
        addProperty( secondNode, "band", "The Clash" );
        // END SNIPPET: nodesAndProps

        // START SNIPPET: addRel
        URI relationshipUri = addRelationship( firstNode, secondNode, "singer",
                "{ \"from\" : \"1976\", \"until\" : \"1986\" }" );
        // END SNIPPET: addRel

        // START SNIPPET: addMetaToRel
        addMetadataToProperty( relationshipUri, "stars", "5" );
        // END SNIPPET: addMetaToRel

        // START SNIPPET: queryForSingers
        findSingersInBands( firstNode );
        // END SNIPPET: queryForSingers
    }

    private static void findSingersInBands( URI startNode )
            throws URISyntaxException
    {
        // START SNIPPET: traversalDesc
        // TraversalDefinition turns into JSON to send to the Server
        TraversalDefinition t = new TraversalDefinition();
        t.setOrder( TraversalDefinition.DEPTH_FIRST );
        t.setUniqueness( TraversalDefinition.NODE );
        t.setMaxDepth( 10 );
        t.setReturnFilter( TraversalDefinition.ALL );
        t.setRelationships( new Relation( "singer", Relation.OUT ) );
        // END SNIPPET: traversalDesc

        // START SNIPPET: traverse
        URI traverserUri = new URI( startNode.toString() + "/traverse/node" );
        WebResource resource = Client.create()
                .resource( traverserUri );
        String jsonTraverserPayload = t.toJson();
        ClientResponse response = resource.accept( MediaType.APPLICATION_JSON )
                .type( MediaType.APPLICATION_JSON )
                .entity( jsonTraverserPayload )
                .post( ClientResponse.class );

        System.out.println( String.format(
                "POST [%s] to [%s], status code [%d], returned data: "
                        + System.getProperty( "line.separator" ) + "%s",
                jsonTraverserPayload, traverserUri, response.getStatus(),
                response.getEntity( String.class ) ) );
        response.close();
        // END SNIPPET: traverse
    }

    // START SNIPPET: insideAddMetaToProp
    private static void addMetadataToProperty( URI relationshipUri,
            String name, String value ) throws URISyntaxException
    {
        URI propertyUri = new URI( relationshipUri.toString() + "/properties" );
        String entity = toJsonNameValuePairCollection( name, value );
        WebResource resource = Client.create()
                .resource( propertyUri );
        ClientResponse response = resource.accept( MediaType.APPLICATION_JSON )
                .type( MediaType.APPLICATION_JSON )
                .entity( entity )
                .put( ClientResponse.class );

        System.out.println( String.format(
                "PUT [%s] to [%s], status code [%d]", entity, propertyUri,
                response.getStatus() ) );
        response.close();
    }

    // END SNIPPET: insideAddMetaToProp

    private static String toJsonNameValuePairCollection( String name,
            String value )
    {
        return String.format( "{ \"%s\" : \"%s\" }", name, value );
    }

    private static URI createNode()
    {
        // START SNIPPET: createNode
        final String nodeEntryPointUri = SERVER_ROOT_URI + "node";
        // http://localhost:7474/db/data/node

        WebResource resource = Client.create()
                .resource( nodeEntryPointUri );
        // POST {} to the node entry point URI
        ClientResponse response = resource.accept( MediaType.APPLICATION_JSON )
                .type( MediaType.APPLICATION_JSON )
                .entity( "{}" )
                .post( ClientResponse.class );

        final URI location = response.getLocation();
        System.out.println( String.format(
                "POST to [%s], status code [%d], location header [%s]",
                nodeEntryPointUri, response.getStatus(), location.toString() ) );
        response.close();

        return location;
        // END SNIPPET: createNode
    }

    // START SNIPPET: insideAddRel
    private static URI addRelationship( URI startNode, URI endNode,
            String relationshipType, String jsonAttributes )
            throws URISyntaxException
    {
        URI fromUri = new URI( startNode.toString() + "/relationships" );
        String relationshipJson = generateJsonRelationship( endNode,
                relationshipType, jsonAttributes );

        WebResource resource = Client.create()
                .resource( fromUri );
        // POST JSON to the relationships URI
        ClientResponse response = resource.accept( MediaType.APPLICATION_JSON )
                .type( MediaType.APPLICATION_JSON )
                .entity( relationshipJson )
                .post( ClientResponse.class );

        final URI location = response.getLocation();
        System.out.println( String.format(
                "POST to [%s], status code [%d], location header [%s]",
                fromUri, response.getStatus(), location.toString() ) );

        response.close();
        return location;
    }
    // END SNIPPET: insideAddRel

    private static String generateJsonRelationship( URI endNode,
            String relationshipType, String... jsonAttributes )
    {
        StringBuilder sb = new StringBuilder();
        sb.append( "{ \"to\" : \"" );
        sb.append( endNode.toString() );
        sb.append( "\", " );

        sb.append( "\"type\" : \"" );
        sb.append( relationshipType );
        if ( jsonAttributes == null || jsonAttributes.length < 1 )
        {
            sb.append( "\"" );
        }
        else
        {
            sb.append( "\", \"data\" : " );
            for ( int i = 0; i < jsonAttributes.length; i++ )
            {
                sb.append( jsonAttributes[i] );
                if ( i < jsonAttributes.length - 1 )
                { // Miss off the final comma
                    sb.append( ", " );
                }
            }
        }

        sb.append( " }" );
        return sb.toString();
    }

    private static void addProperty( URI nodeUri, String propertyName,
            String propertyValue )
    {
        // START SNIPPET: addProp
        String propertyUri = nodeUri.toString() + "/properties/" + propertyName;
        // http://localhost:7474/db/data/node/{node_id}/properties/{property_name}

        WebResource resource = Client.create()
                .resource( propertyUri );
        ClientResponse response = resource.accept( MediaType.APPLICATION_JSON )
                .type( MediaType.APPLICATION_JSON )
                .entity( "\"" + propertyValue + "\"" )
                .put( ClientResponse.class );

        System.out.println( String.format( "PUT to [%s], status code [%d]",
                propertyUri, response.getStatus() ) );
        response.close();
        // END SNIPPET: addProp
    }

    private static void checkDatabaseIsRunning()
    {
        // START SNIPPET: checkServer
        WebResource resource = Client.create()
                .resource( SERVER_ROOT_URI );
        ClientResponse response = resource.get( ClientResponse.class );

        System.out.println( String.format( "GET on [%s], status code [%d]",
                SERVER_ROOT_URI, response.getStatus() ) );
        response.close();
        // END SNIPPET: checkServer
    }
}


text:
require 'spec_helper'

describe 'lamp::web' do
  context 'When all attributes are default, on Ubuntu 14.04' do
    let(:chef_run) do
      runner = ChefSpec::ServerRunner.new(platform: 'ubuntu', version: '14.04')
      runner.converge(described_recipe)
    end

    it 'converges successfully' do
      expect { chef_run }.to_not raise_error
    end

    it "creates httpd_service['customers']" do
      expect(chef_run).to create_httpd_service('customers')
        .with(
          mpm: 'prefork'
        )
    end

    it "creates httpd_config['customers']" do
      expect(chef_run).to create_httpd_config 'customers'
    end

    it "creates directory['/var/www/customers/public_html']" do
      expect(chef_run).to create_directory('/var/www/customers/public_html')
        .with(
          recursive: true
        )
    end

    %w(customer.php index.php).each do |file|
      full_path = File.join('/var/www/customers/public_html', file)
      it "creates cookbook_file[#{full_path}]" do
        expect(chef_run).to create_cookbook_file(full_path)
          .with(
            mode: '0644',
            owner: 'web_admin',
            group: 'web_admin'
          )
      end
    end

    it "installs httpd_module['php5']" do
      expect(chef_run).to create_httpd_module('php5')
    end
  end
end


text:
@import Foundation;

@interface Foo : NSObject
@end


text:
<?php
/**
 * Created by PhpStorm.
 * User: Louis Lam
 * Date: 8/25/2015
 * Time: 12:08 PM
 */

namespace LouisLam\CRUD;

use PhpOffice\PhpSpreadsheet\Cell\DataType;
use PhpOffice\PhpSpreadsheet\Spreadsheet;
use PhpOffice\PhpSpreadsheet\Writer\Xlsx;

class ExcelHelper {
    private $headerClosure;

    public function __construct() {
        $this->headerClosure= function ($key, $value) {
            header("$key: $value");
        };
    }

    public function genExcel(LouisCRUD $crud, array $list, $filename = null) {
        $excel = new Spreadsheet();
        $sheet = $excel->getActiveSheet();
        $fields = $crud->getShowFields();

        // Header
        $i = 1;
        foreach ($fields as $field) {
            $sheet->setCellValueByColumnAndRow($i, 1, $field->getDisplayName());
            $sheet->getColumnDimensionByColumn($i)->setAutoSize(true);
            $i++;
        }

        // Data
        $j = 2;
        foreach ($list as $bean) {
            $i = 1;
            foreach ($fields as $field) {
                $sheet->getCellByColumnAndRow($i, $j)->setValueExplicit(
                    strip_tags($field->cellValue($bean)),
                    DataType::TYPE_STRING
                );
                $i++;
            }
            $j++;
        }

        // Save
        $objWriter = new Xlsx($excel);

        if ($filename == null) {
            $name = $crud->getTableName();
            $date = date("Y-m-d", time());
            $filename = "$name-$date.xlsx";
        }

        $headers = [
            "Content-Type" => "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
            "Content-Disposition" => 'attachment;filename="' . $filename . '"',
            "Cache-Control" => "max-age=0"
        ];

        foreach ($headers as $key => $value) {
            $h = $this->headerClosure;
            $h($key, $value);
        }

        $objWriter->save("php://output");
    }

    /**
     * @param \Closure $headerClosure
     */
    public function setHeaderClosure($headerClosure) {
        $this->headerClosure = $headerClosure;
    }
}


text:
extern crate lmdb;
extern crate lmdb_sys;

use self::lmdb::{Environment, Database, DatabaseFlags, Cursor, WriteFlags, DUP_SORT, INTEGER_KEY};
pub use self::lmdb::Error as LmdbError;
use self::lmdb::Transaction as LmdbTransaction;
use adapter::{Adapter, Transaction};
use block::Block;
use direntry::DirEntry;
use entry::{self, SerializedEntry};
use errors::*;
use id::{BlockId, EntryId};
use metadata::Metadata;
use path::Path;
use protobuf::{self, Message};
use std::io::Write;
use std::path::Path as StdPath;
use std::str;

const MAX_DBS: u32 = 8;
const DB_PERMS: lmdb_sys::mode_t = 0o600;

// Names of "databases" within LMDB: effectively namespaces for keys
const BLOCKS_DB: &str = "blocks";
const DIRECTORIES_DB: &str = "directories";
const ENTRIES_DB: &str = "entries";
const METADATA_DB: &str = "metadata";
const STATE_DB: &str = "state";

// Names of keys within the "state" database
const LOG_ID_KEY: &[u8] = b"log_id";
const LATEST_BLOCK_ID_KEY: &[u8] = b"latest_block_id";

/// Adapter implementation for the Lightning Memory Database
pub struct LmdbAdapter {
    /// LMDB "environment" (directory containing multiple databases)
    env: Environment,

    /// Blocks in the log, persisted by ID
    blocks: Database,

    /// Directory hierarchy, mapping names to entry IDs
    directories: Database,

    /// Entries indexed by integer entry ID
    entries: Database,

    /// Per-entry metadata, e.g. creation/modification time
    metadata: Database,

    /// Global metadata about the current state of the directory
    state: Database,
}

impl<'a> Adapter<'a> for LmdbAdapter {
    type R = RoTransaction<'a>;
    type W = RwTransaction<'a>;

    fn create_database(path: &StdPath) -> Result<LmdbAdapter> {
        let env = Environment::new()
            .set_max_dbs(MAX_DBS)
            .open_with_permissions(path, DB_PERMS)?;

        let blocks = env.create_db(Some(BLOCKS_DB), DatabaseFlags::empty())?;
        let directories = env.create_db(Some(DIRECTORIES_DB), INTEGER_KEY | DUP_SORT)?;
        let entries = env.create_db(Some(ENTRIES_DB), INTEGER_KEY)?;
        let metadata = env.create_db(Some(METADATA_DB), INTEGER_KEY)?;
        let state = env.create_db(Some(STATE_DB), DatabaseFlags::empty())?;

        Ok(LmdbAdapter {
            env: env,
            blocks: blocks,
            directories: directories,
            entries: entries,
            metadata: metadata,
            state: state,
        })
    }

    fn open_database(path: &StdPath) -> Result<LmdbAdapter> {
        let env = Environment::new()
            .set_max_dbs(MAX_DBS)
            .open_with_permissions(path, DB_PERMS)?;

        let blocks = env.open_db(Some(BLOCKS_DB))?;
        let directories = env.open_db(Some(DIRECTORIES_DB))?;
        let entries = env.open_db(Some(ENTRIES_DB))?;
        let metadata = env.open_db(Some(METADATA_DB))?;
        let state = env.open_db(Some(STATE_DB))?;

        Ok(LmdbAdapter {
            env: env,
            blocks: blocks,
            directories: directories,
            entries: entries,
            metadata: metadata,
            state: state,
        })
    }

    fn ro_transaction(&'a self) -> Result<RoTransaction<'a>> {
        Ok(RoTransaction(self.env.begin_ro_txn()?))
    }

    fn rw_transaction(&'a self) -> Result<RwTransaction<'a>> {
        Ok(RwTransaction(self.env.begin_rw_txn()?))
    }

    fn next_free_entry_id(&self, txn: &RwTransaction) -> Result<EntryId> {
        let cursor = txn.0.open_ro_cursor(self.entries)?;

        let last_id = match cursor.get(None, None, lmdb_sys::MDB_LAST) {
            Ok((id, _)) => EntryId::from_bytes(id.unwrap()).unwrap(),
            Err(_) => EntryId::root(),
        };

        Ok(last_id.next())
    }

    fn add_block<'t>(&'t self, txn: &'t mut RwTransaction, block: &Block) -> Result<()> {
        let block_id = BlockId::of(block);
        let parent_id = &block.get_body().parent_id;

        // Ensure the block we're adding is the next in the chain
        if *parent_id == BlockId::zero().as_ref() {
            match txn.lmdb_get(self.state, LOG_ID_KEY) {
                Ok(_) => {
                    let msg = "initial block already set".to_string();
                    return Err(ErrorKind::EntryAlreadyExists(msg).into());
                }
                Err(Error(ErrorKind::Lmdb(LmdbError::NotFound), _)) => (),
                Err(err) => return Err(err),
            };

            txn.put(self.state, LOG_ID_KEY, block_id.as_ref())?;
        } else if *parent_id != self.current_block_id(txn)?.as_ref() {
            let msg = "new block's parent does not match current ID".to_string();
            return Err(ErrorKind::OrderingInvalid(msg).into());
        }

        // This check should be redundant given the one above, but is here just in case
        match txn.lmdb_get(self.blocks, block_id.as_ref()) {
            Ok(_) => {
                let msg = "new block has already been committed".to_string();
                return Err(ErrorKind::EntryAlreadyExists(msg).into());
            }
            Err(Error(ErrorKind::Lmdb(LmdbError::NotFound), _)) => (),
            Err(err) => return Err(err),
        }

        // Store the new block
        txn.put(
            self.blocks,
            block_id.as_ref(),
            &block.write_to_bytes()?,
        )?;

        // Update the current block ID in the state table
        txn.put(self.state, LATEST_BLOCK_ID_KEY, block_id.as_ref())?;

        Ok(())
    }

    fn current_block_id<'t, T>(&'t self, txn: &'t T) -> Result<BlockId>
    where
        T: Transaction,
    {
        BlockId::from_bytes(txn.lmdb_get(self.state, LATEST_BLOCK_ID_KEY)?)
    }

    fn add_entry<'t>(
        &'t self,
        txn: &'t mut RwTransaction,
        entry: &SerializedEntry,
        name: &'t str,
        parent_id: EntryId,
        metadata: &Metadata,
    ) -> Result<DirEntry> {
        match txn.lmdb_get(self.entries, entry.id.as_ref()) {
            Ok(_) => {
                let msg = format!(
                    "error creating '{}': entry ID '{:?}' already exists",
                    name,
                    entry.id
                );
                return Err(ErrorKind::EntryAlreadyExists(msg).into());
            }
            Err(Error(ErrorKind::Lmdb(LmdbError::NotFound), _)) => (),
            Err(err) => return Err(err).chain_err(|| format!("error creating {}", name)),
        }

        match txn.lmdb_get(self.directories, parent_id.as_ref()) {
            Ok(_) => {
                match self.find_child(txn, parent_id, name) {
                    Ok(_) => {
                        let msg = format!("entry '{}' already exists", name);
                        return Err(ErrorKind::EntryAlreadyExists(msg).into());
                    }
                    Err(Error(ErrorKind::NotFound(_), _)) => (),
                    Err(err) => {
                        return Err(err).chain_err(|| {
                            format!("error finding child of entry ID {:?}", parent_id)
                        })
                    }
                }
            }
            Err(Error(ErrorKind::Lmdb(LmdbError::NotFound), _)) => (),
            Err(err) => return Err(err).chain_err(|| format!("error creating {}", name)),
        }

        let direntry = DirEntry {
            id: entry.id,
            parent_id: parent_id,
            name: name,
        };

        if entry.id != EntryId::root() {
            txn.put(
                self.directories,
                parent_id.as_ref(),
                &direntry.to_bytes(),
            )?;
        }

        txn.put(
            self.metadata,
            entry.id.as_ref(),
            &metadata.write_to_bytes()?,
        )?;

        let mut buffer = txn.reserve(
            self.entries,
            entry.id.as_ref(),
            entry::HEADER_SIZE + entry.data.len(),
        )?;

        buffer.write_all(&entry.class.as_bytes())?;
        buffer.write_all(entry.data)?;

        Ok(direntry)
    }

    fn find_direntry<'t, T>(&'t self, txn: &'t T, path: &Path) -> Result<DirEntry>
    where
        T: Transaction,
    {
        let result = path.components().iter().fold(
            Ok(DirEntry::root()),
            |parent_direntry, component| {
                self.find_child(txn, parent_direntry?.id, component)
            },
        );

        match result {
            Ok(_) => result,
            Err(Error(ErrorKind::Lmdb(LmdbError::NotFound), _)) => {
                result.chain_err(|| format!("not found: {:?}", path))
            }
            Err(_) => result.chain_err(|| format!("error reading {:?}", path)),
        }
    }

    fn find_metadata<'t, T>(&'t self, txn: &'t T, id: &EntryId) -> Result<Metadata>
    where
        T: Transaction,
    {
        let proto = txn.lmdb_get(self.metadata, id.as_ref())?;
        Ok(protobuf::parse_from_bytes::<Metadata>(proto)?)
    }

    fn find_entry<'t, T>(&'t self, txn: &'t T, id: &EntryId) -> Result<SerializedEntry>
    where
        T: Transaction,
    {
        let bytes = txn.lmdb_get(self.entries, id.as_ref())?;
        SerializedEntry::from_bytes(*id, bytes)
    }
}

impl LmdbAdapter {
    fn find_child<'a, T>(&'a self, txn: &'a T, parent_id: EntryId, name: &str) -> Result<DirEntry>
    where
        T: Transaction,
    {
        let direntry_bytes = txn.lmdb_find(
            self.directories,
            parent_id.as_ref(),
            |direntry_bytes| {
                let direntry = DirEntry::new(parent_id, direntry_bytes).unwrap();
                direntry.name == name
            },
        )?;

        DirEntry::new(parent_id, direntry_bytes)
    }
}

/// Internal functionality which is not part of the public `Transaction` API
/// NOTE: these methods should not be called from outside of this module
pub trait AdapterTransaction {
    /// Underlying transaction type from the `lmdb` crate
    type T: LmdbTransaction;

    /// Obtain the inner `LmdbTransaction`
    fn lmdb_txn(&self) -> &Self::T;

    /// Get the raw data associated with an object (TODO: remove this from this trait)
    fn lmdb_get(&self, db: Database, key: &[u8]) -> Result<&[u8]> {
        Ok(self.lmdb_txn().get(db, &key)?)
    }

    /// Perform a search of the given database, looking for an entry that matches the predicate
    // TODO: since LMDB is ordered, we could e.g. perform a binary search
    fn lmdb_find<P>(&self, db: Database, key: &[u8], predicate: P) -> Result<&[u8]>
    where
        P: Fn(&[u8]) -> bool,
    {
        // Ensure the entry exists
        // TODO: Fix upstream unwrap in lmdb crate's iter_from
        self.lmdb_get(db, key)?;

        let mut cursor = self.lmdb_txn().open_ro_cursor(db)?;
        let mut result = None;

        // TODO: Remove earlier check once this no longer panics on missing keys
        for (cursor_key, value) in cursor.iter_from(key) {
            if cursor_key != key {
                return Err(ErrorKind::NotFound("key not found".to_string()).into());
            }

            if predicate(value) {
                result = Some(value);
                break;
            }
        }

        result.ok_or_else(|| ErrorKind::NotFound("key not found".to_string()).into())
    }
}

/// Read-write transaction: only one allowed at a time
pub struct RwTransaction<'a>(self::lmdb::RwTransaction<'a>);

/// Read-only transaction: several can be active concurrently
pub struct RoTransaction<'a>(self::lmdb::RoTransaction<'a>);

impl<'a> AdapterTransaction for RwTransaction<'a> {
    type T = self::lmdb::RwTransaction<'a>;

    fn lmdb_txn(&self) -> &self::lmdb::RwTransaction<'a> {
        &self.0
    }
}

impl<'a> AdapterTransaction for RoTransaction<'a> {
    type T = self::lmdb::RoTransaction<'a>;

    fn lmdb_txn(&self) -> &self::lmdb::RoTransaction<'a> {
        &self.0
    }
}

impl<'a> Transaction for RwTransaction<'a> {
    fn commit(self) -> Result<()> {
        Ok(self.0.commit()?)
    }
}

impl<'a> Transaction for RoTransaction<'a> {
    fn commit(self) -> Result<()> {
        Ok(self.0.commit()?)
    }
}

impl<'a> RwTransaction<'a> {
    /// Reserve the given amount of space in LMDB for the given key
    pub fn reserve(&mut self, database: Database, key: &[u8], len: usize) -> Result<&mut [u8]> {
        Ok(self.0.reserve(database, &key, len, WriteFlags::empty())?)

    }

    /// Put the given data into LMDB under the given key
    fn put(&mut self, database: Database, key: &[u8], data: &[u8]) -> Result<()> {
        Ok(self.0.put(database, &key, &data, WriteFlags::empty())?)
    }
}

#[cfg(test)]
mod tests {
    use adapter::{Adapter, Transaction};
    use adapter::lmdb::LmdbAdapter;
    use alg::CipherSuite;
    use block::Block;
    use crypto::signing::KeyPair;
    use entry::{Class, SerializedEntry};
    use errors::*;
    use id::{BlockId, EntryId};
    use metadata::Metadata;
    use path::Path;
    use ring::rand;
    use setup;
    use tempdir::TempDir;
    use timestamp::Timestamp;

    fn create_database() -> LmdbAdapter {
        let dir = TempDir::new("ithos-test").unwrap();
        LmdbAdapter::create_database(dir.path()).unwrap()
    }

    fn example_timestamp() -> Timestamp {
        Timestamp::at(1_231_006_505)
    }

    fn example_block() -> Block {
        let rng = rand::SystemRandom::new();
        let admin_keypair = KeyPair::generate(&rng);

        setup::create_log(
            CipherSuite::Ed25519_AES256GCM_SHA256,
            setup::tests::ADMIN_USERNAME,
            &admin_keypair,
            setup::tests::ADMIN_KEYPAIR_SEALED,
            setup::tests::ADMIN_KEYPAIR_SALT,
            setup::tests::COMMENT,
        )
    }

    fn example_metadata() -> Metadata {
        let mut metadata = Metadata::new();

        let block_id = BlockId::zero();

        metadata.set_created_id(Vec::from(block_id.as_ref()));
        metadata.set_updated_id(Vec::from(block_id.as_ref()));
        metadata.set_created_at(example_timestamp().to_int());
        metadata.set_updated_at(example_timestamp().to_int());

        metadata
    }

    fn example_entry(id: EntryId, data: &[u8]) -> SerializedEntry {
        SerializedEntry {
            id: id,
            class: Class::Root,
            data: data,
        }
    }

    #[test]
    fn duplicate_block() {
        let adapter = create_database();
        let block = example_block();

        let mut txn = adapter.rw_transaction().unwrap();
        adapter.add_block(&mut txn, &block).unwrap();
        txn.commit().unwrap();

        let mut txn = adapter.rw_transaction().unwrap();
        let err = adapter.add_block(&mut txn, &block).expect_err(
            "expected duplicate block to cause error",
        );

        match *err.kind() {
            ErrorKind::EntryAlreadyExists(ref msg) => assert_eq!(msg, "initial block already set"),
            ref other => panic!("unexpected error kind: {:?}", other),
        }
    }

    #[test]
    fn entry_lookup() {
        let adapter = create_database();
        let example_data = b"just an example host entry";

        {
            let mut txn = adapter.rw_transaction().unwrap();

            let domain_id = adapter.next_free_entry_id(&txn).unwrap();
            adapter
                .add_entry(
                    &mut txn,
                    &example_entry(domain_id, b"example domain entry"),
                    "example.com",
                    EntryId::root(),
                    &example_metadata(),
                )
                .unwrap();

            let hosts_id = domain_id.next();
            adapter
                .add_entry(
                    &mut txn,
                    &example_entry(hosts_id, b"example hosts ou"),
                    "hosts",
                    domain_id,
                    &example_metadata(),
                )
                .unwrap();

            let host_id = hosts_id.next();
            adapter
                .add_entry(
                    &mut txn,
                    &example_entry(host_id, example_data),
                    "master.example.com",
                    hosts_id,
                    &example_metadata(),
                )
                .unwrap();

            txn.commit().unwrap();
        }

        {
            let txn = adapter.ro_transaction().unwrap();

            {
                let path = Path::new("/example.com/hosts/master.example.com").unwrap();

                let direntry = adapter.find_direntry(&txn, path).unwrap();
                assert_eq!(direntry.name, "master.example.com");

                let metadata = adapter.find_metadata(&txn, &direntry.id).unwrap();
                assert_eq!(metadata.created_at, example_timestamp().to_int());

                let entry = adapter.find_entry(&txn, &direntry.id).unwrap();
                assert_eq!(entry.data, &example_data[..]);
            }

            txn.commit().unwrap();
        }
    }

    #[test]
    fn duplicate_entry_id() {
        let adapter = create_database();

        let mut txn = adapter.rw_transaction().unwrap();

        let domain_id = adapter.next_free_entry_id(&txn).unwrap();
        adapter
            .add_entry(
                &mut txn,
                &example_entry(domain_id, b"domain"),
                "example.com",
                EntryId::root(),
                &example_metadata(),
            )
            .unwrap();

        let err = adapter
            .add_entry(
                &mut txn,
                &example_entry(domain_id, b"domain"),
                "another.com",
                EntryId::root(),
                &example_metadata(),
            )
            .expect_err("expected duplicate entry ID to cause error");

        match *err.kind() {
            ErrorKind::EntryAlreadyExists(_) => (),
            ref other => panic!("unexpected error kind: {:?}", other),
        }
    }

    #[test]
    fn duplicate_entry_name() {
        let adapter = create_database();

        let mut txn = adapter.rw_transaction().unwrap();

        let domain_id = adapter.next_free_entry_id(&txn).unwrap();
        adapter
            .add_entry(
                &mut txn,
                &example_entry(domain_id, b"domain"),
                "example.com",
                EntryId::root(),
                &example_metadata(),
            )
            .unwrap();

        let err = adapter
            .add_entry(
                &mut txn,
                &example_entry(domain_id.next(), b"domain"),
                "example.com",
                EntryId::root(),
                &example_metadata(),
            )
            .expect_err("expected duplicate entry name to cause error");

        match *err.kind() {
            ErrorKind::EntryAlreadyExists(_) => (),
            ref other => panic!("unexpected error kind: {:?}", other),
        }
    }
}


text:
namespace gin {

class ArrayBufferAllocator : public v8::ArrayBuffer::Allocator {
 public:
  void* Allocate(size_t length) override;
  void* AllocateUninitialized(size_t length) override;
  void Free(void* data, size_t length) override;

  GIN_EXPORT static ArrayBufferAllocator* SharedInstance();
};

class GIN_EXPORT ArrayBuffer {
 public:
  ArrayBuffer();
  ArrayBuffer(v8::Isolate* isolate, v8::Local<v8::ArrayBuffer> buffer);
  ArrayBuffer(const ArrayBuffer&) = delete;
  ~ArrayBuffer();
  ArrayBuffer& operator=(const ArrayBuffer& other);

  void* bytes() const {
    return backing_store_ ? backing_store_->Data() : nullptr;
  }
  size_t num_bytes() const {
    return backing_store_ ? backing_store_->ByteLength() : 0;
  }

 private:
  std::shared_ptr<v8::BackingStore> backing_store_;
};

template<>
struct GIN_EXPORT Converter<ArrayBuffer> {
  static bool FromV8(v8::Isolate* isolate, v8::Local<v8::Value> val,
                     ArrayBuffer* out);
};

class GIN_EXPORT ArrayBufferView {
 public:
  ArrayBufferView();
  ArrayBufferView(v8::Isolate* isolate, v8::Local<v8::ArrayBufferView> view);
  ArrayBufferView(const ArrayBufferView&) = delete;
  ~ArrayBufferView();
  ArrayBufferView& operator=(const ArrayBufferView& other);

  void* bytes() const {
    return static_cast<uint8_t*>(array_buffer_.bytes()) + offset_;
  }
  size_t num_bytes() const { return num_bytes_; }

 private:
  ArrayBuffer array_buffer_;
  size_t offset_;
  size_t num_bytes_;
};

template<>
struct GIN_EXPORT Converter<ArrayBufferView> {
  static bool FromV8(v8::Isolate* isolate, v8::Local<v8::Value> val,
                     ArrayBufferView* out);
};

}  // namespace gin

#endif  // GIN_ARRAY_BUFFER_H_


text:
{-# LANGUAGE RecordWildCards, ImplicitParams, TupleSections #-}

module Internal.ISpec(Spec(..),
             Process(..),
             specTmpVar,
             specStateVar,
             specGetProcess,
             specAllCFAs,
             specAllProcs,
             specAllMBs,
             specLookupMB,
             specGetCFA,
             specMapCFA,
             specInlineWirePrefix,
             cfaLocInlineWirePrefix,
             lookupVar,
             getVar,
             getRelation,
             lookupEnumerator,
             getEnumerator,
             getEnumeration,
             typeWidth,
             enumToInt) where

import Data.List
import Data.Maybe
import Data.Tuple.Select
import qualified Data.Map as M
import qualified Data.Graph.Inductive.Graph as G
import Text.PrettyPrint

import TSLUtil
import Pos
import Util
import Internal.CFA
import Internal.IVar
import Internal.IType
import Internal.IExpr
import Internal.IRelation
import Internal.ITransducer
import Internal.TranSpec
import PP
import Internal.PID
import qualified Frontend.NS as F

data Process = Process {
    procName     :: String,
    procCFA      :: CFA,
    procChildren :: [Process]
}

data Spec = Spec {
    specEnum    :: [Enumeration],
    specVar     :: [Var],
    specWire    :: Maybe CFA,                   -- wire assignment
    specPrefix  :: Maybe CFA,                   -- prefix blocks
    specProc    :: [Process],                   -- processes
    specCAct    :: CFA,                         -- controllable transitions
    specUpds    :: M.Map String [(Expr, Expr)], -- variable update functions specified explicitly
    specRels    :: [Relation],
    specApply   :: [Apply],
    specTran    :: TranSpec,                    -- info required for variable update
                                                -- computation
    specXducers :: [Transducer]                 -- transducers
}

specStateVar :: Spec -> [Var]
specStateVar = filter ((==VarState) . varCat) . specVar

specTmpVar :: Spec -> [Var]
specTmpVar = filter ((==VarTmp) . varCat) . specVar

instance PP Spec where
    pp spec@Spec{..} = (text $ "/* state variables: " ++ (show $ length sv) ++ "(" ++ show sbits ++ "bits), " ++
                               "label variables: "++ (show $ length lv) ++ "(" ++ show lbits ++ "bits)*/" )
                       $+$
                       (vcat $ map (($+$ text "") . pp) specEnum)
                       $+$
                       (vcat $ map (($+$ text "") . pp) specVar)
                       $+$
                       pp specTran
                       where (sv,lv) = partition ((==VarState) . varCat) specVar
                             sbits = let ?spec = spec in sum $ map typeWidth sv
                             lbits = let ?spec = spec in sum $ map typeWidth lv

lookupVar :: (?spec::Spec) => String -> Maybe Var
lookupVar n = find ((==n) . varName) $ specVar ?spec

getVar :: (?spec::Spec) => String -> Var
getVar n = fromJustMsg ("getVar: variable " ++ n ++ " not found") $ lookupVar n

lookupEnumerator :: (?spec::Spec) => String -> Maybe Enumeration
lookupEnumerator e = find (elem e . enumEnums) $ specEnum ?spec

getEnumerator :: (?spec::Spec) => String -> Enumeration
getEnumerator e = fromJustMsg ("getEnumerator: enumerator " ++ e ++ " not found") $ lookupEnumerator e

getEnumeration :: (?spec::Spec) => String -> Enumeration
getEnumeration e = fromJustMsg ("getEnumeration: enumeration " ++ e ++ " not found")
                   $ find ((==e) . enumName) $ specEnum ?spec

getRelation :: (?spec::Spec) => String -> Relation
getRelation r = fromJustMsg ("getRelation: relation " ++ r ++ " not found")
                $ find ((==r) . relName) $ specRels ?spec

twidth :: (?spec::Spec) => Type -> Int
twidth (Bool _)      = 1
twidth (Ptr _ _)     = 64
twidth (SInt _ w)    = w
twidth (UInt _ w)    = w
twidth (Enum _ e)    = bitWidth $ length (enumEnums $ getEnumeration e) - 1
twidth (Array _ t l) = l * twidth t
twidth (Struct _ fs) = sum $ map typeWidth fs
twidth t             = error $ "twidth " ++ show t ++ " undefined"

typeWidth :: (?spec::Spec, Typed a) => a -> Int
typeWidth = twidth . typ

-- Get sequence number of an enumerator
enumToInt :: (?spec::Spec) => String -> Int
enumToInt n = fst $ fromJust $ find ((==n) . snd) $ zip [0..] (enumEnums $ getEnumerator n)

specGetProcess :: Spec -> PrID -> Process
specGetProcess spec (PrID n names) | names == [] = root
                                   | otherwise   = specGetProcess' root names
    where root = fromJustMsg ("specGetProcess " ++ n ++ ": error") $ find ((== n) . procName) $ specProc spec

specGetProcess' :: Process -> [String] -> Process
specGetProcess' proc (n:names) | names == [] = child
                               | otherwise   = specGetProcess' child names
    where child = fromJustMsg "specGetProcess': error" $ find ((== n) . procName) $ procChildren proc

specGetCFA :: Spec -> EPID -> CFA
specGetCFA spec (EPIDProc pid) = procCFA $ specGetProcess spec pid
specGetCFA spec EPIDCont       = specCAct spec

specAllCFAs :: Spec -> [(EPID, CFA)]
specAllCFAs Spec{..} = concatMap (\p -> procAllCFAs (PrID (procName p) []) p) specProc  ++
                       [(EPIDCont, specCAct)]

specAllMBs :: Spec -> [Pos]
specAllMBs spec = nub
                  $ map sel1
                  $ concatMap (\(pid, proc) -> map (\(loc, lab) -> (pos $ locAct lab, pid, loc)) $ filter (isMBLabel . snd) $ G.labNodes $ procCFA proc)
                  $ specAllProcs spec

specLookupMB :: Spec -> Pos -> [(PrID, Loc, F.Scope)]
specLookupMB spec p =
    concat
    $ (\xs -> if' (length xs > 1) (error $ "specLookupMB: MB " ++ show p ++ " is instantiated in multiple processes") xs)
    $ filter (not . null)
    $ map (\(pid, proc) -> map (\(loc, lab) -> (pid, loc, fScope $ head $ locStack lab))
                           $ filter ((== p) . pos . locAct . snd)
                           $ filter (isMBLabel . snd)
                           $ G.labNodes $ procCFA proc)
    $ specAllProcs spec

procAllCFAs :: PrID -> Process -> [(EPID, CFA)]
procAllCFAs pid proc = (EPIDProc pid, procCFA proc) :
                       concatMap (\p -> procAllCFAs (childPID pid (procName p)) p) (procChildren proc)

specAllProcs :: Spec -> [(PrID, Process)]
specAllProcs Spec{..} = concatMap (\p -> procAllForkedProcs (PrID (procName p) []) p) specProc

procAllForkedProcs :: PrID -> Process -> [(PrID, Process)]
procAllForkedProcs pid p = (pid,p) : (concatMap (\p' -> procAllForkedProcs (childPID pid (procName p')) p') $ procChildren p)

-- Apply transformation to all CFA's in the spec
specMapCFA :: (CFA -> CFA) -> Spec -> Spec
specMapCFA f spec =
   spec { specProc = map (procMapCFA f) $ specProc spec
        , specCAct = f $ specCAct spec}

procMapCFA :: (CFA -> CFA) -> Process -> Process
procMapCFA f proc =
    proc { procCFA      = f $ procCFA proc
         , procChildren = map (procMapCFA f) $ procChildren proc
         }

specInlineWirePrefix :: Spec -> Spec
specInlineWirePrefix spec = specMapCFA (cfaInlineWirePrefix spec) spec

cfaInlineWirePrefix :: Spec -> CFA -> CFA
cfaInlineWirePrefix spec cfa = foldl' (\cfa0 loc -> let cfa1 = case specPrefix spec of
                                                                    Nothing -> cfa0
                                                                    Just a  -> cfaLocInline cfa0 loc a
                                                    in case specWire spec of
                                                            Nothing -> cfa1
                                                            Just w  -> cfaLocInline cfa1 loc w)
                                      cfa locs
    -- Find delay locations with outgoing transitions
    where locs = filter (\loc -> (isDelayLabel $ cfaLocLabel loc cfa) && (G.suc cfa loc /= []))
                        $ G.nodes cfa

cfaLocInlineWirePrefix :: Spec -> CFA -> Loc -> CFA
cfaLocInlineWirePrefix spec cfa loc =
    let cfa1 = case specPrefix spec of
                    Nothing -> cfa
                    Just a  -> cfaLocInline cfa loc a
               in case specWire spec of
                       Nothing -> cfa1
                       Just w  -> cfaLocInline cfa1 loc w


text: yes = readFile $ args !! 0


text:
from plenum.test.helper import sdk_send_random_and_check, \
    sdk_send_signed_requests, sdk_eval_timeout, \
    sdk_get_replies, sdk_check_reply, sdk_signed_random_requests
from plenum.test.spy_helpers import getAllReturnVals

def test_already_processed_requests(looper, txnPoolNodeSet,
                                    sdk_pool_handle, sdk_wallet_client):
    """
    Client re-sending request and checking that nodes picked the reply from
    ledger and did not process the request again
    """

    def get_method_call_count(method):
        counts = set()
        for node in txnPoolNodeSet:
            c = node.spylog.count(method)
            counts.add(c)
        assert len(counts) == 1
        return counts.pop()

    def get_getReplyFromLedgerForRequest_call_count():
        return get_method_call_count(
            next(iter(txnPoolNodeSet)).getReplyFromLedgerForRequest)

    def get_recordAndPropagate_call_count():
        return get_method_call_count(
            next(iter(txnPoolNodeSet)).recordAndPropagate)

    def get_last_returned_val():
        rvs = []
        for node in txnPoolNodeSet:
            rv = getAllReturnVals(node, node.getReplyFromLedgerForRequest)
            rvs.append(rv[0])
        # All items are same in the list
        assert rvs.count(rvs[0]) == len(txnPoolNodeSet)
        return rvs[0]

    rlc1 = get_getReplyFromLedgerForRequest_call_count()
    rpc1 = get_recordAndPropagate_call_count()

    # Request which will be send twice
    reqs = sdk_signed_random_requests(looper, sdk_wallet_client, 1)

    # Send, check and getting reply from first request
    sdk_reqs = sdk_send_signed_requests(sdk_pool_handle, reqs)
    total_timeout = sdk_eval_timeout(len(sdk_reqs), len(txnPoolNodeSet))
    request1 = sdk_get_replies(looper, sdk_reqs, timeout=total_timeout)
    for req_res in request1:
        sdk_check_reply(req_res)
    first_req_id = request1[0][0]['reqId']

    rlc2 = get_getReplyFromLedgerForRequest_call_count()
    rpc2 = get_recordAndPropagate_call_count()
    assert rlc2 - rlc1 == 1  # getReplyFromLedgerForRequest was called
    assert rpc2 - rpc1 == 1  # recordAndPropagate was called
    r1 = get_last_returned_val()
    assert r1 is None  # getReplyFromLedgerForRequest returned None since had not seen request

    # Request which we will send only once
    request2 = sdk_send_random_and_check(looper, txnPoolNodeSet, sdk_pool_handle, sdk_wallet_client, 1)
    second_req_id = request2[0][0]['reqId']

    assert second_req_id != first_req_id
    rlc3 = get_getReplyFromLedgerForRequest_call_count()
    rpc3 = get_recordAndPropagate_call_count()
    assert rlc3 - rlc2 == 1  # getReplyFromLedgerForRequest was called again
    assert rpc3 - rpc2 == 1  # recordAndPropagate was called again
    r2 = get_last_returned_val()
    assert r2 is None  # getReplyFromLedgerForRequest returned None since had not seen request

    # Reply for the first request, which is going to be sent again
    rep1 = request1[0][1]['result']

    # Client re-sending first request
    request3 = sdk_send_signed_requests(sdk_pool_handle, reqs)
    total_timeout = sdk_eval_timeout(len(request3), len(txnPoolNodeSet))
    request3 = sdk_get_replies(looper, request3, timeout=total_timeout)
    third_req_id = request3[0][0]['reqId']

    assert third_req_id == first_req_id
    rlc4 = get_getReplyFromLedgerForRequest_call_count()
    rpc4 = get_recordAndPropagate_call_count()
    assert rlc4 - rlc3 == 1  # getReplyFromLedgerForRequest was called again
    assert rpc4 - rpc3 == 0  # recordAndPropagate was not called
    r3 = get_last_returned_val()
    # getReplyFromLedgerForRequest did not return None this time since had seen request
    assert r3 is not None
    rep3 = request3[0][1]['result']

    # Since txnTime is not stored in ledger and reading from ledger return
    # all possible fields from transactions
    rep3 = {k: v for k, v in rep3.items() if v is not None}
    rep1 = {k: v for k, v in rep1.items() if k in rep3}

    assert rep3 == rep1  # The reply client got is same as the previous one


text:
module LCDProc

  module Widgets

    class String
      include LCDProc::Widget
      LCDProc::Widget.add_support( :string, self )

      attr_accessor :x, :y, :widget_text

      @@widget_count = 0

      # Creates a new String widget which can then be displayed anywhere on the screen.
      #
      # * <tt>:id</tt> - A unique string which identifies this widget. Defaults to "StringWidget_" + a sequence number.
      # * <tt>:text</tt> - The text that you wish to display on the screen. Default to "Hello".
      # * <tt>:col</tt> - The column in which you wish to display the text on screen. Defaults to 1.
      # * <tt>:row</tt> - The row in which you wish to display the text on screen. Defaults to 1.
      #
      # Example:
      #
      #   w = String.new
      #
      # or
      #
      #   w = String.new( 'Test', 'This is a string', 1, 5 )
      def initialize( id = "StringWidget_#{@@widget_count}", text = "Hello", col = 1, row = 1 )
        if id.nil?
          id = "StringWidget_#{@@widget_count}"
        end

        @id = id
        @type = :string
        @screen = nil
        @visible = false

        @widget_text = text
        @x = col
        @y = row

        @@widget_count += 1
      end

      # Sends to command to the LCDd server to update the widget on screen
      def update
        if @screen
          response = @screen.client.send_command( Command.new( "widget_set #{@screen.id} #{self.id} #{@x} #{@y} \"#{@widget_text}\"" ) )

          if response.successful?
            @screen.client.add_message( "Widget '#{@id}' was successfully updated" )
            return true
          else
            @screen.client.add_message( "Error: Widget '#{@id}' was NOT successfully updated (#{response.message})" )
            return true
          end
        else
          @screen.client.add_message( "Error: Cannot update Widget '#{@id}' until it is attached to a screen" )
          return false
        end
      end

    end

  end

end


text:
separator()
{
    echo "======================================================================"
}

sectionStart()
{
    echo
    separator
    echo
    echo "$1"
    echo
}

separator
echo -n "arch-maint report for `hostname` on `date`"

sectionStart "SYSTEM"
uname -a
echo
uptime

sectionStart "PENDING UPDATES"
checkupdates

sectionStart "FAILED SERVICES"
systemctl --failed

sectionStart "HIGH PROFILE LOG ENTRIES"
journalctl --no-pager -p 0..3 -xn

sectionStart "MAIL QUEUE"
mailq

sectionStart "DOCKER CONTAINERS"
docker ps -sa

sectionStart "MIRRORLIST CHANGES"
diff /etc/pacman.d/mirrorlist /etc/pacman.d/mirrorlist.pacnew

sectionStart "ETCKEEPER PENDING CHANGES"
etckeeper vcs status -s

sectionStart "ETCKEEPER RECENT CHANGES"
etckeeper vcs log --since "1 week ago"

sectionStart "REMOVE ORPHANED PACKAGES"
if [[ ! -n $(pacman -Qdt) ]]; then
    echo "No orphans to remove."
else
    pacman --noconfirm -Rns $(pacman -Qdtq)
fi

sectionStart "CLEAR OLD PACKAGE CACHE"
pacman  --noconfirm -Sc

sectionStart "OPTIMISE PACKAGE DATABASE"
pacman-optimize --nocolor

sectionStart "DISK SPACE AFTER CLEANUPS"
df -h
echo
du -hs /var

sectionStart "AUR PACKAGES"
pacman -Qem

sectionStart "EXPLICITLY INSTALLED PACKAGES"
pacman -Qen

separator
echo
echo "Report completed at `date`"