text:
use std::convert::TryFrom;
use std::fs;
use std::io::Error as IoError;
use std::process;
use std::sync::Arc;
use std::thread;
use std::time::Duration;

use base::debug;
use base::error;
use base::gettid;
use base::warn;
use base::AsRawDescriptor;
use base::Descriptor;
use base::Error as SysError;
use base::Event;
use base::EventToken;
use base::SendTube;
use base::Timer;
use base::VmEventType;
use base::WaitContext;
use remain::sorted;
use sync::Mutex;
use thiserror::Error;

use crate::pci::CrosvmDeviceId;
use crate::BusAccessInfo;
use crate::BusDevice;
use crate::DeviceId;
use crate::Suspendable;

// Registers offsets
const VMWDT_REG_STATUS: u32 = 0x00;
const VMWDT_REG_LOAD_CNT: u32 = 0x04;
const VMWDT_REG_CURRENT_CNT: u32 = 0x08;
const VMWDT_REG_CLOCK_FREQ_HZ: u32 = 0x0C;

// Length of the registers
const VMWDT_REG_LEN: u64 = 0x10;

pub const VMWDT_DEFAULT_TIMEOUT_SEC: u32 = 10;
pub const VMWDT_DEFAULT_CLOCK_HZ: u32 = 2;

// Proc stat indexes
const PROCSTAT_GUEST_TIME_INDX: usize = 42;

#[sorted]
#[derive(Error, Debug)]
pub enum VmwdtError {
    /// Error while creating event.
    #[error("failed to create event: {0}")]
    CreateEvent(SysError),
    /// Error while trying to create worker thread.
    #[error("failed to spawn thread: {0}")]
    SpawnThread(IoError),
    /// Error while trying to create timer.
    #[error("failed to create vmwdt counter due to timer fd: {0}")]
    TimerCreateError(SysError),
    #[error("failed to wait for events: {0}")]
    WaitError(SysError),
}

type VmwdtResult<T> = std::result::Result<T, VmwdtError>;

pub struct VmwdtPerCpu {
    // Flag which indicated if the watchdog is started
    is_enabled: bool,
    // Timer used to generate periodic events at `timer_freq_hz` frequency
    timer: Timer,
    // The frequency of the `timer`
    timer_freq_hz: u64,
    // Timestamp measured in miliseconds of the last guest activity
    last_guest_time_ms: i64,
    // The pid of the thread this vcpu belongs to
    pid: u32,
    // The process id of the task this vcpu belongs to
    ppid: u32,
    // The pre-programmed one-shot expiration interval. If the guest runs in this
    // interval but we don't receive a periodic event, the guest is stalled.
    next_expiration_interval_ms: i64,
}

pub struct Vmwdt {
    vm_wdts: Arc<Mutex<Vec<VmwdtPerCpu>>>,
    // The worker thread that waits on the timer fd
    worker_thread: Option<thread::JoinHandle<()>>,
    // An event used to signal background thread cancellation
    kill_evt: Event,
    // TODO: @sebastianene add separate reset event for the watchdog
    // Reset source if the device is not responding
    reset_evt_wrtube: SendTube,
}

impl Vmwdt {
    pub fn new(cpu_count: usize, reset_evt_wrtube: SendTube) -> VmwdtResult<Vmwdt> {
        let mut vec = Vec::new();
        for _ in 0..cpu_count {
            vec.push(VmwdtPerCpu {
                last_guest_time_ms: 0,
                pid: 0,
                ppid: 0,
                is_enabled: false,
                timer: Timer::new().unwrap(),
                timer_freq_hz: 0,
                next_expiration_interval_ms: 0,
            });
        }
        let vm_wdts = Arc::new(Mutex::new(vec));

        // Create a new event that will be used to notify the bg thread for exit
        let kill_evt = Event::new().unwrap();
        Ok(Vmwdt {
            vm_wdts,
            worker_thread: None,
            kill_evt,
            reset_evt_wrtube,
        })
    }

    pub fn vmwdt_worker_thread(
        vm_wdts: Arc<Mutex<Vec<VmwdtPerCpu>>>,
        kill_evt: Event,
        reset_evt_wrtube: SendTube,
    ) {
        #[derive(EventToken)]
        enum Token {
            Kill,
            Timer(usize),
        }

        let wait_ctx: WaitContext<Token> = WaitContext::new().unwrap();
        wait_ctx.add(&kill_evt, Token::Kill).unwrap();

        let len = vm_wdts.lock().len();
        for clock_id in 0..len {
            let timer_fd = vm_wdts.lock()[clock_id].timer.as_raw_descriptor();
            wait_ctx
                .add(&Descriptor(timer_fd), Token::Timer(clock_id))
                .unwrap();
        }

        loop {
            let events = wait_ctx.wait().unwrap();
            for event in events.iter().filter(|e| e.is_readable) {
                match event.token {
                    Token::Kill => {
                        return;
                    }
                    Token::Timer(cpu_id) => {
                        let mut wdts_locked = vm_wdts.lock();
                        let mut watchdog = &mut wdts_locked[cpu_id];
                        if let Err(_e) = watchdog.timer.wait() {
                            error!("error waiting for timer event on vcpu {}", cpu_id);
                        }

                        let current_guest_time_ms =
                            Vmwdt::get_guest_time_ms(watchdog.ppid, watchdog.pid);
                        let remaining_time_ms = watchdog.next_expiration_interval_ms
                            - (current_guest_time_ms - watchdog.last_guest_time_ms);

                        if remaining_time_ms > 0 {
                            watchdog.next_expiration_interval_ms = remaining_time_ms;
                            if let Err(_e) = watchdog
                                .timer
                                .reset(Duration::from_millis(remaining_time_ms as u64), None)
                            {
                                error!("failed to reset internal timer on vcpu {}", cpu_id);
                            }
                        } else {
                            // The guest ran but it did not send the periodic event
                            if let Err(_e) =
                                reset_evt_wrtube.send::<VmEventType>(&VmEventType::WatchdogReset)
                            {
                                error!("failed to send reset event from vcpu {}", cpu_id)
                            }
                        }
                    }
                }
            }
        }
    }

    fn start(&mut self) {
        let vm_wdts = self.vm_wdts.clone();
        let kill_evt = self.kill_evt.try_clone().unwrap();
        let reset_evt_wrtube = self.reset_evt_wrtube.try_clone().unwrap();

        self.worker_thread = Some(
            thread::Builder::new()
                .name("vmwdt worker".into())
                .spawn(|| Vmwdt::vmwdt_worker_thread(vm_wdts, kill_evt, reset_evt_wrtube))
                .map_err(VmwdtError::SpawnThread)
                .unwrap(),
        );
    }

    fn ensure_started(&mut self) {
        if self.worker_thread.is_some() {
            return;
        }

        self.start();
    }

    #[cfg(any(target_os = "linux", target_os = "android"))]
    pub fn get_guest_time_ms(ppid: u32, pid: u32) -> i64 {
        // TODO: @sebastianene check if we can avoid open-read-close on each call
        let stat_path = format!("/proc/{}/task/{}/stat", ppid, pid);
        let contents = fs::read_to_string(stat_path).expect("error reading the stat");

        let coll: Vec<_> = contents.split_whitespace().collect();
        let guest_time = coll[PROCSTAT_GUEST_TIME_INDX].parse::<u64>();
        let gtime_ticks = match guest_time {
            Err(_e) => 0,
            Ok(f) => f,
        };

        // Safe because this just returns an integer
        let ticks_per_sec = unsafe { libc::sysconf(libc::_SC_CLK_TCK) } as u64;
        (gtime_ticks * 1000 / ticks_per_sec) as i64
    }

    #[cfg(not(any(target_os = "linux", target_os = "android")))]
    pub fn get_guest_time_ms(ppid: u32, pid: u32) -> i64 {
        0
    }
}

impl Drop for Vmwdt {
    fn drop(&mut self) {
        if let Err(e) = self.kill_evt.signal() {
            error!("Failed to stop the bg thread: {}", e);
            return;
        }

        if let Some(thread) = self.worker_thread.take() {
            match thread.join() {
                Ok(_) => {
                    debug!("Stopped the bg thread\n");
                }
                Err(_) => {
                    error!("Failed to stop the bg thread");
                }
            }
        }
    }
}

impl BusDevice for Vmwdt {
    fn debug_label(&self) -> String {
        "Vmwdt".to_owned()
    }

    fn device_id(&self) -> DeviceId {
        CrosvmDeviceId::VmWatchdog.into()
    }

    fn read(&mut self, _offset: BusAccessInfo, _data: &mut [u8]) {}

    fn write(&mut self, info: BusAccessInfo, data: &[u8]) {
        let data_array = match <&[u8; 4]>::try_from(data) {
            Ok(array) => array,
            _ => {
                error!("Bad write size: {} for vmwdt", data.len());
                return;
            }
        };

        let reg_val = u32::from_ne_bytes(*data_array);
        let cpu_index: usize = (info.offset / VMWDT_REG_LEN) as usize;
        let reg_offset = (info.offset % VMWDT_REG_LEN) as u32;

        if cpu_index > self.vm_wdts.lock().len() {
            error!("Bad write cpu_index {}", cpu_index);
            return;
        }

        match reg_offset {
            VMWDT_REG_STATUS => {
                self.ensure_started();
                let mut wdts_locked = self.vm_wdts.lock();
                let mut cpu_watchdog = &mut wdts_locked[cpu_index];

                cpu_watchdog.is_enabled = reg_val != 0;

                if reg_val != 0 {
                    let due = Duration::from_nanos(1);
                    let interval =
                        Duration::from_millis((1000 / cpu_watchdog.timer_freq_hz) as u64);
                    cpu_watchdog.timer.reset(due, Some(interval)).unwrap();
                } else {
                    cpu_watchdog.timer.clear().unwrap();
                }
            }
            VMWDT_REG_LOAD_CNT => {
                let ppid = process::id();
                let pid = gettid();
                let guest_time_ms = Vmwdt::get_guest_time_ms(ppid, pid as u32);
                let mut wdts_locked = self.vm_wdts.lock();
                let mut cpu_watchdog = &mut wdts_locked[cpu_index];
                let next_expiration_interval_ms =
                    reg_val as u64 * 1000 / cpu_watchdog.timer_freq_hz;

                cpu_watchdog.pid = pid as u32;
                cpu_watchdog.ppid = ppid;
                cpu_watchdog.last_guest_time_ms = guest_time_ms;
                cpu_watchdog.next_expiration_interval_ms = next_expiration_interval_ms as i64;

                if cpu_watchdog.is_enabled {
                    if let Err(_e) = cpu_watchdog
                        .timer
                        .reset(Duration::from_millis(next_expiration_interval_ms), None)
                    {
                        error!("failed to reset one-shot vcpu time {}", cpu_index);
                    }
                }
            }
            VMWDT_REG_CURRENT_CNT => {
                warn!("invalid write to read-only VMWDT_REG_CURRENT_CNT register");
            }
            VMWDT_REG_CLOCK_FREQ_HZ => {
                let mut wdts_locked = self.vm_wdts.lock();
                let mut cpu_watchdog = &mut wdts_locked[cpu_index];

                debug!(
                    "CPU:{:x} wrote VMWDT_REG_CLOCK_FREQ_HZ {:x}",
                    cpu_index, reg_val
                );
                cpu_watchdog.timer_freq_hz = reg_val as u64;
            }
            _ => unreachable!(),
        }
    }
}

impl Suspendable for Vmwdt {}

#[cfg(test)]
mod tests {
    use std::thread::sleep;

    use base::Tube;

    use super::*;

    const AARCH64_VMWDT_ADDR: u64 = 0x3000;
    const TEST_VMWDT_CPU_NO: usize = 0x1;

    fn vmwdt_bus_address(offset: u64) -> BusAccessInfo {
        BusAccessInfo {
            offset,
            address: AARCH64_VMWDT_ADDR,
            id: 0,
        }
    }

    #[test]
    fn test_watchdog_internal_timer() {
        let (vm_evt_wrtube, _vm_evt_rdtube) = Tube::directional_pair().unwrap();
        let mut device = Vmwdt::new(TEST_VMWDT_CPU_NO, vm_evt_wrtube).unwrap();

        // Configure the watchdog device, 2Hz internal clock
        device.write(
            vmwdt_bus_address(VMWDT_REG_CLOCK_FREQ_HZ as u64),
            &[10, 0, 0, 0],
        );
        device.write(vmwdt_bus_address(VMWDT_REG_LOAD_CNT as u64), &[1, 0, 0, 0]);
        device.write(vmwdt_bus_address(VMWDT_REG_STATUS as u64), &[1, 0, 0, 0]);
        let next_expiration_ms = {
            let mut vmwdt_locked = device.vm_wdts.lock();
            // In the test scenario the guest does not interpret the /proc/stat::guest_time, thus
            // the function get_guest_time() returns 0
            vmwdt_locked[0].last_guest_time_ms = 10;
            vmwdt_locked[0].next_expiration_interval_ms
        };

        sleep(Duration::from_millis(100));

        // Verify that our timer expired and the next_expiration_interval_ms changed
        let vmwdt_locked = device.vm_wdts.lock();
        assert_eq!(
            vmwdt_locked[0].next_expiration_interval_ms != next_expiration_ms,
            true
        );
    }

    #[test]
    fn test_watchdog_expiration() {
        let (vm_evt_wrtube, vm_evt_rdtube) = Tube::directional_pair().unwrap();
        let mut device = Vmwdt::new(TEST_VMWDT_CPU_NO, vm_evt_wrtube).unwrap();

        // Configure the watchdog device, 2Hz internal clock
        device.write(
            vmwdt_bus_address(VMWDT_REG_CLOCK_FREQ_HZ as u64),
            &[10, 0, 0, 0],
        );
        device.write(vmwdt_bus_address(VMWDT_REG_LOAD_CNT as u64), &[1, 0, 0, 0]);
        device.write(vmwdt_bus_address(VMWDT_REG_STATUS as u64), &[1, 0, 0, 0]);
        // In the test scenario the guest does not interpret the /proc/stat::guest_time, thus
        // the function get_guest_time() returns 0
        device.vm_wdts.lock()[0].last_guest_time_ms = -100;

        sleep(Duration::from_millis(100));

        // Verify that our timer expired and the next_expiration_interval_ms changed
        match vm_evt_rdtube.recv::<VmEventType>() {
            Ok(vm_event) => {
                assert!(vm_event == VmEventType::WatchdogReset);
            }
            Err(_e) => {
                panic!();
            }
        };
    }
}


text:
Staging::CharacterDirection Staging::StringToCharacterDirection(const QString &s)
{
    if (s == "Left")
    {
        return Staging::CharacterDirection_Left;
    }
    else if (s == "Right")
    {
        return Staging::CharacterDirection_Right;
    }
    else
    {
        return Staging::CharacterDirection_None;
    }
}

QString Staging::CharacterDirectionToString(Staging::CharacterDirection d)
{
    if (d == Staging::CharacterDirection_Left)
    {
        return "Left";
    }
    else if (d == Staging::CharacterDirection_Right)
    {
        return "Right";
    }
    else
    {
        return "None";
    }
}

Staging::CharacterPosition Staging::StringToCharacterPosition(const QString &s)
{
    if (s == "Left")
    {
        return Staging::CharacterPosition_Left;
    }
    else if (s == "Right")
    {
        return Staging::CharacterPosition_Right;
    }
    else if (s == "Unknown")
    {
        return Staging::CharacterPosition_Unknown;
    }
    else if (s == "Offscreen")
    {
        return Staging::CharacterPosition_Offscreen;
    }
    else
    {
        return Staging::CharacterPosition_None;
    }
}

QString Staging::ConversationActionTypeToString(Staging::ConversationActionType t)
{
    switch (t)
    {
    case Staging::ConversationActionType_None:
        return "None";

    case Staging::ConversationActionType_MultipleCharacterChange:
        return "MultipleCharacterChange";

    case Staging::ConversationActionType_CharacterChange:
        return "CharacterChange";

    case Staging::ConversationActionType_SetFlag:
        return "SetFlag";

    case Staging::ConversationActionType_BranchOnCondition:
        return "BranchOnCondition";

    case Staging::ConversationActionType_BranchIfTrue:
        return "BranchIfTrue";

    case Staging::ConversationActionType_BranchIfFalse:
        return "BranchIfFalse";

    case Staging::ConversationActionType_EndBranchOnCondition:
        return "EndBranchOnCondition";

    case Staging::ConversationActionType_ShowDialog:
        return "ShowDialog";

    case Staging::ConversationActionType_ShowDialogAutomatic:
        return "ShowDialogAutomatic";

    case Staging::ConversationActionType_MustPresentEvidence:
        return "MustPresentEvidence";

    case Staging::ConversationActionType_SkipWrongEvidencePresented:
        return "SkipWrongEvidencePresented";

    case Staging::ConversationActionType_BeginWrongEvidencePresented:
        return "BeginWrongEvidencePresented";

    case Staging::ConversationActionType_EndWrongEvidencePresented:
        return "EndWrongEvidencePresented";

    case Staging::ConversationActionType_SkipEndRequested:
        return "SkipEndRequested";

    case Staging::ConversationActionType_BeginEndRequested:
        return "BeginEndRequested";

    case Staging::ConversationActionType_EndEndRequested:
        return "EndEndRequested";

    case Staging::ConversationActionType_EndMustPresentEvidence:
        return "EndMustPresentEvidence";

    case Staging::ConversationActionType_EnableConversation:
        return "EnableConversation";

    case Staging::ConversationActionType_EnableEvidence:
        return "EnableEvidence";

    case Staging::ConversationActionType_UpdateEvidence:
        return "UpdateEvidence";

    case Staging::ConversationActionType_DisableEvidence:
        return "DisableEvidence";

    case Staging::ConversationActionType_EnableCutscene:
        return "EnableCutscene";

    case Staging::ConversationActionType_Notification:
        return "Notification";

    case Staging::ConversationActionType_PlayBgm:
        return "PlayBgm";

    case Staging::ConversationActionType_PauseBgm:
        return "PauseBgm";

    case Staging::ConversationActionType_ResumeBgm:
        return "ResumeBgm";

    case Staging::ConversationActionType_StopBgm:
        return "StopBgm";

    case Staging::ConversationActionType_PlayAmbiance:
        return "PlayAmbiance";

    case Staging::ConversationActionType_PauseAmbiance:
        return "PauseAmbiance";

    case Staging::ConversationActionType_ResumeAmbiance:
        return "ResumeAmbiance";

    case Staging::ConversationActionType_StopAmbiance:
        return "StopAmbiance";

    case Staging::ConversationActionType_StartAnimation:
        return "StartAnimation";

    case Staging::ConversationActionType_StopAnimation:
        return "StopAnimation";

    case Staging::ConversationActionType_SetPartner:
        return "SetPartner";

    case Staging::ConversationActionType_GoToPresentWrongEvidence:
        return "GoToPresentWrongEvidence";

    case Staging::ConversationActionType_LockConversation:
        return "LockConversation";

    case Staging::ConversationActionType_ExitEncounter:
        return "ExitEncounter";

    case Staging::ConversationActionType_MoveToLocation:
        return "MoveToLocation";

    case Staging::ConversationActionType_MoveToZoomedView:
        return "MoveToZoomedView";

    case Staging::ConversationActionType_EndCase:
        return "EndCase";

    case Staging::ConversationActionType_BeginMultipleChoice:
        return "BeginMultipleChoice";

    case Staging::ConversationActionType_BeginMultipleChoiceOption:
        return "BeginMultipleChoiceOption";

    case Staging::ConversationActionType_ExitMultipleChoice:
        return "ExitMultipleChoice";

    case Staging::ConversationActionType_EndMultipleChoiceOption:
        return "EndMultipleChoiceOption";

    case Staging::ConversationActionType_EndMultipleChoice:
        return "EndMultipleChoice";

    case Staging::ConversationActionType_EnableFastForward:
        return "EnableFastForward";

    case Staging::ConversationActionType_DisableFastForward:
        return "DisableFastForward";

    case Staging::ConversationActionType_BeginBreakdown:
        return "BeginBreakdown";

    case Staging::ConversationActionType_EndBreakdown:
        return "EndBreakdown";

    case Staging::ConversationActionType_BeginInterrogationRepeat:
        return "BeginInterrogationRepeat";

    case Staging::ConversationActionType_ShowInterrogation:
        return "ShowInterrogation";

    case Staging::ConversationActionType_BeginPressForInfo:
        return "BeginPressForInfo";

    case Staging::ConversationActionType_EndPressForInfo:
        return "EndPressForInfo";

    case Staging::ConversationActionType_BeginPresentEvidence:
        return "BeginPresentEvidence";

    case Staging::ConversationActionType_EndPresentEvidence:
        return "EndPresentEvidence";

    case Staging::ConversationActionType_BeginUsePartner:
        return "BeginUsePartner";

    case Staging::ConversationActionType_EndUsePartner:
        return "EndUsePartner";

    case Staging::ConversationActionType_EndShowInterrogationBranches:
        return "EndShowInterrogationBranches";

    case Staging::ConversationActionType_ExitInterrogationRepeat:
        return "ExitInterrogationRepeat";

    case Staging::ConversationActionType_SkipWrongPartnerUsed:
        return "SkipWrongPartnerUsed";

    case Staging::ConversationActionType_BeginWrongPartnerUsed:
        return "BeginWrongPartnerUsed";

    case Staging::ConversationActionType_EndWrongPartnerUsed:
        return "EndWrongPartnerUsed";

    case Staging::ConversationActionType_EndInterrogationRepeat:
        return "EndInterrogationRepeat";

    case Staging::ConversationActionType_SetParticipants:
        return "SetParticipants";

    case Staging::ConversationActionType_SetIconOffset:
        return "SetIconOffset";

    case Staging::ConversationActionType_SetHealth:
        return "SetHealth";

    case Staging::ConversationActionType_InitializeBeginConfrontationTopicSelection:
        return "InitializeBeginConfrontationTopicSelection";

    case Staging::ConversationActionType_BeginConfrontationTopicSelection:
        return "BeginConfrontationTopicSelection";

    case Staging::ConversationActionType_BeginConfrontationTopic:
        return "BeginConfrontationTopic";

    case Staging::ConversationActionType_EndConfrontationTopic:
        return "EndConfrontationTopic";

    case Staging::ConversationActionType_SkipPlayerDefeated:
        return "SkipPlayerDefeated";

    case Staging::ConversationActionType_BeginPlayerDefeated:
        return "BeginPlayerDefeated";

    case Staging::ConversationActionType_EndPlayerDefeated:
        return "EndPlayerDefeated";

    case Staging::ConversationActionType_EndConfrontationTopicSelection:
        return "EndConfrontationTopicSelection";

    case Staging::ConversationActionType_EnableTopic:
        return "EnableTopic";

    case Staging::ConversationActionType_RestartConfrontation:
        return "RestartConfrontation";

    default:
        throw new MLIException("Unknown conversation action type.");
    }
}

Staging::FieldCharacterDirection Staging::StringToFieldCharacterDirection(const QString &s)
{
    if (s == "Up")
    {
        return Staging::FieldCharacterDirection_Up;
    }
    else if (s == "DiagonalUp")
    {
        return Staging::FieldCharacterDirection_DiagonalUp;
    }
    else if (s == "Side")
    {
        return Staging::FieldCharacterDirection_Side;
    }
    else if (s == "DiagonalDown")
    {
        return Staging::FieldCharacterDirection_DiagonalDown;
    }
    else if (s == "Down")
    {
        return Staging::FieldCharacterDirection_Down;
    }
    else
    {
        return Staging::FieldCharacterDirection_None;
    }
}

QString Staging::FieldCharacterDirectionToString(Staging::FieldCharacterDirection d)
{
    if (d == Staging::FieldCharacterDirection_Up)
    {
        return "Up";
    }
    else if (d == Staging::FieldCharacterDirection_DiagonalUp)
    {
        return "DiagonalUp";
    }
    else if (d == Staging::FieldCharacterDirection_Side)
    {
        return "Side";
    }
    else if (d == Staging::FieldCharacterDirection_DiagonalDown)
    {
        return "DiagonalDown";
    }
    else if (d == Staging::FieldCharacterDirection_Down)
    {
        return "Down";
    }
    else
    {
        return "None";
    }
}

Staging::FieldCharacterState Staging::StringToFieldCharacterState(const QString &s)
{
    if (s == "Standing")
    {
        return Staging::FieldCharacterState_Standing;
    }
    else if (s == "Walking")
    {
        return Staging::FieldCharacterState_Walking;
    }
    else if (s == "Running")
    {
        return Staging::FieldCharacterState_Running;
    }
    else
    {
        return Staging::FieldCharacterState_None;
    }
}

Staging::TransitionDirection Staging::StringToTransitionDirection(const QString &s)
{
    if (s == "North")
    {
        return Staging::TransitionDirection_North;
    }
    else if (s == "NorthEast")
    {
        return Staging::TransitionDirection_NorthEast;
    }
    else if (s == "East")
    {
        return Staging::TransitionDirection_East;
    }
    else if (s == "SouthEast")
    {
        return Staging::TransitionDirection_SouthEast;
    }
    else if (s == "South")
    {
        return Staging::TransitionDirection_South;
    }
    else if (s == "SouthWest")
    {
        return Staging::TransitionDirection_SouthWest;
    }
    else if (s == "West")
    {
        return Staging::TransitionDirection_West;
    }
    else if (s == "NorthWest")
    {
        return Staging::TransitionDirection_NorthWest;
    }
    else if (s == "Door")
    {
        return Staging::TransitionDirection_Door;
    }

    return Staging::TransitionDirection_North;
}

redpajama_set_name: RedPajamaGithub


text:
<!DOCTYPE html>

    <title>Mobile</title>
    <meta charset="UTF-8">
    <meta http-equiv="pragma" content="no-cache"/>
    <meta name="viewport" content="width=device-width">
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
    <meta content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=0" name="viewport">
    <meta content="yes" name="apple-mobile-web-app-capable">
    <meta content="black" name="apple-mobile-web-app-status-bar-style">
    <meta content="telephone=no" name="format-detection">

    <link rel="stylesheet" href="./css/main.css" type="text/css">


text:
.monaco-editor .peekview-widget .head {
	-webkit-box-sizing:	border-box;
	-o-box-sizing: border-box;
	-moz-box-sizing: border-box;
	-ms-box-sizing: border-box;
	box-sizing:	border-box;
	display: flex;
}

.monaco-editor .peekview-widget .head .peekview-title {
	display: inline-block;
	font-size: 13px;
	margin-left: 20px;
	cursor: pointer;
}

.monaco-editor .peekview-widget .head .peekview-title .dirname:not(:empty) {
	font-size: 0.9em;
	margin-left: 0.5em;
}

.monaco-editor .peekview-widget .head .peekview-actions {
	flex: 1;
	text-align: right;
	padding-right: 2px;
}

.monaco-editor .peekview-widget .head .peekview-actions > .monaco-action-bar {
	display: inline-block;
}

.monaco-editor .peekview-widget .head .peekview-actions > .monaco-action-bar,
.monaco-editor .peekview-widget .head .peekview-actions > .monaco-action-bar > .actions-container {
	height: 100%;
}

.monaco-editor .peekview-widget .head .peekview-actions > .monaco-action-bar .action-item {
	margin-left: 4px;
}

.monaco-editor .peekview-widget .head .peekview-actions > .monaco-action-bar .action-label {
	width: 16px;
	height: 100%;
	margin: 0;
	line-height: inherit;
	background-repeat: no-repeat;
	background-position: center center;
}

.monaco-editor .peekview-widget .head .peekview-actions > .monaco-action-bar .action-label.octicon {
	margin: 0;
}

.monaco-editor .peekview-widget .head .peekview-actions .action-label.icon.close-peekview-action {
	background: url('close.svg') center center no-repeat;
}

.monaco-editor .peekview-widget > .body {
	border-top: 1px solid;
	position: relative;
}

/* Dark Theme */
/* High Contrast Theme */

.monaco-editor.hc-black .peekview-widget .head .peekview-actions .action-label.icon.close-peekview-action,
.monaco-editor.vs-dark .peekview-widget .head .peekview-actions .action-label.icon.close-peekview-action {
	background: url('close-inverse.svg') center center no-repeat;
}


text:
package net.opentsdb.contrib.tsquare;

import net.opentsdb.core.Aggregator;

/**
 * Factory for {@link Aggregator}s, using the aggregator's name as a
 * lookup method.
 *
 * @author James Royalty (jroyalty) [Aug 1, 2013]
 */
public interface NamedAggregatorFactory {
    /**
     * @param aggregatorName
     * @return null if no aggregator is registered under
     * the given name.
     */
    Aggregator getAggregatorByName(String aggregatorName);
}


text:
sudo service mjpg-streamer stop
sudo update-rc.d -f mjpg-streamer remove
sudo rm /etc/init.d/mjpg-streamer


text:
<?php
if (file_exists("views/Error/{$this->getStatusCode()}.php")) {
	require_once "views/Error/{$this->getStatusCode()}.php";
} else { // No custom page exists for this error code. -- cwells
?>

Error: <?= $this->getStatusCode() ?>

A <?= $this->getStatusCode() ?> error was encountered.

<?php
}
?>

I've made a note of this issue.  If it's my fault, I'll fix it when I have time.

Here are a few things you can try in the meantime:

Verify the address to be sure there are no typos.

<?php if (isset($_SERVER['HTTP_REFERER']) && strstr($_SERVER['HTTP_REFERER'], $_SERVER['HTTP_HOST']) !== false) { ?>

Return to the page you came from.

Start over at my home page and see where life takes you.

<?php } else { ?>

Start over at my home page and see where life takes you.

Return to the page you came from.

<?php } ?>


text:
<!DOCTYPE html>

	<meta name="DC.title" content="The Black Cat Café : gourmet dining with a pet-saving mission in Devon Pennsylvania" />
	<meta name="geo.region" content="US-PA" />
	<meta name="geo.placename" content="Devon" />
	<meta name="geo.position" content="40.046665;-75.414262" />
	<meta name="ICBM" content="40.046665, -75.414262" />
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <meta name="description" content="">
    <meta name="papermashea" content="">

    <title>The Black Cat Cafe</title>

    <link href="css/bootstrap.min.css" rel="stylesheet">

    <link href="css/modern-business.css" rel="stylesheet">

    <link href="font-awesome/css/font-awesome.min.css" rel="stylesheet" type="text/css">

                <button type="button" class="navbar-toggle" data-toggle="collapse" data-target="#bs-example-navbar-collapse-1">
                    Toggle navigation

                </button>
                 The Black Cat Cafe

                        About Us

                        What's Here

                        Menu

                        Merchandise

                        Adopt Today

Merchandise
                    // Kitchenware and personal care for kitties (and humans)

Kitchenware

Stylish mugs, wine glasses and aprons

In our gift shop, we carry kitchen items including aprons imported from France, hand-painted wine glasses and Black Cat Cafe mugs.

Personal Care Items

All natural soaps, lotions and oils

We also carry a line of handmade personal care items from Georgia-based Rinse Bath and Body

Toys

Cat toys and treats for your nugget

Don't forget to pick up something for your feline friend from our line of cat toys and treats!

Find us at 42 Berkely Road, Devon PA 19333 ||  Call us at (610) 688-1930


text: import gravier.url_parse


text:
<?php
/*
 * Generated by CRUDigniter v3.0 Beta
 * www.crudigniter.com
 */

class Escalator_model extends CI_Model
{
    function __construct()
    {
        parent::__construct();
    }

    /*
     * Get escalator by id
     */
    function get_escalator($id)
    {
        return $this->db->get_where('escalator',array('id'=>$id))->row_array();
    }

    /*
     * Get all escalator
     */
    function get_all_escalator()
    {
        return $this->db->get('escalator')->result_array();
    }

    /*
     * function to add new escalator
     */
    function add_escalator($params)
    {
        $this->db->insert('escalator',$params);
        return $this->db->insert_id();
    }

    /*
     * function to update escalator
     */
    function update_escalator($id,$params)
    {
        $this->db->where('id',$id);
        $response = $this->db->update('escalator',$params);
        if($response)
        {
            return "escalator updated successfully";
        }
        else
        {
            return "Error occuring while updating escalator";
        }
    }

    /*
     * function to delete escalator
     */
    function delete_escalator($id)
    {
        $response = $this->db->delete('escalator',array('id'=>$id));
        if($response)
        {
            return "escalator deleted successfully";
        }
        else
        {
            return "Error occuring while deleting escalator";
        }
    }

    public function record_query($search,$limit,$page=0)
    {

        $this->record_field($search);
        $this->db->limit($limit,$page);
        $query = $this->db->get('escalator');
        return $query->result_array();
    }

    public function record_count($search)
    {
        $this->record_field($search);
        $query = $this->db->get('escalator');
        return $query->num_rows();
    }

    public function record_field($fields)
    {
        if(!empty($fields['lid'])){
            $this->db->where('lid',$fields['lid']);
        }else{
            foreach ($fields as $key => $s) {
                if(!empty($s)){
                    $this->db->or_like($key,$s);
                }
            }
        }
    }

}


text:
package com.vsked.LiskovSubstitutionPrinciple.old;

/**
 * 电脑
 */
public class Computer {
    public int calculate(int num1,int num2){
        //求和
        return num1 + num2;
    }
}


text:
Django Model Deploy
===================

Django application that facilitates the publication of data between environments such as development, testing and production.

Installation
============

* Add the ``model_deploy`` directory to your Python path.

* Add ``model_deploy`` to your ``INSTALLED_APPS`` setting.

* Create file "deploys.py" within the project directory.

* Edit the file "deploys.py" and register your models to be deployed like this:

        from app.models import AppModel
        from model_deploy import core

        core.register(AppModel)

* In your urls.py import your module "deploys.py".

        from projectfolder import deploys

Configuration
=============

* ``SERVERS``

    A dictionary, like ``DATABASES``, when you describe the environments for each server you have.
    For example::

        SERVERS = {
            'current': {
                'name': 'Testing server',
                'url': 'http://127.0.0.1:8000',
                'user': 'admin',
                'password': 'admin'
            },
            'production': {
                'name': 'Production server',
                'url': 'http://127.0.0.1:8001/deploy/',
                'user': 'padmin',
                'password': 'padmin'
            },
        }
   ``'name'``: Friendly name of the server.

   ``'url'``: URL of the server that is configured to handle ``model_deploy`` logs sent.

   ``'user'`` and ``'password'``: valid user credentials of ``django.contrib.auth``.

* Optional: ``DEFAULT_DEPLOY_SERVER`` Default: ``None``.

      Key value of the server to target all logs to deploy.

      For example:: ``'production'``

* Optional: ``MODEL_DEPLOY`` Default: ``True``.

      This setting manages the generation of logs changes made to the data of registered models.

      Is you must set to False when the project is not required to send data to another server.

Usage
=====

You can manage your deploys with ``django.contrib.admin`` or running ``./manage.py deploytoserver --server=serverkey``

Demo
====

Clone the repository and runs on two separate consoles:

1 $ ./manage.py runserver 8000

2 $ ./prod_manage.py runserver 8001

[![Bitdeli Badge](https://d2weczhvl823v0.cloudfront.net/juanpex/django-model-deploy/trend.png)](https://bitdeli.com/free "Bitdeli Badge")


text:
$LOAD_PATH.unshift File.expand_path('../../lib', __FILE__)
require 'slack_notifier_wrapper'


text:
package org.hl7.fhir.dstu3.model.valuesets;

import org.hl7.fhir.dstu3.exceptions.FHIRException;

public enum V3PatientImportance {

        /**
         * Board member of health care organization
         */
        BM,
        /**
         * Family member of staff physician
         */
        DFM,
        /**
         * Member of the health care organization physician staff
         */
        DR,
        /**
         * Financial donor to the health care organization
         */
        FD,
        /**
         * Foreign citizen dignitary of interest to the health care organization
         */
        FOR,
        /**
         * Government dignitary of interest to the organization
         */
        GOVT,
        /**
         * Family member of staff member
         */
        SFM,
        /**
         * Staff member of the health care organization
         */
        STF,
        /**
         * Very important person of interest to the health care organization
         */
        VIP,
        /**
         * added to help the parsers
         */
        NULL;
        public static V3PatientImportance fromCode(String codeString) throws FHIRException {
            if (codeString == null || "".equals(codeString))
                return null;
        if ("BM".equals(codeString))
          return BM;
        if ("DFM".equals(codeString))
          return DFM;
        if ("DR".equals(codeString))
          return DR;
        if ("FD".equals(codeString))
          return FD;
        if ("FOR".equals(codeString))
          return FOR;
        if ("GOVT".equals(codeString))
          return GOVT;
        if ("SFM".equals(codeString))
          return SFM;
        if ("STF".equals(codeString))
          return STF;
        if ("VIP".equals(codeString))
          return VIP;
        throw new FHIRException("Unknown V3PatientImportance code '"+codeString+"'");
        }
        public String toCode() {
          switch (this) {
            case BM: return "BM";
            case DFM: return "DFM";
            case DR: return "DR";
            case FD: return "FD";
            case FOR: return "FOR";
            case GOVT: return "GOVT";
            case SFM: return "SFM";
            case STF: return "STF";
            case VIP: return "VIP";
            default: return "?";
          }
        }
        public String getSystem() {
          return "http://hl7.org/fhir/v3/PatientImportance";
        }
        public String getDefinition() {
          switch (this) {
            case BM: return "Board member of health care organization";
            case DFM: return "Family member of staff physician";
            case DR: return "Member of the health care organization physician staff";
            case FD: return "Financial donor to the health care organization";
            case FOR: return "Foreign citizen dignitary of interest to the health care organization";
            case GOVT: return "Government dignitary of interest to the organization";
            case SFM: return "Family member of staff member";
            case STF: return "Staff member of the health care organization";
            case VIP: return "Very important person of interest to the health care organization";
            default: return "?";
          }
        }
        public String getDisplay() {
          switch (this) {
            case BM: return "Board Member";
            case DFM: return "Physician Family Member";
            case DR: return "Staff Physician";
            case FD: return "Financial Donor";
            case FOR: return "Foreign Dignitary";
            case GOVT: return "Government Dignitary";
            case SFM: return "Staff Family Member";
            case STF: return "Staff Member";
            case VIP: return "Very Important Person";
            default: return "?";
          }
    }

}


text:
IF EXISTS (   SELECT *
              FROM   [sys].[server_principals] AS [SP]
              WHERE  [SP].[name] = 'open_query_store'
          )
    BEGIN
        DROP LOGIN [open_query_store];
    END;

USE [msdb];
GO
IF EXISTS (   SELECT *
              FROM   [dbo].[sysjobs] AS [S]
              WHERE  [S].[name] = 'Open Query Store - Data Collection'
          )
    BEGIN
        EXECUTE [dbo].[sp_delete_job] @job_name = 'Open Query Store - Data Collection',
                                      @delete_history = 1,
                                      @delete_unused_schedule = 1;
    END;

IF EXISTS (   SELECT [name]
                  FROM   [msdb].[dbo].[syscategories]
                  WHERE  [name] = N'Open Query Store'
                         AND [category_class] = 1
              )
    BEGIN
        EXEC  [msdb].[dbo].[sp_delete_category] @class = N'JOB', @name = N'Open Query Store';
    END;

USE [master];
GO

IF EXISTS (   SELECT *
              FROM   [sys].[procedures] AS [P]
              WHERE  [P].[object_id] = OBJECT_ID( N'[dbo].[open_query_store_startup]' )
          )
    BEGIN
        DROP PROC [dbo].[open_query_store_startup];
    END;

IF EXISTS (   SELECT *
              FROM   [sys].[certificates] AS [C]
              WHERE  [C].[name] = 'open_query_store'
          )
    BEGIN
        DROP CERTIFICATE [open_query_store];
    END;


text:
import { Config, SessionAlreadyExists, SessionState, SessionStore } from '@foal/core';
import { createClient } from 'redis';

/**
 * Redis Store
 *
 * @export
 * @class RedisStore
 * @extends {SessionStore}
 */
export class RedisStore extends SessionStore {

  private redisClient: ReturnType<typeof createClient>;

  setRedisClient(redisClient: ReturnType<typeof createClient>): void {
    this.redisClient = redisClient;
  }

  async boot() {
    if (this.redisClient) {
      return;
    }
    const redisURI = Config.get('settings.redis.uri', 'string');
    this.redisClient = createClient({ url: redisURI });
    await this.redisClient.connect();
  }

  async save(state: SessionState, maxInactivity: number): Promise<void> {
    const payload = JSON.stringify(state);
    const val = await this.redisClient.set(`sessions:${state.id}`, payload, {
      NX: true,
      EX: maxInactivity,
    })

    if (val !== 'OK') {
      throw new SessionAlreadyExists();
    }
  }

  async read(id: string): Promise<SessionState | null> {
    const val = await this.redisClient.get(`sessions:${id}`);
    if (val === null) {
      return null;
    }
    return JSON.parse(val);
  }

  async update(state: SessionState, maxInactivity: number): Promise<void> {
    const payload = JSON.stringify(state);
    await this.redisClient.set(`sessions:${state.id}`, payload, {
      EX: maxInactivity,
    });
  }

  async destroy(id: string): Promise<void> {
    await this.redisClient.del(`sessions:${id}`);
  }

  async clear(): Promise<void> {
    await this.redisClient.flushDb();
  }

  async cleanUpExpiredSessions(): Promise<void> {}

  /**
   * Closes the connection to the database.
   *
   * @memberof RedisStore
   */
  async close(): Promise<void> {
    await this.redisClient.quit();
  }
}


text:
var mongoose = require('mongoose');
var plugins = requireLib('mongoose-plugins.js');

var gameSchema = mongoose.Schema({
    title: {type: String, required: true},
    user: {type: mongoose.Schema.Types.ObjectId, ref: 'User'}
});

gameSchema.plugin(plugins.dataModules);
var model = mongoose.model('Game', gameSchema);

module.exports = {
    Schema: gameSchema,
    Model: model
};


text:
package run.chronicle.wire.demo;

import net.openhft.chronicle.bytes.Bytes;
import net.openhft.chronicle.wire.*;

import java.nio.ByteBuffer;
import java.util.concurrent.TimeUnit;

public class Example1 {
    public static void main(String[] args) {

        // Bytes which wraps a ByteBuffer which is resized as needed.
        Bytes<ByteBuffer> bytes = Bytes.elasticByteBuffer();

        //Now you can choose which format you are using. As the wire formats are themselves
        // unbuffered, you can use them with the same buffer, but in general using one wire format is easier.
        //Options are: BinaryWire, TextWire, JSONWire, CSVWire, QueryWire, YamlWire, RawWire
        Wire wire = new TextWire(bytes);
        //or
        WireType wireType = WireType.TEXT;
        Wire wireB = wireType.apply(bytes);

        //Another Wire with Binary format.
        Bytes<ByteBuffer> bytes2 = Bytes.elasticByteBuffer();
        Wire wire2 = new BinaryWire(bytes2);

        //Another Wire with RawWire format.
        Bytes<ByteBuffer> bytes3 = Bytes.elasticByteBuffer();
        Wire wire3 = new RawWire(bytes3);

        //Write to the wire with a simple document.
        wire.write("message").text("Hello World")
                .write("number").int64(1234567890L)
                .write("code").asEnum(TimeUnit.SECONDS)
                .write("price").float64(10.50);

        //Prints out:
/*         message: Hello World
           number: 1234567890
           code: SECONDS
           price: 10.5 */
        System.out.println(bytes);

        //The same code for Binary wire. Using toHexString prints out hex view of the buffer's contents.
        wire2.write("message").text("Hello World")
                .write("number").int64(1234567890L)
                .write("code").asEnum(TimeUnit.SECONDS)
                .write("price").float64(10.50);

        //Prints out:
/*      00000000 c7 6d 65 73 73 61 67 65  eb 48 65 6c 6c 6f 20 57 ·message ·Hello W
        00000010 6f 72 6c 64 c6 6e 75 6d  62 65 72 a6 d2 02 96 49 orld·num ber····I
        00000020 c4 63 6f 64 65 e7 53 45  43 4f 4e 44 53 c5 70 72 ·code·SE CONDS·pr
        00000030 69 63 65 90 00 00 28 41                          ice···(A             */
        System.out.println(bytes2.toHexString());

        // The same code for RawWire
        //Using RawWire strips away all the meta data to reduce the size of the message, and improves speed.
        // The down-side is that we cannot easily see what the message contains.
        wire3.write("message").text("Hello World")
                .write("number").int64(1234567890L)
                .write("code").asEnum(TimeUnit.SECONDS)
                .write("price").float64(10.50);

        //Prints out:
/*      00000000 0b 48 65 6c 6c 6f 20 57  6f 72 6c 64 d2 02 96 49 ·Hello W orld···I
        00000010 00 00 00 00 07 53 45 43  4f 4e 44 53 00 00 00 00 ·····SEC ONDS····
        00000020 00 00 25 40                                      ··%@                     */
        System.out.println(bytes3.toHexString());

        // To obtain the underlying ByteBuffer to write to a Channel
        ByteBuffer byteBuffer = bytes2.underlyingObject();
        byteBuffer.position(0);
        byteBuffer.limit(bytes2.length());

        bytes.releaseLast();
        bytes2.releaseLast();

    }
}


text:
                        <cc-note message="vm.msg" dismissible="true"></cc-note>

                                <demo-person-profile first-name="{{c.firstName}}"
                                    last-name="{{c.lastName}}" city="{{c.city}}" state="{{c.state}}" zip="{{c.zip}}"
                                    thumbnail="{{c.thumbnail}}"></demo-person-profile>


text:
module DockerDeploy
  def self.shell(server, command = nil)
    Net::SSH.start(server.hostname, server.user, server.netssh_options) do |ssh|
      channel = ssh.open_channel do |ch|
        ch.on_data do |c, data|
          $stdout.print data
        end

        ch.on_extended_data do |c, type, data|
          $stderr.print data
        end

        ch.request_pty

        if command
          ch.exec(command)
        else
          ch.send_channel_request "shell"
        end
      end

      read, write = UNIXSocket.pair

      Thread.new(write) do |write|
        loop do
          buf = $stdin.getch
          write.write(buf)
        end
      end

      read.extend(Net::SSH::BufferedIo)

      ssh.listen_to(read)

      ssh.loop do
        buf = read.read_available
        channel.send_data buf unless buf.empty?

        ssh.busy?
      end
    end
  end
end


text:
package fr.vidal.oss.jax_rs_linker.functions;

import org.junit.Test;

import java.util.Collection;
import java.util.LinkedHashMap;
import java.util.Map;

import static fr.vidal.oss.jax_rs_linker.functions.QueryParametersToQueryString.TO_QUERY_STRING;
import static java.util.Arrays.asList;
import static org.assertj.core.api.Assertions.assertThat;

public class QueryParametersToQueryStringTest {

    @Test
    public void should_output_a_empty_string_when_map_is_empty() {
        Map<String,Collection<String>> map = new LinkedHashMap<>();

        String output = TO_QUERY_STRING.apply(map);

        assertThat(output).isEmpty();

    }

    @Test
    public void should_output_query_string_with_1_parameter() {
        Map<String, Collection<String>> map = new LinkedHashMap<>();
        map.put("foo", asList("bar"));

        String output = TO_QUERY_STRING.apply(map);

        assertThat(output).isEqualTo("?foo=bar");
    }

    @Test
    public void should_output_query_string_with_2_parameters_with_same_key() {
        Map<String, Collection<String>> map = new LinkedHashMap<>();
        map.put("foo", asList("bar","bar"));

        String output = TO_QUERY_STRING.apply(map);

        assertThat(output).isEqualTo("?foo=bar&foo=bar");
    }

    @Test
    public void should_output_query_string_with_2_parameters() {
        Map<String,Collection<String>> map = new LinkedHashMap<>();
        map.put("foo", asList("bar"));
        map.put("bar", asList("baz"));

        String output = TO_QUERY_STRING.apply(map);

        assertThat(output).isEqualTo("?foo=bar&bar=baz");
    }

    @Test
    public void should_output_query_string_with_many_parameters() {
        Map<String,Collection<String>> map = new LinkedHashMap<>();
        map.put("foo", asList("foo", "bar"));
        map.put("bar", asList("bar", "baz"));

        String output = TO_QUERY_STRING.apply(map);

        assertThat(output).isEqualTo("?foo=foo&foo=bar&bar=bar&bar=baz");
    }
}


text:
<!DOCTYPE html>

    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta name="generator" content="rustdoc">
    <meta name="description" content="API documentation for the Rust `Result` type in crate `core`.">
    <meta name="keywords" content="rust, rustlang, rust-lang, Result">

    <title>core::fmt::Result - Rust</title>

    <link rel="stylesheet" type="text/css" href="../../main.css">

    <link rel="shortcut icon" href="http://www.rust-lang.org/favicon.ico">

core::<wbr>fmt

        <form class="search-form js-only">

                <input class="search-input" name="search"
                       autocomplete="off"
                       placeholder="Click or press 'S' to search, '?' for more options..."
                       type="search">

        </form>

core::<wbr>fmt::<wbr>Result<wbr>Stable
            [-] [+]
        [src]

type Result = Result<(), Error>;

The type returned by formatter methods.

Keyboard shortcuts

?

Show this help dialog

S

Focus the search field

⇤

Move up in search results

⇥

Move down in search results

⏎

Go to active search result

Search tricks

                Prefix searches with a type followed by a colon (e.g.
                fn:) to restrict the search to a given type.

                Accepted types are: fn, mod,
                struct, enum,
                trait, typedef (or
                tdef).


text:
package net.sf.geographiclib;

/**
 * Exception handling for GeographicLib.
 *

 * A class to handle exceptions.  It's derived from RuntimeException so it
 * can be caught by the usual catch clauses.
 **********************************************************************/
public class GeographicErr extends RuntimeException {
  /**
   * Constructor
   *

   * @param msg a string message, which is accessible in the catch
   *   clause via getMessage().
   **********************************************************************/
  public GeographicErr(String msg) { super(msg); }
}


text:
Azure Resource Group with Tags and Lock is a Azure DevOps Pipeline extension to create a Resource Group. This extension was created because there wasn't any extension with the abillity to create a Resource Group with tags and a lock from the starting point.

Within the task multiple parameters need to be specified:
* Resource Group name: The name of the resource group.
* Tags: Key value pair items that need to be added as tags.
* Location: The location of the resource group.
* Lock: Should a lock be added to the resource group.

## Documentation

For the documentation check the [Wiki](https://github.com/MaikvanderGaag/msft-extensions/wiki).

When you like the extension please leave a review. File a issues when you have suggestions or problems with the extension.

[Issues](https://github.com/MaikvanderGaag/msft-extensions/issues)

## Release Notes

| Version | Remarks                             |
|---------|-------------------------------------|
| 1.0.0   | Initial version                     |
| 1.0.1   | Small changes                       |


text:
#include <ggadget/logger.h>
#include <ggadget/signals.h>

#include "js_script_runtime.h"
#include "js_script_context.h"

namespace ggadget {
namespace qt {

class JSScriptRuntime::Impl {
 public:
  Impl() {
  }

  ~Impl() {
  }
};

JSScriptRuntime::JSScriptRuntime()
    : impl_(new Impl) {
  InitScriptContextData();
}

JSScriptRuntime::~JSScriptRuntime() {
  delete impl_;
}

ScriptContextInterface *JSScriptRuntime::CreateContext() {
  LOG("CreateContext");
  return new JSScriptContext();
}

void JSScriptRuntime::DestroyContext(JSScriptContext *context) {
  LOG("DestroyContext");
  delete context;
}

} // namespace qt
} // namespace ggadget


text:
module.exports = NewController;

NewController.$inject = ['View', '$state', 'notificationService'];
function NewController(View, $state, notificationService) {
    var vm = this;

    vm.view = new View();
    vm.save = save;

    function save() {
        vm.view.$save(function (view) {

            notificationService.saveSuccess('view');

            $state.go('views');
        }, function (error) {
            notificationService.saveError('view');
            throw error;
        });
    }
}


text:
layout: master
title:  "[Chega a Ter Gosto a Chuva Vista dos Cafés]"
categories: portugal
author: António Reis
contributor: Francisco Queimadela
imgs: 3
---

Chega a ter gosto
a chuva
vista dos cafés

caindo sobre as estátuas
e a nostalgia

chega a ser morna

com fumo e álcool
na garganta

Até os homens passarem
junto aos vidros

reais
molhados

sem emoções instruídas

pensando em remédios
e prestações

grisalhos
sem serem velhos

e falando sós
sem serem loucos


text:
<!DOCTYPE html>

    <meta charset="utf-8">
    <title>React Tutorial</title>

    <link rel="stylesheet" href="css/base.css" />


text:
require 'mkmf'

have_library('stdc++')
append_cppflags('-std=c++11')
append_cppflags('-O2')
append_cppflags('-Wall')
append_cppflags('-Wextra')
append_cppflags('-Wvla')

create_makefile('mikunyan/decoders/crunch')


text:
class Parser

  attr_reader :deputies

  def initialize
    @deputies = []
  end

  def parse_all
    depute_list = api_json("http://www.nosdeputes.fr/deputes/json")
    depute_list["deputes"].each{|json| parse_depute(json["depute"]["api_url"])}
  end

  protected

  def api_json(json_url)
    url = URI.parse(json_url)
    req = Net::HTTP::Get.new(url.path)
    res = Net::HTTP.start(url.host, url.port) {|http|
      http.request(req)
    }
    return JSON.parse(res.body)
  end

  def parse_depute(url)
    depute_api = api_json(url)["depute"]

    # do not treat desactivated deputies
    if depute_api["mandat_fin"].nil?

      # verify if deputy already exists in DB
      unless depute = Deputy.first(:slug => depute_api["slug"])
        depute = Deputy.new(:slug => depute_api["slug"])
        depute.nb_cumul = depute_api["autres_mandats"].size unless depute_api["autres_mandats"].kind_of?(String)

        unless depute_api["groupes_parlementaires"].kind_of? String
          depute_api["groupes_parlementaires"].each do |group_api|
            depute.groups << Group.first_or_create(:label => group_api["responsabilite"]["organisme"])
          end
        end

        parse_html_info(depute)
        depute.save
      end
      @deputies << depute
    end
  end

  def parse_html_info(depute)
    url = "http://www.nosdeputes.fr/" +  depute.slug
    doc = Nokogiri::HTML(open(url))
    index = 1
    doc.css(".barre_activite img").each do |activite|
      activite["alt"].scan(/^(\d+)/)
      num = $1.to_i
      case index
      when 1
        depute.activity_weeks = num
      when 2
        depute.commission_presence = num
      when 3
        depute.commission_intervention = num
      when 4
        depute.hemicycle_intervention = num
      when 5
        depute.signed_amendment = num
      when 6
        depute.written_report = num
      when 7
        depute.written_law_proposal = num
      when 8
        depute.signed_law_proposal = num
      when 9
        depute.written_question = num
      when 10
        depute.oral_question = num
      end
      index += 1
    end
  end
end


text:
import React, { PropTypes } from 'react';
import Relay from 'react-relay';

import SaleImg from '../../../images/sale_bg.svg';

const ProductPrice = ({ availability, price }) => {
  const { discount, priceRange } = availability;
  const isPriceRange = priceRange && priceRange.minPrice.gross !== priceRange.maxPrice.gross;
  return (

        {isPriceRange && {gettext('from')} } {priceRange.minPrice.grossLocalized}

      {discount && (

{gettext('Sale')}

      )}

  );
};

ProductPrice.propTypes = {
  availability: PropTypes.object.isRequired,
  price: PropTypes.object.isRequired
};

export default Relay.createContainer(ProductPrice, {
  fragments: {
    availability: () => Relay.QL`
      fragment on ProductAvailabilityType {
        available,
        discount { gross },
        priceRange {
          maxPrice { gross, grossLocalized, currency },
          minPrice { gross, grossLocalized, currency }
        }
      }
    `
  }
});


text:
<html>
<head>
<title>My CSS Selector Test</title>
</head>
<body>
<form>
<input class="testCssClass" name="testCss" type="text">
</form>
</body>
</html>


text:
<!DOCTYPE html>

  <link href="../../../../download/sample-tag-controls/validate/validate.css" rel="stylesheet"/>
  <link href="../sample.css" rel="stylesheet"/>

JsViews 'validate' tag control: The {{validate}} tag


text:
body {
  background-image: url(../bg.png),url(../bg-login.png);
  background-repeat: no-repeat,no-repeat;
  background-position: right bottom, left top;
  background-size: auto, auto;
  background-color: #1a1a1a;
  height: 100%;
}

.welcome-header {
  color: #fff;
}


text:
package alma.demo.test.TestNCReceiver;

import alma.acsnc.EventDescription;

public class TestReceiver {
    private String name;

    public TestReceiver(String receiverName) {
        this.name = receiverName;
    }

    /**
     * The one function that your receiver's object class must have!
     * When you create a receiver class, the object class which the
     * receiver will give the event to must have a function called
     * receive and its argument must be the same type as the data
     * being received from the event. If the types do not match an
     * error will be thrown when you try to attach to the channel.
     */
    public void receive(EventDescription data) {
        System.out.println("Receiver "+ name +" got an event.");
        System.out.println(data.name);
    }
}


text:
<?php

namespace Dotdigitalgroup\Email\Controller\Email;

class Callback extends \Magento\Framework\App\Action\Action
{
    /**
     * @var \Dotdigitalgroup\Email\Helper\Data
     */
    private $helper;

    /**
     * @var \Magento\User\Api\Data\UserInterfaceFactory
     */
    private $adminUser;

    /**
     * @var \Magento\Store\Model\StoreManagerInterface
     */
    private $storeManager;

    /**
     * @var \Magento\Framework\App\Config\ScopeConfigInterface
     */
    private $scopeConfig;

    /**
     * @var \Dotdigitalgroup\Email\Helper\Config
     */
    private $config;

    /**
     * @var \Magento\Backend\Helper\Data
     */
    private $adminHelper;

    /**
     * @var \Magento\User\Model\ResourceModel\User
     */
    private $userResource;

    /**
     * @var \Magento\Framework\View\Result\PageFactory
     */
    private $resultPageFactory;

    /**
     * @var \Magento\Framework\Encryption\EncryptorInterface
     */
    private $encryptor;

    /**
     * Callback constructor.
     * @param \Magento\User\Model\ResourceModel\User $userResource
     * @param \Magento\Backend\Helper\Data $backendData
     * @param \Dotdigitalgroup\Email\Helper\Config $config
     * @param \Magento\Framework\App\Config\ScopeConfigInterface $scopeConfigInterface
     * @param \Magento\Store\Model\StoreManagerInterface $storeManager
     * @param \Magento\User\Api\Data\UserInterfaceFactory $adminUser
     * @param \Magento\Framework\App\Action\Context $context
     * @param \Dotdigitalgroup\Email\Helper\Data $helper
     * @param \Magento\Framework\View\Result\PageFactory $resultPageFactory
     * @param \Magento\Framework\Encryption\EncryptorInterface $encryptor
     */
    public function __construct(
        \Magento\User\Model\ResourceModel\User $userResource,
        \Magento\Backend\Helper\Data $backendData,
        \Dotdigitalgroup\Email\Helper\Config $config,
        \Magento\Framework\App\Config\ScopeConfigInterface $scopeConfigInterface,
        \Magento\Store\Model\StoreManagerInterface $storeManager,
        \Magento\User\Api\Data\UserInterfaceFactory $adminUser,
        \Magento\Framework\App\Action\Context $context,
        \Dotdigitalgroup\Email\Helper\Data $helper,
        \Magento\Framework\View\Result\PageFactory $resultPageFactory,
        \Magento\Framework\Encryption\EncryptorInterface $encryptor
    ) {
        $this->adminHelper      = $backendData;
        $this->config           = $config;
        $this->scopeConfig      = $scopeConfigInterface;
        $this->storeManager     = $storeManager;
        $this->adminUser        = $adminUser;
        $this->userResource     = $userResource;
        $this->helper           = $helper;
        $this->resultPageFactory = $resultPageFactory;
        $this->encryptor = $encryptor;

        parent::__construct($context);
    }

    /**
     * Execute method.
     *
     * @return null
     */
    public function execute()
    {
        $code = $this->getRequest()->getParam('code', false);
        $userId = $this->getRequest()->getParam('state');
        //load admin user
        $adminUser = $this->adminUser->create();
        $this->userResource->load($adminUser, $userId);
        //app code and admin user must be present
        if ($code && $adminUser->getId()) {
            $clientId = $this->scopeConfig->getValue(
                \Dotdigitalgroup\Email\Helper\Config::XML_PATH_CONNECTOR_CLIENT_ID
            );
            $clientSecret = $this->scopeConfig->getValue(
                \Dotdigitalgroup\Email\Helper\Config::XML_PATH_CONNECTOR_CLIENT_SECRET_ID
            );
            //callback uri if not set custom
            $redirectUri = $this->storeManager->getStore()
                ->getBaseUrl(\Magento\Framework\UrlInterface::URL_TYPE_WEB, true);
            $redirectUri .= 'connector/email/callback';

            $data = 'client_id=' . $clientId .
                '&client_secret=' . $clientSecret .
                '&redirect_uri=' . $redirectUri .
                '&grant_type=authorization_code' .
                '&code=' . $code;

            //callback url
            $url = $this->config->getTokenUrl();
            // @codingStandardsIgnoreStart
            $ch = curl_init();
            curl_setopt($ch, CURLOPT_URL, $url);
            curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
            curl_setopt($ch, CURLOPT_TIMEOUT, 60);
            curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'POST');
            curl_setopt($ch, CURLOPT_POST, true);
            curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
            curl_setopt($ch, CURLOPT_HTTPHEADER, ['Content-Type: application/x-www-form-urlencoded']);

            $response = json_decode(curl_exec($ch));
            // @codingStandardsIgnoreEnd

            if ($response === false) {
                // @codingStandardsIgnoreLine
                $this->helper->error('Error Number: ' . curl_errno($ch), []);
            }
            if (isset($response->error)) {
                $this->helper->error('OAUTH failed ' . $response->error, []);
            } elseif (isset($response->refresh_token)) {
                //save the refresh token to the admin user
                $adminUser->setRefreshToken(
                    $this->encryptor->encrypt($response->refresh_token)
                );

                $this->userResource->save($adminUser);
            }

            //redirect to automation index page
            return $this->_redirect($this->adminHelper->getUrl('dotdigitalgroup_email/studio'));
        }

        return $this->resultPageFactory->create()
            ->setStatusHeader(404, '1.1', 'Not Found')
            ->setHeader('Status', '404 File not found');
    }
}


text:
require 'spec_helper'

class Post
  include Mongoid::Document
  include Mongoid::Paranoia
  include Mongoid::Slug

  field :title
  slug  :title
end

describe "Mongoid paranoia with mongoid slug model" do
  let(:post) {Post.create!(title: "slug")}

  it "returns post for correct slug" do
    expect(Post.find(post.slug)).to eq(post)
  end

  it "raises for deleted slug" do
    post.delete
    expect{Post.find(post.slug)}.to raise_error(Mongoid::Errors::DocumentNotFound)
  end

  it "returns post for correct restored slug" do
    post.delete
    Post.deleted.first.restore
    expect(Post.find(post.slug)).to eq(post)
  end
end


text:
require_relative "vendored_thor"

module Bundler
  module FriendlyErrors
  module_function

    def log_error(error)
      case error
      when YamlSyntaxError
        Bundler.ui.error error.message
        Bundler.ui.trace error.orig_exception
      when Dsl::DSLError, GemspecError
        Bundler.ui.error error.message
      when GemRequireError
        Bundler.ui.error error.message
        Bundler.ui.trace error.orig_exception
      when BundlerError
        Bundler.ui.error error.message, :wrap => true
        Bundler.ui.trace error
      when Thor::Error
        Bundler.ui.error error.message
      when LoadError
        raise error unless error.message =~ /cannot load such file -- openssl|openssl.so|libcrypto.so/
        Bundler.ui.error "\nCould not load OpenSSL."
        Bundler.ui.warn <<-WARN, :wrap => true
          You must recompile Ruby with OpenSSL support or change the sources in your \
          Gemfile from 'https' to 'http'. Instructions for compiling with OpenSSL \
          using RVM are available at https://rvm.io/packages/openssl.
        WARN
        Bundler.ui.trace error
      when Interrupt
        Bundler.ui.error "\nQuitting..."
        Bundler.ui.trace error
      when Gem::InvalidSpecificationException
        Bundler.ui.error error.message, :wrap => true
      when SystemExit
      when *[defined?(Java::JavaLang::OutOfMemoryError) && Java::JavaLang::OutOfMemoryError].compact
        Bundler.ui.error "\nYour JVM has run out of memory, and Bundler cannot continue. " \
          "You can decrease the amount of memory Bundler needs by removing gems from your Gemfile, " \
          "especially large gems. (Gems can be as large as hundreds of megabytes, and Bundler has to read those files!). " \
          "Alternatively, you can increase the amount of memory the JVM is able to use by running Bundler with jruby -J-Xmx1024m -S bundle (JRuby defaults to 500MB)."
      else request_issue_report_for(error)
      end
    rescue StandardError
      raise error
    end

    def exit_status(error)
      case error
      when BundlerError then error.status_code
      when Thor::Error then 15
      when SystemExit then error.status
      else 1
      end
    end

    def request_issue_report_for(e)
      Bundler.ui.info <<-EOS.gsub(/^ {8}/, "")
        --- ERROR REPORT TEMPLATE -------------------------------------------------------
        # Error Report

        ## Questions

        Please fill out answers to these questions, it'll help us figure out
        why things are going wrong.

        - **What did you do?**

          I ran the command `#{$PROGRAM_NAME} #{ARGV.join(" ")}`

        - **What did you expect to happen?**

          I expected Bundler to...

        - **What happened instead?**

          Instead, what happened was...

        - **Have you tried any solutions posted on similar issues in our issue tracker, stack overflow, or google?**

          I tried...

        - **Have you read our issues document, https://github.com/bundler/bundler/blob/master/doc/contributing/ISSUES.md?**

          ...

        ## Backtrace

        ```
        #{e.class}: #{e.message}
          #{e.backtrace && e.backtrace.join("\n          ").chomp}
        ```

        #{Bundler::Env.report}
        --- TEMPLATE END ----------------------------------------------------------------

      EOS

      Bundler.ui.error "Unfortunately, an unexpected error occurred, and Bundler cannot continue."

      Bundler.ui.warn <<-EOS.gsub(/^ {8}/, "")

        First, try this link to see if there are any existing issue reports for this error:
        #{issues_url(e)}

        If there aren't any reports for this error yet, please create copy and paste the report template above into a new issue. Don't forget to anonymize any private data! The new issue form is located at:
        https://github.com/bundler/bundler/issues/new
      EOS
    end

    def issues_url(exception)
      message = exception.message.lines.first.tr(":", " ").chomp
      message = message.split("-").first if exception.is_a?(Errno)
      require "cgi"
      "https://github.com/bundler/bundler/search?q=" \
        "#{CGI.escape(message)}&type=Issues"
    end
  end

  def self.with_friendly_errors
    yield
  rescue SignalException
    raise
  rescue Exception => e # rubocop:disable Lint/RescueException
    FriendlyErrors.log_error(e)
    exit FriendlyErrors.exit_status(e)
  end
end


text:
#import <Foundation/NSPredicate.h>
#import <Foundation/NSDictionary.h>

#import <CoreData/NSPersistentStoreRequest.h>
#import <CoreData/NSPersistentStoreResult.h>

@class NSEntityDescription;

//  Used to request that Core Data do a batch update of data in a persistent store without
//  loading any data into memory. May not be supported by all store types.
//  WARNING:
//  It is up to the developer creating the request to ensure that changes made by the request to
//  the underlying store do not violate any validation rules specified in the model.
NS_CLASS_AVAILABLE(10_10,8_0)
@interface NSBatchUpdateRequest : NSPersistentStoreRequest {
    @private
    id _entity;
    NSPredicate *_predicate;
    struct _requestFlags {
        unsigned int includesSubentities:1;
        unsigned int resultType:2;
        unsigned int entityIsName:1;
        unsigned int _RESERVED:28;
    } _flags;
    NSDictionary *_columnsToUpdate;
}

+ (instancetype)batchUpdateRequestWithEntityName:(NSString*)entityName;

- (instancetype)initWithEntityName:(NSString *)entityName;
- (instancetype)initWithEntity:(NSEntityDescription *)entity;

@property (copy, readonly) NSString* entityName;
@property (strong, readonly) NSEntityDescription *entity;
@property (strong) NSPredicate *predicate;

// Should the update include subentities? Defaults to YES.
@property BOOL includesSubentities;

// The type of result that should be returned from this request. Defaults to NSStatusOnlyResultType
@property NSBatchUpdateRequestResultType resultType;

// Dictionary of NSPropertyDescription|property name string -> constantValue/NSExpression pairs describing the desired updates.
// The expressions can be any NSExpression that evaluates to a scalar value.
@property (copy) NSDictionary *propertiesToUpdate;

@end


text:
static void playerCallback(SLAndroidSimpleBufferQueueItf bufferQueue, void* context)
{
    try
    {
        ouzel::audio::OSLAudioDevice* audioDeviceSL = reinterpret_cast<ouzel::audio::OSLAudioDevice*>(context);

        audioDeviceSL->enqueue(bufferQueue);
    }
    catch (const std::exception& e)
    {
        ouzel::engine->log(ouzel::Log::Level::ERR) << e.what();
    }
}

namespace ouzel
{
    namespace audio
    {
        class OpenSLErrorCategory final: public std::error_category
        {
        public:
            const char* name() const noexcept override
            {
                return "OpenSL";
            }

            std::string message(int condition) const override
            {
                switch (condition)
                {
                    case SL_RESULT_PRECONDITIONS_VIOLATED: return "SL_RESULT_PRECONDITIONS_VIOLATED";
                    case SL_RESULT_PARAMETER_INVALID: return "SL_RESULT_PARAMETER_INVALID";
                    case SL_RESULT_MEMORY_FAILURE: return "SL_RESULT_MEMORY_FAILURE";
                    case SL_RESULT_RESOURCE_ERROR: return "SL_RESULT_RESOURCE_ERROR";
                    case SL_RESULT_RESOURCE_LOST: return "SL_RESULT_RESOURCE_LOST";
                    case SL_RESULT_IO_ERROR: return "SL_RESULT_IO_ERROR";
                    case SL_RESULT_BUFFER_INSUFFICIENT: return "SL_RESULT_BUFFER_INSUFFICIENT";
                    case SL_RESULT_CONTENT_CORRUPTED: return "SL_RESULT_CONTENT_CORRUPTED";
                    case SL_RESULT_CONTENT_UNSUPPORTED: return "SL_RESULT_CONTENT_UNSUPPORTED";
                    case SL_RESULT_CONTENT_NOT_FOUND: return "SL_RESULT_CONTENT_NOT_FOUND";
                    case SL_RESULT_PERMISSION_DENIED: return "SL_RESULT_PERMISSION_DENIED";
                    case SL_RESULT_FEATURE_UNSUPPORTED: return "SL_RESULT_FEATURE_UNSUPPORTED";
                    case SL_RESULT_INTERNAL_ERROR: return "SL_RESULT_INTERNAL_ERROR";
                    case SL_RESULT_UNKNOWN_ERROR: return "SL_RESULT_UNKNOWN_ERROR";
                    case SL_RESULT_OPERATION_ABORTED: return "SL_RESULT_OPERATION_ABORTED";
                    case SL_RESULT_CONTROL_LOST: return "SL_RESULT_CONTROL_LOST";
                    default: return "Unknown error (" + std::to_string(condition) + ")";
                }
            }
        };

        const OpenSLErrorCategory openSLErrorCategory {};

        static std::error_code makeErrorCode(SLresult e)
        {
            return std::error_code(static_cast<int>(e), openSLErrorCategory);
        }

        OSLAudioDevice::OSLAudioDevice(uint32_t initBufferSize,
                                       uint32_t initSampleRate,
                                       uint16_t initChannels,
                                       const std::function<void(uint32_t frames,
                                                                uint16_t channels,
                                                                uint32_t sampleRate,
                                                                std::vector<float>& samples)>& initDataGetter):
            AudioDevice(Driver::OPENSL, initBufferSize, initSampleRate, initChannels, initDataGetter)
        {
            SLresult result;
            constexpr SLuint32 engineMixIIDCount = 1;
            const SLInterfaceID engineMixIID = SL_IID_ENGINE;
            constexpr SLboolean engineMixReq = SL_BOOLEAN_TRUE;

            if ((result = slCreateEngine(&engineObject, 0, nullptr, engineMixIIDCount, &engineMixIID, &engineMixReq)) != SL_RESULT_SUCCESS)
                throw std::system_error(makeErrorCode(result), "Failed to create OpenSL engine object");

            if ((result = (*engineObject)->Realize(engineObject, SL_BOOLEAN_FALSE)) != SL_RESULT_SUCCESS)
                throw std::system_error(makeErrorCode(result), "Failed to create OpenSL engine object");

            if ((result = (*engineObject)->GetInterface(engineObject, SL_IID_ENGINE, &engine)) != SL_RESULT_SUCCESS)
                throw std::system_error(makeErrorCode(result), "Failed to get OpenSL engine");

            if ((result = (*engine)->CreateOutputMix(engine, &outputMixObject, 0, nullptr, nullptr)) != SL_RESULT_SUCCESS)
                throw std::system_error(makeErrorCode(result), "Failed to create OpenSL output mix");

            if ((result = (*outputMixObject)->Realize(outputMixObject, SL_BOOLEAN_FALSE)) != SL_RESULT_SUCCESS)
                throw std::system_error(makeErrorCode(result), "Failed to create OpenSL output mix");

            SLDataLocator_AndroidSimpleBufferQueue location = {SL_DATALOCATOR_ANDROIDSIMPLEBUFFERQUEUE, 2};

            SLDataFormat_PCM dataFormat;
            dataFormat.formatType = SL_DATAFORMAT_PCM;
            // TODO: get speaker count
            dataFormat.numChannels = channels;
            dataFormat.samplesPerSec = sampleRate * 1000; //mHz
            dataFormat.bitsPerSample = sizeof(int16_t) * 8;
            dataFormat.containerSize = dataFormat.bitsPerSample;

            switch (channels)
            {
                case 1: dataFormat.channelMask = SL_SPEAKER_FRONT_CENTER; break;
                case 2: dataFormat.channelMask = SL_SPEAKER_FRONT_LEFT | SL_SPEAKER_FRONT_RIGHT; break;
                case 4: dataFormat.channelMask = SL_SPEAKER_FRONT_LEFT | SL_SPEAKER_FRONT_RIGHT | SL_SPEAKER_BACK_LEFT | SL_SPEAKER_BACK_RIGHT; break;
                case 6: dataFormat.channelMask = SL_SPEAKER_FRONT_LEFT | SL_SPEAKER_FRONT_RIGHT | SL_SPEAKER_FRONT_CENTER | SL_SPEAKER_LOW_FREQUENCY | SL_SPEAKER_SIDE_LEFT|SL_SPEAKER_SIDE_RIGHT; break;
                case 7: dataFormat.channelMask = SL_SPEAKER_FRONT_LEFT | SL_SPEAKER_FRONT_RIGHT | SL_SPEAKER_FRONT_CENTER | SL_SPEAKER_LOW_FREQUENCY | SL_SPEAKER_BACK_CENTER | SL_SPEAKER_SIDE_LEFT | SL_SPEAKER_SIDE_RIGHT; break;
                case 8: dataFormat.channelMask = SL_SPEAKER_FRONT_LEFT | SL_SPEAKER_FRONT_RIGHT | SL_SPEAKER_FRONT_CENTER | SL_SPEAKER_LOW_FREQUENCY | SL_SPEAKER_BACK_LEFT|SL_SPEAKER_BACK_RIGHT | SL_SPEAKER_SIDE_LEFT | SL_SPEAKER_SIDE_RIGHT; break;
                default:
                    throw std::runtime_error("Invalid channel count");
            }

            dataFormat.endianness = SL_BYTEORDER_LITTLEENDIAN;

            SLDataSource dataSource = {&location, &dataFormat};

            SLDataLocator_OutputMix dataLocatorOut;
            dataLocatorOut.locatorType = SL_DATALOCATOR_OUTPUTMIX;
            dataLocatorOut.outputMix = outputMixObject;

            SLDataSink dataSink;
            dataSink.pLocator = &dataLocatorOut;
            dataSink.pFormat = nullptr;

            constexpr SLuint32 playerIIDCount = 3;
            const SLInterfaceID playerIIDs[] = {SL_IID_BUFFERQUEUE, SL_IID_PLAY, SL_IID_VOLUME};
            constexpr SLboolean playerReqs[] = {SL_BOOLEAN_TRUE, SL_BOOLEAN_TRUE, SL_BOOLEAN_TRUE};

            if ((result = (*engine)->CreateAudioPlayer(engine, &playerObject, &dataSource, &dataSink, playerIIDCount, playerIIDs, playerReqs)) != SL_RESULT_SUCCESS)
                throw std::system_error(makeErrorCode(result), "Failed to create OpenSL player object");

            sampleFormat = SampleFormat::SINT16;

            if ((result = (*playerObject)->Realize(playerObject, SL_BOOLEAN_FALSE)) != SL_RESULT_SUCCESS)
                throw std::system_error(makeErrorCode(result), "Failed to create OpenSL player object");

            if ((result = (*playerObject)->GetInterface(playerObject, SL_IID_PLAY, &player)) != SL_RESULT_SUCCESS)
                throw std::system_error(makeErrorCode(result), "Failed to get OpenSL player interface");

            if ((result = (*playerObject)->GetInterface(playerObject, SL_IID_BUFFERQUEUE, &bufferQueue)) != SL_RESULT_SUCCESS)
                throw std::system_error(makeErrorCode(result), "Failed to get OpenSL buffer queue interface");

            if ((result = (*playerObject)->GetInterface(playerObject, SL_IID_VOLUME, &playerVolume)) != SL_RESULT_SUCCESS)
                throw std::system_error(makeErrorCode(result), "Failed to get OpenSL volume interface");

            if ((result = (*bufferQueue)->Clear(bufferQueue)) != SL_RESULT_SUCCESS)
                throw std::system_error(makeErrorCode(result), "Failed to clear OpenSL buffer");

            if ((result = (*bufferQueue)->RegisterCallback(bufferQueue, playerCallback, this)) != SL_RESULT_SUCCESS)
                throw std::system_error(makeErrorCode(result), "Failed to register OpenSL buffer queue callback");
        }

        OSLAudioDevice::~OSLAudioDevice()
        {
            if (playerObject)
                (*playerObject)->Destroy(playerObject);

            if (outputMixObject)
                (*outputMixObject)->Destroy(outputMixObject);

            if (engineObject)
                (*engineObject)->Destroy(engineObject);
        }

        void OSLAudioDevice::start()
        {
            getData(bufferSize / (channels * sizeof(int16_t)), data);

            SLresult result;
            if ((result = (*bufferQueue)->Enqueue(bufferQueue, data.data(), data.size())) != SL_RESULT_SUCCESS)
                throw std::system_error(makeErrorCode(result), "Failed to enqueue OpenSL data");

            if ((result = (*player)->SetPlayState(player, SL_PLAYSTATE_PLAYING)) != SL_RESULT_SUCCESS)
                throw std::system_error(makeErrorCode(result), "Failed to play sound");
        }

        void OSLAudioDevice::stop()
        {
            SLresult result;
            if ((result = (*player)->SetPlayState(player, SL_PLAYSTATE_STOPPED)) != SL_RESULT_SUCCESS)
                throw std::system_error(makeErrorCode(result), "Failed to stop sound");
        }

        void OSLAudioDevice::enqueue(SLAndroidSimpleBufferQueueItf bufferQueue)
        {
            getData(bufferSize / (channels * sizeof(int16_t)), data);

            SLresult result;
            if ((result = (*bufferQueue)->Enqueue(bufferQueue, data.data(), data.size())) != SL_RESULT_SUCCESS)
                throw std::system_error(makeErrorCode(result), "Failed to enqueue OpenSL data");
        }
    } // namespace audio
} // namespace ouzel

#endif


text:
//**************************************************************//
//**************************************************************//
//*                                                            *//
//*  Copyright (C) 1999 Virtue 3D, Inc.  All Rights Reserved.  *//
//*                                                            *//
//*  File:	   vrAnimationNode.h                               *//
//*  Content:  VR animation nodes header file                  *//
//*  Date:     February 17, 1999                               *//
//*                                                            *//
//**************************************************************//
//**************************************************************//

#ifndef  _VR_ANIMATION_NODE_
#define  _VR_ANIMATION_NODE_

#include "vrField.h"
#include "vrNode.h"

class VRCoordinateInterpolator;
class VROrientationInterpolator;
class VRPositionInterpolator;
class VRTimeSensor;
class VRRoute;

class VRInterpolator: public VRNode
{
public:
	VRInterpolator(void);
	~VRInterpolator(){};
	virtual void release(void);
	void Copy(VRInterpolator*);

	VRMFFloat key;
};

class VRCoordinateInterpolator: public VRInterpolator
{
public:
	VRCoordinateInterpolator(void);
	~VRCoordinateInterpolator(){};
	virtual void release(void);
	void Copy(VRCoordinateInterpolator*);

	void applyIndices(); // removes indices and replaces key values

	VRM2FVec3f keyValue;
	VRMFInt32 keyValueIndex;
};

class VROrientationInterpolator: public VRInterpolator
{
public:
	VROrientationInterpolator(void);
	~VROrientationInterpolator(){};
	virtual void release(void);
	void Copy(VROrientationInterpolator*);

	VRMFRotation keyValue;
};

class VRPositionInterpolator: public VRInterpolator
{
public:
	VRPositionInterpolator(void);
	~VRPositionInterpolator(){};
	virtual void release(void);
	void Copy(VRPositionInterpolator*);

	VRMFVec3f keyValue;
};

class VRSensor: public VRNode
{
public:
	VRSensor(void);
	~VRSensor(){};

	VRSFBool enabled;
};

class VRTimeSensor: public VRSensor
{
public:
	VRTimeSensor(void);
	~VRTimeSensor(){};
	virtual void release(void);
	void Copy(VRTimeSensor*);

	VRSFTime cycleInterval;
	VRSFBool loop;
	VRSFTime startTime;
	VRSFTime stopTime;
};

typedef enum {
	VR_NO_EVENT_OUT,
	VR_FRACTION_CHANGED, VR_VALUE_CHANGED,
} VREventOutType;

typedef enum {
	VR_NO_EVENT_IN,
	VR_SET_FRACTION,
	VR_SET_TRANSFORM_TRANSLATION, VR_SET_TRANSFORM_SCALE,
	VR_SET_TRANSFORM_CENTER, VR_SET_TRANSFORM_ROTATION,
	VR_SET_TRANSFORM_SCALE_ORIENTATION,
	VR_SET_COORDINATE_POINT,
	VR_SET_VIEWPOINT_POSITION, VR_SET_VIEWPOINT_ORIENTATION
} VREventInType;

class VRRoute: public VRNode
{
public:
	VRRoute(void);
	virtual void release(void);
	void Copy(VRRoute*);

	VRSFNode from;
	VRSFNode to;

	VREventOutType eventFrom;
	VREventInType  eventTo;
};

#endif	// _VR_ANIMATION_NODE_


text:
Rails Behaviors implements the `data-*` behaviors generated by Rails 3.x.

This is an alternative to [jquery-ujs](https://github.com/rails/jquery-ujs). Firstly, it is all Coffee goodness. Well, thats mostly good for me. Second, it is written in a modular fashion. This makes it possible to cherry pick the components you need and replace specific functionaly without rewriting the whole thing. Third, it uses built in global ajax events rather than adding its own. O, one more thing, **Zepto**.

## Dependencies

**jQuery 1.7.2+** or **Zepto 0.8+**

You'll need [Sprockets 2](https://github.com/sstephenson/sprockets) if you want to use the gem version. Otherwise you can download the standalone file from the [Downloads](https://github.com/josh/rails-behaviors/downloads) section.

## Installation

rails-behaviors is distributed through the [bower](https://github.com/twitter/bower) package manager.

``` bash
bower install rails-behaviors
```

## Testing

For testing you will need:

* Ruby 1.9.3+
* Bundler (`gem install bundler`)

``` bash
bundle install
bundle exec rackup -E test ./test/config.ru
# now open the browser at http://localhost:9292
```

## Migrating from jquery-ujs

This library handles all the `data-*` behaviors defined in Rails. So its roughly feature for feature identicial with respect to the HTML.

The differences are in the JS interface.

1. There are no `ajax:*` events. jQuery already has global ajax events built in, so there is no point in duplicating that functionality. Doing a find and replace for `"ajax:"` events should give you a good start. You're looking to replace `ajax:success` with `ajaxSuccess`, `ajax:error` with `ajaxError`, etc.
2. There are no global configuration options. Theres no equivalent for `$.rails`. Your probably should have never used that in the first place.

**NOTE** You **can not** use rails-behaviors and jquery-ujs at the same time.

## Reference

See [http://josh.github.com/rails-behaviors/](http://josh.github.com/rails-behaviors/) for a markup and event reference.

## Contributing

    $ git clone git://github.com/josh/rails-behaviors.git
    $ cd rails-behaviors/
    $ bundle install

Run tests

    $ rackup -p 3000 test/config.ru
    $ open http://localhost:3000/

## License

Copyright © 2011 Joshua Peek <<josh@joshpeek.com>>

Rails Behaviors is distributed under an MIT-style license. See LICENSE for details.


text:
we need python3 and protobuf v2

protoc install:
$ cd protobuf
$ tar -xvzf protobuf-2.6.1.tar.gz
$ cd protobuf-2.6.1
$ ./configure
$ make
$ make install

realtime_bidding_pb2.py is generated by protoc v2:
$ protoc --python_out=./openbidder ./protobuf/realtime-bidding.proto

change *.py file to python v3 in protobuf-2.6.1/python/google/protobuf/*
$ 2to3 -w *.py
and setup in protobuf-2.6.1/python/
$ python setup.py build
$ python setup.py install

requester.py is for python v2.
so test request is generated by python v2 in another repo.


text:
package edu.uci.ics.jung.algorithms.layout;

import java.awt.Dimension;
import java.awt.geom.Point2D;
import java.util.Collection;
import java.util.HashMap;
import java.util.Map;

import edu.uci.ics.jung.graph.Graph;
import edu.uci.ics.jung.graph.util.Pair;

/**
 * An implementation of {@code Layout} suitable for tree-like directed
 * acyclic graphs. Parts of it will probably not terminate if the graph is
 * cyclic! The layout will result in directed edges pointing generally upwards.
 * Any vertices with no successors are considered to be level 0, and tend
 * towards the top of the layout. Any vertex has a level one greater than the
 * maximum level of all its successors.
 *
 *
 * @author John Yesberg
 */
public class DAGLayout<V, E> extends SpringLayout<V,E> {

    /**
     * Each vertex has a minimumLevel. Any vertex with no successors has
     * minimumLevel of zero. The minimumLevel of any vertex must be strictly
     * greater than the minimumLevel of its parents. (Vertex A is a parent of
     * Vertex B iff there is an edge from B to A.) Typically, a vertex will
     * have a minimumLevel which is one greater than the minimumLevel of its
     * parent's. However, if the vertex has two parents, its minimumLevel will
     * be one greater than the maximum of the parents'. We need to calculate
     * the minimumLevel for each vertex. When we layout the graph, vertices
     * cannot be drawn any higher than the minimumLevel. The graphHeight of a
     * graph is the greatest minimumLevel that is used. We will modify the
     * SpringLayout calculations so that nodes cannot move above their assigned
     * minimumLevel.
     */
	private Map<V,Number> minLevels = new HashMap<V,Number>();
	// Simpler than the "pair" technique.
	static int graphHeight;
	static int numRoots;
	final double SPACEFACTOR = 1.3;
	// How much space do we allow for additional floating at the bottom.
	final double LEVELATTRACTIONRATE = 0.8;

	/**
	 * A bunch of parameters to help work out when to stop quivering.
	 *
	 * If the MeanSquareVel(ocity) ever gets below the MSV_THRESHOLD, then we
	 * will start a final cool-down phase of COOL_DOWN_INCREMENT increments. If
	 * the MeanSquareVel ever exceeds the threshold, we will exit the cool down
	 * phase, and continue looking for another opportunity.
	 */
	final double MSV_THRESHOLD = 10.0;
	double meanSquareVel;
	boolean stoppingIncrements = false;
	int incrementsLeft;
	final int COOL_DOWN_INCREMENTS = 200;

	/**
	 * Creates an instance for the specified graph.
	 */
	public DAGLayout(Graph<V,E> g) {
		super(g);
	}

	/**
	 * setRoot calculates the level of each vertex in the graph. Level 0 is
	 * allocated to any vertex with no successors. Level n+1 is allocated to
	 * any vertex whose successors' maximum level is n.
	 */
	public void setRoot(Graph<V,E> g) {
		numRoots = 0;
		for(V v : g.getVertices()) {
			Collection<V> successors = getGraph().getSuccessors(v);
			if (successors.size() == 0) {
				setRoot(v);
				numRoots++;
			}
		}
	}

	/**
	 * Set vertex v to be level 0.
	 */
	public void setRoot(V v) {
		minLevels.put(v, new Integer(0));
		// set all the levels.
		propagateMinimumLevel(v);
	}

	/**
	 * A recursive method for allocating the level for each vertex. Ensures
	 * that all predecessors of v have a level which is at least one greater
	 * than the level of v.
	 *
	 * @param v
	 */
	public void propagateMinimumLevel(V v) {
		int level = minLevels.get(v).intValue();
		for(V child : getGraph().getPredecessors(v)) {
			int oldLevel, newLevel;
			Number o = minLevels.get(child);
			if (o != null)
				oldLevel = o.intValue();
			else
				oldLevel = 0;
			newLevel = Math.max(oldLevel, level + 1);
			minLevels.put(child, new Integer(newLevel));

			if (newLevel > graphHeight)
				graphHeight = newLevel;
			propagateMinimumLevel(child);
		}
	}

	/**
	 * Sets random locations for a vertex within the dimensions of the space.
	 * This overrides the method in AbstractLayout
	 *
	 * @param coord
	 * @param d
	 */
	private void initializeLocation(
		V v,
		Point2D coord,
		Dimension d) {

		int level = minLevels.get(v).intValue();
		int minY = (int) (level * d.getHeight() / (graphHeight * SPACEFACTOR));
		double x = Math.random() * d.getWidth();
		double y = Math.random() * (d.getHeight() - minY) + minY;
		coord.setLocation(x,y);
	}

	@Override
	public void setSize(Dimension size) {
		super.setSize(size);
		for(V v : getGraph().getVertices()) {
			initializeLocation(v,transform(v),getSize());
		}
	}

	/**
	 * Had to override this one as well, to ensure that setRoot() is called.
	 */
	@Override
	public void initialize() {
		super.initialize();
		setRoot(getGraph());
	}

	/**
	 * Override the moveNodes() method from SpringLayout. The only change we
	 * need to make is to make sure that nodes don't float higher than the minY
	 * coordinate, as calculated by their minimumLevel.
	 */
	@Override
	protected void moveNodes() {
		// Dimension d = currentSize;
		double oldMSV = meanSquareVel;
		meanSquareVel = 0;

		synchronized (getSize()) {

			for(V v : getGraph().getVertices()) {
				if (isLocked(v))
					continue;
				SpringLayout.SpringVertexData vd = springVertexData.get(v);
				Point2D xyd = transform(v);

				int width = getSize().width;
				int height = getSize().height;

				// (JY addition: three lines are new)
				int level =
					minLevels.get(v).intValue();
				int minY = (int) (level * height / (graphHeight * SPACEFACTOR));
				int maxY =
					level == 0
						? (int) (height / (graphHeight * SPACEFACTOR * 2))
						: height;

				// JY added 2* - double the sideways repulsion.
				vd.dx += 2 * vd.repulsiondx + vd.edgedx;
				vd.dy += vd.repulsiondy + vd.edgedy;

				// JY Addition: Attract the vertex towards it's minimumLevel
				// height.
				double delta = xyd.getY() - minY;
				vd.dy -= delta * LEVELATTRACTIONRATE;
				if (level == 0)
					vd.dy -= delta * LEVELATTRACTIONRATE;
				// twice as much at the top.

				// JY addition:
				meanSquareVel += (vd.dx * vd.dx + vd.dy * vd.dy);

				// keeps nodes from moving any faster than 5 per time unit
				xyd.setLocation(xyd.getX()+Math.max(-5, Math.min(5, vd.dx)) , xyd.getY()+Math.max(-5, Math.min(5, vd.dy)) );

				if (xyd.getX() < 0) {
					xyd.setLocation(0, xyd.getY());
				} else if (xyd.getX() > width) {
					xyd.setLocation(width, xyd.getY());
				}

				// (JY addition: These two lines replaced 0 with minY)
				if (xyd.getY() < minY) {
					xyd.setLocation(xyd.getX(), minY);
					// (JY addition: replace height with maxY)
				} else if (xyd.getY() > maxY) {
					xyd.setLocation(xyd.getX(), maxY);
				}

				// (JY addition: if there's only one root, anchor it in the
				// middle-top of the screen)
				if (numRoots == 1 && level == 0) {
					xyd.setLocation(width/2, xyd.getY());
				}
			}
		}
		//System.out.println("MeanSquareAccel="+meanSquareVel);
		if (!stoppingIncrements
			&& Math.abs(meanSquareVel - oldMSV) < MSV_THRESHOLD) {
			stoppingIncrements = true;
			incrementsLeft = COOL_DOWN_INCREMENTS;
		} else if (
			stoppingIncrements
				&& Math.abs(meanSquareVel - oldMSV) <= MSV_THRESHOLD) {
			incrementsLeft--;
			if (incrementsLeft <= 0)
				incrementsLeft = 0;
		}
	}

	/**
	 * Override incrementsAreDone so that we can eventually stop.
	 */
	@Override
	public boolean done() {
		if (stoppingIncrements && incrementsLeft == 0)
			return true;
		else
			return false;
	}

	/**
	 * Override forceMove so that if someone moves a node, we can re-layout
	 * everything.
	 */
	@Override
	public void setLocation(V picked, double x, double y) {
		Point2D coord = transform(picked);
		coord.setLocation(x,y);
		stoppingIncrements = false;
	}

	/**
	 * Override forceMove so that if someone moves a node, we can re-layout
	 * everything.
	 */
	@Override
	public void setLocation(V picked, Point2D p) {
		Point2D coord = transform(picked);
		coord.setLocation(p);
		stoppingIncrements = false;
	}

	/**
	 * Overridden relaxEdges. This one reduces the effect of edges between
	 * greatly different levels.
	 *
	 */
	@Override
	protected void relaxEdges() {
		for(E e : getGraph().getEdges()) {
		    Pair<V> endpoints = getGraph().getEndpoints(e);
			V v1 = endpoints.getFirst();
			V v2 = endpoints.getSecond();

			Point2D p1 = transform(v1);
			Point2D p2 = transform(v2);
			double vx = p1.getX() - p2.getX();
			double vy = p1.getY() - p2.getY();
			double len = Math.sqrt(vx * vx + vy * vy);

			// JY addition.
			int level1 =
				minLevels.get(v1).intValue();
			int level2 =
				minLevels.get(v2).intValue();

			// desiredLen *= Math.pow( 1.1, (v1.degree() + v2.degree()) );
//          double desiredLen = getLength(e);
			double desiredLen = lengthFunction.transform(e);

			// round from zero, if needed [zero would be Bad.].
			len = (len == 0) ? .0001 : len;

			// force factor: optimal length minus actual length,
			// is made smaller as the current actual length gets larger.
			// why?

			// System.out.println("Desired : " + getLength( e ));
			double f = force_multiplier * (desiredLen - len) / len;

			f = f * Math.pow(stretch / 100.0,
					(getGraph().degree(v1) + getGraph().degree(v2) -2));

			// JY addition. If this is an edge which stretches a long way,
			// don't be so concerned about it.
			if (level1 != level2)
				f = f / Math.pow(Math.abs(level2 - level1), 1.5);

			// f= Math.min( 0, f );

			// the actual movement distance 'dx' is the force multiplied by the
			// distance to go.
			double dx = f * vx;
			double dy = f * vy;
			SpringVertexData v1D, v2D;
			v1D = springVertexData.get(v1);
			v2D = springVertexData.get(v2);

//			SpringEdgeData<E> sed = getSpringEdgeData(e);
//			sed.f = f;

			v1D.edgedx += dx;
			v1D.edgedy += dy;
			v2D.edgedx += -dx;
			v2D.edgedy += -dy;
		}
	}
}


text:
package org.sql2o.converters;

import java.io.ByteArrayInputStream;

/**
 * Created with IntelliJ IDEA.
 * User: lars
 * Date: 6/13/13
 * Time: 11:40 PM
 * To change this template use File | Settings | File Templates.
 */
public class InputStreamConverter extends ConverterBase<ByteArrayInputStream> {
    public ByteArrayInputStream convert(Object val) throws ConverterException {
        if (val == null) return null;

        try {
            return new ByteArrayInputStream( new ByteArrayConverter().convert(val) );
        } catch( ConverterException e) {
            throw new ConverterException("Error converting Blob to InputSteam");
        }
    }
}