text:
use std::collections::HashMap;
use std::io::prelude::*;
use std::fs::{self, File};

use conduit::{Handler, Request, Method};

use git2;
use postgres::GenericConnection;
use rustc_serialize::json;
use semver;

use cargo_registry::db::RequestTransaction;
use cargo_registry::dependency::EncodableDependency;
use cargo_registry::download::EncodableVersionDownload;
use cargo_registry::keyword::{Keyword, EncodableKeyword};
use cargo_registry::krate::{Crate, EncodableCrate};
use cargo_registry::upload as u;
use cargo_registry::user::EncodableUser;
use cargo_registry::version::EncodableVersion;

#[derive(RustcDecodable)]
struct CrateList { crates: Vec<EncodableCrate>, meta: CrateMeta }
#[derive(RustcDecodable)]
struct VersionsList { versions: Vec<EncodableVersion> }
#[derive(RustcDecodable)]
struct CrateMeta { total: i32 }
#[derive(RustcDecodable)]
struct GitCrate { name: String, vers: String, deps: Vec<String>, cksum: String }
#[derive(RustcDecodable)]
struct Warnings { invalid_categories: Vec<String>, invalid_badges: Vec<String> }
#[derive(RustcDecodable)]
struct GoodCrate { krate: EncodableCrate, warnings: Warnings }
#[derive(RustcDecodable)]
struct CrateResponse { krate: EncodableCrate, versions: Vec<EncodableVersion>, keywords: Vec<EncodableKeyword> }
#[derive(RustcDecodable)]
struct Deps { dependencies: Vec<EncodableDependency> }
#[derive(RustcDecodable)]
struct RevDeps { dependencies: Vec<EncodableDependency>, meta: CrateMeta }
#[derive(RustcDecodable)]
struct Downloads { version_downloads: Vec<EncodableVersionDownload> }

fn new_crate(name: &str) -> u::NewCrate {
    u::NewCrate {
        name: u::CrateName(name.to_string()),
        vers: u::CrateVersion(semver::Version::parse("1.1.0").unwrap()),
        features: HashMap::new(),
        deps: Vec::new(),
        authors: vec!["foo".to_string()],
        description: Some("desc".to_string()),
        homepage: None,
        documentation: None,
        readme: None,
        keywords: None,
        categories: None,
        license: Some("MIT".to_string()),
        license_file: None,
        repository: None,
        badges: None,
    }
}

#[test]
fn index() {
    let (_b, app, middle) = ::app();
    let mut req = ::req(app, Method::Get, "/api/v1/crates");
    let mut response = ok_resp!(middle.call(&mut req));
    let json: CrateList = ::json(&mut response);
    assert_eq!(json.crates.len(), 0);
    assert_eq!(json.meta.total, 0);

    let krate = ::krate("fooindex");
    ::mock_user(&mut req, ::user("foo"));
    ::mock_crate(&mut req, krate.clone());
    let mut response = ok_resp!(middle.call(&mut req));
    let json: CrateList = ::json(&mut response);
    assert_eq!(json.crates.len(), 1);
    assert_eq!(json.meta.total, 1);
    assert_eq!(json.crates[0].name, krate.name);
    assert_eq!(json.crates[0].id, krate.name);
}

fn tx(req: &Request) -> &GenericConnection { req.tx().unwrap() }

#[test]
fn index_queries() {
    let (_b, app, middle) = ::app();

    let mut req = ::req(app, Method::Get, "/api/v1/crates");
    let u = ::mock_user(&mut req, ::user("foo"));
    let mut krate = ::krate("foo_index_queries");
    krate.readme = Some("readme".to_string());
    krate.description = Some("description".to_string());
    let (krate, _) = ::mock_crate(&mut req, krate.clone());
    let krate2 = ::krate("BAR_INDEX_QUERIES");
    let (krate2, _) = ::mock_crate(&mut req, krate2.clone());
    Keyword::update_crate(tx(&req), &krate, &["kw1".into()]).unwrap();
    Keyword::update_crate(tx(&req), &krate2, &["KW1".into()]).unwrap();

    let mut response = ok_resp!(middle.call(req.with_query("q=baz")));
    assert_eq!(::json::<CrateList>(&mut response).meta.total, 0);

    // All of these fields should be indexed/searched by the queries
    let mut response = ok_resp!(middle.call(req.with_query("q=foo")));
    assert_eq!(::json::<CrateList>(&mut response).meta.total, 1);
    let mut response = ok_resp!(middle.call(req.with_query("q=kw1")));
    assert_eq!(::json::<CrateList>(&mut response).meta.total, 2);
    let mut response = ok_resp!(middle.call(req.with_query("q=readme")));
    assert_eq!(::json::<CrateList>(&mut response).meta.total, 1);
    let mut response = ok_resp!(middle.call(req.with_query("q=description")));
    assert_eq!(::json::<CrateList>(&mut response).meta.total, 1);

    let query = format!("user_id={}", u.id);
    let mut response = ok_resp!(middle.call(req.with_query(&query)));
    assert_eq!(::json::<CrateList>(&mut response).crates.len(), 2);
    let mut response = ok_resp!(middle.call(req.with_query("user_id=0")));
    assert_eq!(::json::<CrateList>(&mut response).crates.len(), 0);

    let mut response = ok_resp!(middle.call(req.with_query("letter=F")));
    assert_eq!(::json::<CrateList>(&mut response).crates.len(), 1);
    let mut response = ok_resp!(middle.call(req.with_query("letter=B")));
    assert_eq!(::json::<CrateList>(&mut response).crates.len(), 1);
    let mut response = ok_resp!(middle.call(req.with_query("letter=b")));
    assert_eq!(::json::<CrateList>(&mut response).crates.len(), 1);
    let mut response = ok_resp!(middle.call(req.with_query("letter=c")));
    assert_eq!(::json::<CrateList>(&mut response).crates.len(), 0);

    let mut response = ok_resp!(middle.call(req.with_query("keyword=kw1")));
    assert_eq!(::json::<CrateList>(&mut response).crates.len(), 2);
    let mut response = ok_resp!(middle.call(req.with_query("keyword=KW1")));
    assert_eq!(::json::<CrateList>(&mut response).crates.len(), 2);
    let mut response = ok_resp!(middle.call(req.with_query("keyword=kw2")));
    assert_eq!(::json::<CrateList>(&mut response).crates.len(), 0);
}

#[test]
fn exact_match_first_on_queries() {
    let (_b, app, middle) = ::app();

    let mut req = ::req(app, Method::Get, "/api/v1/crates");
    let _ = ::mock_user(&mut req, ::user("foo"));
    let mut krate = ::krate("foo_exact");
    krate.description = Some("bar_exact baz_exact".to_string());
    let (_, _) = ::mock_crate(&mut req, krate.clone());
    let mut krate2 = ::krate("bar_exact");
    krate2.description = Some("foo_exact baz_exact foo_exact baz_exact".to_string());
    let (_, _) = ::mock_crate(&mut req, krate2.clone());
    let mut krate3 = ::krate("baz_exact");
    krate3.description = Some("foo_exact bar_exact foo_exact bar_exact foo_exact bar_exact".to_string());
    let (_, _) = ::mock_crate(&mut req, krate3.clone());
    let mut krate4 = ::krate("other_exact");
    krate4.description = Some("other_exact".to_string());
    let (_, _) = ::mock_crate(&mut req, krate4.clone());

    let mut response = ok_resp!(middle.call(req.with_query("q=foo_exact")));
    let json: CrateList = ::json(&mut response);
    assert_eq!(json.meta.total, 3);
    assert_eq!(json.crates[0].name, "foo_exact");
    assert_eq!(json.crates[1].name, "baz_exact");
    assert_eq!(json.crates[2].name, "bar_exact");

    let mut response = ok_resp!(middle.call(req.with_query("q=bar_exact")));
    let json: CrateList = ::json(&mut response);
    assert_eq!(json.meta.total, 3);
    assert_eq!(json.crates[0].name, "bar_exact");
    assert_eq!(json.crates[1].name, "baz_exact");
    assert_eq!(json.crates[2].name, "foo_exact");

    let mut response = ok_resp!(middle.call(req.with_query("q=baz_exact")));
    let json: CrateList = ::json(&mut response);
    assert_eq!(json.meta.total, 3);
    assert_eq!(json.crates[0].name, "baz_exact");
    assert_eq!(json.crates[1].name, "bar_exact");
    assert_eq!(json.crates[2].name, "foo_exact");
}

#[test]
fn exact_match_on_queries_with_sort() {
    let (_b, app, middle) = ::app();

    let mut req = ::req(app, Method::Get, "/api/v1/crates");
    let _ = ::mock_user(&mut req, ::user("foo"));
    let mut krate = ::krate("foo_sort");
    krate.description = Some("bar_sort baz_sort const".to_string());
    krate.downloads = 50;
    let (k, _) = ::mock_crate(&mut req, krate.clone());
    let mut krate2 = ::krate("bar_sort");
    krate2.description = Some("foo_sort baz_sort foo_sort baz_sort const".to_string());
    krate2.downloads = 3333;
    let (k2, _) = ::mock_crate(&mut req, krate2.clone());
    let mut krate3 = ::krate("baz_sort");
    krate3.description = Some("foo_sort bar_sort foo_sort bar_sort foo_sort bar_sort const".to_string());
    krate3.downloads = 100000;
    let (k3, _) = ::mock_crate(&mut req, krate3.clone());
    let mut krate4 = ::krate("other_sort");
    krate4.description = Some("other_sort const".to_string());
    krate4.downloads = 999999;
    let (k4, _) = ::mock_crate(&mut req, krate4.clone());

    {
        let req2: &mut Request = &mut req;
        let tx = req2.tx().unwrap();
        tx.execute("UPDATE crates set downloads = $1
                    WHERE id = $2", &[&krate.downloads, &k.id]).unwrap();
        tx.execute("UPDATE crates set downloads = $1
                    WHERE id = $2", &[&krate2.downloads, &k2.id]).unwrap();
        tx.execute("UPDATE crates set downloads = $1
                    WHERE id = $2", &[&krate3.downloads, &k3.id]).unwrap();
        tx.execute("UPDATE crates set downloads = $1
                    WHERE id = $2", &[&krate4.downloads, &k4.id]).unwrap();
    }

    let mut response = ok_resp!(middle.call(req.with_query("q=foo_sort&sort=downloads")));
    let json: CrateList = ::json(&mut response);
    assert_eq!(json.meta.total, 3);
    assert_eq!(json.crates[0].name, "foo_sort");
    assert_eq!(json.crates[1].name, "baz_sort");
    assert_eq!(json.crates[2].name, "bar_sort");

    let mut response = ok_resp!(middle.call(req.with_query("q=bar_sort&sort=downloads")));
    let json: CrateList = ::json(&mut response);
    assert_eq!(json.meta.total, 3);
    assert_eq!(json.crates[0].name, "bar_sort");
    assert_eq!(json.crates[1].name, "baz_sort");
    assert_eq!(json.crates[2].name, "foo_sort");

    let mut response = ok_resp!(middle.call(req.with_query("q=baz_sort&sort=downloads")));
    let json: CrateList = ::json(&mut response);
    assert_eq!(json.meta.total, 3);
    assert_eq!(json.crates[0].name, "baz_sort");
    assert_eq!(json.crates[1].name, "bar_sort");
    assert_eq!(json.crates[2].name, "foo_sort");

    let mut response = ok_resp!(middle.call(req.with_query("q=const&sort=downloads")));
    let json: CrateList = ::json(&mut response);
    assert_eq!(json.meta.total, 4);
    assert_eq!(json.crates[0].name, "other_sort");
    assert_eq!(json.crates[1].name, "baz_sort");
    assert_eq!(json.crates[2].name, "bar_sort");
    assert_eq!(json.crates[3].name, "foo_sort");
}

#[test]
fn show() {
    let (_b, app, middle) = ::app();
    let mut req = ::req(app, Method::Get, "/api/v1/crates/foo_show");
    ::mock_user(&mut req, ::user("foo"));
    let mut krate = ::krate("foo_show");
    krate.description = Some(format!("description"));
    krate.documentation = Some(format!("https://example.com"));
    krate.homepage = Some(format!("http://example.com"));
    let (krate, _) = ::mock_crate(&mut req, krate.clone());
    Keyword::update_crate(tx(&req), &krate, &["kw1".into()]).unwrap();

    let mut response = ok_resp!(middle.call(&mut req));
    let json: CrateResponse = ::json(&mut response);
    assert_eq!(json.krate.name, krate.name);
    assert_eq!(json.krate.id, krate.name);
    assert_eq!(json.krate.description, krate.description);
    assert_eq!(json.krate.homepage, krate.homepage);
    assert_eq!(json.krate.documentation, krate.documentation);
    assert_eq!(json.krate.keywords, Some(vec!["kw1".into()]));
    let versions = json.krate.versions.as_ref().unwrap();
    assert_eq!(versions.len(), 1);
    assert_eq!(json.versions.len(), 1);
    assert_eq!(json.versions[0].id, versions[0]);
    assert_eq!(json.versions[0].krate, json.krate.id);
    assert_eq!(json.versions[0].num, "1.0.0".to_string());
    let suffix = "/api/v1/crates/foo_show/1.0.0/download";
    assert!(json.versions[0].dl_path.ends_with(suffix),
            "bad suffix {}", json.versions[0].dl_path);
    assert_eq!(1, json.keywords.len());
    assert_eq!("kw1".to_string(), json.keywords[0].id);
}

#[test]
fn versions() {
    let (_b, app, middle) = ::app();
    let mut req = ::req(app, Method::Get, "/api/v1/crates/foo_versions/versions");
    ::mock_user(&mut req, ::user("foo"));
    ::mock_crate(&mut req, ::krate("foo_versions"));
    let mut response = ok_resp!(middle.call(&mut req));
    let json: VersionsList = ::json(&mut response);
    assert_eq!(json.versions.len(), 1);
}

#[test]
fn new_wrong_token() {
    let (_b, app, middle) = ::app();
    let mut req = ::new_req(app.clone(), "foo", "1.0.0");
    bad_resp!(middle.call(&mut req));
    drop(req);

    let mut req = ::new_req(app.clone(), "foo", "1.0.0");
    req.header("Authorization", "bad");
    bad_resp!(middle.call(&mut req));
    drop(req);

    let mut req = ::new_req(app, "foo", "1.0.0");
    ::mock_user(&mut req, ::user("foo"));
    ::logout(&mut req);
    req.header("Authorization", "bad");
    bad_resp!(middle.call(&mut req));
}

#[test]
fn new_bad_names() {
    fn bad_name(name: &str) {
        println!("testing: `{}`", name);
        let (_b, app, middle) = ::app();
        let mut req = ::new_req(app, name, "1.0.0");
        ::mock_user(&mut req, ::user("foo"));
        ::logout(&mut req);
        let json = bad_resp!(middle.call(&mut req));
        assert!(json.errors[0].detail.contains("invalid crate name"),
                "{:?}", json.errors);
    }

    bad_name("");
    bad_name("foo bar");
}

#[test]
fn new_krate() {
    let (_b, app, middle) = ::app();
    let mut req = ::new_req(app, "foo_new", "1.0.0");
    let user = ::mock_user(&mut req, ::user("foo"));
    ::logout(&mut req);
    req.header("Authorization", &user.api_token);
    let mut response = ok_resp!(middle.call(&mut req));
    let json: GoodCrate = ::json(&mut response);
    assert_eq!(json.krate.name, "foo_new");
    assert_eq!(json.krate.max_version, "1.0.0");
}

#[test]
fn new_krate_weird_version() {
    let (_b, app, middle) = ::app();
    let mut req = ::new_req(app, "foo_weird", "0.0.0-pre");
    let user = ::mock_user(&mut req, ::user("foo"));
    ::logout(&mut req);
    req.header("Authorization", &user.api_token);
    let mut response = ok_resp!(middle.call(&mut req));
    let json: GoodCrate = ::json(&mut response);
    assert_eq!(json.krate.name, "foo_weird");
    assert_eq!(json.krate.max_version, "0.0.0-pre");
}

#[test]
fn new_krate_with_dependency() {
    let (_b, app, middle) = ::app();
    let dep = u::CrateDependency {
        name: u::CrateName("foo_dep".to_string()),
        optional: false,
        default_features: true,
        features: Vec::new(),
        version_req: u::CrateVersionReq(semver::VersionReq::parse(">= 0").unwrap()),
        target: None,
        kind: None,
    };
    let mut req = ::new_req_full(app, ::krate("new_dep"), "1.0.0", vec![dep]);
    ::mock_user(&mut req, ::user("foo"));
    ::mock_crate(&mut req, ::krate("foo_dep"));
    let mut response = ok_resp!(middle.call(&mut req));
    ::json::<GoodCrate>(&mut response);
}

#[test]
fn new_krate_with_wildcard_dependency() {
    let (_b, app, middle) = ::app();
    let dep = u::CrateDependency {
        name: u::CrateName("foo_wild".to_string()),
        optional: false,
        default_features: true,
        features: Vec::new(),
        version_req: u::CrateVersionReq(semver::VersionReq::parse("*").unwrap()),
        target: None,
        kind: None,
    };
    let mut req = ::new_req_full(app, ::krate("new_wild"), "1.0.0", vec![dep]);
    ::mock_user(&mut req, ::user("foo"));
    ::mock_crate(&mut req, ::krate("foo_wild"));
    let json = bad_resp!(middle.call(&mut req));
    assert!(json.errors[0].detail.contains("dependency constraints"), "{:?}", json.errors);
}

#[test]
fn new_krate_twice() {
    let (_b, app, middle) = ::app();
    let mut krate = ::krate("foo_twice");
    krate.description = Some("description".to_string());
    let mut req = ::new_req_full(app, krate.clone(), "2.0.0", Vec::new());
    ::mock_user(&mut req, ::user("foo"));
    ::mock_crate(&mut req, ::krate("foo_twice"));
    let mut response = ok_resp!(middle.call(&mut req));
    let json: GoodCrate = ::json(&mut response);
    assert_eq!(json.krate.name, krate.name);
    assert_eq!(json.krate.description, krate.description);
}

#[test]
fn new_krate_wrong_user() {
    let (_b, app, middle) = ::app();

    let mut req = ::new_req(app, "foo_wrong", "2.0.0");

    // Create the 'foo' crate with one user
    ::mock_user(&mut req, ::user("foo"));
    ::mock_crate(&mut req, ::krate("foo_wrong"));

    // But log in another
    ::mock_user(&mut req, ::user("bar"));

    let json = bad_resp!(middle.call(&mut req));
    assert!(json.errors[0].detail.contains("another user"),
            "{:?}", json.errors);
}

#[test]
fn new_krate_bad_name() {
    let (_b, app, middle) = ::app();

    {
        let mut req = ::new_req(app.clone(), "snow☃", "2.0.0");
        ::mock_user(&mut req, ::user("foo"));
        let json = bad_resp!(middle.call(&mut req));
        assert!(json.errors[0].detail.contains("invalid crate name"),
                "{:?}", json.errors);
    }
    {
        let mut req = ::new_req(app, "áccênts", "2.0.0");
        ::mock_user(&mut req, ::user("foo"));
        let json = bad_resp!(middle.call(&mut req));
        assert!(json.errors[0].detail.contains("invalid crate name"),
                "{:?}", json.errors);
    }
}

#[test]
fn new_crate_owner() {
    #[derive(RustcDecodable)] struct O { ok: bool }

    let (_b, app, middle) = ::app();

    // Create a crate under one user
    let mut req = ::new_req(app.clone(), "foo_owner", "1.0.0");
    let u2 = ::mock_user(&mut req, ::user("bar"));
    ::mock_user(&mut req, ::user("foo"));
    let mut response = ok_resp!(middle.call(&mut req));
    ::json::<GoodCrate>(&mut response);

    // Flag the second user as an owner
    let body = r#"{"users":["bar"]}"#;
    let mut response = ok_resp!(middle.call(req.with_path("/api/v1/crates/foo_owner/owners")
                                               .with_method(Method::Put)
                                               .with_body(body.as_bytes())));
    assert!(::json::<O>(&mut response).ok);
    bad_resp!(middle.call(req.with_path("/api/v1/crates/foo_owner/owners")
                             .with_method(Method::Put)
                             .with_body(body.as_bytes())));

    // Make sure this shows up as one of their crates.
    let query = format!("user_id={}", u2.id);
    let mut response = ok_resp!(middle.call(req.with_path("/api/v1/crates")
                                               .with_method(Method::Get)
                                               .with_query(&query)));
    assert_eq!(::json::<CrateList>(&mut response).crates.len(), 1);

    // And upload a new crate as the first user
    let body = ::new_req_body_version_2(::krate("foo_owner"));
    req.mut_extensions().insert(u2);
    let mut response = ok_resp!(middle.call(req.with_path("/api/v1/crates/new")
                                               .with_method(Method::Put)
                                               .with_body(&body)));
    ::json::<GoodCrate>(&mut response);
}

#[test]
fn valid_feature_names() {
    assert!(Crate::valid_feature_name("foo"));
    assert!(!Crate::valid_feature_name(""));
    assert!(!Crate::valid_feature_name("/"));
    assert!(!Crate::valid_feature_name("%/%"));
    assert!(Crate::valid_feature_name("a/a"));
}

#[test]
fn new_krate_too_big() {
    let (_b, app, middle) = ::app();
    let mut req = ::new_req(app, "foo_big", "1.0.0");
    ::mock_user(&mut req, ::user("foo"));
    let body = ::new_crate_to_body(&new_crate("foo_big"), &[b'a'; 2000]);
    bad_resp!(middle.call(req.with_body(&body)));
}

#[test]
fn new_krate_too_big_but_whitelisted() {
    let (_b, app, middle) = ::app();
    let mut req = ::new_req(app, "foo_whitelist", "1.1.0");
    ::mock_user(&mut req, ::user("foo"));
    let mut krate = ::krate("foo_whitelist");
    krate.max_upload_size = Some(2 * 1000 * 1000);
    ::mock_crate(&mut req, krate);
    let body = ::new_crate_to_body(&new_crate("foo_whitelist"), &[b'a'; 2000]);
    let mut response = ok_resp!(middle.call(req.with_body(&body)));
    ::json::<GoodCrate>(&mut response);
}

#[test]
fn new_krate_duplicate_version() {
    let (_b, app, middle) = ::app();
    let mut req = ::new_req(app, "foo_dupe", "1.0.0");
    ::mock_user(&mut req, ::user("foo"));
    ::mock_crate(&mut req, ::krate("foo_dupe"));
    let json = bad_resp!(middle.call(&mut req));
    assert!(json.errors[0].detail.contains("already uploaded"),
            "{:?}", json.errors);
}

#[test]
fn new_crate_similar_name() {
    let (_b, app, middle) = ::app();
    let mut req = ::new_req(app, "foo_similar", "1.1.0");
    ::mock_user(&mut req, ::user("foo"));
    ::mock_crate(&mut req, ::krate("Foo_similar"));
    let json = bad_resp!(middle.call(&mut req));
    assert!(json.errors[0].detail.contains("previously named"),
            "{:?}", json.errors);
}

#[test]
fn new_crate_similar_name_hyphen() {
    {
        let (_b, app, middle) = ::app();
        let mut req = ::new_req(app, "foo-bar-hyphen", "1.1.0");
        ::mock_user(&mut req, ::user("foo"));
        ::mock_crate(&mut req, ::krate("foo_bar_hyphen"));
        let json = bad_resp!(middle.call(&mut req));
        assert!(json.errors[0].detail.contains("previously named"),
                "{:?}", json.errors);
    }
    {
        let (_b, app, middle) = ::app();
        let mut req = ::new_req(app, "foo_bar_underscore", "1.1.0");
        ::mock_user(&mut req, ::user("foo"));
        ::mock_crate(&mut req, ::krate("foo-bar-underscore"));
        let json = bad_resp!(middle.call(&mut req));
        assert!(json.errors[0].detail.contains("previously named"),
                "{:?}", json.errors);
    }
}

#[test]
fn new_krate_git_upload() {
    let (_b, app, middle) = ::app();
    let mut req = ::new_req(app, "fgt", "1.0.0");
    ::mock_user(&mut req, ::user("foo"));
    let mut response = ok_resp!(middle.call(&mut req));
    ::json::<GoodCrate>(&mut response);

    let path = ::git::checkout().join("3/f/fgt");
    assert!(path.exists());
    let mut contents = String::new();
    File::open(&path).unwrap().read_to_string(&mut contents).unwrap();
    let p: GitCrate = json::decode(&contents).unwrap();
    assert_eq!(p.name, "fgt");
    assert_eq!(p.vers, "1.0.0");
    assert!(p.deps.is_empty());
    assert_eq!(p.cksum,
               "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855");
}

#[test]
fn new_krate_git_upload_appends() {
    let (_b, app, middle) = ::app();
    let path = ::git::checkout().join("3/f/fpp");
    fs::create_dir_all(path.parent().unwrap()).unwrap();
    File::create(&path).unwrap().write_all(
        br#"{"name":"FPP","vers":"0.0.1","deps":[],"cksum":"3j3"}
"#).unwrap();

    let mut req = ::new_req(app, "FPP", "1.0.0");
    ::mock_user(&mut req, ::user("foo"));
    let mut response = ok_resp!(middle.call(&mut req));
    ::json::<GoodCrate>(&mut response);

    let mut contents = String::new();
    File::open(&path).unwrap().read_to_string(&mut contents).unwrap();
    let mut lines = contents.lines();
    let p1: GitCrate = json::decode(lines.next().unwrap().trim()).unwrap();
    let p2: GitCrate = json::decode(lines.next().unwrap().trim()).unwrap();
    assert!(lines.next().is_none());
    assert_eq!(p1.name, "FPP");
    assert_eq!(p1.vers, "0.0.1");
    assert!(p1.deps.is_empty());
    assert_eq!(p2.name, "FPP");
    assert_eq!(p2.vers, "1.0.0");
    assert!(p2.deps.is_empty());
}

#[test]
fn new_krate_git_upload_with_conflicts() {
    let (_b, app, middle) = ::app();

    {
        let repo = git2::Repository::open(&::git::bare()).unwrap();
        let target = repo.head().unwrap().target().unwrap();
        let sig = repo.signature().unwrap();
        let parent = repo.find_commit(target).unwrap();
        let tree = repo.find_tree(parent.tree_id()).unwrap();
        repo.commit(Some("HEAD"), &sig, &sig, "empty commit", &tree,
                    &[&parent]).unwrap();
    }

    let mut req = ::new_req(app, "foo_conflicts", "1.0.0");
    ::mock_user(&mut req, ::user("foo"));
    let mut response = ok_resp!(middle.call(&mut req));
    ::json::<GoodCrate>(&mut response);
}

#[test]
fn new_krate_dependency_missing() {
    let (_b, app, middle) = ::app();
    let dep = u::CrateDependency {
        optional: false,
        default_features: true,
        name: u::CrateName("bar_missing".to_string()),
        features: Vec::new(),
        version_req: u::CrateVersionReq(semver::VersionReq::parse(">= 0.0.0").unwrap()),
        target: None,
        kind: None,
    };
    let mut req = ::new_req_full(app, ::krate("foo_missing"), "1.0.0", vec![dep]);
    ::mock_user(&mut req, ::user("foo"));
    let mut response = ok_resp!(middle.call(&mut req));
    let json = ::json::<::Bad>(&mut response);
    assert!(json.errors[0].detail
                .contains("no known crate named `bar_missing`"));
}

#[test]
fn summary_doesnt_die() {
    let (_b, app, middle) = ::app();
    let mut req = ::req(app, Method::Get, "/summary");
    ok_resp!(middle.call(&mut req));
}

#[test]
fn download() {
    let (_b, app, middle) = ::app();
    let mut req = ::req(app, Method::Get, "/api/v1/crates/foo_download/1.0.0/download");
    ::mock_user(&mut req, ::user("foo"));
    ::mock_crate(&mut req, ::krate("foo_download"));
    let resp = t_resp!(middle.call(&mut req));
    assert_eq!(resp.status.0, 302);

    req.with_path("/api/v1/crates/foo_download/1.0.0/downloads");
    let mut resp = ok_resp!(middle.call(&mut req));
    let downloads = ::json::<Downloads>(&mut resp);
    assert_eq!(downloads.version_downloads.len(), 1);

    req.with_path("/api/v1/crates/FOO_DOWNLOAD/1.0.0/download");
    let resp = t_resp!(middle.call(&mut req));
    assert_eq!(resp.status.0, 302);

    req.with_path("/api/v1/crates/FOO_DOWNLOAD/1.0.0/downloads");
    let mut resp = ok_resp!(middle.call(&mut req));
    let downloads = ::json::<Downloads>(&mut resp);
    assert_eq!(downloads.version_downloads.len(), 1);
}

#[test]
fn download_bad() {
    let (_b, app, middle) = ::app();
    let mut req = ::req(app, Method::Get, "/api/v1/crates/foo_bad/0.1.0/download");
    ::mock_user(&mut req, ::user("foo"));
    ::mock_crate(&mut req, ::krate("foo_bad"));
    let mut response = ok_resp!(middle.call(&mut req));
    ::json::<::Bad>(&mut response);
}

#[test]
fn dependencies() {
    let (_b, app, middle) = ::app();

    let mut req = ::req(app, Method::Get, "/api/v1/crates/foo_deps/1.0.0/dependencies");
    ::mock_user(&mut req, ::user("foo"));
    let (_, v) = ::mock_crate(&mut req, ::krate("foo_deps"));
    let (c, _) = ::mock_crate(&mut req, ::krate("bar_deps"));
    ::mock_dep(&mut req, &v, &c, None);

    let mut response = ok_resp!(middle.call(&mut req));
    let deps = ::json::<Deps>(&mut response);
    assert_eq!(deps.dependencies[0].crate_id, "bar_deps");

    req.with_path("/api/v1/crates/foo_deps/1.0.2/dependencies");
    let mut response = ok_resp!(middle.call(&mut req));
    ::json::<::Bad>(&mut response);
}

#[test]
fn following() {
    #[derive(RustcDecodable)] struct F { following: bool }
    #[derive(RustcDecodable)] struct O { ok: bool }

    let (_b, app, middle) = ::app();
    let mut req = ::req(app, Method::Get, "/api/v1/crates/foo_following/following");
    ::mock_user(&mut req, ::user("foo"));
    ::mock_crate(&mut req, ::krate("foo_following"));

    let mut response = ok_resp!(middle.call(&mut req));
    assert!(!::json::<F>(&mut response).following);

    req.with_path("/api/v1/crates/foo_following/follow")
       .with_method(Method::Put);
    let mut response = ok_resp!(middle.call(&mut req));
    assert!(::json::<O>(&mut response).ok);
    let mut response = ok_resp!(middle.call(&mut req));
    assert!(::json::<O>(&mut response).ok);

    req.with_path("/api/v1/crates/foo_following/following")
       .with_method(Method::Get);
    let mut response = ok_resp!(middle.call(&mut req));
    assert!(::json::<F>(&mut response).following);

    req.with_path("/api/v1/crates")
       .with_query("following=1");
    let mut response = ok_resp!(middle.call(&mut req));
    let l = ::json::<CrateList>(&mut response);
    assert_eq!(l.crates.len(), 1);

    req.with_path("/api/v1/crates/foo_following/follow")
       .with_method(Method::Delete);
    let mut response = ok_resp!(middle.call(&mut req));
    assert!(::json::<O>(&mut response).ok);
    let mut response = ok_resp!(middle.call(&mut req));
    assert!(::json::<O>(&mut response).ok);

    req.with_path("/api/v1/crates/foo_following/following")
       .with_method(Method::Get);
    let mut response = ok_resp!(middle.call(&mut req));
    assert!(!::json::<F>(&mut response).following);

    req.with_path("/api/v1/crates")
       .with_query("following=1")
       .with_method(Method::Get);
    let mut response = ok_resp!(middle.call(&mut req));
    assert_eq!(::json::<CrateList>(&mut response).crates.len(), 0);
}

#[test]
fn owners() {
    #[derive(RustcDecodable)] struct R { users: Vec<EncodableUser> }
    #[derive(RustcDecodable)] struct O { ok: bool }

    let (_b, app, middle) = ::app();
    let mut req = ::req(app, Method::Get, "/api/v1/crates/foo_owners/owners");
    let other = ::user("foobar");
    ::mock_user(&mut req, other);
    ::mock_user(&mut req, ::user("foo"));
    ::mock_crate(&mut req, ::krate("foo_owners"));

    let mut response = ok_resp!(middle.call(&mut req));
    let r: R = ::json(&mut response);
    assert_eq!(r.users.len(), 1);

    let mut response = ok_resp!(middle.call(req.with_method(Method::Get)));
    let r: R = ::json(&mut response);
    assert_eq!(r.users.len(), 1);

    let body = r#"{"users":["foobar"]}"#;
    let mut response = ok_resp!(middle.call(req.with_method(Method::Put)
                                               .with_body(body.as_bytes())));
    assert!(::json::<O>(&mut response).ok);

    let mut response = ok_resp!(middle.call(req.with_method(Method::Get)));
    let r: R = ::json(&mut response);
    assert_eq!(r.users.len(), 2);

    let body = r#"{"users":["foobar"]}"#;
    let mut response = ok_resp!(middle.call(req.with_method(Method::Delete)
                                               .with_body(body.as_bytes())));
    assert!(::json::<O>(&mut response).ok);

    let mut response = ok_resp!(middle.call(req.with_method(Method::Get)));
    let r: R = ::json(&mut response);
    assert_eq!(r.users.len(), 1);

    let body = r#"{"users":["foo"]}"#;
    let mut response = ok_resp!(middle.call(req.with_method(Method::Delete)
                                               .with_body(body.as_bytes())));
    ::json::<::Bad>(&mut response);

    let body = r#"{"users":["foobar"]}"#;
    let mut response = ok_resp!(middle.call(req.with_method(Method::Put)
                                               .with_body(body.as_bytes())));
    assert!(::json::<O>(&mut response).ok);
}

#[test]
fn yank() {
    #[derive(RustcDecodable)] struct O { ok: bool }
    #[derive(RustcDecodable)] struct V { version: EncodableVersion }
    let (_b, app, middle) = ::app();
    let path = ::git::checkout().join("3/f/fyk");

    // Upload a new crate, putting it in the git index
    let mut req = ::new_req(app, "fyk", "1.0.0");
    ::mock_user(&mut req, ::user("foo"));
    let mut response = ok_resp!(middle.call(&mut req));
    ::json::<GoodCrate>(&mut response);
    let mut contents = String::new();
    File::open(&path).unwrap().read_to_string(&mut contents).unwrap();
    assert!(contents.contains("\"yanked\":false"));

    // make sure it's not yanked
    let mut r = ok_resp!(middle.call(req.with_method(Method::Get)
                                        .with_path("/api/v1/crates/fyk/1.0.0")));
    assert!(!::json::<V>(&mut r).version.yanked);

    // yank it
    let mut r = ok_resp!(middle.call(req.with_method(Method::Delete)
                                        .with_path("/api/v1/crates/fyk/1.0.0/yank")));
    assert!(::json::<O>(&mut r).ok);
    let mut contents = String::new();
    File::open(&path).unwrap().read_to_string(&mut contents).unwrap();
    assert!(contents.contains("\"yanked\":true"));
    let mut r = ok_resp!(middle.call(req.with_method(Method::Get)
                                        .with_path("/api/v1/crates/fyk/1.0.0")));
    assert!(::json::<V>(&mut r).version.yanked);

    // un-yank it
    let mut r = ok_resp!(middle.call(req.with_method(Method::Put)
                                        .with_path("/api/v1/crates/fyk/1.0.0/unyank")));
    assert!(::json::<O>(&mut r).ok);
    let mut contents = String::new();
    File::open(&path).unwrap().read_to_string(&mut contents).unwrap();
    assert!(contents.contains("\"yanked\":false"));
    let mut r = ok_resp!(middle.call(req.with_method(Method::Get)
                                        .with_path("/api/v1/crates/fyk/1.0.0")));
    assert!(!::json::<V>(&mut r).version.yanked);
}

#[test]
fn yank_not_owner() {
    let (_b, app, middle) = ::app();
    let mut req = ::req(app, Method::Delete, "/api/v1/crates/foo_not/1.0.0/yank");
    ::mock_user(&mut req, ::user("foo"));
    ::mock_crate(&mut req, ::krate("foo_not"));
    ::mock_user(&mut req, ::user("bar"));
    let mut response = ok_resp!(middle.call(&mut req));
    ::json::<::Bad>(&mut response);
}

#[test]
fn bad_keywords() {
    let (_b, app, middle) = ::app();
    {
        let krate = ::krate("foo_bad_key");
        let kws = vec!["super-long-keyword-name-oh-no".into()];
        let mut req = ::new_req_with_keywords(app.clone(), krate, "1.0.0", kws);
        ::mock_user(&mut req, ::user("foo"));
        let mut response = ok_resp!(middle.call(&mut req));
        ::json::<::Bad>(&mut response);
    }
    {
        let krate = ::krate("foo_bad_key2");
        let kws = vec!["?@?%".into()];
        let mut req = ::new_req_with_keywords(app.clone(), krate, "1.0.0", kws);
        ::mock_user(&mut req, ::user("foo"));
        let mut response = ok_resp!(middle.call(&mut req));
        ::json::<::Bad>(&mut response);
    }
    {
        let krate = ::krate("foo_bad_key_3");
        let kws = vec!["?@?%".into()];
        let mut req = ::new_req_with_keywords(app.clone(), krate, "1.0.0", kws);
        ::mock_user(&mut req, ::user("foo"));
        let mut response = ok_resp!(middle.call(&mut req));
        ::json::<::Bad>(&mut response);
    }
    {
        let krate = ::krate("foo_bad_key4");
        let kws = vec!["áccênts".into()];
        let mut req = ::new_req_with_keywords(app.clone(), krate, "1.0.0", kws);
        ::mock_user(&mut req, ::user("foo"));
        let mut response = ok_resp!(middle.call(&mut req));
        ::json::<::Bad>(&mut response);
    }
}

#[test]
fn good_categories() {
    let (_b, app, middle) = ::app();
    let krate = ::krate("foo_good_cat");
    let cats = vec!["cat1".into()];
    let mut req = ::new_req_with_categories(app, krate, "1.0.0", cats);
    ::mock_category(&mut req, "cat1", "cat1");
    ::mock_user(&mut req, ::user("foo"));
    let mut response = ok_resp!(middle.call(&mut req));
    let json: GoodCrate = ::json(&mut response);
    assert_eq!(json.krate.name, "foo_good_cat");
    assert_eq!(json.krate.max_version, "1.0.0");
    assert_eq!(json.warnings.invalid_categories.len(), 0);
}

#[test]
fn ignored_categories() {
    let (_b, app, middle) = ::app();
    let krate = ::krate("foo_ignored_cat");
    let cats = vec!["bar".into()];
    let mut req = ::new_req_with_categories(app, krate, "1.0.0", cats);
    ::mock_user(&mut req, ::user("foo"));
    let mut response = ok_resp!(middle.call(&mut req));
    let json: GoodCrate = ::json(&mut response);
    assert_eq!(json.krate.name, "foo_ignored_cat");
    assert_eq!(json.krate.max_version, "1.0.0");
    assert_eq!(json.warnings.invalid_categories, vec!["bar".to_string()]);
}

#[test]
fn good_badges() {
    let krate = ::krate("foobadger");
    let mut badges = HashMap::new();
    let mut badge_attributes = HashMap::new();
    badge_attributes.insert(
        String::from("repository"),
        String::from("rust-lang/crates.io")
    );
    badges.insert(String::from("travis-ci"), badge_attributes);

    let (_b, app, middle) = ::app();
    let mut req = ::new_req_with_badges(app, krate.clone(), "1.0.0", badges);

    ::mock_user(&mut req, ::user("foo"));
    let mut response = ok_resp!(middle.call(&mut req));

    let json: GoodCrate = ::json(&mut response);
    assert_eq!(json.krate.name, "foobadger");
    assert_eq!(json.krate.max_version, "1.0.0");

    let mut response = ok_resp!(
        middle.call(req.with_method(Method::Get)
                       .with_path("/api/v1/crates/foobadger")));

    let json: CrateResponse = ::json(&mut response);

    let badges = json.krate.badges.unwrap();
    assert_eq!(badges.len(), 1);
    assert_eq!(badges[0].badge_type, "travis-ci");
    assert_eq!(
        badges[0].attributes.get("repository").unwrap(),
        &String::from("rust-lang/crates.io")
    );
}

#[test]
fn ignored_badges() {
    let krate = ::krate("foo_ignored_badge");
    let mut badges = HashMap::new();

    // Known badge type, missing required repository attribute
    let mut badge_attributes = HashMap::new();
    badge_attributes.insert(
        String::from("branch"),
        String::from("master")
    );
    badges.insert(String::from("travis-ci"), badge_attributes);

    // Unknown badge type
    let mut unknown_badge_attributes = HashMap::new();
    unknown_badge_attributes.insert(
        String::from("repository"),
        String::from("rust-lang/rust")
    );
    badges.insert(String::from("not-a-badge"), unknown_badge_attributes);

    let (_b, app, middle) = ::app();
    let mut req = ::new_req_with_badges(app, krate.clone(), "1.0.0", badges);

    ::mock_user(&mut req, ::user("foo"));
    let mut response = ok_resp!(middle.call(&mut req));

    let json: GoodCrate = ::json(&mut response);
    assert_eq!(json.krate.name, "foo_ignored_badge");
    assert_eq!(json.krate.max_version, "1.0.0");
    assert_eq!(json.warnings.invalid_badges.len(), 2);
    assert!(json.warnings.invalid_badges.contains(&"travis-ci".to_string()));
    assert!(json.warnings.invalid_badges.contains(&"not-a-badge".to_string()));

    let mut response = ok_resp!(
        middle.call(req.with_method(Method::Get)
                       .with_path("/api/v1/crates/foo_ignored_badge")));

    let json: CrateResponse = ::json(&mut response);

    let badges = json.krate.badges.unwrap();
    assert_eq!(badges.len(), 0);
}

#[test]
fn reverse_dependencies() {
    let (_b, app, middle) = ::app();

    let v100 = semver::Version::parse("1.0.0").unwrap();
    let v110 = semver::Version::parse("1.1.0").unwrap();
    let mut req = ::req(app, Method::Get,
                        "/api/v1/crates/c1/reverse_dependencies");
    ::mock_user(&mut req, ::user("foo"));
    let (c1, _) = ::mock_crate_vers(&mut req, ::krate("c1"), &v100);
    let (_, c2v1) = ::mock_crate_vers(&mut req, ::krate("c2"), &v100);
    let (_, c2v2) = ::mock_crate_vers(&mut req, ::krate("c2"), &v110);

    ::mock_dep(&mut req, &c2v1, &c1, None);
    ::mock_dep(&mut req, &c2v2, &c1, None);
    ::mock_dep(&mut req, &c2v2, &c1, Some("foo"));

    let mut response = ok_resp!(middle.call(&mut req));
    let deps = ::json::<RevDeps>(&mut response);
    assert_eq!(deps.dependencies.len(), 1);
    assert_eq!(deps.meta.total, 1);
    assert_eq!(deps.dependencies[0].crate_id, "c2");

    // c1 has no dependent crates.
    req.with_path("/api/v1/crates/c2/reverse_dependencies");
    let mut response = ok_resp!(middle.call(&mut req));
    let deps = ::json::<RevDeps>(&mut response);
    assert_eq!(deps.dependencies.len(), 0);
    assert_eq!(deps.meta.total, 0);
}

#[test]
fn author_license_and_description_required() {
    let (_b, app, middle) = ::app();
    ::user("foo");

    let mut req = ::req(app, Method::Put, "/api/v1/crates/new");
    let mut new_crate = new_crate("foo_metadata");
    new_crate.license = None;
    new_crate.description = None;
    new_crate.authors = Vec::new();
    req.with_body(&::new_crate_to_body(&new_crate, &[]));
    let json = bad_resp!(middle.call(&mut req));
    assert!(json.errors[0].detail.contains("author") &&
            json.errors[0].detail.contains("description") &&
            json.errors[0].detail.contains("license"),
            "{:?}", json.errors);

    new_crate.license = Some("MIT".to_string());
    new_crate.authors.push("".to_string());
    req.with_body(&::new_crate_to_body(&new_crate, &[]));
    let json = bad_resp!(middle.call(&mut req));
    assert!(json.errors[0].detail.contains("author") &&
            json.errors[0].detail.contains("description") &&
            !json.errors[0].detail.contains("license"),
            "{:?}", json.errors);

    new_crate.license = None;
    new_crate.license_file = Some("foo".to_string());
    new_crate.authors.push("foo".to_string());
    req.with_body(&::new_crate_to_body(&new_crate, &[]));
    let json = bad_resp!(middle.call(&mut req));
    assert!(!json.errors[0].detail.contains("author") &&
            json.errors[0].detail.contains("description") &&
            !json.errors[0].detail.contains("license"),
            "{:?}", json.errors);
}


text:
package httpjson

func (h *HTTPJSON) SampleConfig() string {
	return `{{ .SampleConfig }}`
}

redpajama_set_name: RedPajamaGithub


text:
This operation can be used to modify the role of a user within an organization.

Only administrators of the organization can invoke this operation.

### Resource URL

`https://api.cavellc.io/organizations/{name}/users/{email}`

### Resource Information

The data must be formatted as JSON, with the following fields:

Field | Description | Notes
:---- | :---------- | :----
role | The role the user should have for this organization | Mandatory

The request must be authenticated with a valid user token, as obtained from a login operation. See [POST /users/login](../users/login.md) for details. The token can be passed as the username (with an empty password) following the Basic Authentication scheme of the HTTP protocol. Alternatively, the same token can be accepted as a Bearer Token, similar to the OAuth2 specification.

### Example Request

    curl -i -u 8b896055-c295-4a30-a29c-5a97d15f1818: \
         -X PATCH  -H "Content-Type: application/json" \
         -d '{ "role": "admin" }' \
         https://api.cavellc.io/organizations/acme/users/vdumitrescu%40gilt.com

### Example Response

    HTTP/1.1 202 Accepted
    Content-Length: 0
    Connection: keep-alive

### See Also

* [Create organization](create-org.md)
* [Retrieve organization info](get-org.md)
* [Update organization](update-org.md)
* [Delete organization](delete-org.md)
* [Retrieve organization users](get-org-users.md)
* [Add user to organization](add-org-user.md)
* [Remove user from organization](remove-org-user.md)

[Back to Organizations](README.md)

[Back to API Main Page](../api.md)


text:
<?php

defined('IN_CODE') or die('This script can not be run by itself.');

?>

Sort order for units:

		Unit type:<select name="userForm[unitOrder]">
			<option value='Mixed'<?php if($User->unitOrder=='Mixed') print "selected"; ?>>Mixed</option>
			<option value='FA'   <?php if($User->unitOrder=='FA')    print "selected"; ?>>Fleets -> Armies</option>
			<option value='AF'   <?php if($User->unitOrder=='AF')    print "selected"; ?>>Armies -> Fleets</option>
		</select> -
		Sort by: <select name="userForm[sortOrder]">
			<option value='BuildOrder'<?php if($User->sortOrder=='BuildOrder') print "selected"; ?>>Build Order</option>
			<option value='TerrName'  <?php if($User->sortOrder=='TerrName')   print "selected"; ?>>Territory Name</option>
			<option value='NorthSouth'<?php if($User->sortOrder=='NorthSouth') print "selected"; ?>>North -> South</option>
			<option value='EastWest'  <?php if($User->sortOrder=='EastWest')   print "selected"; ?>>East -> West</option>
		</select>

		How should the units be sorted in the command overview.

Show countryname:

		In global chat:
		<input type="radio" name="userForm[showCountryNames]" value="Yes" <?php if($User->showCountryNames=='Yes') print "checked"; ?>>Yes
		<input type="radio" name="userForm[showCountryNames]" value="No"  <?php if($User->showCountryNames=='No')  print "checked"; ?>>No

		On the map:
		<input type="radio" name="userForm[showCountryNamesMap]" value="Yes" <?php if($User->showCountryNamesMap=='Yes') print "checked"; ?>>Yes
		<input type="radio" name="userForm[showCountryNamesMap]" value="No"  <?php if($User->showCountryNamesMap=='No')  print "checked"; ?>>No

		Instead of colored chatmessages print the countryname in front of the text and use only black text.
		Print the countryname on the map.

Color vision deficiency setting:

		<select name="userForm[colorCorrect]">
			<option value='Off'        <?php if($User->colorCorrect=='Off')         print "selected"; ?>>Off</option>
			<option value='Protanope'  <?php if($User->colorCorrect=='Protanope')   print "selected"; ?>>Protanope</option>
			<option value='Deuteranope'<?php if($User->colorCorrect=='Deuteranope') print "selected"; ?>>Deuteranope</option>
			<option value='Tritanope'  <?php if($User->colorCorrect=='Tritanope')   print "selected"; ?>>Tritanope</option>
		</select>

		Does enhance the colors of the maps for different types of color blindness. (Does not work for the Haven variant, sorry)

<?php
/*
 * This is done in PHP because Eclipse complains about HTML syntax errors otherwise
 * because the starting <form>
 is elsewhere
 */
print '

<input type="submit" class="form-submit notice" value="Update">
</form>';

?>


text:
const mix = require('laravel-mix');

/*
 |--------------------------------------------------------------------------
 | Mix Asset Management
 |--------------------------------------------------------------------------
 |
 | Mix provides a clean, fluent API for defining some Webpack build steps
 | for your Laravel application. By default, we are compiling the Sass
 | file for the application as well as bundling up all the JS files.
 |
 */

const RemovePlugin = require('remove-files-webpack-plugin');
const ESLintPlugin = require('eslint-webpack-plugin');

const removePlugin = new RemovePlugin({

  before: {
    test: [
      {
        folder: 'public',
        method: (filePath) => {
          return new RegExp(/(?:.*\.js|.*\.map|mix-manifest\.json)$/, 'm').test(filePath);
        }
      },
      {
        folder: 'public/js',
        method: (filePath) => {
          return new RegExp(/(?:.*\.js|.*\.map)$/, 'm').test(filePath);
        },
        recursive: true
      },
      {
        folder: 'public/css',
        method: (filePath) => {
          return new RegExp(/(?:.*\.css|.*\.map)$/, 'm').test(filePath);
        }
      }
    ]
  },

  after: {}
})

mix.webpackConfig({
  plugins: [removePlugin, new ESLintPlugin()],
});

mix.js('resources/js/app.js', 'public/js').react()
  .extract(['@popperjs/core', 'axios', 'bootstrap', 'clsx', 'font-awesome', 'history', 'jquery', 'lodash', 'moment', 'prop-types', 'react', 'react-document-title', 'react-dom', 'react-loadable', 'react-redux', 'react-router-dom', 'reactstrap', 'redux', 'redux-thunk', 'ree-validate'])
  .sass('resources/sass/app.scss', 'public/css')
  .sourceMaps(false, 'source-map')

if (mix.inProduction()) {
  mix.version();
}

if (!mix.inProduction()) {
  mix.browserSync('http://localhost:8100')
}


text:
<?php

class a { }
interface b { }
trait c { }
abstract class d { }
final class e { }

var_dump(get_declared_traits());

?>


text:
package messageimpl;

public class AppliedADJIFYP
{
	public static String appliedAdjIfydIntent(String channel, String period, String user_region, String user_circle, String userzone , String real_tim_timstamp,
			String mtd_applied_adj_ifyp , String ytd_applied_adj_ifyp, String subchannel,String user_clusters, String user_go )

	{
		String finalresponse="";
		if("MLI".equalsIgnoreCase(channel))
		{channel="";}
		if("Monthly".equalsIgnoreCase(period))
		{period="";}
		else
		{
			if("FTD".equalsIgnoreCase(period))
			{
				period="MTD";
			}
			else
			{
				period=period.toUpperCase();
			}
		}
		if(!"".equalsIgnoreCase(user_circle))
		{
			user_region="Circle "+user_circle;
		}
		if(!"".equalsIgnoreCase(user_go))
		{
			user_clusters="Office "+user_go;
		}
		if(!"".equalsIgnoreCase(subchannel))
		{
		        channel = subchannel;
		}
		if("".equalsIgnoreCase(channel) && "".equalsIgnoreCase(userzone) && "".equalsIgnoreCase(user_region)
		  && "".equalsIgnoreCase(user_clusters) && "".equalsIgnoreCase(period))
		{
			finalresponse= "As of "+real_tim_timstamp+" Applied Business Adj IFYP MTD for MLI "
					+ mtd_applied_adj_ifyp+"Cr. Applied Business Adj IFYP YTD for MLI "+ytd_applied_adj_ifyp+
					"Cr. If you want to see the channel wise business numbers, please specify";
		}else if(!"".equalsIgnoreCase(channel) && "".equalsIgnoreCase(userzone) && "".equalsIgnoreCase(user_region)
			&& "".equalsIgnoreCase(user_clusters) && "".equalsIgnoreCase(period))
		{
			finalresponse= "As of "+real_tim_timstamp+" Applied Business Adj IFYP MTD for "+channel+" is "+mtd_applied_adj_ifyp+
					"Cr. Applied Business Adj IFYP YTD for "+channel+" is "+ytd_applied_adj_ifyp+
					"Cr. If you want to see the zone/region wise business numbers, please specify";
		}else if(!"".equalsIgnoreCase(channel) && !"".equalsIgnoreCase(userzone) && "".equalsIgnoreCase(user_region)
			&& "".equalsIgnoreCase(user_clusters) && "".equalsIgnoreCase(period))
		{
			finalresponse="As of "+real_tim_timstamp+" Applied Business Adj IFYP MTD for "+userzone+ " zone is "+ mtd_applied_adj_ifyp+
					"Cr. Applied Business Adj IFYP YTD for "+userzone+" zone is "+ytd_applied_adj_ifyp+
					"Cr. If you want to see the region wise business numbers, please specify";

		}else if(!"".equalsIgnoreCase(channel) && !"".equalsIgnoreCase(userzone) && !"".equalsIgnoreCase(user_region)
			&& "".equalsIgnoreCase(user_clusters) && "".equalsIgnoreCase(period))
		{
			finalresponse="As of "+real_tim_timstamp+ " Applied Business Adj IFYP MTD for "+user_region+" is "+mtd_applied_adj_ifyp+
					"Cr. Applied Business Adj IFYP YTD for "+user_region+" is "+ytd_applied_adj_ifyp+" Cr.";
		}
		else if(!"".equalsIgnoreCase(channel) && !"".equalsIgnoreCase(userzone) && !"".equalsIgnoreCase(user_region)
			&& !"".equalsIgnoreCase(user_clusters) && "".equalsIgnoreCase(period))
		{
			finalresponse="As of "+real_tim_timstamp+ " Applied Business Adj IFYP MTD for "+user_clusters+" is "+mtd_applied_adj_ifyp+
					"Cr. Applied Business Adj IFYP YTD for "+user_clusters+" is "+ytd_applied_adj_ifyp+" Cr.";
		}
		else if(!"".equalsIgnoreCase(channel) && "".equalsIgnoreCase(userzone) && !"".equalsIgnoreCase(user_region)
			&& !"".equalsIgnoreCase(user_clusters) && "".equalsIgnoreCase(period))
		{
			finalresponse="As of "+real_tim_timstamp+ " Applied Business Adj IFYP MTD for "+user_clusters+" is "+mtd_applied_adj_ifyp+
					"Cr. Applied Business Adj IFYP YTD for "+user_clusters+" is "+ytd_applied_adj_ifyp+" Cr.";
		}
		else if(!"".equalsIgnoreCase(channel) && "".equalsIgnoreCase(userzone) && "".equalsIgnoreCase(user_region)
			&& !"".equalsIgnoreCase(user_clusters) && "".equalsIgnoreCase(period))
		{
			finalresponse="As of "+real_tim_timstamp+ " Applied Business Adj IFYP MTD for "+user_clusters+" is "+mtd_applied_adj_ifyp+
					"Cr. Applied Business Adj IFYP YTD for "+user_clusters+" is "+ytd_applied_adj_ifyp+" Cr.";
		}
		else if(!"".equalsIgnoreCase(channel) && "".equalsIgnoreCase(userzone) && !"".equalsIgnoreCase(user_region)
			&& "".equalsIgnoreCase(user_clusters) && "".equalsIgnoreCase(period))
		{
			finalresponse="As of "+real_tim_timstamp+ " Applied Business Adj IFYP MTD for "+user_region+" is "+mtd_applied_adj_ifyp+
					"Cr. Applied Business Adj IFYP YTD for "+user_region+" is "+ytd_applied_adj_ifyp+" Cr.";
		}
		else if(!"".equalsIgnoreCase(channel) && "".equalsIgnoreCase(userzone) && "".equalsIgnoreCase(user_region)
			&& !"".equalsIgnoreCase(period)&& "".equalsIgnoreCase(user_clusters))
		{
			if("YTD".equalsIgnoreCase(period))
			{
				finalresponse="As of" +real_tim_timstamp+ " Applied Business Adj IFYP " +period+" for "+channel+ "is"+ ytd_applied_adj_ifyp+
						"Cr. If you want to see the zone/region wise business numbers, please specify";
			}else
			{
				finalresponse="As of" +real_tim_timstamp+ " Applied Business Adj IFYP " +period+" for "+channel+ "is"+ mtd_applied_adj_ifyp+
						"Cr. If you want to see the zone/region wise business numbers, please specify";
			}
		}else if(!"".equalsIgnoreCase(channel) && !"".equalsIgnoreCase(userzone) && "".equalsIgnoreCase(user_region)
			 && !"".equalsIgnoreCase(period)&& "".equalsIgnoreCase(user_clusters))
		{
			if("YTD".equalsIgnoreCase(period))
			{
				finalresponse="As of "+real_tim_timstamp+" Applied Business Adj IFYP "+period+" for "+userzone+" zone is "+ytd_applied_adj_ifyp+
						". If you want to see the region wise business numbers, please specify";
			}else
			{
				finalresponse="As of "+real_tim_timstamp+" Applied Business Adj IFYP "+period+" for "+userzone+" zone is "+mtd_applied_adj_ifyp+
						". If you want to see the region wise business numbers, please specify";
			}
		}
		else if(!"".equalsIgnoreCase(channel) && "".equalsIgnoreCase(userzone) && !"".equalsIgnoreCase(user_region)
			&& !"".equalsIgnoreCase(period)&& "".equalsIgnoreCase(user_clusters))
		{
			if("YTD".equalsIgnoreCase(period))
			{
				finalresponse="As of "+real_tim_timstamp+" Applied Business Adj IFYP "+period+" for "+user_region+" is "+ytd_applied_adj_ifyp+" Cr";
			}else
			{
				finalresponse="As of "+real_tim_timstamp+" Applied Business Adj IFYP "+period+" for "+user_region+" is "+mtd_applied_adj_ifyp+" Cr";
			}
		}
		else if(!"".equalsIgnoreCase(channel) && "".equalsIgnoreCase(userzone) && "".equalsIgnoreCase(user_region)
			&& !"".equalsIgnoreCase(period)&& !"".equalsIgnoreCase(user_clusters))
		{
			if("YTD".equalsIgnoreCase(period))
			{
				finalresponse="As of "+real_tim_timstamp+" Applied Business Adj IFYP "+period+" for "+user_clusters+" is "+ytd_applied_adj_ifyp+" Cr";
			}else
			{
				finalresponse="As of "+real_tim_timstamp+" Applied Business Adj IFYP "+period+" for "+user_clusters+" is "+mtd_applied_adj_ifyp+" Cr";
			}
		}
		else if(!"".equalsIgnoreCase(channel) && !"".equalsIgnoreCase(userzone) && !"".equalsIgnoreCase(user_region)
			&& !"".equalsIgnoreCase(period)&& "".equalsIgnoreCase(user_clusters))
		{
			if("YTD".equalsIgnoreCase(period))
			{
				finalresponse="As of "+real_tim_timstamp+" Applied Business Adj IFYP "+period+" for "+user_region+" is "+ytd_applied_adj_ifyp+" Cr";
			}else
			{
				finalresponse="As of "+real_tim_timstamp+" Applied Business Adj IFYP "+period+" for "+user_region+" is "+mtd_applied_adj_ifyp+" Cr";
			}
		}
		else if(!"".equalsIgnoreCase(channel) && !"".equalsIgnoreCase(userzone) && !"".equalsIgnoreCase(user_region)
			&& !"".equalsIgnoreCase(period)&& !"".equalsIgnoreCase(user_clusters))
		{
			if("YTD".equalsIgnoreCase(period))
			{
				finalresponse="As of "+real_tim_timstamp+" Applied Business Adj IFYP "+period+" for "+user_clusters+" is "+ytd_applied_adj_ifyp+" Cr";
			}else
			{
				finalresponse="As of "+real_tim_timstamp+" Applied Business Adj IFYP "+period+" for "+user_clusters+" is "+mtd_applied_adj_ifyp+" Cr";
			}
		}
		else
		{
			if("YTD".equalsIgnoreCase(period))
			{
				finalresponse="As of " +real_tim_timstamp+"  Applied Business Adj IFYP "+period+ " for MLI is "+ytd_applied_adj_ifyp+
						" Cr. If you want to see the channel wise business numbers, please specify";
			}else
			{
				finalresponse="As of " +real_tim_timstamp+"  Applied Business Adj IFYP "+period+ " for MLI is "+mtd_applied_adj_ifyp+
						" Cr. If you want to see the channel wise business numbers, please specify";
			}
		}
		return finalresponse.toString();
	}
}


text:
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <parent>
        <artifactId>motech</artifactId>
        <groupId>org.motechproject</groupId>
        <version>1.0-SNAPSHOT</version>
        <relativePath>../../</relativePath>
    </parent>

    <name>MOTECH Core Config</name>
    <artifactId>motech-platform-config-core</artifactId>
    <version>1.0-SNAPSHOT</version>
    <packaging>bundle</packaging>

    <properties>
        <modules.root.dir>${basedir}/../..</modules.root.dir>
    </properties>

    <dependencies>
        <dependency>
            <groupId>${project.groupId}</groupId>
            <artifactId>motech-platform-commons-api</artifactId>
            <version>${project.version}</version>
        </dependency>
        <dependency>
            <groupId>${project.groupId}</groupId>
            <artifactId>motech-platform-commons-date</artifactId>
            <version>${project.version}</version>
        </dependency>
        <dependency>
            <groupId>org.motechproject</groupId>
            <artifactId>motech-pax-it</artifactId>
            <version>${project.version}</version>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>commons-lang</groupId>
            <artifactId>commons-lang</artifactId>
        </dependency>
        <dependency>
            <groupId>commons-configuration</groupId>
            <artifactId>commons-configuration</artifactId>
        </dependency>
        <dependency>
            <groupId>commons-io</groupId>
            <artifactId>commons-io</artifactId>
        </dependency>
        <dependency>
            <groupId>commons-validator</groupId>
            <artifactId>commons-validator</artifactId>
        </dependency>
        <dependency>
            <groupId>commons-digester</groupId>
            <artifactId>commons-digester</artifactId>
        </dependency>
        <dependency>
            <groupId>org.apache.activemq</groupId>
            <artifactId>org.motechproject.org.apache.activemq</artifactId>
        </dependency>
        <dependency>
            <groupId>org.apache.activemq</groupId>
            <artifactId>kahadb</artifactId>
        </dependency>
        <dependency>
            <groupId>javax.transaction</groupId>
            <artifactId>com.springsource.javax.transaction</artifactId>
        </dependency>
        <dependency>
            <groupId>javax.jms</groupId>
            <artifactId>com.springsource.javax.jms</artifactId>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.apache.felix</groupId>
                <artifactId>maven-bundle-plugin</artifactId>
                <configuration>
                    <instructions>
                        <Export-Package>
                            org.motechproject.config.core.constants;version=${project.version},
                            org.motechproject.config.core.domain;version=${project.version},
                            org.motechproject.config.core.exception;version=${project.version},
                            org.motechproject.config.core.filters;version=${project.version},
                            org.motechproject.config.core.service;version=${project.version},
                            org.motechproject.config.core.validator;version=${project.version}
                       </Export-Package>
                        <Import-Package>
                            org.aopalliance.aop,
                            org.springframework.aop,
                            org.springframework.aop.framework,
                            org.springframework.cache,
                            org.springframework.cache.concurrent,
                            org.springframework.cache.support,
                            org.apache.commons.configuration,
                            *
                        </Import-Package>
                    </instructions>
                </configuration>
            </plugin>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-dependency-plugin</artifactId>
            </plugin>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-resources-plugin</artifactId>
                <executions>
                    <execution>
                        <id>copy-bundles</id>
                        <phase>package</phase>
                        <goals>
                            <goal>copy-resources</goal>
                        </goals>
                        <configuration>
                            <outputDirectory>${user.home}/.motech/bundles</outputDirectory>
                            <resources>
                                <resource>
                                    <directory>target</directory>
                                    <includes>
                                        <include>*.jar</include>
                                    </includes>
                                </resource>
                            </resources>
                        </configuration>
                    </execution>
                    <execution>
                        <id>copy-config</id>
                        <phase>initialize</phase>
                        <goals>
                            <goal>copy-resources</goal>
                        </goals>
                        <configuration>
                            <outputDirectory>${user.home}/.motech</outputDirectory>
                            <resources>
                                <resource>
                                    <directory>src/main/resources</directory>
                                    <filtering>true</filtering>
                                    <includes>
                                        <include>config-locations.properties</include>
                                    </includes>
                                </resource>
                            </resources>
                        </configuration>
                    </execution>
                </executions>
            </plugin>
        </plugins>
    </build>
</project>


text:
<!DOCTYPE html>

		<meta http-equiv="content-type" content="text/html; charset=UTF-8">
		<meta charset="utf-8">
		<title>The Firm - One Page Scroller Template</title>
		<meta name="generator" content="Bootply" />
		<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
		<link href="../../js/bootstrap/bootstrap.min.css" rel="stylesheet">

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

Architectural Design

Interior Design

Renovations & Adaptive Re-use

The Firm

        <button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-collapse">

        </button>

Home

Profile

            Projects

Academic

Commercial

Financial

Interior Design

Medical

Religious

Location

Contact

Since 1923

      The Firm has been providing Professional Design Services in the England area since 1923.

Profile

	  The Firm has had a great deal of experience and is highly regarded for its expertise in the areas of design, construction administration, construction management, tight cost control and scheduling.

	  We have been involved in a wide range of building projects, including college facilities, banks, schools, nursing homes, office buildings, churches, industrial buildings and major urban development projects.

	  The various projects have included new construction, renovation and adaptive re-use as a way of providing new space for the various clients. Tessier Associates provides in-house programming, master planning, architectural design, construction documentation, project administration and interior design services. Sustainable design, as appropriate for each client, is incorporated in cost effective ways to benefit the long term value of the buildings created by the firm.

	  Together with selected consultants, The Firm provides complete professional services including landscape architecture, structural engineering, electrical and mechanical engineering and site planning.

Clients & Partners

Renovations

Academic Institutions

Interiors

New Construction

Site Planning

Churches

Location

      <address>
        The Firm, Inc.

        1500 Main Street

        Springfield, MA 01115

        P: (413) 700-5999
      </address>

      <address>
        Email Us

        first.last@example.com
      </address>

Contact Us

          <input type="text" class="form-control" id="firstName" name="name" placeholder="Your Name">

          <input type="text" class="form-control" id="organization" name="organization" placeholder="Company or Organization">

          <input type="text" class="form-control" name="email" placeholder="Email">

          <input type="text" class="form-control" name="phone" placeholder="Phone">

            <textarea class="form-control" placeholder="Comments"></textarea>

            <button class="btn btn-default pull-right">Contact Us</button>

Copyright ©2014 ACME, Inc.

		<button class="close" type="button" data-dismiss="modal">×</button>

		<button class="btn btn-default" data-dismiss="modal">Close</button>


text:
<?php

namespace Bakkerij\Bundle\Repository;
use Doctrine\ORM\EntityRepository;

class CategorieRepository extends EntityRepository {

}


text:
import Meteor from 'react-native-meteor';
// import { Actions } from 'react-native-router-flux';

import AppUtil from '../lib/util';
import AppConfig from '../constants/config';
// import Network from '../network';

import Constants from './constants';
import VCUtil from '../network/VCUtil';

const PushNotification = require('react-native-push-notification');

class PushService {

  init() {
    PushService._token = undefined;
    // setup notifications
    PushNotification.configure({

      // (optional) Called when Token is generated (iOS and Android)
      onRegister(token) {
        AppUtil.debug(token, Constants.MODULE);
        // Alert.alert('TOKEN', JSON.stringify(token));
        PushService._token = token;
      },

      // (required) Called when a remote or local notification is opened or received
      onNotification(notification) {
        // Alert.alert('NOTIFICATION', JSON.stringify(notification));
        AppUtil.debug(notification, 'PUSH Notification');
        console.log('Kumar pushy', notification);

        // lets clear the badge
        PushNotification.setApplicationIconBadgeNumber(0);
        console.log('Kumar pushy', notification);
        if (notification && notification.ejson) {
          const pushData = JSON.parse(notification.ejson);
          const pushMsg = notification.message;
          console.log('Kumar push', pushData, pushMsg);

          if (pushData.name === null && pushMsg === 'Started a call' && !notification.foreground) {
            PushService.handlePushAnswer(pushData);
          } else if (pushData.name === null && pushMsg === 'Started a call' && notification.foreground) {
            PushNotification.cancelAllLocalNotifications();
          } else if (pushData.name === null && pushMsg === 'Call Ended') {
            PushService.handlePushDecline();
          }
        }

        // - lets take the user to the correct channel, refresh the contents
        // notification object have
        /*
        { foreground: false,
          soundname: 'default',
          'google.sent_time': 1507607930561,
          summaryText: '%n% new messages',
          msgcnt: '2',
          userInteraction: false,
          id: '1129599577',
          ejson: '{"host":"https://hostname/","rid":"otReF8uZJ6v5irTZC","sender":{"_id":"xvx4w2hLb29SYXsK4","username":"admin","name":"admin"},"type":"c","name":"new-test"}',
          image: 'https://instance/assets/favicon_192.png',
          notId: '579037750',
          style: 'inbox',
          title: '#new-test',
          'google.message_id': '0:1507607930564505%3889947b0034af1a',
          message: 'admin: test1 @eyal ',
          collapse_key: 'push' }
        */
        // take the user to correct channel onthe following logic
        //   - notification is remote (how to differentiate??)
        //   - userInteraction: true
        //   - app is not in foreground - foreground: false
        //   - ejson is there and rid is specified
        if (notification && notification.foreground === false && notification.userInteraction === true &&
          notification.ejson) {
          // Actions.app({ type: 'reset' });
          // Actions.helpView({ type: 'reset' });
          // const data = JSON.parse(notification.ejson);
          // if (data && data.rid) {
          //   const n = new Network();
          //   if (n.db && n.db.groups) {
          //   // lookup group object
          //     const gObj = n.db.groups.findById(data.rid);
          //     if (gObj) {
          //       AppUtil.debug(gObj.heading, 'PUSH - switch screen');
          //       Actions.chatDetail({ obj: gObj, title: gObj.heading });
          //     }
          //   }
          // }
        }
      },

      // ANDROID ONLY: GCM Sender ID (optional - not required for local notifications, but is needed
      // to receive remote push notifications)
      senderID: Constants.SENDER_ID,

      // IOS ONLY (optional): default: all - Permissions to register.
      permissions: {
        alert: true,
        badge: true,
        sound: true,
      },

      // Should the initial notification be popped automatically
      // default: true
      popInitialNotification: true,

      /**
        * (optional) default: true
        * - Specified if permissions (ios) and token (android and ios) will requested or not,
        * - if not, you must call PushNotificationsHandler.requestPermissions() later
        */
      requestPermissions: true,
    });

    PushService.handlePushAnswer = (pushData) => {
      console.log('Kumar push handlePushAnswer', pushData.rid, pushData.sender._id);
      console.log('Kumar push getInstance', VCUtil.getInstance());
      VCUtil.getInstance().incomingVC(pushData.rid, pushData.sender._id, pushData.sender.username);
    };
    PushService.handlePushDecline = () => {
      console.log('Kumar push handlePushDecline');
      VCUtil.getInstance().incomingVCDisconnect();
    };
  }

  // register token, user to backend
  register() {
    if (PushService._token) {
      // Set the data object
      const data = {
        id: Math.random().toString(36).slice(2), // Generate random string
        token: null,
        appName: AppConfig.appName || 'main',
        userId: AppConfig.userId,
        metadata: {},
      };

      if (PushService._token.os === 'android') {
        data.token = {
          gcm: PushService._token.token,
        };
      } else if (PushService._token.os === 'ios') {
        data.token = {
          apn: PushService._token.token,
        };
      }

      // console.log('==============> push =================', data);
      Meteor.call('raix:push-update', data, (err, res) => {
        AppUtil.debug('Push backend', JSON.stringify(res));
      });
      // clear badges on init
      PushNotification.setApplicationIconBadgeNumber(0);
    }
  }

  // -- this method is just for reference
  test() {
    PushNotification.localNotification({
    /* Android Only Properties */
      id: '0', // (optional) Valid unique 32 bit integer specified as string. default: Autogenerated Unique ID
      ticker: 'My Notification Ticker', // (optional)
      autoCancel: true, // (optional) default: true
      largeIcon: 'ic_launcher', // (optional) default: "ic_launcher"
      smallIcon: 'ic_notification', // (optional) default: "ic_notification" with fallback for "ic_launcher"
      bigText: 'My big text that will be shown when notification is expanded', // (optional) default: "message" prop
      subText: 'This is a subText', // (optional) default: none
      color: 'red', // (optional) default: system default
      vibrate: true, // (optional) default: true
      vibration: 300, // vibration length in milliseconds, ignored if vibrate=false, default: 1000
      tag: 'some_tag', // (optional) add tag to message
      group: 'group', // (optional) add group to message
      ongoing: false, // (optional) set whether this is an "ongoing" notification

    /* iOS only properties */
    // alertAction: // (optional) default: view
    // category: // (optional) default: null
    // userInfo: // (optional) default: null (object containing additional notification data)

    /* iOS and Android properties */
      title: 'My Notification Title', // (optional, for iOS this is only used in apple
        // watch, the title will be the app name on other iOS devices)
      message: 'My Notification Message', // (required)
      playSound: false, // (optional) default: true
      soundName: 'default', // (optional) Sound to play when the notification
        // is shown. Value of 'default' plays the default sound. It can be set to a
        // custom sound such as 'android.resource://com.xyz/raw/my_sound'. It will
        // look for the 'my_sound' audio file in 'res/raw' directory and play it.
        // default: 'default' (default sound is played)
      number: 10, // (optional) Valid 32 bit integer specified as string. default: none (Cannot be zero)
      repeatType: 'day', // (Android only) Repeating interval.
        // Could be one of `week`, `day`, `hour`, `minute, `time`. If specified
        // as time, it should be accompanied by one more parameter 'repeatTime` which
        // should the number of milliseconds between each interval
      actions: '["Yes", "No"]',  // (Android only) See the doc for notification actions to know more
    });
    // // console.log('Set ******* notifications *******');
    // PushNotification.localNotificationSchedule({
    //   message: 'My Notification Message', // (required)
    //   date: new Date(Date.now() + (60 * 1000)), // in 60 secs
    // });
  }
}

export default PushService;


text:
package org.kaazing.k3po.driver.internal.http;

import java.util.Random;

import org.kaazing.k3po.lang.el.Function;
import org.kaazing.k3po.lang.el.spi.FunctionMapperSpi;

public final class Functions {

    private static final Random RANDOM = new Random();

    @Function
    public static byte[] randomBytes(int length) {
        byte[] bytes = new byte[length];
        for (int i = 0; i < length; i++) {
            bytes[i] = (byte) RANDOM.nextInt(0x100);
        }
        return bytes;
    }

    public static class Mapper extends FunctionMapperSpi.Reflective {

        public Mapper() {
            super(Functions.class);
        }

        @Override
        public String getPrefixName() {
            return "itest";
        }

    }

    private Functions() {
        // utility
    }

}


text:
using System.Collections.Generic;
using System.Threading.Tasks;
using GRA.Domain.Model;
using GRA.Domain.Model.Filters;

namespace GRA.Domain.Repository
{
    public interface INewsPostRepository : IRepository<NewsPost>
    {
        Task<bool> AnyPublishedPostsAsync(int siteId);
        Task<DataWithCount<IEnumerable<NewsPost>>> PageAsync(NewsFilter filter);
        Task<int> GetLatestActiveIdAsync(BaseFilter filter);
    }
}


text:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">

<!--
 * Licensed to The Apereo Foundation under one or more contributor license
 * agreements. See the NOTICE file distributed with this work for
 * additional information regarding copyright ownership.
 *
 * The Apereo Foundation licenses this file to you under the Apache License,
 * Version 2.0 (the "License"); you may not use this file except in
 * compliance with the License. You may obtain a copy of the License at:
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 -->
<hibernate-mapping package="org.unitime.timetable.model">
    <class name="QueryLog" table="query_log">
        <cache include="non-lazy" usage="transactional"/>
        <id
            name="uniqueId"
            column="uniqueid"
            type="java.lang.Long">
            <generator class="org.unitime.commons.hibernate.id.UniqueIdGenerator">
                <param name="sequence">pref_group_seq</param>
            </generator>
        </id>

        <property
            name="timeStamp"
            column="time_stamp"
            type="java.sql.Timestamp"
            not-null="true"/>

        <property
            name="timeSpent"
            column="time_spent"
            type="java.lang.Long"
            not-null="true"/>

        <property
            name="uri"
            column="uri"
            type="java.lang.String"
            not-null="true"
            length="255"/>

        <property
            name="type"
            column="type"
            type="java.lang.Integer"
            not-null="true"/>

        <property
            name="sessionId"
            column="session_id"
            type="java.lang.String"
            not-null="false"
            length="32"/>

        <property
            name="uid"
            column="userid"
            type="java.lang.String"
            not-null="false"
            length="40"/>

        <property
            name="query"
            column="query"
            type="java.lang.String"
            not-null="false"
            lazy="true"/>

        <property
            name="exception"
            column="exception"
            type="java.lang.String"
            not-null="false"
            lazy="true"/>
    </class>
</hibernate-mapping>


text:
'use strict';

const { couchdbHost, couchdbPort, ldapAuthConfig } = require('../constants');

module.exports = {
  url: `http://${couchdbHost}:${couchdbPort}`,
  port: 3000,
  auth: {
    couchdb: {
      showLogin: true,
    },
    ldap: ldapAuthConfig,
  },
  username: 'rest-on-couch',
  password: 'roc-123',
  adminPassword: 'admin',
  // Already administrator from global configuration
  superAdministrators: ['admin@a.com', 'a@a.com', 'admin@zakodium.com'],
  sessionSigned: true,
  allowedOrigins: ['http://localhost:8080'],
  getUserInfo: function (user) {
    return {
      uid: user.uid,
      displayName: user.displayName,
    };
  },
  getPublicUserInfo(user) {
    return {
      displayName: user.displayName,
      email: user.mail,
    };
  },
};


text:
import 'rxjs/add/operator/switchMap';
import { Component, OnInit } from '@angular/core';
import { Location } from '@angular/common';
import { ActivatedRoute, ParamMap } from '@angular/router';
import { Clinic } from '../../models/clinic';
import { TherapistService } from '../../services/therapist.service';
import { ClinicService } from '../../services/clinic.service';
import { Therapist } from '../../models/therapist';
import { TherapistClinic } from '../../models/therapist-clinic';

@Component({
  selector: 'app-therapist-detail',
  templateUrl: './therapist-detail.component.html',
})
export class TherapistDetailComponent implements OnInit {

  public clinics: Clinic[];

  public therapist: any;

  public therapistClinicId: string;

  constructor(private therapistService: TherapistService,
              private clinicService: ClinicService,
              private route: ActivatedRoute,
              private location: Location) { }

  ngOnInit() {
    this.clinics = this.clinicService.getAll();
    this.route.paramMap
      .switchMap((params: ParamMap) => this.therapistService.getEntity(params.get('id')))
      .subscribe(therapist => this.therapist = <Therapist>therapist);

    this.route.paramMap
      .switchMap((params: ParamMap) => this.getRelatedClinicId(params.get('id')))
      .subscribe(relatedClinicId => this.therapistClinicId = relatedClinicId);
  }

  public goBack(): void {
    this.location.back();
  }

  private getRelatedClinicId(therapistId: string): Promise<string> {
    const therapistClinic: TherapistClinic[] = this.therapistService.getRelationsToClinic();

    const relatedClinic: TherapistClinic[] = therapistClinic.filter(item => item.therapistId === therapistId);

    return Promise.resolve(relatedClinic[0] && relatedClinic[0].clinicId ? relatedClinic[0].clinicId : '');
  }

  // Because we have two-ways binding we dont need to re-save therapist model.
  public linkToClinic(): void {
    this.therapistService.linkToClinic(this.therapist.id, this.therapistClinicId);
  }

}


text:
@interface ViewController ()
<
UITableViewDelegate,
UITableViewDataSource,
UICollectionViewDelegate,
UICollectionViewDataSource
>
// 声明tableView
TableView_(upTableView)
// 声明collectionView
CollectionView_(downCollectionView)
// 声明flowLayout
FlowLayout_(downLayout)
// 声明button
Button_(backBtn)
// 声明TextField
TextField_(nameField)
// 声明imageView
ImageView_(imageView)
// 自定义View
DIYObj_(LYDiyView, lyView)
@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];

    self.view.backgroundColor = [UIColor colorWithWhite:0.3 alpha:1];
    self.title = @"魔法";

    [self configUI];
}

#pragma mark - 设置UI
- (void)configUI
{
    [self upTableView];
    [self downCollectionView];
    [self backBtn];
    [self nameField];
    [self imageView];
    [self lyView];

    // 不使用懒加载,创建可变数组并添加属性
    NSMutableArray *arrayM = NEW_Class_(NSMutableArray,
                                        [obj addObject:@"value1"];
                                        [obj addObject:@"value2"];
                                        NSLog(@"%@",obj)
                                        )
    // 创建普通数组
    NSArray *array = NEW_Class_(NSArray,
                                obj = arrayM.copy;
                                )
    NSLog(@"%@",array);
}

#pragma mark - 懒加载控件
// 懒加载tableView
GET_TableView_(upTableView, self.view,UITableViewStylePlain,
               obj.frame = CGRectMake(0, 0, UIScreen_W, UIScreen_H/3);
               [obj registerClass:[UITableViewCell class] forCellReuseIdentifier:@"tableID"];
               obj.rowHeight = 54;
               )
// 懒加载flowlayout
GET_FlowLayout_(downLayout,
                UICollectionViewScrollDirectionVertical,
                CGSizeMake((UIScreen_W-20)/4, (UIScreen_W-20)/4), 5, 5,
                )
// 懒加载collectionView
GET_CollectionView_(downCollectionView, self.view, self.downLayout, [UIColor whiteColor],
                    obj.frame = CGRectMake(0, UIScreen_H/3+5, UIScreen_W, UIScreen_H/3);
                    [obj registerClass:[UICollectionViewCell class] forCellWithReuseIdentifier:@"collectionID"];
                    obj.backgroundColor = [UIColor grayColor];
                    )
// 懒加载button
GET_Button_(backBtn, self.view, @selector(backClick), nil, @"Magic", 15, [UIColor whiteColor],
            obj.backgroundColor = [UIColor blackColor];
            obj.frame = CGRectMake(0, UIScreen_H*2/3 + 10, 60, 44);
            )
// 懒加载textFiled
GET_TextField_(nameField, self.view, [UIFont systemFontOfSize:16], @"魔法宏布局",
               obj.frame = CGRectMake(0, UIScreen_H*2/3+60, 150,35);
               obj.clearButtonMode = UITextFieldViewModeAlways;
               )
// 懒加载imageView
GET_ImageView_(imageView, self.view, @"mo",
               [obj sizeToFit];
               obj.frame = CGRectMake(160, UIScreen_H*2/3+60, 100, 100);
               )
// 懒加载自定义LYView
GET_DIYObj_(LYDiyView, lyView,
            [self.view addSubview:obj];
            obj.backgroundColor = [UIColor purpleColor];
            obj.frame = CGRectMake(280, UIScreen_H*2/3+60, 130, 44);
            )

#pragma mark - 按钮的点击方法
- (void)backClick
{
    NSLog(@"点击了backClick按钮");
}

#pragma mark - tableView和collectionView的数据源代理方法
// tableView
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return 20;
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    UITableViewCell * cell = [tableView dequeueReusableCellWithIdentifier:@"tableID"];
    cell.backgroundColor = UIColorWithRandom;
    return cell;
}

// collectionView
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    return 20;
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    UICollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"collectionID" forIndexPath:indexPath];
    cell.backgroundColor = UIColorWithRandom;

    return cell;
}
@end


text:
<?php

namespace Fimak\SiteBundle\DataFixtures\ORM;

use Doctrine\Common\DataFixtures\AbstractFixture;
use Doctrine\Common\DataFixtures\OrderedFixtureInterface;
use Doctrine\Common\Persistence\ObjectManager;
use Fimak\SiteBundle\Entity\Comment;

class CommentFixtures extends AbstractFixture implements OrderedFixtureInterface
{
    public function load(ObjectManager $manager)
    {
        $comment = new Comment();
        $comment->setAuthor('symfony');
        $comment->setComment('To make a long story short. You can\'t go wrong by choosing Symfony! And no one has ever been fired for using Symfony.');
        $comment->setArticle($manager->merge($this->getReference('article-1')));
        $manager->persist($comment);

        $comment = new Comment();
        $comment->setAuthor('David');
        $comment->setComment('To make a long story short. Choosing a framework must not be taken lightly; it is a long-term commitment. Make sure that you make the right selection!');
        $comment->setArticle($manager->merge($this->getReference('article-1')));
        $manager->persist($comment);

        $comment = new Comment();
        $comment->setAuthor('Dade');
        $comment->setComment('Anything else, mom? You want me to mow the lawn? Oops! I forgot, New York, No grass.');
        $comment->setArticle($manager->merge($this->getReference('article-2')));
        $manager->persist($comment);

        $comment = new Comment();
        $comment->setAuthor('Kate');
        $comment->setComment('Are you challenging me? ');
        $comment->setArticle($manager->merge($this->getReference('article-2')));
        $comment->setCreated(new \DateTime("2011-07-23 06:15:20"));
        $manager->persist($comment);

        $comment = new Comment();
        $comment->setAuthor('Dade');
        $comment->setComment('Name your stakes.');
        $comment->setArticle($manager->merge($this->getReference('article-2')));
        $comment->setCreated(new \DateTime("2011-07-23 06:18:35"));
        $manager->persist($comment);

        $comment = new Comment();
        $comment->setAuthor('Kate');
        $comment->setComment('If I win, you become my slave.');
        $comment->setArticle($manager->merge($this->getReference('article-2')));
        $comment->setCreated(new \DateTime("2011-07-23 06:22:53"));
        $manager->persist($comment);

        $comment = new Comment();
        $comment->setAuthor('Dade');
        $comment->setComment('Your SLAVE?');
        $comment->setArticle($manager->merge($this->getReference('article-2')));
        $comment->setCreated(new \DateTime("2011-07-23 06:25:15"));
        $manager->persist($comment);

        $comment = new Comment();
        $comment->setAuthor('Kate');
        $comment->setComment('You wish! You\'ll do shitwork, scan, crack copyrights...');
        $comment->setArticle($manager->merge($this->getReference('article-2')));
        $comment->setCreated(new \DateTime("2011-07-23 06:46:08"));
        $manager->persist($comment);

        $comment = new Comment();
        $comment->setAuthor('Dade');
        $comment->setComment('And if I win?');
        $comment->setArticle($manager->merge($this->getReference('article-2')));
        $comment->setCreated(new \DateTime("2011-07-23 10:22:46"));
        $manager->persist($comment);

        $comment = new Comment();
        $comment->setAuthor('Kate');
        $comment->setComment('Make it my first-born!');
        $comment->setArticle($manager->merge($this->getReference('article-2')));
        $comment->setCreated(new \DateTime("2011-07-23 11:08:08"));
        $manager->persist($comment);

        $comment = new Comment();
        $comment->setAuthor('Dade');
        $comment->setComment('Make it our first-date!');
        $comment->setArticle($manager->merge($this->getReference('article-2')));
        $comment->setCreated(new \DateTime("2011-07-24 18:56:01"));
        $manager->persist($comment);

        $comment = new Comment();
        $comment->setAuthor('Kate');
        $comment->setComment('I don\'t DO dates. But I don\'t lose either, so you\'re on!');
        $comment->setArticle($manager->merge($this->getReference('article-2')));
        $comment->setCreated(new \DateTime("2011-07-25 22:28:42"));
        $manager->persist($comment);

        $comment = new Comment();
        $comment->setAuthor('Stanley');
        $comment->setComment('It\'s not gonna end like this.');
        $comment->setArticle($manager->merge($this->getReference('article-3')));
        $manager->persist($comment);

        $comment = new Comment();
        $comment->setAuthor('Gabriel');
        $comment->setComment('Oh, come on, Stan. Not everything ends the way you think it should. Besides, audiences love happy endings.');
        $comment->setArticle($manager->merge($this->getReference('article-3')));
        $manager->persist($comment);

        $comment = new Comment();
        $comment->setAuthor('Mile');
        $comment->setComment('Doesn\'t Bill Gates have something like that?');
        $comment->setArticle($manager->merge($this->getReference('article-5')));
        $manager->persist($comment);

        $comment = new Comment();
        $comment->setAuthor('Gary');
        $comment->setComment('Bill Who?');
        $comment->setArticle($manager->merge($this->getReference('article-5')));
        $manager->persist($comment);

        $manager->flush();
    }

    public function getOrder()
    {
        return 2;
    }
}


text:
class SubmittedSettlement < Settlement
  # destroy時に自動でnilにしてもらうため
  has_one :resource, :class_name => 'Settlement', :foreign_key => 'submitted_settlement_id', :dependent => :nullify

  # submitはできない
  def submit
    raise "相手から提出済にされることによってできた精算データを提出することはできません。"
  end

  protected
  def validate

  end
  def after_save
    # なにもしない
  end
end


text:
package armdatamigration

import (
	"context"
	"errors"
	"github.com/Azure/azure-sdk-for-go/sdk/azcore"
	"github.com/Azure/azure-sdk-for-go/sdk/azcore/arm"
	armruntime "github.com/Azure/azure-sdk-for-go/sdk/azcore/arm/runtime"
	"github.com/Azure/azure-sdk-for-go/sdk/azcore/cloud"
	"github.com/Azure/azure-sdk-for-go/sdk/azcore/policy"
	"github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime"
	"net/http"
	"net/url"
	"strings"
)

// UsagesClient contains the methods for the Usages group.
// Don't use this type directly, use NewUsagesClient() instead.
type UsagesClient struct {
	host           string
	subscriptionID string
	pl             runtime.Pipeline
}

// NewUsagesClient creates a new instance of UsagesClient with the specified values.
// subscriptionID - Identifier of the subscription
// credential - used to authorize requests. Usually a credential from azidentity.
// options - pass nil to accept the default values.
func NewUsagesClient(subscriptionID string, credential azcore.TokenCredential, options *arm.ClientOptions) (*UsagesClient, error) {
	if options == nil {
		options = &arm.ClientOptions{}
	}
	ep := cloud.AzurePublic.Services[cloud.ResourceManager].Endpoint
	if c, ok := options.Cloud.Services[cloud.ResourceManager]; ok {
		ep = c.Endpoint
	}
	pl, err := armruntime.NewPipeline(moduleName, moduleVersion, credential, runtime.PipelineOptions{}, options)
	if err != nil {
		return nil, err
	}
	client := &UsagesClient{
		subscriptionID: subscriptionID,
		host:           ep,
		pl:             pl,
	}
	return client, nil
}

// NewListPager - This method returns region-specific quotas and resource usage information for the Database Migration Service.
// If the operation fails it returns an *azcore.ResponseError type.
// Generated from API version 2021-06-30
// location - The Azure region of the operation
// options - UsagesClientListOptions contains the optional parameters for the UsagesClient.List method.
func (client *UsagesClient) NewListPager(location string, options *UsagesClientListOptions) *runtime.Pager[UsagesClientListResponse] {
	return runtime.NewPager(runtime.PagingHandler[UsagesClientListResponse]{
		More: func(page UsagesClientListResponse) bool {
			return page.NextLink != nil && len(*page.NextLink) > 0
		},
		Fetcher: func(ctx context.Context, page *UsagesClientListResponse) (UsagesClientListResponse, error) {
			var req *policy.Request
			var err error
			if page == nil {
				req, err = client.listCreateRequest(ctx, location, options)
			} else {
				req, err = runtime.NewRequest(ctx, http.MethodGet, *page.NextLink)
			}
			if err != nil {
				return UsagesClientListResponse{}, err
			}
			resp, err := client.pl.Do(req)
			if err != nil {
				return UsagesClientListResponse{}, err
			}
			if !runtime.HasStatusCode(resp, http.StatusOK) {
				return UsagesClientListResponse{}, runtime.NewResponseError(resp)
			}
			return client.listHandleResponse(resp)
		},
	})
}

// listCreateRequest creates the List request.
func (client *UsagesClient) listCreateRequest(ctx context.Context, location string, options *UsagesClientListOptions) (*policy.Request, error) {
	urlPath := "/subscriptions/{subscriptionId}/providers/Microsoft.DataMigration/locations/{location}/usages"
	if client.subscriptionID == "" {
		return nil, errors.New("parameter client.subscriptionID cannot be empty")
	}
	urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID))
	if location == "" {
		return nil, errors.New("parameter location cannot be empty")
	}
	urlPath = strings.ReplaceAll(urlPath, "{location}", url.PathEscape(location))
	req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.host, urlPath))
	if err != nil {
		return nil, err
	}
	reqQP := req.Raw().URL.Query()
	reqQP.Set("api-version", "2021-06-30")
	req.Raw().URL.RawQuery = reqQP.Encode()
	req.Raw().Header["Accept"] = []string{"application/json"}
	return req, nil
}

// listHandleResponse handles the List response.
func (client *UsagesClient) listHandleResponse(resp *http.Response) (UsagesClientListResponse, error) {
	result := UsagesClientListResponse{}
	if err := runtime.UnmarshalAsJSON(resp, &result.QuotaList); err != nil {
		return UsagesClientListResponse{}, err
	}
	return result, nil
}


text:
require 'active_support/callbacks'

module ActiveSupport
  module Testing
    module SetupAndTeardown
      def self.included(base)
        base.class_eval do
          include ActiveSupport::Callbacks
          define_callbacks :setup, :teardown

          if defined?(MiniTest::Assertions) && TestCase < MiniTest::Assertions
            include ForMiniTest
          else
            include ForClassicTestUnit
          end
        end
      end

      module ForMiniTest
        def run(runner)
          result = '.'
          begin
            run_callbacks :setup
            result = super
          rescue Exception => e
            result = runner.puke(self.class, self.name, e)
          ensure
            begin
              run_callbacks :teardown, :enumerator => :reverse_each
            rescue Exception => e
              result = runner.puke(self.class, self.name, e)
            end
          end
          result
        end
      end

      module ForClassicTestUnit
        # For compatibility with Ruby < 1.8.6
        PASSTHROUGH_EXCEPTIONS = Test::Unit::TestCase::PASSTHROUGH_EXCEPTIONS rescue [NoMemoryError, SignalException, Interrupt, SystemExit]

        # This redefinition is unfortunate but test/unit shows us no alternative.
        # Doubly unfortunate: hax to support Mocha's hax.
        def run(result)
          return if @method_name.to_s == "default_test"

          if using_mocha = respond_to?(:mocha_verify)
            assertion_counter_klass = if defined?(Mocha::TestCaseAdapter::AssertionCounter)
                                        Mocha::TestCaseAdapter::AssertionCounter
                                      else
                                        Mocha::Integration::TestUnit::AssertionCounter
                                      end
            assertion_counter = assertion_counter_klass.new(result)
          end

          yield(Test::Unit::TestCase::STARTED, name)
          @_result = result
          begin
            begin
              run_callbacks :setup
              setup
              __send__(@method_name)
              mocha_verify(assertion_counter) if using_mocha
            rescue Mocha::ExpectationError => e
              add_failure(e.message, e.backtrace)
            rescue Test::Unit::AssertionFailedError => e
              add_failure(e.message, e.backtrace)
            rescue Exception => e
              raise if PASSTHROUGH_EXCEPTIONS.include?(e.class)
              add_error(e)
            ensure
              begin
                teardown
                run_callbacks :teardown, :enumerator => :reverse_each
              rescue Test::Unit::AssertionFailedError => e
                add_failure(e.message, e.backtrace)
              rescue Exception => e
                raise if PASSTHROUGH_EXCEPTIONS.include?(e.class)
                add_error(e)
              end
            end
          ensure
            mocha_teardown if using_mocha
          end
          result.add_run
          yield(Test::Unit::TestCase::FINISHED, name)
        end
      end
    end
  end
end