text:
use std::env::consts::EXE_SUFFIX;
use std::path::Path;
use std::process::Command;

use super::super::errors::*;
use super::path_update::PathUpdateMethod;
use super::{install_bins, InstallOpts};
use crate::dist::dist::TargetTriple;
use crate::process;
use crate::utils::utils;
use crate::utils::Notification;

// Provide guidance about setting up MSVC if it doesn't appear to be
// installed
pub fn do_msvc_check(opts: &InstallOpts<'_>) -> Result<bool> {
    // Test suite skips this since it's env dependent
    if process().var("RUSTUP_INIT_SKIP_MSVC_CHECK").is_ok() {
        return Ok(true);
    }

    use cc::windows_registry;
    let host_triple = if let Some(trip) = opts.default_host_triple.as_ref() {
        trip.to_owned()
    } else {
        TargetTriple::from_host_or_build().to_string()
    };
    let installing_msvc = host_triple.contains("msvc");
    let have_msvc = windows_registry::find_tool(&host_triple, "cl.exe").is_some();
    if installing_msvc && !have_msvc {
        return Ok(false);
    }

    Ok(true)
}

/// Run by rustup-gc-$num.exe to delete CARGO_HOME
pub fn complete_windows_uninstall() -> Result<utils::ExitCode> {
    use std::ffi::OsStr;
    use std::process::Stdio;

    wait_for_parent()?;

    // Now that the parent has exited there are hopefully no more files open in CARGO_HOME
    let cargo_home = utils::cargo_home()?;
    utils::remove_dir("cargo_home", &cargo_home, &|_: Notification<'_>| ())?;

    // Now, run a *system* binary to inherit the DELETE_ON_CLOSE
    // handle to *this* process, then exit. The OS will delete the gc
    // exe when it exits.
    let rm_gc_exe = OsStr::new("net");

    Command::new(rm_gc_exe)
        .stdin(Stdio::null())
        .stdout(Stdio::null())
        .stderr(Stdio::null())
        .spawn()
        .chain_err(|| ErrorKind::WindowsUninstallMadness)?;

    Ok(utils::ExitCode(0))
}

pub fn wait_for_parent() -> Result<()> {
    use std::io;
    use std::mem;
    use winapi::shared::minwindef::DWORD;
    use winapi::um::handleapi::{CloseHandle, INVALID_HANDLE_VALUE};
    use winapi::um::processthreadsapi::{GetCurrentProcessId, OpenProcess};
    use winapi::um::synchapi::WaitForSingleObject;
    use winapi::um::tlhelp32::{
        CreateToolhelp32Snapshot, Process32First, Process32Next, PROCESSENTRY32, TH32CS_SNAPPROCESS,
    };
    use winapi::um::winbase::{INFINITE, WAIT_OBJECT_0};
    use winapi::um::winnt::SYNCHRONIZE;

    unsafe {
        // Take a snapshot of system processes, one of which is ours
        // and contains our parent's pid
        let snapshot = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0);
        if snapshot == INVALID_HANDLE_VALUE {
            let err = io::Error::last_os_error();
            return Err(err).chain_err(|| ErrorKind::WindowsUninstallMadness);
        }

        let snapshot = scopeguard::guard(snapshot, |h| {
            let _ = CloseHandle(h);
        });

        let mut entry: PROCESSENTRY32 = mem::zeroed();
        entry.dwSize = mem::size_of::<PROCESSENTRY32>() as DWORD;

        // Iterate over system processes looking for ours
        let success = Process32First(*snapshot, &mut entry);
        if success == 0 {
            let err = io::Error::last_os_error();
            return Err(err).chain_err(|| ErrorKind::WindowsUninstallMadness);
        }

        let this_pid = GetCurrentProcessId();
        while entry.th32ProcessID != this_pid {
            let success = Process32Next(*snapshot, &mut entry);
            if success == 0 {
                let err = io::Error::last_os_error();
                return Err(err).chain_err(|| ErrorKind::WindowsUninstallMadness);
            }
        }

        // FIXME: Using the process ID exposes a race condition
        // wherein the parent process already exited and the OS
        // reassigned its ID.
        let parent_id = entry.th32ParentProcessID;

        // Get a handle to the parent process
        let parent = OpenProcess(SYNCHRONIZE, 0, parent_id);
        if parent.is_null() {
            // This just means the parent has already exited.
            return Ok(());
        }

        let parent = scopeguard::guard(parent, |h| {
            let _ = CloseHandle(h);
        });

        // Wait for our parent to exit
        let res = WaitForSingleObject(*parent, INFINITE);

        if res != WAIT_OBJECT_0 {
            let err = io::Error::last_os_error();
            return Err(err).chain_err(|| ErrorKind::WindowsUninstallMadness);
        }
    }

    Ok(())
}

pub fn do_add_to_path(methods: &[PathUpdateMethod]) -> Result<()> {
    assert!(methods.len() == 1 && methods[0] == PathUpdateMethod::Windows);

    use std::ptr;
    use winapi::shared::minwindef::*;
    use winapi::um::winuser::{
        SendMessageTimeoutA, HWND_BROADCAST, SMTO_ABORTIFHUNG, WM_SETTINGCHANGE,
    };
    use winreg::enums::{RegType, HKEY_CURRENT_USER, KEY_READ, KEY_WRITE};
    use winreg::{RegKey, RegValue};

    let old_path = if let Some(s) = get_windows_path_var()? {
        s
    } else {
        // Non-unicode path
        return Ok(());
    };

    let mut new_path = utils::cargo_home()?
        .join("bin")
        .to_string_lossy()
        .into_owned();
    if old_path.contains(&new_path) {
        return Ok(());
    }

    if !old_path.is_empty() {
        new_path.push_str(";");
        new_path.push_str(&old_path);
    }

    let root = RegKey::predef(HKEY_CURRENT_USER);
    let environment = root
        .open_subkey_with_flags("Environment", KEY_READ | KEY_WRITE)
        .chain_err(|| ErrorKind::PermissionDenied)?;

    let reg_value = RegValue {
        bytes: utils::string_to_winreg_bytes(&new_path),
        vtype: RegType::REG_EXPAND_SZ,
    };

    environment
        .set_raw_value("PATH", &reg_value)
        .chain_err(|| ErrorKind::PermissionDenied)?;

    // Tell other processes to update their environment
    unsafe {
        SendMessageTimeoutA(
            HWND_BROADCAST,
            WM_SETTINGCHANGE,
            0 as WPARAM,
            "Environment\0".as_ptr() as LPARAM,
            SMTO_ABORTIFHUNG,
            5000,
            ptr::null_mut(),
        );
    }

    Ok(())
}

// Get the windows PATH variable out of the registry as a String. If
// this returns None then the PATH variable is not unicode and we
// should not mess with it.
fn get_windows_path_var() -> Result<Option<String>> {
    use std::io;
    use winreg::enums::{HKEY_CURRENT_USER, KEY_READ, KEY_WRITE};
    use winreg::RegKey;

    let root = RegKey::predef(HKEY_CURRENT_USER);
    let environment = root
        .open_subkey_with_flags("Environment", KEY_READ | KEY_WRITE)
        .chain_err(|| ErrorKind::PermissionDenied)?;

    let reg_value = environment.get_raw_value("PATH");
    match reg_value {
        Ok(val) => {
            if let Some(s) = utils::string_from_winreg_value(&val) {
                Ok(Some(s))
            } else {
                warn!("the registry key HKEY_CURRENT_USER\\Environment\\PATH does not contain valid Unicode. \
                       Not modifying the PATH variable");
                return Ok(None);
            }
        }
        Err(ref e) if e.kind() == io::ErrorKind::NotFound => Ok(Some(String::new())),
        Err(e) => Err(e).chain_err(|| ErrorKind::WindowsUninstallMadness),
    }
}

// Returns None if the existing old_path does not need changing
fn _remove_from_path(old_path: &str, path_str: &str) -> Option<String> {
    let idx = old_path.find(&path_str)?;
    // If there's a trailing semicolon (likely, since we probably added one
    // during install), include that in the substring to remove. We don't search
    // for that to find the string, because if its the last string in the path,
    // there may not be.
    let mut len = path_str.len();
    if old_path.as_bytes().get(idx + path_str.len()) == Some(&b';') {
        len += 1;
    }

    let mut new_path = old_path[..idx].to_string();
    new_path.push_str(&old_path[idx + len..]);
    // Don't leave a trailing ; though, we don't want an empty string in the
    // path.
    if new_path.ends_with(';') {
        new_path.pop();
    }
    Some(new_path)
}

fn _path_without_cargo_home_bin() -> Result<Option<String>> {
    let old_path = if let Some(s) = get_windows_path_var()? {
        s
    } else {
        // Non-unicode path
        return Ok(None);
    };

    let path_str = utils::cargo_home()?
        .join("bin")
        .to_string_lossy()
        .into_owned();

    Ok(_remove_from_path(&old_path, &path_str))
}

pub fn do_remove_from_path(methods: &[PathUpdateMethod]) -> Result<()> {
    assert!(methods.len() == 1 && methods[0] == PathUpdateMethod::Windows);

    use std::ptr;
    use winapi::shared::minwindef::*;
    use winapi::um::winuser::{
        SendMessageTimeoutA, HWND_BROADCAST, SMTO_ABORTIFHUNG, WM_SETTINGCHANGE,
    };
    use winreg::enums::{RegType, HKEY_CURRENT_USER, KEY_READ, KEY_WRITE};
    use winreg::{RegKey, RegValue};

    let new_path = match _path_without_cargo_home_bin()? {
        Some(new_path) => new_path,
        None => return Ok(()), // No need to set the path
    };

    let root = RegKey::predef(HKEY_CURRENT_USER);
    let environment = root
        .open_subkey_with_flags("Environment", KEY_READ | KEY_WRITE)
        .chain_err(|| ErrorKind::PermissionDenied)?;

    if new_path.is_empty() {
        environment
            .delete_value("PATH")
            .chain_err(|| ErrorKind::PermissionDenied)?;
    } else {
        let reg_value = RegValue {
            bytes: utils::string_to_winreg_bytes(&new_path),
            vtype: RegType::REG_EXPAND_SZ,
        };
        environment
            .set_raw_value("PATH", &reg_value)
            .chain_err(|| ErrorKind::PermissionDenied)?;
    }

    // Tell other processes to update their environment
    unsafe {
        SendMessageTimeoutA(
            HWND_BROADCAST,
            WM_SETTINGCHANGE,
            0 as WPARAM,
            "Environment\0".as_ptr() as LPARAM,
            SMTO_ABORTIFHUNG,
            5000,
            ptr::null_mut(),
        );
    }

    Ok(())
}

pub fn run_update(setup_path: &Path) -> Result<utils::ExitCode> {
    Command::new(setup_path)
        .arg("--self-replace")
        .spawn()
        .chain_err(|| "unable to run updater")?;

    Ok(utils::ExitCode(0))
}

pub fn self_replace() -> Result<utils::ExitCode> {
    wait_for_parent()?;
    install_bins()?;

    Ok(utils::ExitCode(0))
}

// The last step of uninstallation is to delete *this binary*,
// rustup.exe and the CARGO_HOME that contains it. On Unix, this
// works fine. On Windows you can't delete files while they are open,
// like when they are running.
//
// Here's what we're going to do:
// - Copy rustup to a temporary file in
//   CARGO_HOME/../rustup-gc-$random.exe.
// - Open the gc exe with the FILE_FLAG_DELETE_ON_CLOSE and
//   FILE_SHARE_DELETE flags. This is going to be the last
//   file to remove, and the OS is going to do it for us.
//   This file is opened as inheritable so that subsequent
//   processes created with the option to inherit handles
//   will also keep them open.
// - Run the gc exe, which waits for the original rustup
//   process to close, then deletes CARGO_HOME. This process
//   has inherited a FILE_FLAG_DELETE_ON_CLOSE handle to itself.
// - Finally, spawn yet another system binary with the inherit handles
//   flag, so *it* inherits the FILE_FLAG_DELETE_ON_CLOSE handle to
//   the gc exe. If the gc exe exits before the system exe then at
//   last it will be deleted when the handle closes.
//
// This is the DELETE_ON_CLOSE method from
// https://www.catch22.net/tuts/win32/self-deleting-executables
//
// ... which doesn't actually work because Windows won't really
// delete a FILE_FLAG_DELETE_ON_CLOSE process when it exits.
//
// .. augmented with this SO answer
// https://stackoverflow.com/questions/10319526/understanding-a-self-deleting-program-in-c
pub fn delete_rustup_and_cargo_home() -> Result<()> {
    use std::io;
    use std::mem;
    use std::os::windows::ffi::OsStrExt;
    use std::ptr;
    use std::thread;
    use std::time::Duration;
    use winapi::shared::minwindef::DWORD;
    use winapi::um::fileapi::{CreateFileW, OPEN_EXISTING};
    use winapi::um::handleapi::{CloseHandle, INVALID_HANDLE_VALUE};
    use winapi::um::minwinbase::SECURITY_ATTRIBUTES;
    use winapi::um::winbase::FILE_FLAG_DELETE_ON_CLOSE;
    use winapi::um::winnt::{FILE_SHARE_DELETE, FILE_SHARE_READ, GENERIC_READ};

    // CARGO_HOME, hopefully empty except for bin/rustup.exe
    let cargo_home = utils::cargo_home()?;
    // The rustup.exe bin
    let rustup_path = cargo_home.join(&format!("bin/rustup{}", EXE_SUFFIX));

    // The directory containing CARGO_HOME
    let work_path = cargo_home
        .parent()
        .expect("CARGO_HOME doesn't have a parent?");

    // Generate a unique name for the files we're about to move out
    // of CARGO_HOME.
    let numbah: u32 = rand::random();
    let gc_exe = work_path.join(&format!("rustup-gc-{:x}.exe", numbah));
    // Copy rustup (probably this process's exe) to the gc exe
    utils::copy_file(&rustup_path, &gc_exe)?;
    let gc_exe_win: Vec<_> = gc_exe.as_os_str().encode_wide().chain(Some(0)).collect();

    // Make the sub-process opened by gc exe inherit its attribute.
    let mut sa = SECURITY_ATTRIBUTES {
        nLength: mem::size_of::<SECURITY_ATTRIBUTES>() as DWORD,
        lpSecurityDescriptor: ptr::null_mut(),
        bInheritHandle: 1,
    };

    let _g = unsafe {
        // Open an inheritable handle to the gc exe marked
        // FILE_FLAG_DELETE_ON_CLOSE.
        let gc_handle = CreateFileW(
            gc_exe_win.as_ptr(),
            GENERIC_READ,
            FILE_SHARE_READ | FILE_SHARE_DELETE,
            &mut sa,
            OPEN_EXISTING,
            FILE_FLAG_DELETE_ON_CLOSE,
            ptr::null_mut(),
        );

        if gc_handle == INVALID_HANDLE_VALUE {
            let err = io::Error::last_os_error();
            return Err(err).chain_err(|| ErrorKind::WindowsUninstallMadness);
        }

        scopeguard::guard(gc_handle, |h| {
            let _ = CloseHandle(h);
        })
    };

    Command::new(gc_exe)
        .spawn()
        .chain_err(|| ErrorKind::WindowsUninstallMadness)?;

    // The catch 22 article says we must sleep here to give
    // Windows a chance to bump the processes file reference
    // count. acrichto though is in disbelief and *demanded* that
    // we not insert a sleep. If Windows failed to uninstall
    // correctly it is because of him.

    // (.. and months later acrichto owes me a beer).
    thread::sleep(Duration::from_millis(100));

    Ok(())
}

/// Decide which rcfiles we're going to update, so we
/// can tell the user before they confirm.
pub fn get_add_path_methods() -> Vec<PathUpdateMethod> {
    vec![PathUpdateMethod::Windows]
}

/// Decide which rcfiles we're going to update, so we
/// can tell the user before they confirm.
pub fn get_remove_path_methods() -> Result<Vec<PathUpdateMethod>> {
    Ok(vec![PathUpdateMethod::Windows])
}

#[cfg(test)]
mod tests {
    use std::sync::Mutex;

    use lazy_static::lazy_static;
    use winreg::enums::{RegType, HKEY_CURRENT_USER, KEY_READ, KEY_WRITE};
    use winreg::{RegKey, RegValue};

    use crate::currentprocess;
    use crate::utils::utils;

    pub fn get_path() -> Option<String> {
        let root = RegKey::predef(HKEY_CURRENT_USER);
        let environment = root
            .open_subkey_with_flags("Environment", KEY_READ | KEY_WRITE)
            .unwrap();
        // XXX: copied from the mock support crate, but I am suspicous of this
        // code: This uses ok to allow signalling None for 'delete', but this
        // can fail e.g. with !(winerror::ERROR_BAD_FILE_TYPE) or other
        // failures; which will lead to attempting to delete the users path
        // rather than aborting the test suite.
        environment.get_value("PATH").ok()
    }

    pub fn restore_path(p: Option<String>) {
        let root = RegKey::predef(HKEY_CURRENT_USER);
        let environment = root
            .open_subkey_with_flags("Environment", KEY_READ | KEY_WRITE)
            .unwrap();
        if let Some(p) = p.as_ref() {
            let reg_value = RegValue {
                bytes: utils::string_to_winreg_bytes(&p),
                vtype: RegType::REG_EXPAND_SZ,
            };
            environment.set_raw_value("PATH", &reg_value).unwrap();
        } else {
            let _ = environment.delete_value("PATH");
        }
    }

    fn with_registry_edits(f: &dyn Fn()) {
        // Lock protects concurrent mutation of registry
        lazy_static! {
            static ref LOCK: Mutex<()> = Mutex::new(());
        }
        let _g = LOCK.lock();

        // On windows these tests mess with the user's PATH. Save
        // and restore them here to keep from trashing things.
        let saved_path = get_path();
        let _g = scopeguard::guard(saved_path, restore_path);

        f();
    }

    #[test]
    fn windows_uninstall_doesnt_mess_with_a_non_unicode_path() {
        // This writes an error, so we want a sink for it.
        let tp = Box::new(currentprocess::TestProcess::default());
        with_registry_edits(&|| {
            currentprocess::with(tp.clone(), || {
                let root = RegKey::predef(HKEY_CURRENT_USER);
                let environment = root
                    .open_subkey_with_flags("Environment", KEY_READ | KEY_WRITE)
                    .unwrap();
                let reg_value = RegValue {
                    bytes: vec![
                        0x00, 0xD8, // leading surrogate
                        0x01, 0x01, // bogus trailing surrogate
                        0x00, 0x00,
                    ], // null
                    vtype: RegType::REG_EXPAND_SZ,
                };
                environment.set_raw_value("PATH", &reg_value).unwrap();
                // Ok(None) signals no change to the PATH setting layer
                assert_eq!(None, super::_path_without_cargo_home_bin().unwrap());
            })
        });
        assert_eq!(
            r"warning: the registry key HKEY_CURRENT_USER\Environment\PATH does not contain valid Unicode. Not modifying the PATH variable
",
            String::from_utf8(tp.get_stderr()).unwrap()
        );
    }

    #[test]
    fn windows_uninstall_removes_semicolon_from_path_prefix() {
        assert_eq!(
            "foo",
            super::_remove_from_path(
                r"c:\users\example\.cargo\bin;foo",
                r"c:\users\example\.cargo\bin"
            )
            .unwrap()
        )
    }

    #[test]
    fn windows_uninstall_removes_semicolon_from_path_suffix() {
        assert_eq!(
            "foo",
            super::_remove_from_path(
                r"foo;c:\users\example\.cargo\bin",
                r"c:\users\example\.cargo\bin"
            )
            .unwrap()
        )
    }
}


text:
const helper = function () {}

helper.prototype.register = function () {

	enduro.templating_engine.registerHelper('default', function (name, defaultValue, options) {

		if (typeof options === 'undefined') {
			defaultValue = ''
		}

		return typeof name !== 'undefined'
			? name
			: defaultValue
	})

}

module.exports = new helper()

redpajama_set_name: RedPajamaGithub


text:
#include "../Precompiled.h"

#include "../IO/File.h"
#include "../IO/FileSystem.h"
#include "../IO/FileWatcher.h"
#include "../IO/Log.h"
#include "../Core/Profiler.h"

#ifdef _WIN32
#include <windows.h>
#elif __linux__
#include <sys/inotify.h>
extern "C"
{
// Need read/close for inotify
#include "unistd.h"
}
#elif defined(__APPLE__) && !defined(IOS) && !defined(TVOS)
extern "C"
{
#include "../IO/MacFileWatcher.h"
}
#endif

namespace Urho3D
{
#ifndef __APPLE__
static const unsigned BUFFERSIZE = 4096;
#endif

FileWatcher::FileWatcher(Context* context) :
    Object(context),
    fileSystem_(GetSubsystem<FileSystem>()),
    delay_(1.0f),
    watchSubDirs_(false),
    fullWatch_(false)
{
#ifdef URHO3D_FILEWATCHER
#ifdef __linux__
    watchHandle_ = inotify_init();
#elif defined(__APPLE__) && !defined(IOS) && !defined(TVOS)
    supported_ = IsFileWatcherSupported();
#endif
#endif
}

FileWatcher::~FileWatcher()
{
    StopWatching();
#ifdef URHO3D_FILEWATCHER
#ifdef __linux__
    close(watchHandle_);
#endif
#endif
}

bool FileWatcher::StartWatching(const String& pathName, bool watchSubDirs, bool fullWatch)
{
    if (!fileSystem_)
    {
        URHO3D_LOGERROR("No FileSystem, can not start watching");
        return false;
    }

    // Stop any previous watching
    StopWatching();

#if defined(URHO3D_FILEWATCHER) && defined(URHO3D_THREADING)
#ifdef _WIN32
    String nativePath = GetNativePath(RemoveTrailingSlash(pathName));

    dirHandle_ = (void*)CreateFileW(
        WString(nativePath).CString(),
        FILE_LIST_DIRECTORY,
        FILE_SHARE_WRITE | FILE_SHARE_READ | FILE_SHARE_DELETE,
        nullptr,
        OPEN_EXISTING,
        FILE_FLAG_BACKUP_SEMANTICS,
        nullptr);

    if (dirHandle_ != INVALID_HANDLE_VALUE)
    {
        path_ = AddTrailingSlash(pathName);
        watchSubDirs_ = watchSubDirs;
        fullWatch_ = fullWatch;
        Run();

        URHO3D_LOGDEBUG("Started watching path " + pathName);
        return true;
    }
    else
    {
        URHO3D_LOGERROR("Failed to start watching path " + pathName);
        return false;
    }
#elif defined(__linux__)
    int flags = IN_CREATE | IN_DELETE | IN_MODIFY | IN_MOVED_FROM | IN_MOVED_TO;
    int handle = inotify_add_watch(watchHandle_, pathName.CString(), (unsigned)flags);

    if (handle < 0)
    {
        URHO3D_LOGERROR("Failed to start watching path " + pathName);
        return false;
    }
    else
    {
        // Store the root path here when reconstructed with inotify later
        dirHandle_[handle] = "";
        path_ = AddTrailingSlash(pathName);
        watchSubDirs_ = watchSubDirs;

        if (watchSubDirs_)
        {
            Vector<String> subDirs;
            fileSystem_->ScanDir(subDirs, pathName, "*", SCAN_DIRS, true);

            for (unsigned i = 0; i < subDirs.Size(); ++i)
            {
                String subDirFullPath = AddTrailingSlash(path_ + subDirs[i]);

                // Don't watch ./ or ../ sub-directories
                if (!subDirFullPath.EndsWith("./"))
                {
                    handle = inotify_add_watch(watchHandle_, subDirFullPath.CString(), (unsigned)flags);
                    if (handle < 0)
                        URHO3D_LOGERROR("Failed to start watching subdirectory path " + subDirFullPath);
                    else
                    {
                        // Store sub-directory to reconstruct later from inotify
                        dirHandle_[handle] = AddTrailingSlash(subDirs[i]);
                    }
                }
            }
        }
        Run();

        URHO3D_LOGDEBUG("Started watching path " + pathName);
        return true;
    }
#elif defined(__APPLE__) && !defined(IOS) && !defined(TVOS)
    if (!supported_)
    {
        URHO3D_LOGERROR("Individual file watching not supported by this OS version, can not start watching path " + pathName);
        return false;
    }

    watcher_ = CreateFileWatcher(pathName.CString(), watchSubDirs);
    if (watcher_)
    {
        path_ = AddTrailingSlash(pathName);
        watchSubDirs_ = watchSubDirs;
        Run();

        URHO3D_LOGDEBUG("Started watching path " + pathName);
        return true;
    }
    else
    {
        URHO3D_LOGERROR("Failed to start watching path " + pathName);
        return false;
    }
#else
    URHO3D_LOGERROR("FileWatcher not implemented, can not start watching path " + pathName);
    return false;
#endif
#else
    URHO3D_LOGDEBUG("FileWatcher feature not enabled");
    return false;
#endif
}

void FileWatcher::StopWatching()
{
    if (handle_)
    {
        shouldRun_ = false;

        // Create and delete a dummy file to make sure the watcher loop terminates
        // This is only required on Windows platform
        // TODO: Remove this temp write approach as it depends on user write privilege
#ifdef _WIN32
        String dummyFileName = path_ + "dummy.tmp";
        File file(context_, dummyFileName, FILE_WRITE);
        file.Close();
        if (fileSystem_)
            fileSystem_->Delete(dummyFileName);
#endif

#if defined(__APPLE__) && !defined(IOS) && !defined(TVOS)
        // Our implementation of file watcher requires the thread to be stopped first before closing the watcher
        Stop();
#endif

#ifdef _WIN32
        CloseHandle((HANDLE)dirHandle_);
#elif defined(__linux__)
        for (HashMap<int, String>::Iterator i = dirHandle_.Begin(); i != dirHandle_.End(); ++i)
            inotify_rm_watch(watchHandle_, i->first_);
        dirHandle_.Clear();
#elif defined(__APPLE__) && !defined(IOS) && !defined(TVOS)
        CloseFileWatcher(watcher_);
#endif

#ifndef __APPLE__
        Stop();
#endif

        URHO3D_LOGDEBUG("Stopped watching path " + path_);
        path_.Clear();
    }
}

void FileWatcher::SetDelay(float interval)
{
    delay_ = Max(interval, 0.0f);
}

void FileWatcher::ThreadFunction()
{
#ifdef URHO3D_FILEWATCHER
    URHO3D_PROFILE_THREAD("FileWatcher Thread");

#ifdef _WIN32
    unsigned char buffer[BUFFERSIZE];
    DWORD bytesFilled = 0;

    DWORD flags;
    if (fullWatch_)
        flags = FILE_NOTIFY_CHANGE_FILE_NAME | FILE_NOTIFY_CHANGE_LAST_WRITE | FILE_NOTIFY_CHANGE_CREATION | FILE_NOTIFY_CHANGE_DIR_NAME;
    else
        flags = FILE_NOTIFY_CHANGE_FILE_NAME | FILE_NOTIFY_CHANGE_LAST_WRITE;

    while (shouldRun_)
    {
        if (ReadDirectoryChangesW((HANDLE)dirHandle_,
            buffer,
            BUFFERSIZE,
            watchSubDirs_,
            flags,
            &bytesFilled,
            nullptr,
            nullptr))
        {
            unsigned offset = 0;

            while (offset < bytesFilled)
            {
                FILE_NOTIFY_INFORMATION* record = (FILE_NOTIFY_INFORMATION*)&buffer[offset];

                FileChangeType changeType;

                String fileName;
                const wchar_t* src = record->FileName;
                const wchar_t* end = src + record->FileNameLength / 2;
                while (src < end)
                    fileName.AppendUTF8(String::DecodeUTF16(src));

                fileName = GetInternalPath(fileName);

                switch (record->Action)
                {
                case FILE_ACTION_MODIFIED:
                    changeType = FILECHANGE_MODIFIED;
                    break;
                case FILE_ACTION_ADDED:
                case FILE_ACTION_RENAMED_NEW_NAME:
                    changeType = FILECHANGE_ADDED;
                    break;
                case FILE_ACTION_REMOVED:
                case FILE_ACTION_RENAMED_OLD_NAME:
                    changeType = FILECHANGE_REMOVED;
                    break;
                default:
                    changeType = FILECHANGE_UNKNOWN;
                }

                AddChange({fileName, changeType});

                if (!record->NextEntryOffset)
                    break;
                else
                    offset += record->NextEntryOffset;
            }
        }
    }
#elif defined(__linux__)
    unsigned char buffer[BUFFERSIZE];

    while (shouldRun_)
    {
        int i = 0;
        auto length = (int)read(watchHandle_, buffer, sizeof(buffer));

        if (length < 0)
            return;

        while (i < length)
        {
            auto* event = (inotify_event*)&buffer[i];

            if (event->len > 0)
            {
                if (event->mask & IN_MODIFY || event->mask & IN_MOVE)
                {
                    String fileName;
                    fileName = dirHandle_[event->wd] + event->name;
                    AddChange({fileName, FILECHANGE_UNKNOWN});
                }
            }

            i += sizeof(inotify_event) + event->len;
        }
    }
#elif defined(__APPLE__) && !defined(IOS) && !defined(TVOS)
    while (shouldRun_)
    {
        Time::Sleep(100);

        String changes = ReadFileWatcher(watcher_);
        if (!changes.Empty())
        {
            Vector<String> fileNames = changes.Split(1);
            for (unsigned i = 0; i < fileNames.Size(); ++i)
                AddChange({fileNames[i], FILECHANGE_UNKNOWN});
        }
    }
#endif
#endif
}

void FileWatcher::AddChange(const FileChange& change)
{
    MutexLock lock(changesMutex_);

    if (fullWatch_)
    {
        allChanges_.Resize(allChanges_.Size() + 1);

        TimedFileChange& timedChange = allChanges_.Back();
        timedChange.change_ = change;

        // Reset the timer associated with the filename. Will be notified once timer exceeds the delay
        timedChange.timer_.Reset();
    }
    else
    {
        HashMap<String, TimedFileChange>::Iterator it = fileChanges_.Find(change.fileName_);
        if (it == fileChanges_.End())
        {
            fileChanges_[change.fileName_].change_ = change;
        }
        else
        {
            // Reset the timer associated with the filename. Will be notified once timer exceeds the delay
            it->second_.timer_.Reset();
        }
    }
}

bool FileWatcher::GetNextChange(FileChange& dest)
{
    MutexLock lock(changesMutex_);

    auto delayMsec = (unsigned)(delay_ * 1000.0f);

    if (fullWatch_)
    {
        if (allChanges_.Empty())
            return false;

        TimedFileChange& timedChange = allChanges_.Front();
        if (timedChange.timer_.GetMSec(false) >= delayMsec)
        {
            dest = timedChange.change_;
            allChanges_.PopFront();
            return true;
        }
    }
    else
    {
        if (fileChanges_.Empty())
            return false;

        for (HashMap<String, TimedFileChange>::Iterator i = fileChanges_.Begin(); i != fileChanges_.End(); ++i)
        {
            if (i->second_.timer_.GetMSec(false) >= delayMsec)
            {
                dest = i->second_.change_;
                fileChanges_.Erase(i);
                return true;
            }
        }
    }

    return false;
}

}


text:
function setup() {
  createCanvas(600, 400);
  fill(0, 102);
  noStroke();
}

function draw() {
  background(mouseY); // background color changes based on mouseY
  ellipse(300, 200, mouseX, 50); // width changes based on mouseX
  ellipse(mouseX, mouseY, 10, 10); // ellipse follows mouse
}


text:
var faker = require('faker');

exports = module.exports = (function(){

  function getRandomName(long) {
    if (long) {
      return faker.internet.domainName(); + ' ' + faker.finance.accountName(); // long enough for layout testing purposes
    }
    else {
      return faker.internet.domainName();
    }
  }

  function generateDummyService (i){
    return {
      name: getRandomName(false),
      interval: 60 * 1000,
      failureInterval: 20 * 1000,
      url: 'http://apple.com',
      port: 443,
      timeout: 10000,
      warningThreshold: 3000,
      pingServiceName: 'http-head'
    }
  }

  return {
    generate : function(number){
      var services = [];
      for (var i = 0; i < number; i++) {
        services.push(generateDummyService(i));
      }
      return services;
    }
  };

})();


text:
using System.Collections.Generic;
using strange.extensions.command.impl;
using strange.extensions.context.api;
using UnityEngine;
using VisualiseR.Common;
using VisualiseR.Util;

namespace VisualiseR.CodeReview
{
    /// <summary>
    /// Command to show all code fragments in the scene.
    /// Uses <see cref="SimpleCodeReviewScreenView"/> for  the display.
    /// </summary>
    public class ShowAllCodeCommand : Command
    {
        private static readonly JCsLogger Logger = new JCsLogger(typeof(ShowAllCodeCommand));

        private static readonly float SPAWN_DISTANCE = 20;
        private static readonly float START_ANGLE = 30;
        private static readonly float END_ANGLE = 150;
        private static readonly float MIN_AGNLE_BETWEEN_ELEMENTS = 30;
        private static readonly float MAX_STAGES = 3;
        private static readonly float START_POS_Y = 5;
        private static readonly float POS_Y_DISTANCE = 10;
        private GameObject _simpleScreenParent;

        [Inject(ContextKeys.CONTEXT_VIEW)]
        public GameObject _contextView { get; set; }

        public override void Execute()
        {
            DeactivateOtherObjects();
            InitialiseSimpleScreens();
            Logger.InfoFormat("All code are shown");
        }

        private void DeactivateOtherObjects()
        {
            DeactivateScreen();
            DeactivatateMenus();
            DeactivateInfoScreen();
            DeactivatePiles();
        }

        private static void DeactivateScreen()
        {
            GameObject screens = UnityUtil.FindGameObject("Screens");
            screens.SetActive(false);
        }

        private void DeactivatateMenus()
        {
            GameObject sceneMenu = UnityUtil.FindGameObject("CodeReviewSceneMenuCanvas");
            CodeReviewSceneMenuView sceneMenuView = sceneMenu.GetComponent<CodeReviewSceneMenuView>();
            sceneMenuView.Hide();
        }

        private void DeactivateInfoScreen()
        {
            GameObject infoCanvas = UnityUtil.FindGameObject("InfoCanvas");
            infoCanvas.SetActive(false);
        }

        private void DeactivatePiles()
        {
            GameObject piles = UnityUtil.FindGameObject("Piles");
            piles.SetActive(false);
        }

        private void InitialiseSimpleScreens()
        {
            CodeReviewControllerView screenView = _contextView.GetComponent<CodeReviewControllerView>();
            ICodeMedium medium = screenView._medium;
            if (medium == null) return;
            IPlayer player = screenView._player;

            InstantiateSimpleScreenParent();
            List<Vector3> positions = GetPositions(medium);
            for (int i = 0; i < positions.Count; i++)
            {
                InstantiatePresentationScreen(positions[positions.Count - i - 1], medium.CodeFragments[i], i, player);
            }
        }

        private List<Vector3> GetPositions(ICodeMedium codeMedium)
        {
            return ScreenPositionUtil.ComputeSpawnPositionsWithAngle(SPAWN_DISTANCE, codeMedium.CodeFragments.Count,
                START_ANGLE, END_ANGLE,
                MIN_AGNLE_BETWEEN_ELEMENTS, MAX_STAGES, START_POS_Y, POS_Y_DISTANCE, Camera.main.transform.position.x,
                Camera.main.transform.position.z);
        }

        private void InstantiateSimpleScreenParent()
        {
            if (_simpleScreenParent == null)
            {
                _simpleScreenParent = new GameObject();
                _simpleScreenParent.name = "SimpleScreens";
                _simpleScreenParent.transform.SetParent(_contextView.transform);
            }
        }

        private void InstantiatePresentationScreen(Vector3 pos, ICode code, int codePos, IPlayer player)
        {
            Vector3 relativePos = Camera.main.transform.position - pos;
            Quaternion rotation = Quaternion.LookRotation(relativePos);

            var screen =
                (GameObject) GameObject.Instantiate(Resources.Load("SimpleCodeReviewScreen"), pos, rotation);
            screen.transform.Rotate(-270, 180, 180);
            screen.name = "SimpleScreen_" + codePos;
            screen.transform.SetParent(_simpleScreenParent.transform);

            SimpleCodeReviewScreenView screenView = screen.GetComponent<SimpleCodeReviewScreenView>();
            screenView.Init(code, player);
        }
    }
}


text:
using namespace at3;
using namespace ezecs;
using namespace rtu::topics;

struct PlayerAvatarSet{
    entityId ctrlId = 0;
    entityId camId = 0;
    entityId gimbalId = 0;

    std::unique_ptr<Pyramid> pyramid;
    std::unique_ptr<DuneBuggy> duneBuggy;
    std::unique_ptr<Walker> walker;
};

class Triceratone : public Game<EntityComponentSystemInterface, Triceratone> {

    ControlSystem controlSystem;
    NetworkSystem netSyncSystem;
    PhysicsSystem physicsSystem;
    SceneSystem   sceneSystem;

    std::vector<PlayerAvatarSet> players;

    std::unique_ptr<Subscription> key0Sub, key1Sub, key2Sub, key3Sub;

    PlayerAvatarSet & player() {
      return network->getRole() == settings::network::SERVER ? players.at(0) : players.at(1);
    }

  public:

    Triceratone() : controlSystem(&state), netSyncSystem(&state), physicsSystem(&state), sceneSystem(&state) { }

    bool onInit() {

      // Initialize the systems
      bool initSuccess = true;
      initSuccess &= controlSystem.init();
      initSuccess &= netSyncSystem.init();
      initSuccess &= physicsSystem.init();
      initSuccess &= sceneSystem.init();
      AT3_ASSERT(initSuccess, "System initialization failed!\n");

      // Make sure the transform functions are always registered in the same order, regardless of access order.
      Pyramid::getTopTransFuncDesc();
      Pyramid::getFireTransFuncDesc();
      DuneBuggy::getWheelTransFuncDesc();
      Walker::getBodyTransFuncDesc();

      // an identity matrix
      glm::mat4 ident(1.f);

      // the ark (the cylinder)
      glm::mat4 arkMat = glm::scale(ident, glm::vec3(100.f, 100.f, 100.f));
      entityId arkId;
      state.createEntity(&arkId);
      state.add_Placement(arkId, arkMat);
      state.add_Mesh(arkId, "terrainArk", "cliff1024_01");
      state.add_Physics(arkId, 0, std::make_shared<std::string>("terrainArk"), Physics::STATIC_MESH);
      state.add_SceneNode(arkId, 0);

//      components->openEntityRequest();
//      components->requestPlacement(glm::scale(ident, glm::vec3(100.f, 100.f, 100.f)));
//      components->requestMesh("terrainArk", "cliff1024_01");
//      std::shared_ptr<void> meshName = std::make_shared<std::string>("terrainArk");
//      components->requestPhysics(0, meshName, Physics::STATIC_MESH);
//      components->requestSceneNode(0);
//      components->closeEntityRequest();

//      if (network->getRole() == settings::network::CLIENT) {
//        components->openEntityRequest();
//        components->requestPlacement(glm::translate(ident, {0, -790, -120}));
//        components->requestMesh("humanBean", "");
//        std::shared_ptr<void> radius = std::make_shared<float>(1.f);
//        components->requestPhysics(100.f, radius, Physics::SPHERE);
//        components->requestSceneNode(0);
//        components->closeEntityRequest();
//      }

      // the player avatars
      for (int i = 0; i < 2; ++i) {
        players.emplace_back();

        // the free cameras
        state.createEntity(&players.back().camId);
        float back = 0.f;
        float tilt = 0.f;
        glm::mat4 camMat = glm::rotate(glm::translate(ident, {0.f, 0.f, back}), tilt , glm::vec3(1.0f, 0.0f, 0.0f));
        state.add_Placement(players.back().camId, camMat);
        state.add_Camera(players.back().camId, settings::graphics::fovy, 0.1f, 10000.f);

        state.createEntity(&players.back().gimbalId);
        state.add_Placement(players.back().gimbalId, ident);
        Placement *placement;
        state.get_Placement(players.back().gimbalId, &placement);
        placement->forceLocalRotationAndScale = true;
        state.add_MouseControls(
            players.back().gimbalId, settings::controls::mouseInvertX, settings::controls::mouseInvertY);

        glm::mat4 start = glm::translate(ident, {0, -790, -120});
        state.createEntity(&players.back().ctrlId);
        state.add_Placement(players.back().ctrlId, start);
        state.add_FreeControls(players.back().ctrlId, players.back().gimbalId);

        state.add_SceneNode(players.back().ctrlId, 0);
        state.add_SceneNode(players.back().gimbalId, players.back().ctrlId);
        state.add_SceneNode(players.back().camId, players.back().gimbalId);

        // the human
        glm::vec3 walkerPos = glm::vec3(10, -790, -100 + i * 10);
        glm::mat4 walkerMat = glm::translate(ident, walkerPos);
        players.back().walker = std::make_unique<Walker>(state, walkerMat);

        // the car
        glm::vec3 buggyPos = glm::vec3(0, -790, -100 + i * 10);
        glm::mat4 buggyMat = glm::translate(ident, buggyPos);
        buggyMat *= glm::mat4(getCylStandingRot(buggyPos, (float) M_PI * -0.5f, 0));
        players.back().duneBuggy = std::make_unique<DuneBuggy>(state, buggyMat);

        // the flying illuminati pyramid
        glm::vec3 pyramidPos = glm::vec3(-10, -790, -100 + i * 10);
        glm::mat4 pyramidMat = glm::translate(ident, pyramidPos);
        pyramidMat *= glm::mat4(getCylStandingRot(pyramidPos, (float) M_PI * -0.5f, 0));
        players.back().pyramid = std::make_unique<Pyramid>(state, ecs, pyramidMat);
      }
      makeFreeCamActiveControl();

      // the event subscriptions
      key0Sub = RTU_MAKE_SUB_UNIQUEPTR("key_down_0", Triceratone::makeFreeCamActiveControl, this);
      key1Sub = RTU_MAKE_SUB_UNIQUEPTR("key_down_1", Walker::makeActiveControl, player().walker.get());
      key2Sub = RTU_MAKE_SUB_UNIQUEPTR("key_down_2", DuneBuggy::makeActiveControl, player().duneBuggy.get());
      key3Sub = RTU_MAKE_SUB_UNIQUEPTR("key_down_3", Pyramid::makeActiveControl, player().pyramid.get());

      return initSuccess;
    }

    std::string exampleSetting = "1337_H4XX0R5";
    virtual void registerCustomSettings() {
      settings::addCustom("example_custom_setting_s", &exampleSetting);
    }

    void onTick(float dt) {
      // Order matters here
      netSyncSystem.tick(dt); // First receive and/or send any network updates about controls or physics state
      controlSystem.tick(dt); // Process all control signals, remote or otherwise
      physicsSystem.tick(dt); // Given these inputs, step the physics simulation
      sceneSystem.tick(dt); // Given the most recent physics and world states, traverse the scene to cache transforms
    }

    void makeFreeCamActiveControl() {
      publish<entityId>("switch_to_camera", player().camId);
      publish<entityId>("switch_to_free_controls", player().ctrlId);
      publish<entityId>("switch_to_mouse_controls", player().gimbalId);

//      if (network->getRole() == settings::network::CLIENT) {
////        printf("\nIDS: %u %u %u\n", player().camId, player().ctrlId, player().gimbalId);
//        publish<entityId>("switch_to_camera", 22);
//        publish<entityId>("switch_to_free_controls", 24);
//        publish<entityId>("switch_to_mouse_controls", 23);
//      } else {
//        publish<entityId>("switch_to_camera", player().camId);
//        publish<entityId>("switch_to_free_controls", player().ctrlId);
//        publish<entityId>("switch_to_mouse_controls", player().gimbalId);
//      }
    }
};

int main(int argc, char **argv) {

  Triceratone game;

  std::cout << std::endl << "AT3 is initializing..." << std::endl;
  if ( ! game.init("triceratone", "at3_triceratone_settings.ini")) {
    return -1;
  }

  std::cout << std::endl << "AT3 has started." << std::endl;
  while ( ! game.getIsQuit()) {
    game.tick();
  }

  std::cout << std::endl << "AT3 has finished." << std::endl;
  return 0;
}


text:
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy import (
    select, update, MetaData, create_engine, Table, column)
from sqlalchemy.orm import sessionmaker, relationship
import pandas as pd
import pprint as pp

engine = create_engine(
    'postgresql+psycopg2://lter:bigdata@45.55.241.186/popler_3'
)
conn = engine.connect()

# Mapping metadata
metadata = MetaData(bind=engine)
# Creating base
base = declarative_base()

# creating classes for tables to query things
class lter_table(base):
    __table__ = Table('lter_table', metadata, autoload=True)
class study_site_table(base):
    __table__ = Table('study_site_table', metadata, autoload=True)
class project_table(base):
    __table__ = Table('project_table', metadata, autoload=True)
    taxa = relationship(
        'taxa_table', cascade="delete, delete-orphan")
    count = relationship(
        'count_table', cascade="delete, delete-orphan")
    density = relationship(
        'density_table', cascade="delete, delete-orphan")
    biomass = relationship(
        'biomass_table', cascade="delete, delete-orphan")
    percent_cover = relationship(
        'percent_cover_table', cascade="delete, delete-orphan")
    individual = relationship(
        'individual_table', cascade="delete, delete-orphan")
class site_in_project_table(base):
    __table__ = Table('site_in_project_table', metadata, autoload=True)
class taxa_table(base):
    __table__ = Table('taxa_table', metadata, autoload=True)
class taxa_accepted_table(base):
    __table__ = Table('taxa_accepted_table', metadata, autoload=True)
class count_table(base):
    __table__ = Table('count_table', metadata, autoload=True)
class biomass_table(base):
    __table__ = Table('biomass_table', metadata, autoload=True)
class density_table(base):
    __table__ = Table('density_table', metadata, autoload=True)
class percent_cover_table(base):
    __table__ = Table('percent_cover_table', metadata, autoload=True)
class individual_table(base):
    __table__ = Table('individual_table', metadata, autoload=True)

Session = sessionmaker(bind=engine, autoflush=False)

session = Session()
sitecheck = session.query(
    study_site_table.study_site_key).order_by(
        study_site_table.study_site_key).filter(
            study_site_table.lter_table_fkey == 'SBC'
            )
session.close()
sitecheckdf = pd.read_sql(
    sitecheck.statement, sitecheck.session.bind)

site_in_proj_subq_stmt = (
    select(
        [
            site_in_project_table,
            study_site_table,
            lter_table.lat_lter,
            lter_table.lng_lter,
            lter_table.lterid,
            project_table
        ]).
    select_from(
        site_in_project_table.__table__.
        join(study_site_table.__table__).
        join(lter_table.__table__).join(project_table)).alias()
)

pretty = pp.PrettyPrinter()

# pretty.pprint(site_in_proj_subq_stmt.compile().string)
Session = sessionmaker(bind=engine)
session = Session()
site_in_proj_subq_result = session.execute(site_in_proj_subq_stmt)
site_in_proj_subq_df = pd.DataFrame(site_in_proj_subq_result.fetchall())
site_in_proj_subq_df.columns = site_in_proj_subq_result.keys()
session.close()


text:
// Copyright 2020 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//      http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

package com.google.firebase.appcheck;

import android.annotation.SuppressLint;
import androidx.annotation.NonNull;
import com.google.android.gms.tasks.Task;
import com.google.firebase.FirebaseApp;
import com.google.firebase.appcheck.interop.AppCheckTokenListener;
import com.google.firebase.appcheck.interop.InternalAppCheckTokenProvider;

public abstract class FirebaseAppCheck implements InternalAppCheckTokenProvider {

  /** Gets the default instance of {@code FirebaseAppCheck}. */
  @NonNull
  public static FirebaseAppCheck getInstance() {
    return getInstance(FirebaseApp.getInstance());
  }

  /**
   * Gets the instance of {@code FirebaseAppCheck} associated with the given {@link FirebaseApp}
   * instance.
   */
  @NonNull
  public static FirebaseAppCheck getInstance(@NonNull FirebaseApp firebaseApp) {
    return firebaseApp.get(FirebaseAppCheck.class);
  }

  /**
   * Installs the given {@link AppCheckProviderFactory}, overwriting any that were previously
   * associated with this {@code FirebaseAppCheck} instance. Any {@link AppCheckTokenListener}s
   * attached to this {@code FirebaseAppCheck} instance will be transferred from existing factories
   * to the newly installed one.
   *
   *
Automatic token refreshing will only occur if the global {@code
   * isDataCollectionDefaultEnabled} flag is set to true. To allow automatic token refreshing for
   * Firebase App Check without changing the {@code isDataCollectionDefaultEnabled} flag for other
   * Firebase SDKs, use {@link #installAppCheckProviderFactory(AppCheckProviderFactory, boolean)}
   * instead or call {@link #setTokenAutoRefreshEnabled(boolean)} after installing the {@code
   * factory}.
   */
  public abstract void installAppCheckProviderFactory(@NonNull AppCheckProviderFactory factory);

  /**
   * Installs the given {@link AppCheckProviderFactory}, overwriting any that were previously
   * associated with this {@code FirebaseAppCheck} instance. Any {@link AppCheckTokenListener}s
   * attached to this {@code FirebaseAppCheck} instance will be transferred from existing factories
   * to the newly installed one.
   *
   *
Automatic token refreshing will only occur if the {@code isTokenAutoRefreshEnabled} field is
   * set to true. To use the global {@code isDataCollectionDefaultEnabled} flag for determining
   * automatic token refreshing, call {@link
   * #installAppCheckProviderFactory(AppCheckProviderFactory)} instead.
   */
  @SuppressLint("FirebaseLambdaLast")
  public abstract void installAppCheckProviderFactory(
      @NonNull AppCheckProviderFactory factory, boolean isTokenAutoRefreshEnabled);

  /** Sets the {@code isTokenAutoRefreshEnabled} flag. */
  public abstract void setTokenAutoRefreshEnabled(boolean isTokenAutoRefreshEnabled);

  /**
   * Requests a Firebase App Check token. This method should be used ONLY if you need to authorize
   * requests to a non-Firebase backend. Requests to Firebase backends are authorized automatically
   * if configured.
   */
  @NonNull
  public abstract Task<AppCheckToken> getAppCheckToken(boolean forceRefresh);

  /**
   * Registers an {@link AppCheckListener} to changes in the token state. This method should be used
   * ONLY if you need to authorize requests to a non-Firebase backend. Requests to Firebase backends
   * are authorized automatically if configured.
   */
  public abstract void addAppCheckListener(@NonNull AppCheckListener listener);

  /** Unregisters an {@link AppCheckListener} to changes in the token state. */
  public abstract void removeAppCheckListener(@NonNull AppCheckListener listener);

  public interface AppCheckListener {
    /**
     * This method gets invoked on the UI thread on changes to the token state. Does not trigger on
     * token expiry.
     */
    void onAppCheckTokenChanged(@NonNull AppCheckToken token);
  }
}


text:
ARG JDK_VERSION=11-jdk-slim
ARG DISTROLESS_JAVA_VERSION=11
FROM openjdk:${JDK_VERSION} as build-env
WORKDIR /app
COPY *.gradle gradle.* gradlew /app/
COPY gradle /app/gradle
RUN /app/gradlew --version

FROM build-env as app-build
ADD . /app
WORKDIR /app
USER root
RUN ./gradlew clean :cdc:shadowJar && \
  mv cdc/build/libs/cdc-*-all.jar Main.jar

FROM gcr.io/distroless/java:${DISTROLESS_JAVA_VERSION} as prod
COPY --from=app-build /app/Main.jar /app/Main.jar
WORKDIR /app
ENTRYPOINT ["java"]


text:
import argparse
import pandas
from mypyli import plotmaster

if __name__ == "__main__":
    parser = argparse.ArgumentParser(description="Tries to answer the question: What impact did binning the plate scrapes have on what was ultimately assembled? by looking at where the coverage for the good contigs that were assembled comes from. The idea is that if there was sufficient coverage to assemble in a single sample, binning was no help to assemble the contig.")
    parser.add_argument("-depth", help="the depth file metaBAT uses", required=True)
    parser.add_argument("-out", help="output file path for the plot [%(default)s]", default="contig_coverage_barplot.png")
    parser.add_argument("-min_cov", help="the minimum fold coverage to be considered assemble-able [%(default)s]", default=20.0, type=float)
    parser.add_argument("-min_rel", help="minimum relative coverage for a single sample to require to claim other samples added a negligible amount [%(default)s]", default=.85, type=float)
    parser.add_argument("-min_len", help="minimum length of contigs to consider [%(default)s]", default=1500, type=int)

    args = parser.parse_args()

    # read in depth file
    df = pandas.read_csv(args.depth, sep="\t", header=0, index_col=0)

    # remove contigs that are too short
    #df["contigLen"] = df['contigLen'].astype(int)
    df = df[df["contigLen"] >= args.min_len]

    # get a list of columns that have coverage
    cov_columns = [col for col in df.columns if col.endswith(".bam")]

    categories = {
                'asm_in_multiple': 0,       # suf. coverage to asm in multiple samples
                'asm_in_single': 0,         # suf. coverage to asm in single sample
                'asm_by_group': 0,          # would not have assembled in any single sample but does in mult
                'no_asm_single': 0,         # below asm cov but most comes from a single sample
                'no_asm_multi': 0,          # below asm cov but cov comes from multiple samples
                }
    # loop over each row in the dataframe
    for index, row in df.iterrows():
        total_cov = row['totalAvgDepth']

        # contig had total cov required to asm
        if total_cov >= args.min_cov:

            # count the number of samples that had sufficient cov
            asm_count = 0
            for col in cov_columns:
                if row[col] >= args.min_cov:
                    asm_count += 1

            if asm_count > 1:
                categories['asm_in_multiple'] += 1
            elif asm_count == 1:
                categories['asm_in_single'] += 1
            else:
                categories['asm_by_group'] += 1

        else:
            # check if most of the cov is from a single sample
            for col in cov_columns:
                if row[col] / total_cov >= args.min_rel:
                    #print((total_cov, row[col]))
                    categories['no_asm_single'] += 1
                    break       # no need to check the rest

            else:
                categories['no_asm_multi'] += 1

    # convert to series and make a barplot
    category_s = pandas.Series(data=categories)

    # sort the series like I want
    category_s = category_s[["asm_in_multiple", "asm_in_single", "asm_by_group", "no_asm_single", "no_asm_multi"]]

    ax = category_s.plot(kind="bar")
    ax.set_xlabel("Category")
    ax.set_ylabel("Number of Contigs (>= {}bp)".format(args.min_len))
    ax.set_title("Impact of Binning on Contig Coverage")
    plotmaster.save_ax(ax, args.out)


text:
ACCEPTED

#### According to
The Catalogue of Life, 3rd January 2011

#### Published in
Eur J Protistol 39 (4), December: 377.

#### Original name
null

### Remarks
null


text:
layout: page
title: "About"
description: "Hey, this is Lollipop."
header-img: "img/about-bg.jpg"
---

我拥有的都是侥幸啊,我失去的都是人生

                       ——张悬

Hey,我是荣儿,测试工程师.

热爱音乐,电影,晚睡

讨厌加班

{% if site.duoshuo_username %}

{% endif %}


text:
package com.jnardari.popularmovies.presenters;

/**
 * Created by jnardari on 15/08/16.
 */
public class MainPresenterImpl implements MainPresenter {
    @Override
    public void onResume() {
        // TODO
    }

    @Override
    public void onMovieClicked(int position) {
        // TODO
    }

    @Override
    public void onDestroy() {
        // TODO
    }
}


text:
import { Injectable } from '@angular/core';
import {Game} from './game'

@Injectable()
export class AddService {
	games:Game[] = [];
	addGame(model:Game)
	{
		if(localStorage.getItem('games'))
			this.games = JSON.parse(localStorage.getItem('games'));
		this.games.push(model);
		localStorage.setItem('games',JSON.stringify(this.games));
		console.log(this.games);
	}
	getGames()
	{
		/*this.games = [{'title':'maneehsa',url:'https://raw.githubusercontent.com/christiannwamba/angular2-carousel-component/master/images/covered.jpg','note':'test'},{'title':'vipin',url:'test.png','note':'test'},
		{'title':'veena',url:'test.png','note':'https://raw.githubusercontent.com/christiannwamba/angular2-carousel-component/master/images/potter.jpg'},{'title':'aswathi',url:'https://raw.githubusercontent.com/christiannwamba/angular2-carousel-component/master/images/generation.jpg','note':'test'},{'title':'minu',url:'test.png','note':'test'},{'title':'deepthi',url:'https://raw.githubusercontent.com/christiannwamba/angular2-carousel-component/master/images/preschool.jpg','note':'test'},{'title':'maneehsa',url:'https://raw.githubusercontent.com/christiannwamba/angular2-carousel-component/master/images/soccer.jpg','note':'test'}];*/
		if(localStorage.getItem('games'))
			this.games = JSON.parse(localStorage.getItem('games'));
		return this.games;

	}
}


text:
package com.dynatrace.diagnostics.plugins.domain;

import java.util.Date;

public class SqlMetrics {
	private String sid;
	private String sqlFulltext;
	private String key;
	private Double executions;
	private Double elapsedTime;
	private Double averageElapsedTime;
	private Double cpuTime;
	private Double averageCpuTime;
	private Double diskReads;
	private Double directWrites;
	private Double bufferGets;
	private Double rowsProcessed;
	private Double parseCalls;
	private String firstLoadTime;
	private Date firstLoadTimeDate;
	private String lastLoadTime;
	private Date lastLoadTimeDate;
	private Double childNumber;
	private Long planHashValue;
	private Long explainPlanId;
	private String explainPlan;
	private Long srcDbNameId;

	public String getSid() {
		return sid;
	}
	public void setSid(String sid) {
		this.sid = sid;
	}
	public String getSqlFulltext() {
		return sqlFulltext;
	}
	public void setSqlFulltext(String sql) {
		this.sqlFulltext = sql;
	}
	public String getKey() {
		return key;
	}
	public void setKey(String key) {
		this.key = key;
	}
	public Double getExecutions() {
		return executions;
	}
	public void setExecutions(Double executions) {
		this.executions = executions;
	}
	public Double getElapsedTime() {
		return elapsedTime;
	}
	public void setElapsedTime(Double elapsedTime) {
		this.elapsedTime = elapsedTime;
	}
	public Double getAverageElapsedTime() {
		return averageElapsedTime;
	}
	public void setAverageElapsedTime(Double averageElapsedTime) {
		this.averageElapsedTime = averageElapsedTime;
	}
	public Double getCpuTime() {
		return cpuTime;
	}
	public void setCpuTime(Double cpuTime) {
		this.cpuTime = cpuTime;
	}
	public Double getAverageCpuTime() {
		return averageCpuTime;
	}
	public void setAverageCpuTime(Double averageCpuTime) {
		this.averageCpuTime = averageCpuTime;
	}
	public Double getDiskReads() {
		return diskReads;
	}
	public void setDiskReads(Double diskReads) {
		this.diskReads = diskReads;
	}
	public Double getDirectWrites() {
		return directWrites;
	}
	public void setDirectWrites(Double directWrites) {
		this.directWrites = directWrites;
	}
	public Double getBufferGets() {
		return bufferGets;
	}
	public void setBufferGets(Double bufferGets) {
		this.bufferGets = bufferGets;
	}
	public Double getRowsProcessed() {
		return rowsProcessed;
	}
	public void setRowsProcessed(Double rowsProcessed) {
		this.rowsProcessed = rowsProcessed;
	}
	public Double getParseCalls() {
		return parseCalls;
	}
	public void setParseCalls(Double parseCalls) {
		this.parseCalls = parseCalls;
	}
	public String getFirstLoadTime() {
		return firstLoadTime;
	}
	public void setFirstLoadTime(String firstLoadTime) {
		this.firstLoadTime = firstLoadTime;
	}
	public Date getFirstLoadTimeDate() {
		return firstLoadTimeDate;
	}
	public void setFirstLoadTimeDate(Date firstLoadTimeDate) {
		this.firstLoadTimeDate = firstLoadTimeDate;
	}
	public String getLastLoadTime() {
		return lastLoadTime;
	}
	public void setLastLoadTime(String lastLoadTime) {
		this.lastLoadTime = lastLoadTime;
	}
	public Date getLastLoadTimeDate() {
		return lastLoadTimeDate;
	}
	public void setLastLoadTimeDate(Date lastLoadTimeDate) {
		this.lastLoadTimeDate = lastLoadTimeDate;
	}
	public Double getChildNumber() {
		return childNumber;
	}
	public void setChildNumber(Double childNumber) {
		this.childNumber = childNumber;
	}
	public Long getPlanHashValue() {
		return planHashValue;
	}
	public void setPlanHashValue(Long planHashValue) {
		this.planHashValue = planHashValue;
	}
	public String getExplainPlan() {
		return explainPlan;
	}
	public Long getExplainPlanId() {
		return explainPlanId;
	}
	public void setExplainPlanId(Long explainPlanId) {
		this.explainPlanId = explainPlanId;
	}
	public void setExplainPlan(String explainPlan) {
		this.explainPlan = explainPlan;
	}
	public Long getSrcDbNameId() {
		return srcDbNameId;
	}
	public void setSrcDbNameId(Long srcDbNameId) {
		this.srcDbNameId = srcDbNameId;
	}
	@Override
	public String toString() {
		StringBuilder builder = new StringBuilder();
		builder.append("SqlMetrics [sid=").append(sid).append(", sqlFulltext=")
				.append(sqlFulltext).append(", key=").append(key)
				.append(", executions=").append(executions)
				.append(", elapsedTime=").append(elapsedTime)
				.append(", averageElapsedTime=").append(averageElapsedTime)
				.append(", cpuTime=").append(cpuTime)
				.append(", averageCpuTime=").append(averageCpuTime)
				.append(", diskReads=").append(diskReads)
				.append(", directWrites=").append(directWrites)
				.append(", bufferGets=").append(bufferGets)
				.append(", rowsProcessed=").append(rowsProcessed)
				.append(", parseCalls=").append(parseCalls)
				.append(", firstLoadTime=").append(firstLoadTime)
				.append(", firstLoadTimeDate=").append(firstLoadTimeDate)
				.append(", lastLoadTime=").append(lastLoadTime)
				.append(", lastLoadTimeDate=").append(lastLoadTimeDate)
				.append(", childNumber=").append(childNumber)
				.append(", planHashValue=").append(planHashValue)
				.append(", explainPlanId=").append(explainPlanId)
				.append(", explainPlan=").append(explainPlan)
				.append(", srcDbNameId=").append(srcDbNameId).append("]");
		return builder.toString();
	}

}


text:
import testUtils
import p2p_test_peers
import random
import time
import copy
import threading

from core_symbol import CORE_SYMBOL

class StressNetwork:
    speeds=[1,5,10,30,60,100,500]
    sec=10
    maxthreads=100
    trList=[]

    def maxIndex(self):
        return len(self.speeds)

    def randAcctName(self):
        s=""
        for i in range(12):
            s=s+random.choice("abcdefghijklmnopqrstuvwxyz12345")
        return s

    def _transfer(self, node, acc1, acc2, amount, threadId, round):
        memo="%d %d" % (threadId, round)
        tr = node.transferFunds(acc1, acc2, amount, memo)
        self.trList.append(tr)

    def execute(self, cmdInd, node, ta, eosio):
        print("\n==== network stress test: %d transaction(s)/s for %d secs ====" % (self.speeds[cmdInd], self.sec))
        total = self.speeds[cmdInd] * self.sec

        ta.name = self.randAcctName()
        acc1 = copy.copy(ta)
        print("creating new account %s" % (ta.name))
        tr = node.createAccount(ta, eosio, stakedDeposit=0, waitForTransBlock=True, exitOnError=True)
        trid = node.getTransId(tr)
        if trid is None:
            return ([], "", 0.0, "failed to create account")
        print("transaction id %s" % (trid))

        ta.name = self.randAcctName()
        acc2 = copy.copy(ta)
        print("creating new account %s" % (ta.name))
        tr = node.createAccount(ta, eosio, stakedDeposit=0, waitForTransBlock=True, exitOnError=True)
        trid = node.getTransId(tr)
        if trid is None:
            return ([], "", 0.0, "failed to create account")
        print("transaction id %s" % (trid))

        print("issue currency0000 into %s" % (acc1.name))
        contract="eosio"
        action="issue"
        data="{\"to\":\"" + acc1.name + "\",\"quantity\":\"1000000.0000 "+CORE_SYMBOL+"\"}"
        opts="--permission eosio@active"
        tr=node.pushMessage(contract, action, data, opts)
        trid = node.getTransId(tr[1])
        if trid is None:
            return ([], "", 0.0, "failed to issue currency0000")
        print("transaction id %s" % (trid))
        node.waitForTransInBlock(trid)

        self.trList = []
        expBal = 0
        nthreads=self.maxthreads
        if nthreads > self.speeds[cmdInd]:
            nthreads = self.speeds[cmdInd]
        cycle = int(total / nthreads)
        total = cycle * nthreads # rounding
        delay = 1.0 / self.speeds[cmdInd] * nthreads

        print("start currency0000 trasfer from %s to %s for %d times with %d threads" % (acc1.name, acc2.name, total, nthreads))

        t00 = time.time()
        for k in range(cycle):
            t0 = time.time()
            amount = 1
            threadList = []
            for m in range(nthreads):
                th = threading.Thread(target = self._transfer,args = (node, acc1, acc2, amount, m, k))
                th.start()
                threadList.append(th)
            for th in threadList:
                th.join()
            expBal = expBal + amount * nthreads
            t1 = time.time()
            if (t1-t0 < delay):
                time.sleep(delay - (t1-t0))
        t11 = time.time()
        print("time used = %lf" % (t11 - t00))

        actBal = node.getAccountBalance(acc2.name)
        print("account %s: expect Balance:%d, actual Balance %d" % (acc2.name, expBal, actBal))

        transIdlist = []
        for tr in self.trList:
            trid = node.getTransId(tr)
            transIdlist.append(trid)
            node.waitForTransInBlock(trid)
        return (transIdlist, acc2.name, expBal, "")

    def on_exit(self):
        print("end of network stress tests")


text:
package org.gradle.internal.execution.history.changes;

import com.google.common.collect.ImmutableList;
import org.gradle.api.Describable;
import org.gradle.internal.snapshot.impl.ImplementationSnapshot;

import javax.annotation.Nullable;

public class ImplementationChanges implements ChangeContainer {
    private final ImplementationSnapshot previousImplementation;
    private final ImmutableList<ImplementationSnapshot> previousAdditionalImplementations;
    private final ImplementationSnapshot currentImplementation;
    private final ImmutableList<ImplementationSnapshot> currentAdditionalImplementations;
    private final Describable executable;

    public ImplementationChanges(
        ImplementationSnapshot previousImplementation,
        ImmutableList<ImplementationSnapshot> previousAdditionalImplementations,
        ImplementationSnapshot currentImplementation,
        ImmutableList<ImplementationSnapshot> currentAdditionalImplementations,
        Describable executable
    ) {
        this.previousImplementation = previousImplementation;
        this.previousAdditionalImplementations = previousAdditionalImplementations;
        this.currentImplementation = currentImplementation;
        this.currentAdditionalImplementations = currentAdditionalImplementations;
        this.executable = executable;
    }

    @Override
    public boolean accept(ChangeVisitor visitor) {
        if (!currentImplementation.getTypeName().equals(previousImplementation.getTypeName())) {
            return visitor.visitChange(new DescriptiveChange("The type of %s has changed from '%s' to '%s'.",
                executable.getDisplayName(), previousImplementation.getTypeName(), currentImplementation.getTypeName()));
        }
        if (currentImplementation.isUnknown()) {
            return visitor.visitChange(new DescriptiveChange("The type of %s %s",
                    executable.getDisplayName(), currentImplementation.getUnknownReason()));
        }
        if (previousImplementation.isUnknown()) {
            return visitor.visitChange(new DescriptiveChange("During the previous execution of %s, it %s",
                    executable.getDisplayName(), previousImplementation.getUnknownReason()));
        }
        if (!currentImplementation.getClassLoaderHash().equals(previousImplementation.getClassLoaderHash())) {
            return visitor.visitChange(new DescriptiveChange("Class path of %s has changed from %s to %s.",
                    executable.getDisplayName(), previousImplementation.getClassLoaderHash(), currentImplementation.getClassLoaderHash()));
        }

        ImplementationSnapshot unknownImplementation = findUnknownImplementation(currentAdditionalImplementations);
        if (unknownImplementation != null) {
            return visitor.visitChange(new DescriptiveChange("Additional action for %s: %s",
                    executable.getDisplayName(), unknownImplementation.getUnknownReason()));
        }
        ImplementationSnapshot previousUnknownImplementation = findUnknownImplementation(previousAdditionalImplementations);
        if (previousUnknownImplementation != null) {
            return visitor.visitChange(new DescriptiveChange("During the previous execution of %s, it had an additional action that %s",
                    executable.getDisplayName(), previousUnknownImplementation.getUnknownReason()));
        }
        if (!currentAdditionalImplementations.equals(previousAdditionalImplementations)) {
            return visitor.visitChange(new DescriptiveChange("One or more additional actions for %s have changed.",
                    executable.getDisplayName()));
        }
        return true;
    }

    @Nullable
    private static ImplementationSnapshot findUnknownImplementation(Iterable<ImplementationSnapshot> implementations) {
        for (ImplementationSnapshot implementation : implementations) {
            if (implementation.isUnknown()) {
                return implementation;
            }
        }
        return null;
    }
}


text:
<?php get_template_part('templates/head'); ?>
<body <?php body_class(); ?>>

  <?php
    do_action('get_header');
    get_template_part('templates/header');
  ?>

      <?php include forward_template_path(); ?>

    <?php if (forward_display_sidebar()) : ?>

        <?php include forward_sidebar_path(); ?>

    <?php endif; ?>

  <?php get_template_part('templates/footer'); ?>

  <?php wp_footer(); ?>


text:
const gulp         = require('gulp')
const pug          = require('gulp-pug')
const less         = require('gulp-less')
const autoprefixer = require('gulp-autoprefixer')
const clean_css    = require('gulp-clean-css')
const sourcemaps   = require('gulp-sourcemaps')

gulp.task('pug:docs', function () {
  return gulp.src('docs/{index,phi,code,principles,base,obj,comp-typo,comp-ui,help,atom}.pug')
    .pipe(pug({
      basedir: './',
      locals: {
        Xmeter: require('xmeter'),
        Docs: require('./docs/_models/Docs.class.js'),
      },
    }))
    .pipe(gulp.dest('./docs/'))
})

gulp.task('lessc:docs', function () {
  return gulp.src('docs/css/src/docs.less')
    .pipe(less())
    .pipe(autoprefixer({
      grid: true,
      cascade: false,
    }))
    .pipe(gulp.dest('./docs/css/'))
})

gulp.task('lessc:core', function () {
  return gulp.src(__dirname + '/css/src/still-alive.less')
    .pipe(less())
    .pipe(autoprefixer({
      grid: true,
      cascade: false,
    }))
    .pipe(gulp.dest('./css/'))
    .pipe(sourcemaps.init())
    .pipe(clean_css())
    .pipe(sourcemaps.write('./')) // writes to an external .map file
    .pipe(gulp.dest('./css/'))
})

gulp.task('build', ['pug:docs', 'lessc:docs', 'lessc:core'])


text:
using System;
using System.ComponentModel;
using System.Threading;

using NCrawler.Interfaces;

namespace NCrawler.Services
{
	public class ThreadTaskRunnerService : ITaskRunner
	{
		#region ITaskRunner Members

		public bool RunSync(Action<CancelEventArgs> action, TimeSpan maxRuntime)
		{
			if (maxRuntime.TotalMilliseconds <= 0)
			{
				throw new ArgumentOutOfRangeException("maxRuntime");
			}

			CancelEventArgs args = new CancelEventArgs(false);
			IAsyncResult functionResult = action.BeginInvoke(args, null, null);
			WaitHandle waitHandle = functionResult.AsyncWaitHandle;
			if (!waitHandle.WaitOne(maxRuntime))
			{
				args.Cancel = true; // flag to worker that it should cancel!
				ThreadPool.UnsafeRegisterWaitForSingleObject(waitHandle,
					(state, timedOut) => action.EndInvoke(functionResult),
					null, -1, true);
				return false;
			}

			action.EndInvoke(functionResult);
			return true;
		}

		#endregion
	}
}


text:
<?php

use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;

class CreateCardTagTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('card_tag', function (Blueprint $table) {
            $table->increments('id');

            $table->integer('card_id')->unsigned();
            $table->foreign('card_id')->references('id')->on('board_card');

            $table->string('tag_title');
            $table->nullableTimestamps();
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::dropIfExists('card_tag');
    }
}


text:
package com.canyinghao.canrefresh.classic;

import android.content.Context;

import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.LinearInterpolator;
import android.view.animation.RotateAnimation;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.ImageView.ScaleType;

import com.canyinghao.canrefresh.CanRefresh;
import com.canyinghao.canrefresh.R;

public class RotateRefreshView extends FrameLayout implements CanRefresh {

    private final int ROTATION_ANIMATION_DURATION = 1200;

    private final Animation mRotateAnimation;

    private ImageView ivRotate;

    private  int rotateHight ;

    public RotateRefreshView(Context context) {
        this(context, null);
    }

    public RotateRefreshView(Context context, AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public RotateRefreshView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);

        mRotateAnimation = new RotateAnimation(0, 720, Animation.RELATIVE_TO_SELF, 0.5f, Animation.RELATIVE_TO_SELF,
                0.5f);
        rotateHight=(int) getResources().getDimension(R.dimen.refresh_height_rotate);

       View v=  LayoutInflater.from(context).inflate(R.layout.layout_rotate_refresh,null);

        addView(v);

        FrameLayout.LayoutParams params = (LayoutParams) v.getLayoutParams();
        params.height = rotateHight;
        v.setLayoutParams(params);

    }

    @Override
    protected void onFinishInflate() {
        super.onFinishInflate();

        ivRotate = (ImageView) findViewById(R.id.ivRotate);

        ivRotate.setScaleType(ScaleType.MATRIX);

        mRotateAnimation.setInterpolator(new LinearInterpolator());
        mRotateAnimation.setDuration(ROTATION_ANIMATION_DURATION);
        mRotateAnimation.setRepeatCount(Animation.INFINITE);
        mRotateAnimation.setRepeatMode(Animation.RESTART);

    }

    @Override
    public void onPrepare() {

    }

    @Override
    public void onRelease() {
        ivRotate.startAnimation(mRotateAnimation);
    }

    @Override
    public void onReleaseNoEnough(float currentPercent) {

    }

    @Override
    public void onComplete() {

    }

    @Override
    public void onPositionChange(float currentPercent) {

        ivRotate.setRotation(currentPercent*rotateHight);

    }

    @Override
    public void setIsHeaderOrFooter(boolean isHeader) {

    }

    @Override
    public void onReset() {
        resetImageRotation();
    }

    private void resetImageRotation() {

        ivRotate.clearAnimation();

    }

}


text:
(function () {
  'use strict';

  angular.module('exceptionless.validators')
    .directive('searchFilterValidator', ['$q', 'searchService', function($q, searchService) {
      return {
        restrict: 'A',
        require: 'ngModel',
        link: function(scope, element, attrs, ngModel) {
          ngModel.$asyncValidators.valid = function(query) {
            var deferred = $q.defer();

            if (ngModel.$pristine) {
              deferred.resolve(true);
            } else {
              searchService.validate(query).then(function(response) {
                if (!response.data.is_valid) {
                  deferred.reject(response.data.message);
                }
                deferred.resolve(true);
              });
            }

            return deferred.promise;
          };
        }
      };
    }]);
}());


text:
    <link rel="stylesheet" href="../../../../../node_modules/mocha/mocha.css" />
    <meta name="manual-polyfills" />