text:
// Copyright 2010-2015 RethinkDB, all rights reserved.

#include <limits>

#include "rdb_protocol/geo/distances.hpp"
#include "rdb_protocol/geo/ellipsoid.hpp"
#include "rdb_protocol/geo/exceptions.hpp"
#include "rdb_protocol/geo/geojson.hpp"
#include "rdb_protocol/geo/inclusion.hpp"
#include "rdb_protocol/geo/intersection.hpp"
#include "rdb_protocol/geo/primitives.hpp"
#include "rdb_protocol/geo/s2/s2polygon.h"
#include "rdb_protocol/op.hpp"
#include "rdb_protocol/pseudo_geometry.hpp"
#include "rdb_protocol/term.hpp"
#include "rdb_protocol/terms/obj_or_seq.hpp"
#include "rdb_protocol/terms/terms.hpp"

using geo::S2Point;
using geo::S2Polygon;

namespace ql {

/* A term type for geo queries. The only difference to op_term_t is that it catches
`geo_exception_t`s. */
class geo_term_t : public op_term_t {
public:
    geo_term_t(compile_env_t *env, const raw_term_t &term,
               const argspec_t &argspec, optargspec_t optargspec = optargspec_t({}))
        : op_term_t(env, term, argspec, optargspec) { }
private:
    // With the exception of r.point(), all geo terms are only deterministic on a single
    // server because they typically depend on floating point results that might diverge
    // between machines / compilers / libraries.
    // Even seemingly harmless things such as r.line() are affected because they perform
    // geometric validation.
    deterministic_t is_deterministic() const {
        return op_term_t::is_deterministic().join(deterministic_t::single_server());
    }
    virtual scoped_ptr_t<val_t> eval_geo(
            scope_env_t *env, args_t *args, eval_flags_t flags) const = 0;
    scoped_ptr_t<val_t> eval_impl(
            scope_env_t *env, args_t *args, eval_flags_t flags) const {
        try {
            return eval_geo(env, args, flags);
        } catch (const geo_exception_t &e) {
            rfail(base_exc_t::LOGIC, "%s", e.what());
        }
    }
};

class geo_obj_or_seq_op_term_t : public obj_or_seq_op_term_t {
public:
    geo_obj_or_seq_op_term_t(compile_env_t *env, const raw_term_t &term,
                             poly_type_t _poly_type, argspec_t argspec)
        : obj_or_seq_op_term_t(env, term, _poly_type, argspec,
                               std::set<std::string>{"GEOMETRY"}) { }
private:
    // See comment in geo_term_t about non-determinism
    deterministic_t is_deterministic() const {
        return obj_or_seq_op_term_t::is_deterministic().join(deterministic_t::single_server());
    }
    virtual scoped_ptr_t<val_t> obj_eval_geo(
            scope_env_t *env, args_t *args, const scoped_ptr_t<val_t> &v0) const = 0;
    scoped_ptr_t<val_t> obj_eval(
            scope_env_t *env, args_t *args, const scoped_ptr_t<val_t> &v0) const {
        try {
            return obj_eval_geo(env, args, v0);
        } catch (const geo_exception_t &e) {
            rfail(base_exc_t::LOGIC, "%s", e.what());
        }
    }
};

class geojson_term_t : public geo_term_t {
public:
    geojson_term_t(compile_env_t *env, const raw_term_t &term)
        : geo_term_t(env, term, argspec_t(1)) { }
private:
    scoped_ptr_t<val_t> eval_geo(scope_env_t *env, args_t *args, eval_flags_t) const {
        scoped_ptr_t<val_t> v = args->arg(env, 0);
        datum_t geo_json = v->as_datum();
        validate_geojson(geo_json);

        // Store the geo_json object inline, just add a $reql_type$ field
        datum_object_builder_t result(geo_json);
        bool dup = result.add(datum_t::reql_type_string,
                              datum_t(pseudo::geometry_string));
        rcheck(!dup, base_exc_t::LOGIC, "GeoJSON object already had a "
                                          "$reql_type$ field.");
        // Drop the `bbox` field in case it exists. We don't have any use for it.
        UNUSED bool had_bbox = result.delete_field("bbox");

        return new_val(std::move(result).to_datum());
    }
    virtual const char *name() const { return "geojson"; }
};

// to_geojson doesn't actually perform any geometric calculations, nor does it do
// geometry validation. That's why it's derived from op_term_t rather than geo_term_t.
// It's also deterministic.
class to_geojson_term_t : public op_term_t {
public:
    to_geojson_term_t(compile_env_t *env, const raw_term_t &term)
        : op_term_t(env, term, argspec_t(1)) { }
private:
    scoped_ptr_t<val_t> eval_impl(scope_env_t *env, args_t *args, eval_flags_t) const {
        scoped_ptr_t<val_t> v = args->arg(env, 0);

        datum_object_builder_t result(v->as_ptype(pseudo::geometry_string));
        bool success = result.delete_field(datum_t::reql_type_string);
        r_sanity_check(success);
        return new_val(std::move(result).to_datum());
    }
    virtual const char *name() const { return "to_geojson"; }
};

class point_term_t : public geo_term_t {
public:
    point_term_t(compile_env_t *env, const raw_term_t &term)
        : geo_term_t(env, term, argspec_t(2)) { }
private:
    // point_term_t is deterministic because it doesn't perform any complex
    // arithmetics. It only checks the range of the values as part of
    // `validate_geojson()`.
    // Note that this is *only* true because S2 doesn't perform any additional
    // checks on the S2Point constructed in validate_geojson(). The construction
    // of the S2Point itself depends on the M_PI constant which could be system
    // dependent. Therefore if anything in validate_geojson() starts using
    // the constructed S2Point some day, determinism will need to be reconsidered.
    deterministic_t is_deterministic() const {
        return op_term_t::is_deterministic(); // NB: skip over geo_term_t
    }
    scoped_ptr_t<val_t> eval_geo(scope_env_t *env, args_t *args, eval_flags_t) const {
        double lon = args->arg(env, 0)->as_num();
        double lat = args->arg(env, 1)->as_num();
        lon_lat_point_t point(lon, lat);

        const datum_t result = construct_geo_point(point, env->env->limits());
        validate_geojson(result);

        return new_val(result);
    }
    virtual const char *name() const { return "point"; }
};

// Accepts either a geometry object of type Point, or an array with two coordinates.
// We often want to support both.
lon_lat_point_t parse_point_argument(const datum_t &point_datum) {
    if (point_datum.is_ptype(pseudo::geometry_string)) {
        // The argument is a point (should be at least, if not this will throw)
        return extract_lon_lat_point(point_datum);
    } else {
        // The argument must be a coordinate pair
        rcheck_target(&point_datum,
                      point_datum.arr_size() == 2,
                      base_exc_t::LOGIC,
                      strprintf("Expected point coordinate pair.  "
                                "Got %zu element array instead of a 2 element one.",
                                point_datum.arr_size()));
        double lon = point_datum.get(0).as_num();
        double lat = point_datum.get(1).as_num();
        return lon_lat_point_t(lon, lat);
    }
}

// Used by line_term_t and polygon_term_t
lon_lat_line_t parse_line_from_args(scope_env_t *env, args_t *args) {
    lon_lat_line_t line;
    line.reserve(args->num_args());
    for (size_t i = 0; i < args->num_args(); ++i) {
        scoped_ptr_t<const val_t> point_arg = args->arg(env, i);
        const datum_t &point_datum = point_arg->as_datum();
        line.push_back(parse_point_argument(point_datum));
    }

    return line;
}

class line_term_t : public geo_term_t {
public:
    line_term_t(compile_env_t *env, const raw_term_t &term)
        : geo_term_t(env, term, argspec_t(2, -1)) { }
private:
    scoped_ptr_t<val_t> eval_geo(scope_env_t *env, args_t *args, eval_flags_t) const {
        const lon_lat_line_t line = parse_line_from_args(env, args);

        const datum_t result = construct_geo_line(line, env->env->limits());
        validate_geojson(result);

        return new_val(result);
    }
    virtual const char *name() const { return "line"; }
};

class polygon_term_t : public geo_term_t {
public:
    polygon_term_t(compile_env_t *env, const raw_term_t &term)
        : geo_term_t(env, term, argspec_t(3, -1)) { }
private:
    scoped_ptr_t<val_t> eval_geo(scope_env_t *env, args_t *args, eval_flags_t) const {
        const lon_lat_line_t shell = parse_line_from_args(env, args);

        const datum_t result = construct_geo_polygon(shell, env->env->limits());
        validate_geojson(result);

        return new_val(result);
    }
    virtual const char *name() const { return "polygon"; }
};

class intersects_term_t : public geo_obj_or_seq_op_term_t {
public:
    intersects_term_t(compile_env_t *env, const raw_term_t &term)
        : geo_obj_or_seq_op_term_t(env, term, poly_type_t::FILTER, argspec_t(2)) { }
private:
    scoped_ptr_t<val_t> obj_eval_geo(
            scope_env_t *env, args_t *args, const scoped_ptr_t<val_t> &v0) const {
        scoped_ptr_t<val_t> other = args->arg(env, 1);

        bool result = geo_does_intersect(v0->as_ptype(pseudo::geometry_string),
                                         other->as_ptype(pseudo::geometry_string));

        return new_val_bool(result);
    }
    virtual const char *name() const { return "intersects"; }
};

class includes_term_t : public geo_obj_or_seq_op_term_t {
public:
    includes_term_t(compile_env_t *env, const raw_term_t &term)
        : geo_obj_or_seq_op_term_t(env, term, poly_type_t::FILTER, argspec_t(2)) { }
private:
    scoped_ptr_t<val_t> obj_eval_geo(
            scope_env_t *env, args_t *args, const scoped_ptr_t<val_t> &v0) const {
        scoped_ptr_t<val_t> g = args->arg(env, 1);

        scoped_ptr_t<S2Polygon> s2polygon =
            to_s2polygon(v0->as_ptype(pseudo::geometry_string));
        bool result = geo_does_include(*s2polygon, g->as_ptype(pseudo::geometry_string));

        return new_val_bool(result);
    }
    virtual const char *name() const { return "includes"; }
};

ellipsoid_spec_t pick_reference_ellipsoid(scope_env_t *env, args_t *args) {
    scoped_ptr_t<val_t> geo_system_arg = args->optarg(env, "geo_system");
    if (geo_system_arg.has()) {
        if (geo_system_arg->as_datum().get_type() == datum_t::R_OBJECT) {
            // We expect a reference ellipsoid with parameters 'a' and 'f'.
            // (equator radius and the flattening)
            double a = geo_system_arg->as_datum().get_field("a").as_num();
            double f = geo_system_arg->as_datum().get_field("f").as_num();
            rcheck_target(geo_system_arg.get(),
                          a > 0.0,
                          base_exc_t::LOGIC,
                          "The equator radius `a` must be positive.");
            rcheck_target(geo_system_arg.get(),
                          f >= 0.0 && f < 1.0,
                          base_exc_t::LOGIC,
                          "The flattening `f` must be in the range [0, 1).");
            return ellipsoid_spec_t(a, f);
        } else {
            const std::string v = geo_system_arg->as_str().to_std();
            if (v == "WGS84") {
                return WGS84_ELLIPSOID;
            } else if (v == "unit_sphere") {
                return UNIT_SPHERE;
            } else {
                rfail_target(geo_system_arg.get(), base_exc_t::LOGIC,
                             "Unrecognized geo system \"%s\" (valid options: "
                             "\"WGS84\", \"unit_sphere\").", v.c_str());
            }
        }
    } else {
        return WGS84_ELLIPSOID;
    }
}

dist_unit_t pick_dist_unit(scope_env_t *env, args_t *args) {
    scoped_ptr_t<val_t> geo_system_arg = args->optarg(env, "unit");
    if (geo_system_arg.has()) {
        return parse_dist_unit(geo_system_arg->as_str().to_std());
    } else {
        return dist_unit_t::M;
    }
}

class distance_term_t : public geo_term_t {
public:
    distance_term_t(compile_env_t *env, const raw_term_t &term)
        : geo_term_t(env, term, argspec_t(2), optargspec_t({"geo_system", "unit"})) { }
private:
    scoped_ptr_t<val_t> eval_geo(scope_env_t *env, args_t *args, eval_flags_t) const {
        scoped_ptr_t<val_t> g1_arg = args->arg(env, 0);
        scoped_ptr_t<val_t> g2_arg = args->arg(env, 1);

        ellipsoid_spec_t reference_ellipsoid = pick_reference_ellipsoid(env, args);
        dist_unit_t result_unit = pick_dist_unit(env, args);

        // (At least) one of the arguments must be a point.
        // Find out which one it is.
        scoped_ptr_t<S2Point> p;
        datum_t g;
        const std::string g1_type =
            g1_arg->as_ptype(pseudo::geometry_string).get_field("type").as_str().to_std();
        if (g1_type == "Point") {
            p = to_s2point(g1_arg->as_ptype(pseudo::geometry_string));
            g = g2_arg->as_ptype(pseudo::geometry_string);
        } else {
            p = to_s2point(g2_arg->as_ptype(pseudo::geometry_string));
            g = g1_arg->as_ptype(pseudo::geometry_string);
        }

        double result = geodesic_distance(*p, g, reference_ellipsoid);
        result = convert_dist_unit(result, dist_unit_t::M, result_unit);

        return new_val(datum_t(result));
    }
    virtual const char *name() const { return "distance"; }
};

class circle_term_t : public geo_term_t {
public:
    circle_term_t(compile_env_t *env, const raw_term_t &term)
        : geo_term_t(env, term, argspec_t(2),
          optargspec_t({"geo_system", "unit", "fill", "num_vertices"})) { }
private:
    scoped_ptr_t<val_t> eval_geo(scope_env_t *env, args_t *args, eval_flags_t) const {
        scoped_ptr_t<val_t> center_arg = args->arg(env, 0);
        scoped_ptr_t<val_t> radius_arg = args->arg(env, 1);

        scoped_ptr_t<val_t> fill_arg = args->optarg(env, "fill");
        bool fill = true;
        if (fill_arg.has()) {
            fill = fill_arg->as_bool();
        }
        scoped_ptr_t<val_t> num_vertices_arg = args->optarg(env, "num_vertices");
        unsigned int num_vertices = 32;
        if (num_vertices_arg.has()) {
            num_vertices = num_vertices_arg->as_int<unsigned int>();
            rcheck_target(num_vertices_arg.get(),
                          num_vertices > 0,
                          base_exc_t::LOGIC,
                          "num_vertices must be positive.");
        }

        ellipsoid_spec_t reference_ellipsoid = pick_reference_ellipsoid(env, args);
        dist_unit_t radius_unit = pick_dist_unit(env, args);

        lon_lat_point_t center = parse_point_argument(center_arg->as_datum());
        double radius = radius_arg->as_num();
        radius = convert_dist_unit(radius, radius_unit, dist_unit_t::M);

        const lon_lat_line_t circle =
            build_circle(center, radius, num_vertices, reference_ellipsoid);

        const datum_t result =
            fill
            ? construct_geo_polygon(circle, env->env->limits())
            : construct_geo_line(circle, env->env->limits());
        validate_geojson(result);

        return new_val(result);
    }
    virtual const char *name() const { return "circle"; }
};

class get_intersecting_term_t : public geo_term_t {
public:
    get_intersecting_term_t(compile_env_t *env, const raw_term_t &term)
        : geo_term_t(env, term, argspec_t(2), optargspec_t({ "index" })) { }
private:
    scoped_ptr_t<val_t> eval_geo(scope_env_t *env, args_t *args, eval_flags_t) const {
        counted_t<table_t> table = args->arg(env, 0)->as_table();
        scoped_ptr_t<val_t> query_arg = args->arg(env, 1);
        scoped_ptr_t<val_t> index = args->optarg(env, "index");
        rcheck(index.has(), base_exc_t::LOGIC,
               "get_intersecting requires an index argument.");
        std::string index_str = index->as_str().to_std();
        rcheck(index_str != table->get_pkey(), base_exc_t::LOGIC,
               "get_intersecting cannot use the primary index.");
        counted_t<datum_stream_t> stream = table->get_intersecting(
            env->env, query_arg->as_ptype(pseudo::geometry_string), index_str,
            this);
        return new_val(make_counted<selection_t>(table, stream));
    }
    virtual const char *name() const { return "get_intersecting"; }
};

class fill_term_t : public geo_term_t {
public:
    fill_term_t(compile_env_t *env, const raw_term_t &term)
        : geo_term_t(env, term, argspec_t(1)) { }
private:
    scoped_ptr_t<val_t> eval_geo(scope_env_t *env, args_t *args, eval_flags_t) const {
        scoped_ptr_t<val_t> l_arg = args->arg(env, 0);
        const lon_lat_line_t shell =
            extract_lon_lat_line(l_arg->as_ptype(pseudo::geometry_string));

        const datum_t result = construct_geo_polygon(shell, env->env->limits());
        validate_geojson(result);

        return new_val(result);
    }
    virtual const char *name() const { return "fill"; }
};

class get_nearest_term_t : public geo_term_t {
public:
    get_nearest_term_t(compile_env_t *env, const raw_term_t &term)
        : geo_term_t(env, term, argspec_t(2),
          optargspec_t({ "index", "max_results", "max_dist", "geo_system", "unit" })) { }
private:
    scoped_ptr_t<val_t> eval_geo(scope_env_t *env, args_t *args, eval_flags_t) const {
        counted_t<table_t> table = args->arg(env, 0)->as_table();
        scoped_ptr_t<val_t> center_arg = args->arg(env, 1);
        scoped_ptr_t<val_t> index = args->optarg(env, "index");
        rcheck(index.has(), base_exc_t::LOGIC,
               "get_nearest requires an index argument.");
        std::string index_str = index->as_str().to_std();
        rcheck(index_str != table->get_pkey(), base_exc_t::LOGIC,
               "get_nearest cannot use the primary index.");
        lon_lat_point_t center = parse_point_argument(center_arg->as_datum());
        ellipsoid_spec_t reference_ellipsoid = pick_reference_ellipsoid(env, args);
        dist_unit_t dist_unit = pick_dist_unit(env, args);
        scoped_ptr_t<val_t> max_dist_arg = args->optarg(env, "max_dist");
        double max_dist = 100000; // Default: 100 km
        if (max_dist_arg.has()) {
            max_dist =
                convert_dist_unit(max_dist_arg->as_num(), dist_unit, dist_unit_t::M);
            rcheck_target(max_dist_arg,
                          max_dist > 0.0,
                          base_exc_t::LOGIC,
                          "max_dist must be positive.");
        }
        scoped_ptr_t<val_t> max_results_arg = args->optarg(env, "max_results");
        int64_t max_results = 100; // Default: 100 results
        if (max_results_arg.has()) {
            max_results = max_results_arg->as_int();
            rcheck_target(max_results_arg,
                          max_results > 0,
                          base_exc_t::LOGIC,
                          "max_results must be positive.");
        }

        datum_t results = table->get_nearest(
                env->env, center, max_dist, max_results, reference_ellipsoid,
                dist_unit, index_str, env->env->limits());
        return new_val(results);
    }
    virtual const char *name() const { return "get_nearest"; }
};

class polygon_sub_term_t : public geo_term_t {
public:
    polygon_sub_term_t(compile_env_t *env, const raw_term_t &term)
        : geo_term_t(env, term, argspec_t(2)) { }
private:
    const datum_t check_arg(scoped_ptr_t<val_t> arg) const {
        const datum_t res = arg->as_ptype(pseudo::geometry_string);

        rcheck_target(arg.get(),
                      res.get_field("type").as_str() == "Polygon",
                      base_exc_t::LOGIC,
                      strprintf("Expected a Polygon but found a %s.",
                                res.get_field("type").as_str().to_std().c_str()));
        rcheck_target(arg.get(),
                      res.get_field("coordinates").arr_size() <= 1,
                      base_exc_t::LOGIC,
                      "Expected a Polygon with only an outer shell.  "
                      "This one has holes.");
        return res;
    }

    scoped_ptr_t<val_t> eval_geo(scope_env_t *env, args_t *args, eval_flags_t) const {
        const datum_t lhs = check_arg(args->arg(env, 0));
        const datum_t rhs = check_arg(args->arg(env, 1));

        {
            scoped_ptr_t<S2Polygon> lhs_poly = to_s2polygon(lhs);
            if (!geo_does_include(*lhs_poly, rhs)) {
                throw geo_exception_t("The second argument to `polygon_sub` is not "
                                      "contained in the first one.");
            }
        }

        // Construct a polygon from lhs with rhs cut out
        datum_object_builder_t result;
        bool dup;
        dup = result.add(datum_t::reql_type_string, datum_t(pseudo::geometry_string));
        r_sanity_check(!dup);
        dup = result.add("type", datum_t("Polygon"));
        r_sanity_check(!dup);

        datum_array_builder_t coordinates_builder(lhs.get_field("coordinates"),
                                                  env->env->limits());
        coordinates_builder.add(rhs.get_field("coordinates").get(0));
        dup = result.add("coordinates", std::move(coordinates_builder).to_datum());
        r_sanity_check(!dup);
        datum_t result_datum = std::move(result).to_datum();
        validate_geojson(result_datum);

        return new_val(result_datum);
    }
    virtual const char *name() const { return "polygon_sub"; }
};

counted_t<term_t> make_geojson_term(
        compile_env_t *env, const raw_term_t &term) {
    return make_counted<geojson_term_t>(env, term);
}
counted_t<term_t> make_to_geojson_term(
        compile_env_t *env, const raw_term_t &term) {
    return make_counted<to_geojson_term_t>(env, term);
}
counted_t<term_t> make_point_term(
        compile_env_t *env, const raw_term_t &term) {
    return make_counted<point_term_t>(env, term);
}
counted_t<term_t> make_line_term(
        compile_env_t *env, const raw_term_t &term) {
    return make_counted<line_term_t>(env, term);
}
counted_t<term_t> make_polygon_term(
        compile_env_t *env, const raw_term_t &term) {
    return make_counted<polygon_term_t>(env, term);
}
counted_t<term_t> make_intersects_term(
        compile_env_t *env, const raw_term_t &term) {
    return make_counted<intersects_term_t>(env, term);
}
counted_t<term_t> make_includes_term(
        compile_env_t *env, const raw_term_t &term) {
    return make_counted<includes_term_t>(env, term);
}
counted_t<term_t> make_distance_term(
        compile_env_t *env, const raw_term_t &term) {
    return make_counted<distance_term_t>(env, term);
}
counted_t<term_t> make_circle_term(
        compile_env_t *env, const raw_term_t &term) {
    return make_counted<circle_term_t>(env, term);
}
counted_t<term_t> make_get_intersecting_term(
        compile_env_t *env, const raw_term_t &term) {
    return make_counted<get_intersecting_term_t>(env, term);
}
counted_t<term_t> make_fill_term(
        compile_env_t *env, const raw_term_t &term) {
    return make_counted<fill_term_t>(env, term);
}
counted_t<term_t> make_get_nearest_term(
        compile_env_t *env, const raw_term_t &term) {
    return make_counted<get_nearest_term_t>(env, term);
}
counted_t<term_t> make_polygon_sub_term(
        compile_env_t *env, const raw_term_t &term) {
    return make_counted<polygon_sub_term_t>(env, term);
}

} // namespace ql


text:
using BenchmarkDotNet.Exporters;

namespace BenchmarkDotNet.Attributes.Exporters
{
    public class RPlotExporterAttribute : ExporterConfigBaseAttribute
    {
        public RPlotExporterAttribute() : base(DefaultExporters.RPlot)
        {
        }
    }
}

redpajama_set_name: RedPajamaGithub


text:
// <copyright file="BernoulliDistribution.cs" company="Math.NET">
// Math.NET Numerics, part of the Math.NET Project
// http://numerics.mathdotnet.com
// http://github.com/mathnet/mathnet-numerics
// http://mathnetnumerics.codeplex.com
// Copyright (c) 2009-2010 Math.NET
// Permission is hereby granted, free of charge, to any person
// obtaining a copy of this software and associated documentation
// files (the "Software"), to deal in the Software without
// restriction, including without limitation the rights to use,
// copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following
// conditions:
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
// OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
// WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
// OTHER DEALINGS IN THE SOFTWARE.
// </copyright>

using System;
using MathNet.Numerics.Distributions;

namespace Examples.DiscreteDistributionsExamples
{
    ///
    /// Bernoulli distribution example
    ///
    public class BernoulliDistribution : IExample
    {
        ///
        /// Gets the name of this example
        ///
        /// <seealso cref="http://reference.wolfram.com/mathematica/ref/BernoulliDistribution.html"/>
        public string Name
        {
            get
            {
                return "Bernoulli distribution";
            }
        }

        ///
        /// Gets the description of this example
        ///
        public string Description
        {
            get
            {
                return "Bernoulli distribution properties and samples generating examples";
            }
        }

        ///
        /// Run example
        ///
        /// Bernoulli distribution
        public void Run()
        {
            // 1. Initialize the new instance of the Bernoulli distribution class with parameter P = 0.2
            var bernoulli = new Bernoulli(0.2);
            Console.WriteLine(@"1. Initialize the new instance of the Bernoulli distribution class with parameter P = {0}", bernoulli.P);
            Console.WriteLine();

            // 2. Distributuion properties:
            Console.WriteLine(@"2. {0} distributuion properties:", bernoulli);

            // Cumulative distribution function
            Console.WriteLine(@"{0} - Сumulative distribution at location '3'", bernoulli.CumulativeDistribution(3).ToString(" #0.00000;-#0.00000"));

            // Probability density
            Console.WriteLine(@"{0} - Probability mass at location '3'", bernoulli.Probability(3).ToString(" #0.00000;-#0.00000"));

            // Log probability density
            Console.WriteLine(@"{0} - Log probability mass at location '3'", bernoulli.ProbabilityLn(3).ToString(" #0.00000;-#0.00000"));

            // Entropy
            Console.WriteLine(@"{0} - Entropy", bernoulli.Entropy.ToString(" #0.00000;-#0.00000"));

            // Largest element in the domain
            Console.WriteLine(@"{0} - Largest element in the domain", bernoulli.Maximum.ToString(" #0.00000;-#0.00000"));

            // Smallest element in the domain
            Console.WriteLine(@"{0} - Smallest element in the domain", bernoulli.Minimum.ToString(" #0.00000;-#0.00000"));

            // Mean
            Console.WriteLine(@"{0} - Mean", bernoulli.Mean.ToString(" #0.00000;-#0.00000"));

            // Mode
            Console.WriteLine(@"{0} - Mode", bernoulli.Mode.ToString(" #0.00000;-#0.00000"));

            // Variance
            Console.WriteLine(@"{0} - Variance", bernoulli.Variance.ToString(" #0.00000;-#0.00000"));

            // Standard deviation
            Console.WriteLine(@"{0} - Standard deviation", bernoulli.StdDev.ToString(" #0.00000;-#0.00000"));

            // Skewness
            Console.WriteLine(@"{0} - Skewness", bernoulli.Skewness.ToString(" #0.00000;-#0.00000"));
            Console.WriteLine();

            // 3. Generate 10 samples of the Bernoulli distribution
            Console.WriteLine(@"3. Generate 10 samples of the Bernoulli distribution");
            for (var i = 0; i < 10; i++)
            {
                Console.Write(bernoulli.Sample().ToString("N05") + @" ");
            }

            Console.WriteLine();
            Console.WriteLine();

            // 4. Generate 100000 samples of the Bernoulli(0.2) distribution and display histogram
            Console.WriteLine(@"4. Generate 100000 samples of the Bernoulli(0.2) distribution and display histogram");
            var data = new int[100000];
            Bernoulli.Samples(data, 0.2);
            ConsoleHelper.DisplayHistogram(data);
            Console.WriteLine();

            // 5. Generate 100000 samples of the Bernoulli(4) distribution and display histogram
            Console.WriteLine(@"5. Generate 100000 samples of the Bernoulli(0.9) distribution and display histogram");
            Bernoulli.Samples(data, 0.9);
            ConsoleHelper.DisplayHistogram(data);
            Console.WriteLine();

            // 6. Generate 100000 samples of the Bernoulli(8) distribution and display histogram
            Console.WriteLine(@"6. Generate 100000 samples of the Bernoulli(0.5) distribution and display histogram");
            Bernoulli.Samples(data, 0.5);
            ConsoleHelper.DisplayHistogram(data);
        }
    }
}


text:
<!DOCTYPE html>

  <title>Removing slow-loading iframe stops load delay</title>


text:
title: Overflow Property
localeTitle: Propiedad de desbordamiento
---
## Propiedad de desbordamiento

Esto es un talón. [Ayuda a nuestra comunidad a expandirla](https://github.com/freecodecamp/guides/tree/master/src/pages/css/properties/overflow-property/index.md) .

[Esta guía rápida de estilo ayudará a asegurar que su solicitud de extracción sea aceptada](https://github.com/freecodecamp/guides/blob/master/README.md) .

#### Más información:


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;

namespace Extract_emails
{
    class Program
    {
        static void Main(string[] args)
        {
            var input = Console.ReadLine();

            var pattern = @"[a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+\.[a-zA-Z0-9-]+";
            var regex = new Regex(pattern);
            var reg = regex.Matches(input);

            for (int i = 0; i < reg.Count; i++)
            {
                Console.WriteLine(reg[i]);
            }
        }
    }
}


text:
/* eslint import/no-extraneous-dependencies: ["error", {"devDependencies": true}] */
// @ts-nocheck

// ----------------------
// IMPORTS

import path from 'path';
import webpack from 'webpack';
import WebpackConfig from 'webpack-config';

// Plugin to allow us to exclude `node_modules` packages from the final
// bundle.  Since we'll be running `server.js` from Node, we'll have access
// to those modules locally and they don't need to wind up in the bundle file
import nodeModules from 'webpack-node-externals';

// Plugin that forks TypeScript's checker to a separate process
import { CheckerPlugin, TsConfigPathsPlugin } from 'awesome-typescript-loader';

// Common config
import { css } from './common';

import PATHS from '../../config/paths';

// ----------------------

// Helper function to recursively filter through loaders, and apply the
// supplied function
function recursiveLoader(root = {}, func) {
  if (root.loaders) {
    root.loaders.forEach(l => recursiveLoader(l, func));
  }
  if (root.loader) return func(root);
  return false;
}

export default new WebpackConfig().extend({
  '[root]/base.js': conf => {
    // Prevent file emission, since the browser bundle will already have done it
    conf.module.loaders.forEach(loader => {
      recursiveLoader(loader, l => {
        if (l.loader === 'file-loader') {
          // eslint-disable-next-line
          l.query.emitFile = false;
        }
      });
    });

    // Optimise images
    conf.module.loaders.find(l => l.test.toString() === /\.(jpe?g|png|gif|svg)$/i.toString())
      .loaders.push({
        // `image-webpack-loader` is used on the server build even `emitFile`
        // on `fileLoader` disabled so that the correct hash can be generated.
        loader: 'image-webpack-loader',
        // workaround for https://github.com/tcoopman/image-webpack-loader/issues/88
        options: {},
      });

    return conf;
  },
}).merge({

  // Set the target to Node.js, since we'll be running the bundle on the server
  target: 'node',

  // Output to the `dist` folder
  output: {
    path: PATHS.dist,
    filename: 'server.js',
  },

  entry: {
    javascript: [
      // Server entry point
      path.join(PATHS.entry, 'server.tsx'),
    ],
  },

  // Make __dirname work properly
  node: {
    __dirname: true,
  },

  module: {
    loaders: [
      // CSS loaders
      ...(function* loadCss() {
        for (const loader of css.loaders) {
          // Iterate over CSS/SASS/LESS and yield local and global mod configs
          for (const mod of css.getModuleRegExp(loader.ext)) {
            yield {
              test: new RegExp(mod[0]),
              loader: [
                {
                  loader: 'css-loader/locals',
                  query: Object.assign({}, css.loaderDefaults, mod[1]),
                },
                'postcss-loader',
                ...loader.use,
              ],
            };
          }
        }
      }()),
      // .(j|t)s(x) files can extend the `.babelrc` file at the root of the project
      // (which was used to spawn Webpack in the first place), because that's
      // exactly the same polyfill config we'll want to use for this bundle
      {
        test: /\.(j|t)sx?$/,
        exclude: /node_modules/,
        loader: 'awesome-typescript-loader',
        query: {
          useCache: true,
          cacheDirectory: '.awcache-server',
        },
      },
    ],
  },
  plugins: [
    new webpack.DefinePlugin({
      // We're running on the Node.js server, so set `SERVER` to true
      SERVER: true,

      // React constantly checking process.env.NODE_ENV causes massive
      // slowdowns during rendering. Replacing process.env.NODE_ENV
      // with a string not only removes this expensive check, it allows
      // a minifier to remove all of React's warnings in production.
      'process.env': {
        NODE_ENV: JSON.stringify('production'),
      },
    }),

    // Fork TypeScript checker to a separate process
    new CheckerPlugin(),

    // Allow use of `paths` and `baseUrl`
    new TsConfigPathsPlugin(),
  ],
  // No need to transpile `node_modules` files, since they'll obviously
  // still be available to Node.js when we run the resulting `server.js` entry
  externals: nodeModules(),
});


text:
#pragma checksum "D:\Repos\programatron\projects\mobosiSema\PivotPage.xaml" "{406ea660-64cf-4c82-b6f0-42d48172a799}" "AD80401C08E7F2619304F2F4557AEAB1"
//------------------------------------------------------------------------------
// <auto-generated>
//     This code was generated by a tool.
//
//     Changes to this file may cause incorrect behavior and will be lost if
//     the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------

namespace mobosiSema
{
    partial class PivotPage : global::Windows.UI.Xaml.Controls.Page
    {
        [global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.Windows.UI.Xaml.Build.Tasks"," 4.0.0.0")]
        private global::Windows.UI.Xaml.Controls.ListBox listBox;
        [global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.Windows.UI.Xaml.Build.Tasks"," 4.0.0.0")]
        private global::Windows.UI.Xaml.Controls.AppBarButton AddAppBarButton;
        [global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.Windows.UI.Xaml.Build.Tasks"," 4.0.0.0")]
        private bool _contentLoaded;

        [global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.Windows.UI.Xaml.Build.Tasks"," 4.0.0.0")]
        [global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
        public void InitializeComponent()
        {
            if (_contentLoaded)
                return;

            _contentLoaded = true;
            global::Windows.UI.Xaml.Application.LoadComponent(this, new global::System.Uri("ms-appx:///PivotPage.xaml"), global::Windows.UI.Xaml.Controls.Primitives.ComponentResourceLocation.Application);

            listBox = (global::Windows.UI.Xaml.Controls.ListBox)this.FindName("listBox");
            AddAppBarButton = (global::Windows.UI.Xaml.Controls.AppBarButton)this.FindName("AddAppBarButton");
        }
    }
}


text:
package org.apache.hedwig.client.netty;

import java.net.InetSocketAddress;
import java.util.TimerTask;

import org.apache.hedwig.client.api.MessageHandler;
import org.apache.hedwig.client.data.PubSubData;
import org.apache.hedwig.client.data.TopicSubscriber;
import org.apache.hedwig.client.exceptions.AlreadyStartDeliveryException;
import org.apache.hedwig.client.handlers.SubscribeResponseHandler;
import org.apache.hedwig.exceptions.PubSubException.ClientNotSubscribedException;
import org.apache.hedwig.protocol.PubSubProtocol.ResponseBody;
import org.apache.hedwig.util.Callback;

/**
 * A manager manages 1) all channels established to hub servers,
 * 2) the actions taken by the topic subscribers.
 */
public interface HChannelManager {

    /**
     * Submit a pub/sub request after a given delay.
     *
     * @param op
     *          Pub/Sub Request.
     * @param delay
     *          Delay time in ms.
     */
    public void submitOpAfterDelay(PubSubData op, long delay);

    /**
     * Submit a pub/sub request.
     *
     * @param pubSubData
     *          Pub/Sub Request.
     */
    public void submitOp(PubSubData pubSubData);

    /**
     * Submit a pub/sub request to default server.
     *
     * @param pubSubData
     *           Pub/Sub request.
     */
    public void submitOpToDefaultServer(PubSubData pubSubData);

    /**
     * Submit a pub/sub request to a given host.
     *
     * @param pubSubData
     *          Pub/Sub request.
     * @param host
     *          Given host address.
     */
    public void redirectToHost(PubSubData pubSubData, InetSocketAddress host);

    /**
     * Generate next transaction id for pub/sub request sending thru this manager.
     *
     * @return next transaction id.
     */
    public long nextTxnId();

    /**
     * Schedule a timer task after a given delay.
     *
     * @param task
     *          A timer task
     * @param delay
     *          Delay time in ms.
     */
    public void schedule(TimerTask task, long delay);

    /**
     * Get the subscribe response handler managed the given topicSubscriber.
     *
     * @param topicSubscriber
     *          Topic Subscriber
     * @return subscribe response handler managed it, otherwise return null.
     */
    public SubscribeResponseHandler getSubscribeResponseHandler(
                                    TopicSubscriber topicSubscriber);

    /**
     * Start delivering messages for a given topic subscriber.
     *
     * @param topicSubscriber
     *            Topic Subscriber
     * @param messageHandler
     *            MessageHandler to register for this ResponseHandler instance.
     * @throws ClientNotSubscribedException
     *            If the client is not currently subscribed to the topic
     * @throws AlreadyStartDeliveryException
     *            If someone started delivery a message handler before stopping existed one.
     */
    public void startDelivery(TopicSubscriber topicSubscriber,
                              MessageHandler messageHandler)
    throws ClientNotSubscribedException, AlreadyStartDeliveryException;

    /**
     * Stop delivering messages for a given topic subscriber.
     *
     * @param topicSubscriber
     *            Topic Subscriber
     * @throws ClientNotSubscribedException
     *             If the client is not currently subscribed to the topic
     */
    public void stopDelivery(TopicSubscriber topicSubscriber)
    throws ClientNotSubscribedException;

    /**
     * Close the subscription of the given topicSubscriber.
     *
     * @param topicSubscriber
     *          Topic Subscriber
     * @param callback
     *          Callback
     * @param context
     *          Callback context
     */
    public void asyncCloseSubscription(TopicSubscriber topicSubscriber,
                                       Callback<ResponseBody> callback,
                                       Object context);

    /**
     * Return the subscription event emitter to emit subscription events.
     *
     * @return subscription event emitter.
     */
    public SubscriptionEventEmitter getSubscriptionEventEmitter();

    /**
     * Is the channel manager closed.
     *
     * @return true if the channel manager is closed, otherwise return false.
     */
    public boolean isClosed();

    /**
     * Close the channel manager.
     */
    public void close();
}


text:
This repository is a synthetic mirror.

Contributions to netstack must be submitted by sending pull requests to
[gVisor](https://www.github.com/google/gvisor), where there are complete
[instructions](https://github.com/google/gvisor/blob/master/CONTRIBUTING.md).


text:
if [ ! -e /usr/sbin/sendmail ];then
	ln -s ssmtp /usr/sbin/sendmail
else
	echo '/usr/sbin/sendmail already exists!'
fi


text:
'use strict';

const os = require('os');

const _ = require('lodash');

const ts = require('swagen-typescript-language');

class Generator {
    constructor(definition, profile) {
        this.definition = definition;
        this.profile = profile;
    }

    generate() {
        this.code = [];
        this.generateInitialCode();
        this.code.push('');
        this.generateInterfaces();
        this.code.push('');
        this.generateImplementations();
        this.code.push('');
        this.generateModels();
        return this.code.join(os.EOL);
    }

    generateInitialCode() {
        this.code.push(...ts.buildHeader(this.profile, this.definition));

        this.code.push('');

        for (let i = 0; i < (this.profile.options.references || []).length; i++) {
            this.code.push(`/// <reference path="${this.profile.options.references[i]}" />`);
        }
    }

    generateInterfaces() {
        this.code.push(
            `namespace ${this.profile.options.namespaces.services} {`,
            `    import __models = ${this.profile.options.namespaces.models};`,
            ``
        );
        const sortedKeys = _.keys(this.definition.services).sort();
        for (let i = 0; i < sortedKeys.length; i++) {
            const serviceName = sortedKeys[i];
            const service = this.definition.services[serviceName];
            const transformedServiceName = this.transform.serviceName(serviceName, {
                service: service
            }) + (this.profile.options.serviceSuffix || 'Client');
            this.code.push(
                `    export interface I${transformedServiceName} {`
            );
            for (const operationName in service) {
                const operation = service[operationName];
                const transformedOperationName = this.transform.operationName(operationName, {
                    transformedServiceName: transformedServiceName,
                    serviceName: serviceName,
                    service: service
                });
                const docComments = ts.buildOperationDocComments(operation)
                    .map(c => `        ${c}`);
                this.code.push(...docComments);
                this.code.push(`        ${this.getMethodSignature(transformedOperationName, operation)};`);
                this.code.push('');
            }
            this.code.push(
                `    }`
            );
            if (i < sortedKeys.length - 1) {
                this.code.push(``);
            }
        }
        this.code.push(
            '}'
        );
    }

    generateImplementations() {
        const baseUrl = this.profile.options.baseUrl;
        const baseUrlProvider = baseUrl.provider || _.camelCase(baseUrl.type);
        const baseUrlPath = baseUrl.path && baseUrl.path.length > 0 ? baseUrlProvider + '.' + baseUrl.path.join('.') : baseUrlProvider;

        this.code.push(
            `namespace ${this.profile.options.namespaces.services} {`,
            `    import __models = ${this.profile.options.namespaces.models};`,
            ``
        );

        const sortedKeys = _.keys(this.definition.services).sort();
        for (let i = 0; i < sortedKeys.length; i++) {
            const serviceName = sortedKeys[i];
            const service = this.definition.services[serviceName];
            const transformedServiceName = this.transform.serviceName(serviceName, {
                service: service
            }) + (this.profile.options.serviceSuffix || 'Client');
            this.code.push(
                `    export class ${transformedServiceName} implements I${transformedServiceName} {`,
                `        private baseUrl: string;`,
                ``,
                `        public static $inject: string[] = ['$http', '${baseUrlProvider}'];`,
                `        constructor (private $http: ng.IHttpService, ${baseUrlProvider}: ${baseUrl.type}) {`,
                `            this.baseUrl = ${baseUrlPath};`,
                `        }`
            );

            for (const operationName in service) {
                const operation = service[operationName];
                const transformedOperationName = this.transform.operationName(operationName, {
                    transformedServiceName: transformedServiceName,
                    serviceName: serviceName,
                    service: service
                });

                this.code.push(
                    ``,
                    `        public ${this.getMethodSignature(transformedOperationName, operation)} {`
                );

                //Check required parameters
                const requiredParams = (operation.parameters || []).filter(p => !!p.required);
                for (let i = 0; i < requiredParams.length; i++) {
                    const requiredParam = requiredParams[i];
                    this.code.push(
                        `            if (${requiredParam.name} == undefined || ${requiredParam.name} == null) {`,
                        `                throw new Error(\`The parameter '${requiredParam.name}' must be defined.\`);`,
                        `            }`
                    );
                }

                //Resolve path parameters in relative URL.
                const pathParams = (operation.parameters || []).filter(p => p.type === 'path');
                const hasPathParams = pathParams.length > 0;
                this.code.push(
                    `            let resourceUrl: string = '${operation.path}'${hasPathParams ? '' : ';'}`
                );
                for (let i = 0; i < pathParams.length; i++) {
                    const isLastParam = i === pathParams.length - 1;
                    this.code.push(
                        `                .replace('{${pathParams[i].name}}', encodeURIComponent('' + ${pathParams[i].name}))${isLastParam ? ';' : ''}`
                    );
                }

                //Query parameters
                const queryParams = (operation.parameters || []).filter(p => p.type === 'query');
                if (queryParams.length > 0) {
                    this.code.push(`            let queryParams: {[key: string]: string} = {`);
                    for (let i = 0; i < queryParams.length; i++) {
                        const isLastParam = i === queryParams.length - 1;
                        this.code.push(`                 ${queryParams[i].name}: encodeURIComponent('' + ${queryParams[i].name})${isLastParam ? '' : ','}`);
                    }
                    this.code.push(`            };`);
                }

                const bodyParam = (operation.parameters || []).find(p => p.type === 'body');
                const formDataParams = (operation.parameters || []).filter(p => p.type === 'formData');
                const headerParams = (operation.parameters || []).filter(p => p.type === 'header');
                const returnType = this.getReturnType(operation);

                if (formDataParams.length > 0) {
                    this.code.push(
                        `            let fd: FormData = new FormData();`
                    );
                    for (let i = 0; i < formDataParams.length; i++) {
                        this.code.push(
                            `            fd.append('${formDataParams[i].name}', ${formDataParams[i].name});`
                        );
                    }
                }
                this.code.push(
                    `            return this.$http<${returnType}>({`,
                    `                method: '${operation.verb.toUpperCase()}',`
                );
                if (bodyParam) {
                    this.code.push(
                        `                data: ${bodyParam.name},`
                    );
                } else if (formDataParams.length > 0) {
                    this.code.push(
                        `                data: fd,`,
                        `                transformRequest: angular.identity,`
                    );
                }
                if (formDataParams.length > 0 || headerParams.length > 0) {
                    const headers = [];
                    if (formDataParams.length > 0) {
                        headers.push({key: 'Content-Type', value: 'undefined'});
                    }
                    for (let i = 0; i < headerParams.length; i++) {
                        headers.push({key: headerParams[i].name, value: headerParams[i].name});
                    }
                    this.code.push(
                        `                headers: {`
                    );
                    for (let i = 0; i < headers.length; i++) {
                        this.code.push(
                            `                    '${headers[i].key}': ${headers[i].value}`
                        );
                    }
                    this.code.push(
                        `                },`
                    );
                }
                if (queryParams.length > 0) {
                    this.code.push(
                        `                url: buildServiceUrl(this.baseUrl, resourceUrl, queryParams)`
                    );
                } else {
                    this.code.push(
                        `                url: buildServiceUrl(this.baseUrl, resourceUrl)`
                    );
                }
                this.code.push(
                    `            })`,
                    `                .then((response: ng.IHttpPromiseCallbackArg<${returnType}>) => response.data)`,
                    `                .catch((response: ng.IHttpPromiseCallbackArg<any>) => response.data);`,
                    `        }`
                );
            }

            //Class closing
            this.code.push(
                '    }'
            );

            //Module registration
            const registeredServiceName = _.camelCase(transformedServiceName);
            this.code.push(`    angular.module('${this.profile.options.moduleName}').service('${registeredServiceName}', ${transformedServiceName});`);
            this.code.push('');
        }

        this.generateBuildUrlFunction();

        //Namespace closing
        this.code.push(
            '}'
        );
    }

    getReturnType(operation) {
        if (!operation.responses) {
            return 'any';
        }

        for (const statusKey in operation.responses) {
            const statusCode = +statusKey;
            if (statusCode >= 200 && statusCode < 300 && operation.responses[statusKey].dataType) {
                return ts.getDataType(operation.responses[statusKey].dataType, '__models');
            }
        }

        return 'any';
    }

    getMethodSignature(operationName, operation) {
        const orderedParams = (operation.parameters || []).filter(p => p.required).concat(
            (operation.parameters || []).filter(p => !p.required)
        );
        let parameters = '';
        for (let p = 0; p < orderedParams.length; p++) {
            const parameter = orderedParams[p];
            if (parameters) {
                parameters += ', ';
            }
            parameters += `${parameter.name}${parameter.required ? '' : '?'}: ${ts.getDataType(parameter.dataType, '__models')}`;
        }

        const returnType = this.getReturnType(operation);

        const methodSig = `${operationName}(${parameters}): ng.IPromise<${returnType}>`;
        return methodSig;
    }

    generateBuildUrlFunction() {
        this.code.push(
            `    function buildServiceUrl(baseUrl: string, resourceUrl: string, queryParams?: {[key: string]: string}): string {`,
            `        let url: string = baseUrl;`,
            `        let baseUrlSlash: boolean = url[url.length - 1] === '/';`,
            `        let resourceUrlSlash: boolean = resourceUrl[0] === '/';`,
            `        if (!baseUrlSlash && !resourceUrlSlash) {`,
            `            url += '/';`,
            `        } else if (baseUrlSlash && resourceUrlSlash) {`,
            `            url = url.substr(0, url.length - 1);`,
            `        }`,
            `        url += resourceUrl;`,
            ``,
            `        if (queryParams) {`,
            `            let isFirst: boolean = true;`,
            `            for (let p in queryParams) {`,
            `                if (queryParams.hasOwnProperty(p) && queryParams[p]) {`,
            `                    let separator: string = isFirst ? '?' : '&';`,
            `                    url += \`\${separator}\${p}=\${queryParams[p]}\`;`,
            `                    isFirst = false;`,
            `                }`,
            `            }`,
            `        }`,
            `        return url;`,
            `    }`
        );
    }

    generateModels() {
        this.code.push(
            `namespace ${this.profile.options.namespaces.models} {`
        );

        const sortedKeys = _.keys(this.definition.models).sort((x, y) => x.toLowerCase().localeCompare(y.toLowerCase()));

        for (let i = 0; i < sortedKeys.length; i++) {
            const modelName = sortedKeys[i];
            const model = this.definition.models[modelName];
            if (i > 0) {
                this.code.push('');
            }
            this.code.push(
                `    export interface ${modelName} {`
            );

            for (const propertyName in model) {
                const property = model[propertyName];
                this.code.push(
                    `        ${propertyName}${property.required ? '?' : ''}: ${ts.getDataType(property)};`
                );
            }

            this.code.push(
                '    }'
            );
        }

        const enumKeys = _.keys(this.definition.enums).sort((x, y) => x.toLowerCase().localeCompare(y.toLowerCase()));

        for (let i = 0; i < enumKeys.length; i++) {
            const enumName = enumKeys[i];
            const enumValues = this.definition.enums[enumName]
                .map(e => `"${e}"`)
                .join(' | ');
            if (sortedKeys.length > 0 || i > 0) {
                this.code.push('');
            }
            this.code.push(`    export type ${enumName} = ${enumValues};`);
        }

        if (this.profile.options.modelFactory) {
            this.generateModelFactory(sortedKeys, enumKeys);
        }

        //Namespace end
        this.code.push(
            `}`
        );
    }

    generateModelFactory(modelKeys, enumKeys) {
        if (modelKeys.length > 0 || enumKeys.length > 0) {
            this.code.push('');
        }
        this.code.push(
            `    export type Initializer<TModel> = (model: TModel) => void;`,
            ``,
            `    export class ModelFactory {`
        );

        for (let i = 0; i < modelKeys.length; i++) {
            const modelName = modelKeys[i];
            const model = this.definition.models[modelName];
            if (i > 0) {
                this.code.push('');
            }
            this.code.push(
                `        public static createEmpty${modelName}(initializer?: Initializer<${modelName}>): ${modelName} {`
            );
            this.code.push(
                `            let model: ${modelName} =  {`
            );
            for (const propertyName in model) {
                const property = model[propertyName];
                let value;
                if (property.isArray) {
                    value = '[]';
                } else if (property.complex) {
                    value = `ModelFactory.createEmpty${ts.getDataType(property)}()`;
                } else if (property.enum) {
                    value = 'undefined';
                } else if (property.primitive) {
                    value = this.getDefaultValueForPrimitive(property);
                } else {
                    value = 'undefined';
                }
                this.code.push(`                ${propertyName}: ${value},`);
            }
            this.code.push(
                `            };`,
                `            if (!!initializer) {`,
                `                initializer(model);`,
                `            }`,
                `            return model;`,
                `        }`
            );
        }

        //ModelFactory close
        this.code.push(
            `    }`
        );
    }

    getDefaultValueForPrimitive(property) {
        switch (property.primitive) {
            case 'integer':
            case 'number':
                return 'undefined';
            case 'string': {
                switch (property.subType) {
                    case 'date-time':
                        return 'undefined';
                    case 'uuid':
                        return 'undefined';
                    case 'byte':
                        return 'undefined';
                    case 'enum':
                        return `''`;
                    default:
                        return `''`;
                }
            }
            case 'boolean':
                return 'false';
            case 'file':
            case 'object':
                return 'undefined';
            default:
                throw `Cannot get a default value for primitive type ${JSON.stringify(property, null, 4)}`;
        }
    }
}

module.exports = (definition, profile) => {
    const generator = new Generator(definition, profile);
    return generator.generate();
};


text:
import {
  ExperimentInfo, // eslint-disable-line no-unused-vars
  getExperimentBranch,
  randomlySelectUnsetExperiments,
} from '../../src/experiments';

/** @const {string} */
export const ADSENSE_AMP_AUTO_ADS_RESPONSIVE_EXPERIMENT_NAME =
    'amp-auto-ads-adsense-responsive';

/**
 * @enum {string}
 */
export const AdSenseAmpAutoAdsResponsiveBranches = {
  CONTROL: '19861210', // don't attempt to expand auto ads to responsive format
  EXPERIMENT: '19861211', // do attempt to expand auto ads to responsive format
};

/** @const {!ExperimentInfo} */
const ADSENSE_AMP_AUTO_ADS_RESPONSIVE_EXPERIMENT_INFO = {
  isTrafficEligible: win => !!win.document.querySelector('AMP-AUTO-ADS'),
  branches: [
    AdSenseAmpAutoAdsResponsiveBranches.CONTROL,
    AdSenseAmpAutoAdsResponsiveBranches.EXPERIMENT,
  ],
};

/**
 * This has the side-effect of selecting the page into a branch of the
 * experiment, which becomes sticky for the entire pageview.
 *
 * @param {!Window} win
 * @return {?string}
 */
export function getAdSenseAmpAutoAdsResponsiveExperimentBranch(win) {
  const experiments = /** @type {!Object<string, !ExperimentInfo>} */ ({});
  experiments[ADSENSE_AMP_AUTO_ADS_RESPONSIVE_EXPERIMENT_NAME] =
      ADSENSE_AMP_AUTO_ADS_RESPONSIVE_EXPERIMENT_INFO;
  randomlySelectUnsetExperiments(win, experiments);
  return getExperimentBranch(win,
      ADSENSE_AMP_AUTO_ADS_RESPONSIVE_EXPERIMENT_NAME) || null;
}


text:
    <form class="form-horizontal" name="registerForm">
        <fieldset>
            <legend>Edit profile</legend>

                Username

                    <input type="text" class="form-control" id="inputUserName" ng-model="vm.user.userName">

                Password

                    <input type="password" class="form-control" id="inputPassword" ng-model="vm.user.password">

                First name

                    <input type="text" class="form-control" id="inputFirstName" ng-model="vm.user.firstName">

                Last name

                    <input type="text" class="form-control" id="inputLastName" ng-model="vm.user.lastName">

                Registration date

                    <input type="text" class="form-control" id="inputRegistrationDate"  ng-model="vm.user.registrationDate">

                Token

                    <input type="text" class="form-control" id="inputToken" ng-model="vm.user.token">

                Roles

                    <input type="text" class="form-control" id="inputRoles" ng-model="vm.user.rolesJson">

                Banned

                    <input type="checkbox" class="form-control" id="inputIsBaned" ng-checked="vm.currentUser.isBanned"  ng-model="vm.user.isBanned">

                <button class="btn btn-success" ng-click="vm.editUser(vm.user)">Save</button>

</fieldset>
</form>


text:
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.

using Microsoft.Fx.Portability.ObjectModel;
using System.Collections.Generic;
using System.Runtime.Versioning;
using Xunit;
using static Microsoft.Fx.Portability.Tests.TestData.TestFrameworks;

namespace Microsoft.Fx.Portability.Tests.ObjectModel
{
    public class NuGetPackageInfoComparerTests
    {
        [Fact]
        public void SortingTest()
        {
            var target1 = NetStandard16;
            var target2 = Net40;

            var packageId1 = "Remotion.Linq";
            var packageId2 = "Antlr3.Runtime";
            var packageId3 = "NHibernate";
            var nuget1 = new NuGetPackageInfo(packageId1, new Dictionary<FrameworkName, string>(), "");
            var nuget2 = new NuGetPackageInfo(packageId2, new Dictionary<FrameworkName, string>(), "");
            var nuget3 = new NuGetPackageInfo(packageId3, new Dictionary<FrameworkName, string>(), "");

            var nugetList = new List<NuGetPackageInfo>() { nuget1, nuget2, nuget3 };
            nugetList.Sort(new NuGetPackageInfoComparer());

            var expectedOrderedlist = new List<NuGetPackageInfo>() { nuget2, nuget3, nuget1 };
            Assert.Equal(expectedOrderedlist, nugetList);
        }
    }
}


text:
---
title: HTTP Session
type: laravel 5.4
order: 5.8
---

## Introduction

Since HTTP driven applications are stateless, sessions provide a way to store information about the user across multiple requests. Laravel ships with a variety of session backends that are accessed through an expressive, unified API. Support for popular backends such as [Memcached](https://memcached.org), [Redis](http://redis.io), and databases is included out of the box.

### Configuration

The session configuration file is stored at `config/session.php`. Be sure to review the options available to you in this file. By default, Laravel is configured to use the `file` session driver, which will work well for many applications. In production applications, you may consider using the `memcached` or `redis` drivers for even faster session performance.

The session `driver` configuration option defines where session data will be stored for each request. Laravel ships with several great drivers out of the box:

- `file` - sessions are stored in `storage/framework/sessions`.
- `cookie` - sessions are stored in secure, encrypted cookies.
- `database` - sessions are stored in a relational database.
- `memcached` / `redis` - sessions are stored in one of these fast, cache based stores.
- `array` - sessions are stored in a PHP array and will not be persisted.

> {tip} The array driver is used during [testing](/mk/laravel/testing.html) and prevents the data stored in the session from being persisted.

### Driver Prerequisites

#### Database

When using the `database` session driver, you will need to create a table to contain the session items. Below is an example `Schema` declaration for the table:
```php
    Schema::create('sessions', function ($table) {
        $table->string('id')->unique();
        $table->unsignedInteger('user_id')->nullable();
        $table->string('ip_address', 45)->nullable();
        $table->text('user_agent')->nullable();
        $table->text('payload');
        $table->integer('last_activity');
    });
```
You may use the `session:table` Artisan command to generate this migration:
```php
    php artisan session:table

    php artisan migrate
```
#### Redis

Before using Redis sessions with Laravel, you will need to install the `predis/predis` package (~1.0) via Composer. You may configure your Redis connections in the `database` configuration file. In the `session` configuration file, the `connection` option may be used to specify which Redis connection is used by the session.

## Using The Session

### Retrieving Data

There are two primary ways of working with session data in Laravel: the global `session` helper and via a `Request` instance. First, let's look at accessing the session via a `Request` instance, which can be type-hinted on a controller method. Remember, controller method dependencies are automatically injected via the Laravel [service container](/mk/laravel/container.html):
```php
    <?php

    namespace App\Http\Controllers;

    use Illuminate\Http\Request;
    use App\Http\Controllers\Controller;

    class UserController extends Controller
    {
        /**
         * Show the profile for the given user.
         *
         * @param  Request  $request
         * @param  int  $id
         * @return Response
         */
        public function show(Request $request, $id)
        {
            $value = $request->session()->get('key');

            //
        }
    }
```
When you retrieve a value from the session, you may also pass a default value as the second argument to the `get` method. This default value will be returned if the specified key does not exist in the session. If you pass a `Closure` as the default value to the `get` method and the requested key does not exist, the `Closure` will be executed and its result returned:
```php
    $value = $request->session()->get('key', 'default');

    $value = $request->session()->get('key', function () {
        return 'default';
    });
```
#### The Global Session Helper

You may also use the global `session` PHP function to retrieve and store data in the session. When the `session` helper is called with a single, string argument, it will return the value of that session key. When the helper is called with an array of key / value pairs, those values will be stored in the session:
```php
    Route::get('home', function () {
        // Retrieve a piece of data from the session...
        $value = session('key');

        // Specifying a default value...
        $value = session('key', 'default');

        // Store a piece of data in the session...
        session(['key' => 'value']);
    });
```
> {tip} There is little practical difference between using the session via an HTTP request instance versus using the global `session` helper. Both methods are [testable](/mk/laravel/testing.html) via the `assertSessionHas` method which is available in all of your test cases.

#### Retrieving All Session Data

If you would like to retrieve all the data in the session, you may use the `all` method:
```php
    $data = $request->session()->all();
```
#### Determining If An Item Exists In The Session

To determine if a value is present in the session, you may use the `has` method. The `has` method returns `true` if the value is present and is not `null`:
```php
    if ($request->session()->has('users')) {
        //
    }
```
To determine if a value is present in the session, even if its value is `null`, you may use the `exists` method. The `exists` method returns `true` if the value is present:
```php
    if ($request->session()->exists('users')) {
        //
    }
```

### Storing Data

To store data in the session, you will typically use the `put` method or the `session` helper:
```php
    // Via a request instance...
    $request->session()->put('key', 'value');

    // Via the global helper...
    session(['key' => 'value']);
```
#### Pushing To Array Session Values

The `push` method may be used to push a new value onto a session value that is an array. For example, if the `user.teams` key contains an array of team names, you may push a new value onto the array like so:
```php
    $request->session()->push('user.teams', 'developers');
```
#### Retrieving & Deleting An Item

The `pull` method will retrieve and delete an item from the session in a single statement:
```php
    $value = $request->session()->pull('key', 'default');
```

### Flash Data

Sometimes you may wish to store items in the session only for the next request. You may do so using the `flash` method. Data stored in the session using this method will only be available during the subsequent HTTP request, and then will be deleted. Flash data is primarily useful for short-lived status messages:
```php
    $request->session()->flash('status', 'Task was successful!');
```
If you need to keep your flash data around for several requests, you may use the `reflash` method, which will keep all of the flash data for an additional request. If you only need to keep specific flash data, you may use the `keep` method:
```php
    $request->session()->reflash();

    $request->session()->keep(['username', 'email']);
```

### Deleting Data

The `forget` method will remove a piece of data from the session. If you would like to remove all data from the session, you may use the `flush` method:
```php
    $request->session()->forget('key');

    $request->session()->flush();
```

### Regenerating The Session ID

Regenerating the session ID is often done in order to prevent malicious users from exploiting a [session fixation](https://en.wikipedia.org/wiki/Session_fixation) attack on your application.

Laravel automatically regenerates the session ID during authentication if you are using the built-in `LoginController`; however, if you need to manually regenerate the session ID, you may use the `regenerate` method.
```php
    $request->session()->regenerate();
```

## Adding Custom Session Drivers

#### Implementing The Driver

Your custom session driver should implement the `SessionHandlerInterface`. This interface contains just a few simple methods we need to implement. A stubbed MongoDB implementation looks something like this:
```php
    <?php

    namespace App\Extensions;

    class MongoHandler implements SessionHandlerInterface
    {
        public function open($savePath, $sessionName) {}
        public function close() {}
        public function read($sessionId) {}
        public function write($sessionId, $data) {}
        public function destroy($sessionId) {}
        public function gc($lifetime) {}
    }
```
> {tip} Laravel does not ship with a directory to contain your extensions. You are free to place them anywhere you like. In this example, we have created an `Extensions` directory to house the `MongoHandler`.

Since the purpose of these methods is not readily understandable, let's quickly cover what each of the methods do:

- The `open` method would typically be used in file based session store systems. Since Laravel ships with a `file` session driver, you will almost never need to put anything in this method. You can leave it as an empty stub. It is simply a fact of poor interface design (which we'll discuss later) that PHP requires us to implement this method.
- The `close` method, like the `open` method, can also usually be disregarded. For most drivers, it is not needed.
- The `read` method should return the string version of the session data associated with the given `$sessionId`. There is no need to do any serialization or other encoding when retrieving or storing session data in your driver, as Laravel will perform the serialization for you.
- The `write` method should write the given `$data` string associated with the `$sessionId` to some persistent storage system, such as MongoDB, Dynamo, etc.  Again, you should not perform any serialization - Laravel will have already handled that for you.
- The `destroy` method should remove the data associated with the `$sessionId` from persistent storage.
- The `gc` method should destroy all session data that is older than the given `$lifetime`, which is a UNIX timestamp. For self-expiring systems like Memcached and Redis, this method may be left empty.

#### Registering The Driver

Once your driver has been implemented, you are ready to register it with the framework. To add additional drivers to Laravel's session backend, you may use the `extend` method on the `Session` [facade](/mk/laravel/facades.html). You should call the `extend` method from the `boot` method of a [service provider](/mk/laravel/providers.html). You may do this from the existing `AppServiceProvider` or create an entirely new provider:
```php
    <?php

    namespace App\Providers;

    use App\Extensions\MongoSessionStore;
    use Illuminate\Support\Facades\Session;
    use Illuminate\Support\ServiceProvider;

    class SessionServiceProvider extends ServiceProvider
    {
        /**
         * Perform post-registration booting of services.
         *
         * @return void
         */
        public function boot()
        {
            Session::extend('mongo', function ($app) {
                // Return implementation of SessionHandlerInterface...
                return new MongoSessionStore;
            });
        }

        /**
         * Register bindings in the container.
         *
         * @return void
         */
        public function register()
        {
            //
        }
    }
```
Once the session driver has been registered, you may use the `mongo` driver in your `config/session.php` configuration file.


text:
<?xml version="1.0" encoding="utf-8"?>
<!--
  ~ Copyright (C) 2015 The Android Open Source Project
  ~
  ~ Licensed under the Apache License, Version 2.0 (the "License");
  ~ you may not use this file except in compliance with the License.
  ~ You may obtain a copy of the License at
  ~
  ~      http://www.apache.org/licenses/LICENSE-2.0
  ~
  ~ Unless required by applicable law or agreed to in writing, software
  ~ distributed under the License is distributed on an "AS IS" BASIS,
  ~ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  ~ See the License for the specific language governing permissions and
  ~ limitations under the License
  -->

<resources>
    <style name="PreferenceThemeOverlay">
        <item name="preferenceScreenStyle">@style/Preference.PreferenceScreen.Material</item>
        <item name="preferenceFragmentCompatStyle">@style/PreferenceFragment.Material</item>
        <item name="preferenceFragmentStyle">@style/PreferenceFragment.Material</item>
        <item name="preferenceCategoryStyle">@style/Preference.Category.Material</item>
        <item name="preferenceStyle">@style/Preference.Material</item>
        <item name="preferenceInformationStyle">@style/Preference.Information.Material</item>
        <item name="checkBoxPreferenceStyle">@style/Preference.CheckBoxPreference.Material</item>
        <item name="switchPreferenceCompatStyle">@style/Preference.SwitchPreferenceCompat.Material</item>
        <item name="switchPreferenceStyle">@style/Preference.SwitchPreference.Material</item>
        <item name="dialogPreferenceStyle">@style/Preference.DialogPreference.Material</item>
        <item name="editTextPreferenceStyle">@style/Preference.DialogPreference.EditTextPreference.Material</item>
        <item name="preferenceFragmentListStyle">@style/PreferenceFragmentList.Material</item>
        <item name="dropDownPreferenceStyle">@style/Preference.DropDownPreference</item>
        <item name="simpleMenuPreferenceStyle">@style/Preference.SimpleMenuPreference</item>
    </style>
</resources>


text:
``` eval_rst
.. include:: /stub-notice.rst
```
# Station Operations Table (MSSQL)


text:
package com.ccadllc.cedi.dtrace
package logging

import cats.effect.Sync

import io.chrisdavenport.log4cats.slf4j.Slf4jLogger

/**
 * Provides the for the platform-specific initialization of the underlying logging
 * configuration for the JVM platform, using `slf4j`.
 */
object LoggingConfig {
  def createLoggers[F[_]: Sync](names: Loggers.Names): Loggers[F] = new Loggers(
    Slf4jLogger.getLoggerFromName[F](names.text),
    Slf4jLogger.getLoggerFromName[F](names.json))
}


text:
"""
* *******************************************************
* Copyright VMware, Inc. 2016. All Rights Reserved.
* SPDX-License-Identifier: MIT
* *******************************************************
*
* DISCLAIMER. THIS PROGRAM IS PROVIDED TO YOU "AS IS" WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, WHETHER ORAL OR WRITTEN,
* EXPRESS OR IMPLIED. THE AUTHOR SPECIFICALLY DISCLAIMS ANY IMPLIED
* WARRANTIES OR CONDITIONS OF MERCHANTABILITY, SATISFACTORY QUALITY,
* NON-INFRINGEMENT AND FITNESS FOR A PARTICULAR PURPOSE.
"""

__author__ = 'VMware, Inc.'
__copyright__ = 'Copyright 2016 VMware, Inc. All rights reserved.'
__vcenter_version__ = '6.0+'

try:
    import urllib2
except ImportError:
    import urllib.request as urllib2

from com.vmware.content.library.item_client import UpdateSessionModel
from samples.vsphere.common.id_generator import generate_random_uuid
from samples.vsphere.common.sample_base import SampleBase
from samples.vsphere.contentlibrary.lib.cls_api_client import ClsApiClient
from samples.vsphere.contentlibrary.lib.cls_api_helper import ClsApiHelper

class ContentUpdate(SampleBase):
    """
    Demonstrates the workflow of updating a content library item.

    Note: the workflow needs an existing datastore (of type vmfs) with available storage.
    """

    ISO_FILE_1 = 'test.iso'
    ISO_FILE_2 = 'test-2.iso'
    ISO_ITEM_NAME = 'test'

    def __init__(self):
        SampleBase.__init__(self, self.__doc__)
        self.servicemanager = None
        self.client = None
        self.helper = None
        self.datastore_name = None
        self.lib_name = "demo-lib"
        self.local_library = None

    def _options(self):
        self.argparser.add_argument('-datastorename', '--datastorename',
                                    help='The name of the datastore where '
                                         'the library will be created.')

    def _setup(self):
        self.datastore_name = self.args.datastorename
        assert self.datastore_name is not None

        self.servicemanager = self.get_service_manager()
        self.client = ClsApiClient(self.servicemanager)
        self.helper = ClsApiHelper(self.client, self.skip_verification)

    def _execute(self):
        storage_backings = self.helper.create_storage_backings(self.servicemanager,
                                                               self.datastore_name)

        library_id = self.helper.create_local_library(storage_backings, self.lib_name)
        self.local_library = self.client.local_library_service.get(library_id)
        self.delete_and_upload_scenario(library_id)
        self.replace_scenario(library_id)

    def replace_scenario(self, library_id):
        """
        :param library_id: the Iso item will be created, and then replaced in this library
        :return: None

        Content update scenario 2:
        Update ISO library item by creating an update session for the
        item, then adding the new ISO file using the same session file
        name into the update session, which will replace the existing
        ISO file upon session complete.
        """

        iso_item_id = self.helper.create_library_item(library_id=library_id,
                                                      item_name=self.ISO_ITEM_NAME,
                                                      item_description='Sample iso file',
                                                      item_type='iso')
        print('ISO Library item version (on creation) {0}:'.format(
            self.get_item_version(iso_item_id)))

        iso_files_map = self.helper.get_iso_file_map(item_filename=self.ISO_FILE_1,
                                                     disk_filename=self.ISO_FILE_1)
        self.helper.upload_files(library_item_id=iso_item_id, files_map=iso_files_map)
        original_version = self.get_item_version(iso_item_id)
        print('ISO Library item version (on original content upload) {0}:'.format(
            original_version))

        session_id = self.client.upload_service.create(
            create_spec=UpdateSessionModel(library_item_id=iso_item_id),
            client_token=generate_random_uuid())
        # Use the same item filename (update endpoint, as it's a replace scenario)
        iso_files_map = self.helper.get_iso_file_map(item_filename=self.ISO_FILE_1,
                                                     disk_filename=self.ISO_FILE_2)

        self.helper.upload_files_in_session(iso_files_map, session_id)
        self.client.upload_service.complete(session_id)
        self.client.upload_service.delete(session_id)
        updated_version = self.get_item_version(iso_item_id)
        print('ISO Library item version (after content update): {0}'.format(
            updated_version))
        assert updated_version > original_version, 'content update should increase the version'

    def delete_and_upload_scenario(self, library_id):
        """
        :param library_id: the OVF item will be created and updated in this library
        :return: None

        Content update scenario 1:
        Update OVF library item by creating an update session for the
        OVF item, removing all existing files in the session, then
        adding all new files into the same update session, and completing
        the session to finish the content update.
        """

        # Create a new library item in the content library for uploading the files
        ovf_item_id = self.helper.create_library_item(library_id=library_id,
                                                      item_name='demo-ovf-item',
                                                      item_description='Sample simple VM template',
                                                      item_type='ovf')
        assert ovf_item_id is not None
        print('Library item created id: {0}'.format(ovf_item_id))
        print('OVF Library item version (at creation) {0}:'.format(
            self.get_item_version(ovf_item_id)))

        # Upload a VM template to the CL
        ovf_files_map = self.helper.get_ovf_files_map(ClsApiHelper.SIMPLE_OVF_RELATIVE_DIR)
        self.helper.upload_files(library_item_id=ovf_item_id, files_map=ovf_files_map)
        print('Uploaded ovf and vmdk files to library item {0}'.format(ovf_item_id))
        original_version = self.get_item_version(ovf_item_id)
        print('OVF Library item version (on original content upload): {0}'.format(
            original_version))

        # Create a new session and perform content update
        session_id = self.client.upload_service.create(
            create_spec=UpdateSessionModel(library_item_id=ovf_item_id),
            client_token=generate_random_uuid())
        existing_files = self.client.upload_file_service.list(session_id)
        for file in existing_files:
            print('deleting {0}'.format(file.name))
            self.client.upload_file_service.remove(session_id, file.name)
        ovf_files_map = self.helper.get_ovf_files_map(
            ovf_location=ClsApiHelper.PLAIN_OVF_RELATIVE_DIR)
        self.helper.upload_files_in_session(ovf_files_map, session_id)
        self.client.upload_service.complete(session_id)
        self.client.upload_service.delete(session_id)
        updated_version = self.get_item_version(ovf_item_id)
        print('OVF Library item version (after content update): {0}'.format(
            updated_version))
        assert updated_version > original_version, 'content update should increase the version'

    def get_item_version(self, item_id):
        ovf_item_model = self.client.library_item_service.get(item_id)
        pre_update_version = ovf_item_model.content_version
        return pre_update_version

    def _cleanup(self):
        if self.local_library:
            self.client.local_library_service.delete(library_id=self.local_library.id)
            print('Deleted Library Id: {0}'.format(self.local_library.id))

def main():
    content_update_sample = ContentUpdate()
    content_update_sample.main()

if __name__ == '__main__':
    main()


text:
Edge

### Version Introduced
4.5.1

### Source Analyzer Status
Planned

### Change Description

Beginning in the .NET Framework 4.5.1, the .NET Framework will attempt to
automatically reconnect broken SQL connections. Although this will typically
make apps more reliable, there are edge cases in which an app needs to know that
the connection was lost so that it can take some action upon reconnection.

- [ ] Quirked
- [ ] Build-time break

### Recommended Action

If this feature is undesirable due to compatibility concerns, it can be disabled
by setting the
<xref:System.Data.SqlClient.SqlConnectionStringBuilder.ConnectRetryCount?displayProperty=name>
property of a connection string (or
<xref:System.Data.SqlClient.SqlConnectionStringBuilder?displayProperty=name>) to
0.

### Affected APIs
* `M:System.Data.IDbConnection.set_ConnectionString(System.String)`
* `M:System.Data.SqlClient.SqlConnection.set_ConnectionString(System.String)`
* `M:System.Configuration.ConnectionStringSettings.set_ConnectionString(System.String)`
* `M:System.Data.Common.DbConnection.set_ConnectionString(System.String)`
* `M:System.Data.Common.DbConnectionStringBuilder.set_ConnectionString(System.String)`
* `M:System.Data.SqlClient.SqlConnectionStringBuilder.#ctor`
* `M:System.Data.SqlClient.SqlConnectionStringBuilder.#ctor(System.String)`
* `M:System.Data.Common.DbConnectionStringBuilder.#ctor`
* `M:System.Data.Common.DbConnectionStringBuilder.#ctor(System.Boolean)`

### Categories
ADO.NET
Data

[More information](http://blogs.msdn.com/b/dotnet/archive/2013/10/17/net-framework-4-5-1-rtm-gt-start-coding.aspx)

<!--
    ### Notes
    It would be very difficult to know if code depended on not auto-reconnecting and ADO.NET connection.
    Source analyzer status: Planned - No tracking work item yet
    Single-diagnostic compilation action analyzer
-->

<!-- breaking change id: 119 -->


text:
package org.apache.felix.ipojo.handlers.dependency;

import org.apache.felix.ipojo.Factory;
import org.apache.felix.ipojo.architecture.HandlerDescription;
import org.apache.felix.ipojo.dependency.impl.ServiceReferenceManager;
import org.apache.felix.ipojo.dependency.interceptors.ServiceTrackingInterceptor;
import org.apache.felix.ipojo.metadata.Attribute;
import org.apache.felix.ipojo.metadata.Element;
import org.apache.felix.ipojo.util.DependencyModel;
import org.osgi.framework.Constants;
import org.osgi.framework.ServiceReference;

import java.util.List;
import java.util.Map;

/**
 * Dependency Handler Description.
 *
 * @author Felix Project Team
 */
public class DependencyHandlerDescription extends HandlerDescription {

    /**
     * Dependencies managed by the dependency handler.
     */
    private DependencyDescription[] m_dependencies = new DependencyDescription[0];

    /**
     * Creates the Dependency Handler description.
     * @param handler the Dependency Handler.
     * @param deps the Dependencies
     */
    public DependencyHandlerDescription(DependencyHandler handler, Dependency[] deps) {
        super(handler);
        m_dependencies = new DependencyDescription[deps.length];
        for (int i = 0; i < m_dependencies.length; i++) {
            m_dependencies[i] = new DependencyDescription(deps[i]);
        }
    }

    /**
     * Get dependencies description.
     * @return the dependencies list.
     */
    public DependencyDescription[] getDependencies() {
        return m_dependencies;
    }

    /**
     * Builds the Dependency Handler description.
     * @return the handler description.
     * @see org.apache.felix.ipojo.architecture.HandlerDescription#getHandlerInfo()
     */
    public Element getHandlerInfo() {
        Element deps = super.getHandlerInfo();
        for (DependencyDescription dependency : m_dependencies) {
            String state = "resolved";
            if (dependency.getState() == DependencyModel.UNRESOLVED) {
                state = "unresolved";
            }
            if (dependency.getState() == DependencyModel.BROKEN) {
                state = "broken";
            }
            Element dep = new Element("Requires", "");
            dep.addAttribute(new Attribute("Specification", dependency.getInterface()));
            dep.addAttribute(new Attribute("Id", dependency.getId()));

            if (dependency.getFilter() != null) {
                dep.addAttribute(new Attribute("Filter", dependency.getFilter()));
            }

            if (dependency.isOptional()) {
                dep.addAttribute(new Attribute("Optional", "true"));
                if (dependency.supportsNullable()) {
                    dep.addAttribute(new Attribute("Nullable", "true"));
                }
                if (dependency.getDefaultImplementation() != null) {
                    dep.addAttribute(new Attribute("Default-Implementation", dependency.getDefaultImplementation()));
                }
            } else {
                dep.addAttribute(new Attribute("Optional", "false"));
            }

            if (dependency.isMultiple()) {
                dep.addAttribute(new Attribute("Aggregate", "true"));
            } else {
                dep.addAttribute(new Attribute("Aggregate", "false"));
            }

            if (dependency.isProxy()) {
                dep.addAttribute(new Attribute("Proxy", "true"));
            } else {
                dep.addAttribute(new Attribute("Proxy", "false"));
            }

            String policy = "dynamic";
            if (dependency.getPolicy() == DependencyModel.STATIC_BINDING_POLICY) {
                policy = "static";
            } else if (dependency.getPolicy() == DependencyModel.DYNAMIC_PRIORITY_BINDING_POLICY) {
                policy = "dynamic-priority";
            }
            dep.addAttribute(new Attribute("Binding-Policy", policy));

            if (dependency.getComparator() != null) {
                dep.addAttribute(new Attribute("Comparator", dependency.getComparator()));
            }

            dep.addAttribute(new Attribute("State", state));
            List<ServiceReference> set = dependency.getUsedServices();
            if (set != null) {
                for (ServiceReference ref : set) {
                    Element use = new Element("Uses", "");
                    computeServiceReferenceDescription(ref, use);
                    dep.addElement(use);
                }
            }

            set = dependency.getServiceReferences();
            if (set != null) {
                for (ServiceReference ref : set) {
                    Element use = new Element("Selected", "");
                    computeServiceReferenceDescription(ref, use);
                    dep.addElement(use);
                }
            }

            final ServiceReferenceManager serviceReferenceManager = dependency.getDependency()
                    .getServiceReferenceManager();
            if (serviceReferenceManager == null) {
                // Exit here, cannot compute anything else.
                deps.addElement(dep);
                continue;
            }

            set = serviceReferenceManager.getMatchingServices();
            if (set != null) {
                for (ServiceReference ref : set) {
                    Element use = new Element("Matches", "");
                    computeServiceReferenceDescription(ref, use);
                    dep.addElement(use);
                }
            }

            // Add interceptors to the description
            List<ServiceReference> interceptors = serviceReferenceManager.getTrackingInterceptorReferences();
            for (ServiceReference ref : interceptors) {
                Element itcp = new Element("ServiceTrackingInterceptor", "");
                computeInterceptorDescription(ref, itcp);
                dep.addElement(itcp);
            }

            ServiceReference ref = serviceReferenceManager.getRankingInterceptorReference();
            if (ref != null) {
                Element itcp = new Element("ServiceRankingInterceptor", "");
                computeInterceptorDescription(ref, itcp);
                dep.addElement(itcp);
            }

            interceptors = serviceReferenceManager.getBindingInterceptorReferences();
            for (ServiceReference rf : interceptors) {
                Element itcp = new Element("ServiceBindingInterceptor", "");
                computeInterceptorDescription(rf, itcp);
                dep.addElement(itcp);
            }

            deps.addElement(dep);
        }
        return deps;
    }

    private void computeServiceReferenceDescription(ServiceReference ref, Element use) {
        use.addAttribute(new Attribute(Constants.SERVICE_ID, ref.getProperty(Constants.SERVICE_ID).toString()));
        String instance = (String) ref.getProperty(Factory.INSTANCE_NAME_PROPERTY);
        if (instance != null) {
            use.addAttribute(new Attribute(Factory.INSTANCE_NAME_PROPERTY, instance));
        }
    }

    private void computeInterceptorDescription(ServiceReference ref, Element itcp) {
        itcp.addAttribute(new Attribute(Constants.SERVICE_ID, ref.getProperty(Constants.SERVICE_ID).toString()));
        itcp.addAttribute(new Attribute("bundle.id", Long.toString(ref.getBundle().getBundleId())));
        String instance = (String) ref.getProperty(Factory.INSTANCE_NAME_PROPERTY);
        if (instance != null) {
            itcp.addAttribute(new Attribute(Factory.INSTANCE_NAME_PROPERTY, instance));
        }
        itcp.addAttribute(new Attribute("target", ref.getProperty(ServiceTrackingInterceptor.TARGET_PROPERTY)
                .toString()));
    }

}


text:
package org.levigo.jadice.server.converterclient.gui.jmx;

import org.jfree.data.time.RegularTimePeriod;
import org.jfree.data.time.TimeSeriesDataItem;

import com.levigo.jadice.server.Job.State;

public class JobExecutionDataItem extends TimeSeriesDataItem {

  private static final long serialVersionUID = 1L;

  private final JobStateEventDTO event;

  public JobExecutionDataItem(RegularTimePeriod period, JobStateEventDTO event) {
    super(period, event.age);
    this.event = event;
  }

  public String getID() {
    return event.id;
  }

  public String getJobType() {
    return event.type;
  }

  public State getState() {
    return event.state;
  }
}