text:
#include "config.h"

#include "Reporter.hpp"
#include "geopm_reporter.h"

#include <unistd.h>
#include <string.h>
#include <fcntl.h>
#include <limits.h>
#include <cmath>

#include <sstream>
#include <fstream>
#include <algorithm>
#include <numeric>
#include <iostream>
#include <iomanip>

#include "geopm/PlatformIO.hpp"
#include "geopm/PlatformTopo.hpp"
#include "SampleAggregator.hpp"
#include "ProcessRegionAggregator.hpp"
#include "ApplicationIO.hpp"
#include "Comm.hpp"
#include "TreeComm.hpp"
#include "geopm/Exception.hpp"
#include "geopm/Helper.hpp"
#include "geopm_hash.h"
#include "geopm_version.h"
#include "geopm_debug.hpp"
#include "Environment.hpp"
#include "PlatformIOProf.hpp"
#include "geopm_time.h"

namespace geopm
{
    ReporterImp::ReporterImp(const std::string &start_time,
                             const std::string &report_name,
                             PlatformIO &platform_io,
                             const PlatformTopo &platform_topo,
                             int rank)
        : ReporterImp(start_time,
                      report_name,
                      platform_io,
                      platform_topo,
                      rank,
                      SampleAggregator::make_unique(),
                      nullptr,
                      environment().report_signals(),
                      environment().policy(),
                      environment().do_endpoint())
    {

    }

    ReporterImp::ReporterImp(const std::string &start_time,
                             const std::string &report_name,
                             PlatformIO &platform_io,
                             const PlatformTopo &platform_topo,
                             int rank,
                             std::shared_ptr<SampleAggregator> sample_agg,
                             std::shared_ptr<ProcessRegionAggregator> proc_agg,
                             const std::vector<std::pair<std::string, int> > &env_signals,
                             const std::string &policy_path,
                             bool do_endpoint)
        : m_start_time(start_time)
        , m_report_name(report_name)
        , m_platform_io(platform_io)
        , m_platform_topo(platform_topo)
        , m_sample_agg(sample_agg)
        , m_proc_region_agg(proc_agg)
        , m_env_signals(env_signals)
        , m_policy_path(policy_path)
        , m_do_endpoint(do_endpoint)
        , m_rank(rank)
        , m_sticker_freq(m_platform_io.read_signal("CPUINFO::FREQ_STICKER", GEOPM_DOMAIN_BOARD, 0))
        , m_epoch_count_idx(-1)
    {
        GEOPM_DEBUG_ASSERT(m_sample_agg != nullptr, "m_sample_agg cannot be null");

        init_sync_fields();

        init_environment_signals();

        m_epoch_count_idx = m_platform_io.push_signal("EPOCH_COUNT", GEOPM_DOMAIN_BOARD, 0);

        if (!m_rank) {
            // check if report file can be created
            if (!m_report_name.empty()) {
                std::ofstream test_open(m_report_name);
                if (!test_open.good()) {
                    std::cerr << "Warning: <geopm> Unable to open report file '" << m_report_name
                              << "' for writing: " << strerror(errno) << std::endl;
                }
                std::remove(m_report_name.c_str());
            }
        }
    }

    void ReporterImp::init(void)
    {
        if (m_proc_region_agg == nullptr) {
            // ProcessRegionAggregator should not be constructed until
            // application connection is established.
            m_proc_region_agg = ProcessRegionAggregator::make_unique();
        }
    }

    void ReporterImp::update()
    {
        m_sample_agg->update();
        if (m_proc_region_agg != nullptr) {
            m_proc_region_agg->update();
        }
    }

    void ReporterImp::generate(const std::string &agent_name,
                               const std::vector<std::pair<std::string, std::string> > &agent_report_header,
                               const std::vector<std::pair<std::string, std::string> > &agent_host_report,
                               const std::map<uint64_t, std::vector<std::pair<std::string, std::string> > > &agent_region_report,
                               const ApplicationIO &application_io,
                               std::shared_ptr<Comm> comm,
                               const TreeComm &tree_comm)
    {
        std::string report_name(application_io.report_name());
        if (report_name.size() == 0) {
            return;
        }

        int rank = comm->rank();
        std::ofstream common_report;
        if (!rank) {
            common_report.open(report_name);
            if (!common_report.good()) {
                throw Exception("Failed to open report file", GEOPM_ERROR_INVALID, __FILE__, __LINE__);
            }
            common_report << create_header(agent_name, application_io.profile_name(), agent_report_header);
        }

        std::string host_report = create_report(application_io.region_name_set(),
                                                get_max_memory(),
                                                tree_comm.overhead_send(),
                                                agent_host_report,
                                                agent_region_report);
        std::string full_report = gather_report(host_report, comm);

        if (!rank) {
            common_report << full_report;
            common_report << std::endl;
            common_report.close();
        }
    }

    std::string ReporterImp::generate(const std::string &profile_name,
                                      const std::string &agent_name,
                                      const std::vector<std::pair<std::string, std::string> > &agent_report_header,
                                      const std::vector<std::pair<std::string, std::string> > &agent_host_report,
                                      const std::map<uint64_t, std::vector<std::pair<std::string, std::string> > > &agent_region_report)
    {
        std::ostringstream common_report;
        common_report << create_header(agent_name, profile_name, agent_report_header);

        common_report << create_report({},
                                       get_max_memory(),
                                       0.0,
                                       agent_host_report,
                                       agent_region_report);
        common_report << std::endl;
        return common_report.str();
    }

    std::string ReporterImp::create_header(const std::string &agent_name,
                                           const std::string &profile_name,
                                           const std::vector<std::pair<std::string, std::string> > &agent_report_header)
    {
        std::ostringstream common_report;
        // make header
        std::string policy_str = "{}";
        if (m_do_endpoint) {
            policy_str = "DYNAMIC";
        }
        else if (m_policy_path.size() > 0) {
            try {
                policy_str = read_file(m_policy_path);
            }
            catch(...) {
                policy_str = m_policy_path;
            }
        }
        std::vector<std::pair<std::string, std::string> > header {
            {"GEOPM Version", geopm_version()},
            {"Start Time", m_start_time},
            {"Profile", profile_name},
            {"Agent", agent_name},
            {"Policy", policy_str}
        };
        yaml_write(common_report, M_INDENT_HEADER, header);
        yaml_write(common_report, M_INDENT_HEADER, agent_report_header);
        common_report << "\n";
        yaml_write(common_report, M_INDENT_HOST, "Hosts:");
        return common_report.str();
    }

    std::string ReporterImp::create_report(const std::set<std::string> &region_name_set, double max_memory, double comm_overhead,
                                           const std::vector<std::pair<std::string, std::string> > &agent_host_report,
                                           const std::map<uint64_t, std::vector<std::pair<std::string, std::string> > > &agent_region_report)
    {
        // per-host report
        std::ostringstream report;
        yaml_write(report, M_INDENT_HOST_NAME, hostname() + ":");
        yaml_write(report, M_INDENT_HOST_AGENT, agent_host_report);
        if (region_name_set.size() != 0) {
            yaml_write(report, M_INDENT_REGION, "Regions:");
        }

        // vector of region data, in descending order by runtime
        struct region_info {
            std::string name;
            uint64_t hash;
            double per_rank_avg_runtime;
            int count;
        };

        std::vector<region_info> region_ordered;
        GEOPM_DEBUG_ASSERT(region_name_set.size() == 0 ||
                           m_proc_region_agg != nullptr,
                           "ReporterImp::create_report(): region set is not empty, but region aggregator pointer is null");
        for (const auto &region : region_name_set) {
            uint64_t region_hash = geopm_crc32_str(region.c_str());
            int count = m_proc_region_agg->get_count_average(region_hash);
            if (count > 0) {
                region_ordered.push_back({region,
                                          region_hash,
                                          m_proc_region_agg->get_runtime_average(region_hash),
                                          count});
            }
        }
        // sort based on averge runtime, descending
        std::sort(region_ordered.begin(), region_ordered.end(),
                  [] (const region_info &a,
                      const region_info &b) -> bool {
                      return a.per_rank_avg_runtime > b.per_rank_avg_runtime;
                  });

        double total_marked_runtime = 0.0;
        for (const auto &region : region_ordered) {
#ifdef GEOPM_DEBUG
            if (GEOPM_REGION_HASH_INVALID == region.hash) {
                throw Exception("ReporterImp::generate(): Invalid hash value detected.",
                                GEOPM_ERROR_LOGIC, __FILE__, __LINE__);
            }
#endif
            yaml_write(report, M_INDENT_REGION, "-");
            yaml_write(report, M_INDENT_REGION_FIELD,
                       {{"region", '"' + region.name + '"'},
                        {"hash", geopm::string_format_hex(region.hash)}});
            yaml_write(report, M_INDENT_REGION_FIELD,
                       {{"runtime (s)", region.per_rank_avg_runtime},
                        {"count", region.count}});
            auto region_data = get_region_data(region.hash);
            yaml_write(report, M_INDENT_REGION_FIELD, region_data);
            const auto &it = agent_region_report.find(region.hash);
            if (it != agent_region_report.end()) {
                yaml_write(report, M_INDENT_REGION_FIELD, agent_region_report.at(region.hash));
            }
            total_marked_runtime += region.per_rank_avg_runtime;
        }

        double epoch_count = m_platform_io.sample(m_epoch_count_idx);
        // Do not add epoch or unmarked section if no application attached
        if (!std::isnan(epoch_count)) {
            yaml_write(report, M_INDENT_UNMARKED, "Unmarked Totals:");
            double unmarked_time = m_sample_agg->sample_application(m_sync_signal_idx["TIME"]) -
                                   total_marked_runtime;
            yaml_write(report, M_INDENT_UNMARKED_FIELD,
                       {{"runtime (s)", unmarked_time},
                        {"count", 0}});
            auto unmarked_data = get_region_data(GEOPM_REGION_HASH_UNMARKED);
            yaml_write(report, M_INDENT_UNMARKED_FIELD, unmarked_data);
            // agent extensions for unmarked
            const auto &it = agent_region_report.find(GEOPM_REGION_HASH_UNMARKED);
            if (it != agent_region_report.end()) {
                yaml_write(report, M_INDENT_UNMARKED_FIELD, agent_region_report.at(GEOPM_REGION_HASH_UNMARKED));
            }

            yaml_write(report, M_INDENT_EPOCH, "Epoch Totals:");
            double epoch_runtime = m_sample_agg->sample_epoch(m_sync_signal_idx["TIME"]);
            yaml_write(report, M_INDENT_EPOCH_FIELD,
                       {{"runtime (s)", epoch_runtime},
                        {"count", (int)epoch_count}});
            auto epoch_data = get_region_data(GEOPM_REGION_HASH_EPOCH);
            yaml_write(report, M_INDENT_EPOCH_FIELD, epoch_data);
        }

        yaml_write(report, M_INDENT_TOTALS, "Application Totals:");
        double total_runtime = m_sample_agg->sample_application(m_sync_signal_idx["TIME"]);
        yaml_write(report, M_INDENT_TOTALS_FIELD,
                   {{"runtime (s)", total_runtime},
                    {"count", 0}});
        auto region_data = get_region_data(GEOPM_REGION_HASH_APP);
        yaml_write(report, M_INDENT_TOTALS_FIELD, region_data);
        // Controller overhead
        std::vector<std::pair<std::string, double> > overhead {
            {"geopmctl memory HWM (B)", max_memory},
            {"geopmctl network BW (B/s)", comm_overhead / total_runtime}
        };
        yaml_write(report, M_INDENT_TOTALS_FIELD, overhead);
        return report.str();
    }

    std::string ReporterImp::gather_report(const std::string &host_report, std::shared_ptr<Comm> comm)
    {
        // aggregate reports from every node
        size_t buffer_size = host_report.size();
        std::vector<char> report_buffer;
        std::vector<size_t> buffer_size_array;
        std::vector<off_t> buffer_displacement;
        int num_ranks = comm->num_rank();
        buffer_size_array.resize(num_ranks);
        buffer_displacement.resize(num_ranks);
        comm->gather(&buffer_size, sizeof(size_t), buffer_size_array.data(),
                     sizeof(size_t), 0);

        if (comm->rank() == 0) {
            int full_report_size = std::accumulate(buffer_size_array.begin(), buffer_size_array.end(), 0) + 1;
            report_buffer.resize(full_report_size);
            buffer_displacement[0] = 0;
            for (int i = 1; i < num_ranks; ++i) {
                buffer_displacement[i] = buffer_displacement[i-1] + buffer_size_array[i-1];
            }
        }

        comm->gatherv((void *) (host_report.c_str()), sizeof(char) * buffer_size,
                      (void *) report_buffer.data(), buffer_size_array, buffer_displacement, 0);
        if (report_buffer.size() != 0) {
            report_buffer.back() = '\0';
        }
        else {
            report_buffer.push_back('\0');
        }
        return report_buffer.data();
    }

    void ReporterImp::init_sync_fields(void)
    {
        auto sample_only = [this](uint64_t hash, const std::vector<std::string> &sig) -> double
        {
            GEOPM_DEBUG_ASSERT(sig.size() == 1, "Wrong number of signals for sample_only()");
            return m_sample_agg->sample_region(m_sync_signal_idx[sig[0]], hash);
        };
        auto divide = [this](uint64_t hash, const std::vector<std::string> &sig) -> double
        {
            GEOPM_DEBUG_ASSERT(sig.size() == 2, "Wrong number of signals for divide()");
            double numer = m_sample_agg->sample_region(m_sync_signal_idx[sig[0]], hash);
            double denom = m_sample_agg->sample_region(m_sync_signal_idx[sig[1]], hash);
            return denom == 0 ? 0.0 : numer / denom;
        };
        auto divide_pct = [this](uint64_t hash, const std::vector<std::string> &sig) -> double
        {
            GEOPM_DEBUG_ASSERT(sig.size() == 2, "Wrong number of signals for divide_pct()");
            double numer = m_sample_agg->sample_region(m_sync_signal_idx[sig[0]], hash);
            double denom = m_sample_agg->sample_region(m_sync_signal_idx[sig[1]], hash);
            return denom == 0 ? 0.0 : 100.0 * numer / denom;
        };
        auto divide_sticker_scale = [this](uint64_t hash, const std::vector<std::string> &sig) -> double
        {
            GEOPM_DEBUG_ASSERT(sig.size() == 2, "Wrong number of signals for divide_sticker_scale()");
            double numer = m_sample_agg->sample_region(m_sync_signal_idx[sig[0]], hash);
            double denom = m_sample_agg->sample_region(m_sync_signal_idx[sig[1]], hash);
            return denom == 0 ? 0.0 : m_sticker_freq * numer / denom;
        };

        m_sync_fields = {
            {"sync-runtime (s)", {"TIME"}, sample_only},
            {"package-energy (J)", {"CPU_ENERGY"}, sample_only},
            {"dram-energy (J)", {"DRAM_ENERGY"}, sample_only},
            {"power (W)", {"CPU_ENERGY", "TIME"}, divide},
            {"frequency (%)", {"CPU_CYCLES_THREAD", "CPU_CYCLES_REFERENCE"}, divide_pct},
            {"frequency (Hz)", {"CPU_CYCLES_THREAD", "CPU_CYCLES_REFERENCE"}, divide_sticker_scale},
            {"time-hint-network (s)", {"TIME_HINT_NETWORK"}, sample_only},
            {"time-hint-ignore (s)", {"TIME_HINT_IGNORE"}, sample_only},
            {"time-hint-compute (s)", {"TIME_HINT_COMPUTE"}, sample_only},
            {"time-hint-memory (s)", {"TIME_HINT_MEMORY"}, sample_only},
            {"time-hint-io (s)", {"TIME_HINT_IO"}, sample_only},
            {"time-hint-serial (s)", {"TIME_HINT_SERIAL"}, sample_only},
            {"time-hint-parallel (s)", {"TIME_HINT_PARALLEL"}, sample_only},
            {"time-hint-unknown (s)", {"TIME_HINT_UNKNOWN"}, sample_only},
            {"time-hint-unset (s)", {"TIME_HINT_UNSET"}, sample_only},
            {"time-hint-spin (s)", {"TIME_HINT_SPIN"}, sample_only},
        };

        auto all_names = m_platform_io.signal_names();
        std::vector<m_sync_field_s> conditional_sync_fields = {
            {"gpu-energy (J)", {"GPU_ENERGY"}, sample_only},
            {"gpu-power (W)", {"GPU_POWER"}, sample_only},
            {"gpu-frequency (Hz)", {"GPU_CORE_FREQUENCY_STATUS"}, sample_only},
            {"uncore-frequency (Hz)", {"CPU_UNCORE_FREQUENCY_STATUS"}, sample_only}
        };

        for (const auto &field : conditional_sync_fields) {
            for (const auto &signal : field.supporting_signals) {
                if (all_names.count(signal) != 0) {
                    m_sync_fields.push_back(field);
                }
            }
        }

        for (const auto &field : m_sync_fields) {
            for (const auto &signal : field.supporting_signals) {
                m_sync_signal_idx[signal] = m_sample_agg->push_signal(signal, GEOPM_DOMAIN_BOARD, 0);
            }
        }
    }

    void ReporterImp::init_environment_signals(void)
    {
        for (const auto& signal_domain_pair : m_env_signals) {
            if (signal_domain_pair.second == GEOPM_DOMAIN_BOARD) {
                m_env_signal_name_idx.emplace_back(
                    signal_domain_pair.first,
                    m_sample_agg->push_signal(signal_domain_pair.first, GEOPM_DOMAIN_BOARD, 0));
            }
            else {
                std::string full_signal_name;
                const int& domain_type = signal_domain_pair.second;
                const int num_domains = m_platform_topo.num_domain(domain_type);
                for (int domain_idx = 0; domain_idx < num_domains; ++domain_idx) {
                    full_signal_name = signal_domain_pair.first + "@" + m_platform_topo.domain_type_to_name(signal_domain_pair.second);
                    full_signal_name += '-';
                    full_signal_name += std::to_string(domain_idx);
                    m_env_signal_name_idx.emplace_back(
                        full_signal_name,
                        m_sample_agg->push_signal(signal_domain_pair.first, domain_type, domain_idx));
                }
            }
        }
    }

    std::vector<std::pair<std::string, double> > ReporterImp::get_region_data(uint64_t region_hash)
    {
        std::vector<std::pair<std::string, double> > result;

        // sync fields as initialized in init_sync_fields
        for (const auto &field : m_sync_fields) {
            double value = field.func(region_hash, field.supporting_signals);
            if (!std::isnan(value)) { // Remove nan fields
                result.push_back({field.field_label, value});
            }
        }

        // signals added by user through environment
        for (const auto &env_it : m_env_signal_name_idx) {
            result.push_back({env_it.first, m_sample_agg->sample_region(env_it.second, region_hash)});
        }
        return result;
    }

    double ReporterImp::get_max_memory()
    {
        char status_buffer[8192];
        status_buffer[8191] = '\0';
        const char *proc_path = "/proc/self/status";

        int fd = open(proc_path, O_RDONLY);
        if (fd == -1) {
            throw Exception("ReporterImp::get_max_memory(): Unable to open " + std::string(proc_path),
                            errno ? errno : GEOPM_ERROR_RUNTIME, __FILE__, __LINE__);
        }

        ssize_t num_read = read(fd, status_buffer, 8191);
        if (num_read == -1) {
            (void)close(fd);
            throw Exception("ReporterImp::get_max_memory(): Unable to read " + std::string(proc_path),
                            errno ? errno : GEOPM_ERROR_RUNTIME, __FILE__, __LINE__);
        }
        status_buffer[num_read] = '\0';

        int err = close(fd);
        if (err) {
            throw Exception("ReporterImp::get_max_memory(): Unable to close " + std::string(proc_path),
                            errno ? errno : GEOPM_ERROR_RUNTIME, __FILE__, __LINE__);
        }

        std::istringstream proc_stream(status_buffer);
        std::string line;
        std::string max_memory;
        const std::string key("VmHWM:");
        while (proc_stream.good()) {
            getline(proc_stream, line);
            if (line.find(key) == 0) {
                max_memory = line.substr(key.length());
                size_t off = max_memory.find_first_not_of(" \t");
                if (off != std::string::npos) {
                    max_memory = max_memory.substr(off);
                }
            }
        }
        if (!max_memory.size()) {
            throw Exception("ReporterImp::get_max_memory(): Unable to get memory overhead from /proc",
                            GEOPM_ERROR_RUNTIME, __FILE__, __LINE__);
        }
        // expect kibibyte units
        size_t len = max_memory.size();
        if (max_memory.substr(len - 2) != "kB") {
            throw Exception("ReporterImp::get_max_memory(): HWM not in units of kB",
                            GEOPM_ERROR_RUNTIME, __FILE__, __LINE__);
        }
        double max_memory_bytes = std::stod(max_memory.substr(0, len - 2));
        return max_memory_bytes;
    }

    void ReporterImp::yaml_write(std::ostream &os, int indent_level,
                                 const std::string &val)
    {
        std::string indent(indent_level * M_SPACES_INDENT, ' ');
        os << indent << val << std::endl;
    }

    void ReporterImp::yaml_write(std::ostream &os, int indent_level,
                                 const std::vector<std::pair<std::string, std::string> > &data)
    {
        std::string indent(indent_level * M_SPACES_INDENT, ' ');
        for (const auto &kv : data) {
            os << indent << kv.first << ": " << kv.second << std::endl;
        }
    }

    void ReporterImp::yaml_write(std::ostream &os, int indent_level,
                                 const std::vector<std::pair<std::string, double> > &data)
    {
        std::string indent(indent_level * M_SPACES_INDENT, ' ');
        for (const auto &kv: data) {
            os << indent << kv.first << ": " << kv.second << std::endl;
        }
    }

    static Reporter &basic_reporter(const std::string &start_time)
    {
        static ReporterImp instance(start_time,
                                    "",
                                    PlatformIOProf::platform_io(),
                                    platform_topo(),
                                    0);
        return instance;
    }

    static Reporter &basic_reporter(void)
    {
        return basic_reporter("");
    }

}

int geopm_reporter_init(void)
{
    char start_time[NAME_MAX];
    int err = geopm_time_string(NAME_MAX, start_time);
    if (!err) {
        try {
            geopm::basic_reporter(start_time);
        }
        catch (...) {
            err = geopm::exception_handler(std::current_exception());
            err = err < 0 ? err : GEOPM_ERROR_RUNTIME;
        }
    }
    return err;
}

int geopm_reporter_update(void)
{
    int err = 0;
    try {
        geopm::basic_reporter().update();
    }
    catch (...) {
        err = geopm::exception_handler(std::current_exception());
        err = err < 0 ? err : GEOPM_ERROR_RUNTIME;
    }
    return err;
}

int geopm_reporter_generate(const char *profile_name,
                            const char *agent_name,
                            size_t result_max,
                            char *result)
{
    int err = 0;
    try {
        std::string result_cxx = geopm::basic_reporter().generate(profile_name, agent_name, {}, {}, {});
        result[result_max - 1] = '\0';
        strncpy(result, result_cxx.c_str(), result_max);
        if (result[result_max - 1] != '\0') {
            err = GEOPM_ERROR_INVALID;
            result[result_max - 1] = '\0';
        }
    }
    catch (...) {
        err = geopm::exception_handler(std::current_exception());
        err = err < 0 ? err : GEOPM_ERROR_RUNTIME;
    }
    return err;
}


text:
import { Nullable } from "babylonjs/types";
import { Observer } from "babylonjs/Misc/observable";
import { Vector2 } from "babylonjs/Maths/math.vector";
import { Camera } from "babylonjs/Cameras/camera";
import { AbstractMesh } from "babylonjs/Meshes/abstractMesh";

import { MultiLine } from "./controls/multiLine";
import { ValueAndUnit } from "./valueAndUnit";
import { Control } from "./controls/control";

/**
 * Class used to store a point for a MultiLine object.
 * The point can be pure 2D coordinates, a mesh or a control
 */
export class MultiLinePoint {

    private _multiLine: MultiLine;

    private _x: ValueAndUnit;
    private _y: ValueAndUnit;
    private _control: Nullable<Control>;
    private _mesh: Nullable<AbstractMesh>;

    private _controlObserver: Nullable<Observer<Control>>;
    private _meshObserver: Nullable<Observer<Camera>>;

    /** @hidden */
    public _point: Vector2;

    /**
     * Creates a new MultiLinePoint
     * @param multiLine defines the source MultiLine object
     */
    constructor(multiLine: MultiLine) {
        this._multiLine = multiLine;

        this._x = new ValueAndUnit(0);
        this._y = new ValueAndUnit(0);

        this._point = new Vector2(0, 0);
    }

    /** Gets or sets x coordinate */
    public get x(): string | number {
        return this._x.toString(this._multiLine._host);
    }

    public set x(value: string | number) {
        if (this._x.toString(this._multiLine._host) === value) {
            return;
        }

        if (this._x.fromString(value)) {
            this._multiLine._markAsDirty();
        }
    }

    /** Gets or sets y coordinate */
    public get y(): string | number {
        return this._y.toString(this._multiLine._host);
    }

    public set y(value: string | number) {
        if (this._y.toString(this._multiLine._host) === value) {
            return;
        }

        if (this._y.fromString(value)) {
            this._multiLine._markAsDirty();
        }
    }

    /** Gets or sets the control associated with this point */
    public get control(): Nullable<Control> {
        return this._control;
    }

    public set control(value: Nullable<Control>) {
        if (this._control === value) {
            return;
        }

        if (this._control && this._controlObserver) {
            this._control.onDirtyObservable.remove(this._controlObserver);

            this._controlObserver = null;
        }

        this._control = value;

        if (this._control) {
            this._controlObserver = this._control.onDirtyObservable.add(this._multiLine.onPointUpdate);
        }

        this._multiLine._markAsDirty();
    }

    /** Gets or sets the mesh associated with this point */
    public get mesh(): Nullable<AbstractMesh> {
        return this._mesh;
    }

    public set mesh(value: Nullable<AbstractMesh>) {
        if (this._mesh === value) {
            return;
        }

        if (this._mesh && this._meshObserver) {
            this._mesh.getScene().onAfterCameraRenderObservable.remove(this._meshObserver);
        }

        this._mesh = value;

        if (this._mesh) {
            this._meshObserver = this._mesh.getScene().onAfterCameraRenderObservable.add(this._multiLine.onPointUpdate);
        }

        this._multiLine._markAsDirty();
    }

    /** Resets links */
    public resetLinks(): void {
        this.control = null;
        this.mesh = null;
    }

    /**
     * Gets a translation vector
     * @returns the translation vector
     */
    public translate(): Vector2 {
        this._point = this._translatePoint();

        return this._point;
    }

    private _translatePoint(): Vector2 {
        if (this._mesh != null) {
            return this._multiLine._host.getProjectedPosition(this._mesh.getBoundingInfo().boundingSphere.center, this._mesh.getWorldMatrix());
        }
        else if (this._control != null) {
            return new Vector2(this._control.centerX, this._control.centerY);
        }
        else {
            var host: any = this._multiLine._host as any;

            var xValue: number = this._x.getValueInPixel(host, Number(host._canvas.width));
            var yValue: number = this._y.getValueInPixel(host, Number(host._canvas.height));

            return new Vector2(xValue, yValue);
        }
    }

    /** Release associated resources */
    public dispose(): void {
        this.resetLinks();
    }

}

redpajama_set_name: RedPajamaGithub


text:
% Preambel mit Einstellungen importieren
\input{preambel}

% Dokumenteninfos importieren
\input{docinfo.tex}

\begin{document}
\frontmatter

% Römische Ziffern für die "Front-Matter"
\setcounter{page}{0}
\changefont{ptm}{m}{n}  % Times New Roman für den Fließtext
\renewcommand{\rmdefault}{ptm}

% Titelblatt
\input{titelblatt}

% Inhaltsverzeichnis erzeugen
\tableofcontents

% Korrigiert Nummerierung bei mehrseitigem Inhaltsverzeichnis
\cleardoublepage
\newcounter{frontmatterpage}
\setcounter{frontmatterpage}{\value{page}}

% Arabische Zahlen für den Hauptteil
\mainmatter

% Den Hauptteil mit vergrößertem Zeilenabstand setzen
\onehalfspacing

% ------------------------------------------------------------------
% Hauptteil der Arbeit
\input{kapitel1} % Externe Datei einbinden
\input{kapitel2} % Externe Datei einbinden
% ------------------------------------------------------------------

\label{lastpage}

% Neue Seite
\cleardoublepage

% Backmatter mit normalem Zeilenabstand setzen
\singlespacing

% Römische Ziffern für die "Back-Matter", fortlaufend mit frontmatter
\pagenumbering{roman}
\setcounter{page}{\value{frontmatterpage}}

% Abkürzungsverzeichnis
\input{abkuerzungen}

% Tabellenverzeichnis erzeugen
\cleardoublepage
\phantomsection
\addcontentsline{toc}{chapter}{Tabellenverzeichnis}
\listoftables

% Abbildungsverzeichnis erzeugen
\cleardoublepage
\phantomsection
\addcontentsline{toc}{chapter}{Abbildungsverzeichnis}
\listoffigures

% Literaturverzeichnis erzeugen (nach DIN)
\begin{flushleft}
\bibliographystyle{dinat} % Literatur nach DIN
%\bibliographystyle{abbrv} % Zitate mit [1], [2] etc.
%\bibliographystyle{alpha} % Zitate mit [Kor01], [Vix99] etc.
\bibliography{literatur}   % BibTeX-Datei mit Literaturquellen einbinden
\end{flushleft}

% Index ausgeben
\cleardoublepage
\phantomsection
\addcontentsline{toc}{chapter}{Index}
\printindex

\end{document}


text:
package net.ralphbroenink.muzei.unsplash.rss;

import android.net.Uri;

/**
 * Created by ralphje on 15/02/14.
 */
public class RssItem {
    private String title;
    private Uri link;
    private String description;

    public String getTitle() {
        return this.title;
    }

    public void setTitle(String title) {
        this.title = title;
    }

    public Uri getLink() {
        return this.link;
    }

    public void setLink(Uri link) {
        this.link = link;
    }

    public void setLink(String link) {
        this.link = Uri.parse(link);
    }

    public String getDescription() {
        return this.description;
    }

    public void setDescription(String description) {
        this.description = description;
    }

    @Override
    public String toString() {
        return this.title;
    }

}


text:
namespace Igneel { namespace PhysX {

	XTriangleMesh::XTriangleMesh(NxTriangleMesh* nxMesh)
	{
		this->m_mesh = nxMesh;

		int size = nxMesh->getCount(0, NxInternalArray::NX_ARRAY_NORMALS)  * sizeof(Vector3) +
			nxMesh->getCount(0, NxInternalArray::NX_ARRAY_VERTICES) *  sizeof(Vector3) +
			nxMesh->getCount(0, NxInternalArray::NX_ARRAY_TRIANGLES) * sizeof(short) +
			nxMesh->getCount(0, NxInternalArray::NX_ARRAY_HULL_POLYGONS) +
			nxMesh->getCount(0, NxInternalArray::NX_ARRAY_HULL_VERTICES) * sizeof(Vector3);

		GC::AddMemoryPressure(size + sizeof(NxTriangleMesh));
	}

	void XTriangleMesh::Load(Stream^ stream)
	{
		BinaryReader^ reader = gcnew BinaryReader(stream);
		BinaryWriter^ writter = gcnew BinaryWriter(stream);
		WrapperStream ws = WrapperStream(reader, writter);

		try
		{
		m_mesh->load(ws);

		}
		finally
		{
			stream->Close();
		}
	}

	void XTriangleMesh::OnDispose(bool d)
	{
		if(m_mesh)
		{
			auto physic =  static_cast<PXPhysicManager^>(PhysicManager::Sigleton);
			physic->sdk->releaseTriangleMesh(*m_mesh);
			m_mesh = NULL;
		}
		__super::OnDispose(d);
	}
}}


text:
> Like a Set, but provides the index of the `key` in the backing array

This is designed to allow synchronizing a second array with the contents of the backing array, like
how in a sourcemap `sourcesContent[i]` is the source content associated with `source[i]`, and there
are never duplicates.

## Installation

```sh
npm install @jridgewell/set-array
```

## Usage

```js
import { SetArray, get, put, pop } from '@jridgewell/set-array';

const sa = new SetArray();

let index = put(sa, 'first');
assert.strictEqual(index, 0);

index = put(sa, 'second');
assert.strictEqual(index, 1);

assert.deepEqual(sa.array, [ 'first', 'second' ]);

index = get(sa, 'first');
assert.strictEqual(index, 0);

pop(sa);
index = get(sa, 'second');
assert.strictEqual(index, undefined);
assert.deepEqual(sa.array, [ 'first' ]);
```


text:
namespace pdalboost {} namespace boost = pdalboost; namespace pdalboost { namespace mpl {

// no default implementation; the definition is needed to make MSVC happy

template< typename Tag >
struct pop_back_impl
{
    template< typename Sequence > struct apply;
};

BOOST_MPL_ALGORITM_TRAITS_LAMBDA_SPEC(1, pop_back_impl)

}}

#endif // BOOST_MPL_AUX_POP_BACK_IMPL_HPP_INCLUDED


text:
@interface CCWebViewController : UIViewController <CCWebViewProtocol>

@end


text:
/**
 * @fileOverview
 * Everything about component event which includes event object, event listener,
 * event emitter and lifecycle hooks.
 */

/**
 * Event object definition. An event object has `type`, `timestamp` and
 * `detail` from which a component emit. The event object could be dispatched to
 * parents or broadcasted to children except `this.stop()` is called.
 * @param {string} type
 * @param {any}    detail
 */
function Evt (type, detail) {
  if (detail instanceof Evt) {
    return detail
  }

  this.timestamp = Date.now()
  this.detail = detail
  this.type = type

  let shouldStop = false

  /**
   * stop dispatch and broadcast
   */
  this.stop = function () {
    shouldStop = true
  }

  /**
   * check if it can't be dispatched or broadcasted
   */
  this.hasStopped = function () {
    return shouldStop
  }
}

/**
 * Emit an event but not broadcast down or dispatch up.
 * @param  {string} type
 * @param  {any}    detail
 */
export function $emit (type, detail) {
  const events = this._vmEvents
  const handlerList = events[type]
  if (handlerList) {
    const evt = new Evt(type, detail)
    handlerList.forEach((handler) => {
      handler.call(this, evt)
    })
  }
}

/**
 * Emit an event and dispatch it up.
 * @param  {string} type
 * @param  {any}    detail
 */
export function $dispatch (type, detail) {
  const evt = new Evt(type, detail)
  this.$emit(type, evt)

  if (!evt.hasStopped() && this._parent && this._parent.$dispatch) {
    this._parent.$dispatch(type, evt)
  }
}

/**
 * Emit an event and broadcast it down.
 * @param  {string} type
 * @param  {any}    detail
 */
export function $broadcast (type, detail) {
  const evt = new Evt(type, detail)
  this.$emit(type, evt)

  if (!evt.hasStopped() && this._childrenVms) {
    this._childrenVms.forEach((subVm) => {
      subVm.$broadcast(type, evt)
    })
  }
}

/**
 * Add event listener.
 * @param  {string}   type
 * @param  {function} handler
 */
export function $on (type, handler) {
  if (!type || typeof handler !== 'function') {
    return
  }
  const events = this._vmEvents
  const handlerList = events[type] || []
  handlerList.push(handler)
  events[type] = handlerList

  // fixed old version lifecycle design
  if (type === 'hook:ready' && this._ready) {
    this.$emit('hook:ready')
  }
}

/**
 * Remove event listener.
 * @param  {string}   type
 * @param  {function} handler
 */
export function $off (type, handler) {
  if (!type) {
    return
  }
  const events = this._vmEvents
  if (!handler) {
    delete events[type]
    return
  }
  const handlerList = events[type]
  if (!handlerList) {
    return
  }
  handlerList.$remove(handler)
}

const LIFE_CYCLE_TYPES = ['init', 'created', 'ready', 'destroyed']

/**
 * Init events:
 * 1. listen `events` in component options & `externalEvents`.
 * 2. bind lifecycle hooks.
 * @param  {Vm}     vm
 * @param  {object} externalEvents
 */
export function initEvents (vm, externalEvents) {
  const options = vm._options || {}
  const events = options.events || {}
  for (const type1 in events) {
    vm.$on(type1, events[type1])
  }
  for (const type2 in externalEvents) {
    vm.$on(type2, externalEvents[type2])
  }
  LIFE_CYCLE_TYPES.forEach((type) => {
    vm.$on(`hook:${type}`, options[type])
  })
}

/**
 * Bind event related methods to ViewModel instance.
 * @param  {Vm} vm
 */
export function mixinEvents (vm) {
  vm.$emit = $emit
  vm.$dispatch = $dispatch
  vm.$broadcast = $broadcast
  vm.$on = $on
  vm.$off = $off
}


text:
define([
  'jquery',
  'underscore',
  'backbone',
  'router', // Request router.js
], function($, _, Backbone, Router){
  var initialize = function(){
    // Pass in our Router module and call it's initialize function
    // The router defines all our components at startup and proceeds be a
    Router.initialize();
  };

  // run the above initialize method as the default action
  return {
    initialize: initialize
  };
});


text:
import functools
import tensorflow as tf
import matplotlib as mpl
mpl.use('TkAgg')
import matplotlib.pyplot as plt
import numpy as np
import params as prm
import matplotlib.pyplot as plt
import tensorflow.contrib.slim as slim
from tensorflow.examples.tutorials.mnist import input_data

def doublewrap(function):
    """
    A decorator decorator, allowing to use the decorator to be used without
    parentheses if not arguments are provided. All arguments must be optional.
    credits: ttps://danijar.github.io/structuring-your-tensorflow-models
    """

    @functools.wraps(function)
    def decorator(*args, **kwargs):
        if len(args) == 1 and len(kwargs) == 0 and callable(args[0]):
            return function(args[0])
        else:
            return lambda wrapee: function(wrapee, *args, **kwargs)

    return decorator

@doublewrap
def define_scope(function, scope=None, *args, **kwargs):
    """
    A decorator for functions that define TensorFlow operations. The wrapped
    function will only be executed once. Subsequent calls to it will directly
    return the result so that operations are added to the graph only once.

    The operations added by the function live within a tf.variable_scope(). If
    this decorator is used with arguments, they will be forwarded to the
    variable scope. The scope name defaults to the name of the wrapped function.
    credits: ttps://danijar.github.io/structuring-your-tensorflow-models
    """
    attribute = '_cache_' + function.__name__
    name = scope or function.__name__

    @property
    @functools.wraps(function)
    def decorator(self):
        if not hasattr(self, attribute):
            with tf.variable_scope(name, *args, **kwargs):
                setattr(self, attribute, function(self))
        return getattr(self, attribute)

    return decorator

class Model:
    """
    This class responsible to build and wrap all of the functionalities
    of the tensor graph. Attributes of prediction, optimization and
    loss function will be stored under tensorflow variable scope.
    """

    def __init__(self, image, label):
        self.image = image
        self.label = label
        self.prediction
        self.optimize
        self.error
        self.hidden_1
        self.hidden_2
        self.hidden_3

    @define_scope(initializer=slim.xavier_initializer())
    def prediction(self):
        x = self.image
        x_image = tf.reshape(x, [-1, prm.mnist_img_size, prm.mnist_img_size, 1])
        self.hidden_1 = slim.conv2d(x_image, 5,
                                    [prm.conv_size, prm.conv_size])
        pool_1 = slim.max_pool2d(self.hidden_1,
                                 [prm.max_pool_size, prm.max_pool_size])
        self.hidden_2 = slim.conv2d(pool_1, 5, [prm.conv_size, prm.conv_size])
        pool_2 = slim.max_pool2d(self.hidden_2,
                                 [prm.max_pool_size, prm.max_pool_size])
        hidden_3 = slim.conv2d(pool_2, 20, [prm.conv_size, prm.conv_size])
        self.hidden_3 = slim.dropout(hidden_3, 1.0)
        x = slim.fully_connected(
            slim.flatten(self.hidden_3), 10, activation_fn=tf.nn.softmax)
        return x

    @define_scope
    def optimize(self):
        logprob = tf.log(self.prediction + 1e-12)
        cross_entropy = -tf.reduce_sum(self.label * logprob)
        optimizer = tf.train.AdamOptimizer(1e-4)
        return optimizer.minimize(cross_entropy)

    @define_scope
    def error(self):
        mistakes = tf.not_equal(
            tf.argmax(self.label, 1), tf.argmax(self.prediction, 1))
        return tf.reduce_mean(tf.cast(mistakes, tf.float32))


text:
.class Lorg/holoeverywhere/widget/AbsSpinner$SavedState;
.super Landroid/view/View$BaseSavedState;
.source "AbsSpinner.java"

# annotations
.annotation system Ldalvik/annotation/EnclosingClass;
    value = Lorg/holoeverywhere/widget/AbsSpinner;
.end annotation

.annotation system Ldalvik/annotation/InnerClass;
    accessFlags = 0x8
    name = "SavedState"
.end annotation

# static fields
.field public static final CREATOR:Landroid/os/Parcelable$Creator;
    .annotation system Ldalvik/annotation/Signature;
        value = {
            "Landroid/os/Parcelable$Creator",
            "<",
            "Lorg/holoeverywhere/widget/AbsSpinner$SavedState;",
            ">;"
        }
    .end annotation
.end field

# instance fields
.field position:I

.field selectedId:J

# direct methods
.method static constructor <clinit>()V
    .locals 1

    .prologue
    .line 52
    new-instance v0, Lorg/holoeverywhere/widget/AbsSpinner$SavedState$1;

    invoke-direct {v0}, Lorg/holoeverywhere/widget/AbsSpinner$SavedState$1;-><init>()V

    sput-object v0, Lorg/holoeverywhere/widget/AbsSpinner$SavedState;->CREATOR:Landroid/os/Parcelable$Creator;

    return-void
.end method

.method private constructor <init>(Landroid/os/Parcel;)V
    .locals 2
    .param p1, "in"    # Landroid/os/Parcel;

    .prologue
    .line 68
    invoke-direct {p0, p1}, Landroid/view/View$BaseSavedState;-><init>(Landroid/os/Parcel;)V

    .line 69
    invoke-virtual {p1}, Landroid/os/Parcel;->readLong()J

    move-result-wide v0

    iput-wide v0, p0, Lorg/holoeverywhere/widget/AbsSpinner$SavedState;->selectedId:J

    .line 70
    invoke-virtual {p1}, Landroid/os/Parcel;->readInt()I

    move-result v0

    iput v0, p0, Lorg/holoeverywhere/widget/AbsSpinner$SavedState;->position:I

    .line 71
    return-void
.end method

.method synthetic constructor <init>(Landroid/os/Parcel;Lorg/holoeverywhere/widget/AbsSpinner$1;)V
    .locals 0
    .param p1, "x0"    # Landroid/os/Parcel;
    .param p2, "x1"    # Lorg/holoeverywhere/widget/AbsSpinner$1;

    .prologue
    .line 51
    invoke-direct {p0, p1}, Lorg/holoeverywhere/widget/AbsSpinner$SavedState;-><init>(Landroid/os/Parcel;)V

    return-void
.end method

.method constructor <init>(Landroid/os/Parcelable;)V
    .locals 0
    .param p1, "superState"    # Landroid/os/Parcelable;

    .prologue
    .line 74
    invoke-direct {p0, p1}, Landroid/view/View$BaseSavedState;-><init>(Landroid/os/Parcelable;)V

    .line 75
    return-void
.end method

# virtual methods
.method public toString()Ljava/lang/String;
    .locals 3

    .prologue
    .line 79
    new-instance v0, Ljava/lang/StringBuilder;

    invoke-direct {v0}, Ljava/lang/StringBuilder;-><init>()V

    const-string v1, "AbsSpinner.SavedState{"

    invoke-virtual {v0, v1}, Ljava/lang/StringBuilder;->append(Ljava/lang/String;)Ljava/lang/StringBuilder;

    move-result-object v0

    invoke-static {p0}, Ljava/lang/System;->identityHashCode(Ljava/lang/Object;)I

    move-result v1

    invoke-static {v1}, Ljava/lang/Integer;->toHexString(I)Ljava/lang/String;

    move-result-object v1

    invoke-virtual {v0, v1}, Ljava/lang/StringBuilder;->append(Ljava/lang/String;)Ljava/lang/StringBuilder;

    move-result-object v0

    const-string v1, " selectedId="

    invoke-virtual {v0, v1}, Ljava/lang/StringBuilder;->append(Ljava/lang/String;)Ljava/lang/StringBuilder;

    move-result-object v0

    iget-wide v1, p0, Lorg/holoeverywhere/widget/AbsSpinner$SavedState;->selectedId:J

    invoke-virtual {v0, v1, v2}, Ljava/lang/StringBuilder;->append(J)Ljava/lang/StringBuilder;

    move-result-object v0

    const-string v1, " position="

    invoke-virtual {v0, v1}, Ljava/lang/StringBuilder;->append(Ljava/lang/String;)Ljava/lang/StringBuilder;

    move-result-object v0

    iget v1, p0, Lorg/holoeverywhere/widget/AbsSpinner$SavedState;->position:I

    invoke-virtual {v0, v1}, Ljava/lang/StringBuilder;->append(I)Ljava/lang/StringBuilder;

    move-result-object v0

    const-string v1, "}"

    invoke-virtual {v0, v1}, Ljava/lang/StringBuilder;->append(Ljava/lang/String;)Ljava/lang/StringBuilder;

    move-result-object v0

    invoke-virtual {v0}, Ljava/lang/StringBuilder;->toString()Ljava/lang/String;

    move-result-object v0

    return-object v0
.end method

.method public writeToParcel(Landroid/os/Parcel;I)V
    .locals 2
    .param p1, "out"    # Landroid/os/Parcel;
    .param p2, "flags"    # I

    .prologue
    .line 87
    invoke-super {p0, p1, p2}, Landroid/view/View$BaseSavedState;->writeToParcel(Landroid/os/Parcel;I)V

    .line 88
    iget-wide v0, p0, Lorg/holoeverywhere/widget/AbsSpinner$SavedState;->selectedId:J

    invoke-virtual {p1, v0, v1}, Landroid/os/Parcel;->writeLong(J)V

    .line 89
    iget v0, p0, Lorg/holoeverywhere/widget/AbsSpinner$SavedState;->position:I

    invoke-virtual {p1, v0}, Landroid/os/Parcel;->writeInt(I)V

    .line 90
    return-void
.end method


text:
package com.twitter.storehaus.cassandra.cql

import com.datastax.driver.core.{ BatchStatement, ConsistencyLevel, Cluster, Session, ProtocolVersion }
import com.datastax.driver.core.policies.{ LoadBalancingPolicy, Policies, ReconnectionPolicy, RetryPolicy, RoundRobinPolicy, TokenAwarePolicy }
import com.twitter.util.Duration
import java.util.concurrent.TimeUnit

object CQLCassandraConfiguration {

  val DEFAULT_VALUE_COLUMN_NAME = "value"
  val DEFAULT_KEY_COLUMN_NAME = "key"
  val DEFAULT_TOKEN_COLUMN_NAME = "tokencol"
  val DEFAULT_FUTURE_POOL_SIZE = 10
  val DEFAULT_CONSISTENCY_LEVEL = ConsistencyLevel.QUORUM
  val DEFAULT_TTL_DURATION = None
  val DEFAULT_BATCH_STATEMENT_TYPE = BatchStatement.Type.UNLOGGED
  val DEFAULT_SYNC = CassandraExternalSync(NoSync(), NoSync())
  val DEFAULT_SHUTDOWN_TIMEOUT = Duration(60, TimeUnit.SECONDS)
  val DEFAULT_SCHEMA_AGREEMENT_TIMEOUT = Duration(10, TimeUnit.SECONDS);

  case class StoreHost(val name: String)

  case class StoreCredentials(val user: String, val pwd: String)

  case class StoreCluster(val name: String, val hosts: Set[StoreHost],
                          val credentials: Option[StoreCredentials] = None,
                          val loadBalancing: LoadBalancingPolicy = Policies.defaultLoadBalancingPolicy,
                          val reconnectPolicy: ReconnectionPolicy = Policies.defaultReconnectionPolicy,
                          val retryPolicy: RetryPolicy = Policies.defaultRetryPolicy,
                          val shutdownTimeout: Duration = DEFAULT_SHUTDOWN_TIMEOUT,
                          val maxSchemaAgreementWaitSeconds: Duration = DEFAULT_SCHEMA_AGREEMENT_TIMEOUT) {
    lazy val cluster = createCluster
    def getCluster: Cluster = cluster
    def createCluster: Cluster = {
      val clusterBuilder = Cluster.builder()
      hosts.foreach(host => {
        val hostPort = host.name.split(":")
        hostPort.length match {
          case 2 => {
            clusterBuilder.addContactPoint(hostPort.apply(0)).withPort(hostPort.apply(1).toInt)
          }
          case _ => clusterBuilder.addContactPoint(host.name)
        }
      })
      credentials.map(cred => clusterBuilder.withCredentials(cred.user, cred.pwd))
      clusterBuilder.withLoadBalancingPolicy(loadBalancing)
      clusterBuilder.withReconnectionPolicy(reconnectPolicy)
      clusterBuilder.withRetryPolicy(retryPolicy)
      clusterBuilder.withMaxSchemaAgreementWaitSeconds(maxSchemaAgreementWaitSeconds.inUnit(TimeUnit.SECONDS).toInt)
      clusterBuilder.withProtocolVersion(ProtocolVersion.V3)
      clusterBuilder.build()
    }
    def close: Unit = cluster.close
  }

  case class StoreColumnFamily(name: String, val session: StoreSession) {
    lazy val getName = name.filterNot(_ == '"')
    lazy val getPreparedNamed = {
      val lowerName = getName.toLowerCase
      if (getName != lowerName)
        "\"" + getName + "\""
      else
        getName
    }
    def dropAndDeleteColumnFamilyAndContainedData = {
      val stmt = "DROP TABLE \"" + getName + "\";"
      session.getSession.execute(stmt)
    }
  }

  case class StoreSession(val keyspacename: String, val cluster: StoreCluster, val replicationOptions: String = "{'class' : 'SimpleStrategy', 'replication_factor' : 3}") {
    lazy val session = cluster.getCluster.connect("\"" + getKeyspacename + "\"")
    def getSession: Session = session
    def getCluster: Cluster = getSession.getCluster
    def getKeyspacename: String = keyspacename.filterNot(_ == '"')
    def createKeyspace = {
      val stmt = "CREATE KEYSPACE IF NOT EXISTS \"" + getKeyspacename + "\" WITH REPLICATION = " + replicationOptions + " ;"
      independentKeyspaceOp(stmt)
    }
    /**
     * WARNING! *Permanently DELETES* given keyspace and contained data. Session may not be used afterwards.
     */
    def dropAndDeleteKeyspaceAndContainedData = {
      val stmt = "DROP KEYSPACE \"" + getKeyspacename + "\";"
      independentKeyspaceOp(stmt)
    }
    private def independentKeyspaceOp(stmt: String) = {
      val tmpSession = cluster.getCluster.connect()
      tmpSession.execute(stmt)
      tmpSession.close()
    }
  }

  // can be used to create a set of column names easily
  def defaultValueColumnNames(size: Int): List[String] = (1 to size).map(n => s"value_${n.toString}").toList
}


text:
import morepath

from .app import App
from .model import db

def run():   # pragma: no cover
    db.bind('sqlite', 'morepath_ponyorm.db', create_db=True)
    db.generate_mapping(create_tables=True)

    morepath.autoscan()
    morepath.run(App())


text:
package com.thoughtworks.go.util;

import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;

import java.io.File;
import java.io.IOException;
import java.util.Properties;
import java.util.UUID;

import static org.hamcrest.Matchers.not;
import static org.hamcrest.Matchers.is;
import static org.hamcrest.MatcherAssert.assertThat;

public class TempFilesTest {
    TempFiles files;
    private Properties original;

    @BeforeEach
    public void setUp() {
        original = new Properties();
        original.putAll(System.getProperties());
        files = new TempFiles();
    }

    @AfterEach
    public void cleanUp() {
        System.setProperties(original);
        files.cleanUp();
    }

    @Test
    public void shouldRecordFilesThatAreCreated() throws IOException {
        File created = files.createFile("foo");

        assertThat(created.exists(), is(true));
        files.cleanUp();

        assertThat(created.exists(), is(false));
    }

    @Test
    public void shouldRecordFoldersThatAreCreated() {
        File dir = files.mkdir("foo");
        assertThat(dir.exists(), is(true));

        files.cleanUp();
        assertThat(dir.exists(), is(false));
    }

    @Test
    public void shouldDeleteNonEmptyFolders() throws IOException {
        File dir = files.mkdir("foo");
        assertThat(dir.exists(), is(true));

        File file = new File(dir, "foo");
        file.createNewFile();

        files.cleanUp();
        assertThat(dir.exists(), is(false));
    }

    @Test
    public void shouldForgetFolders() throws IOException {
        File file = files.mkdir("foo");

        files.cleanUp();
        files.cleanUp();
    }

    @Test
    public void shouldCreateFilesInTempDirectory() throws IOException {
        File file = files.createFile("foo");
        File parentFile = file.getParentFile();
        assertThat(parentFile.getName(), is("cruise"));
        assertThat(parentFile.getParentFile(), is(tmpDir()));
    }

    private File tmpDir() {
        return new File(System.getProperty("java.io.tmpdir"));
    }

    @Test
    public void shouldCreateDirsInTempDirectory() throws IOException {
        File dir = files.mkdir("foo");
        File parentFile = dir.getParentFile();
        assertThat(parentFile.getName(), is("cruise"));
        assertThat(parentFile.getParentFile(), is(tmpDir()));
    }

    @Test
    public void shouldCreateUniqueFilesEveryTime() throws IOException {
        TestingClock clock = new TestingClock();
        files.setClock(clock);
        File file1 = files.createUniqueFile("foo");
        File file2 = files.createUniqueFile("foo");
        assertThat(file1, not(file2));
    }

    @Test
    public void shouldCreateUniqueFilesParentDirectoryIfDoesNotExist() throws IOException {
        String newTmpDir = original.getProperty("java.io.tmpdir") + "/" + UUID.randomUUID();
        System.setProperty("java.io.tmpdir", newTmpDir);
        File file = files.createUniqueFile("foo");
        assertThat(file.getParentFile().exists(), is(true));
    }

    @Test
    public void shouldCreateUniqueFolders() throws IOException {
        TestingClock clock = new TestingClock();
        files.setClock(clock);
        File file1 = files.createUniqueFolder("foo");
        clock.addSeconds(1);
        File file2 = files.createUniqueFolder("foo");
        assertThat(file2, not(file1));
    }

    @Test
    public void willNotDeleteParentDirectoriesIfPathologicalFilesGetCreated() throws IOException {
        File file1 = files.createFile("foo/bar/baz.zip");
        assertThat(file1.exists(), is(true));
        files.cleanUp();
        assertThat(file1.exists(), is(false));
        assertThat(new File(new File(tmpDir(), "cruise"), "foo").exists(), is(true));
    }
}


text:
from __future__ import unicode_literals

from django.apps import AppConfig

class PermisoConfig(AppConfig):
    name = 'permiso'


text:
package org.la4j.vector.sparse;

import org.la4j.io.VectorIterator;
import org.la4j.vector.Vector;
import org.la4j.vector.Vectors;
import org.la4j.vector.functor.VectorFunction;
import org.la4j.vector.functor.VectorProcedure;
import org.la4j.vector.source.VectorSource;

import java.io.IOException;
import java.io.ObjectInput;
import java.io.ObjectOutput;

public class CompressedVector extends SparseVector {

    private static final long serialVersionUID = 4071505L;

    private static final int MINIMUM_SIZE = 32;

    private double values[];
    private int indices[];

    public CompressedVector() {
        this(0);
    }

    public CompressedVector(int length) {
        this(length, 0);
    }

    public CompressedVector(Vector vector) {
        this(Vectors.asVectorSource(vector));
    }

    public CompressedVector(double array[]) {
        this(Vectors.asArraySource(array));
    }

    public CompressedVector(VectorSource source) {
        this(source.length(), 0);

        for (int i = 0; i < length; i++) {
            double value = source.get(i);
            //if (Math.abs(value) > Vectors.EPS || value < 0.0) {
            if (value != 0.0) {

                if (values.length < cardinality + 1) {
                    growup();
                }

                values[cardinality] = value;
                indices[cardinality] = i;
                cardinality++;
            }
        }
    }

    public CompressedVector(int length, int capacity) {
        super(length, 0);
        int alignedSize = align(length, capacity);
        this.values = new double[alignedSize];
        this.indices = new int[alignedSize];
    }

    public CompressedVector(int length, int cardinality, double values[], int indices[]) {
        super(length, cardinality);
        this.values = values;
        this.indices = indices;
    }

    @Override
    public double getOrElse(int i, double defaultValue) {

        int k = searchForIndex(i);

        if (k < cardinality && indices[k] == i) {
            return values[k];
        }

        return defaultValue;
    }

    @Override
    public void set(int i, double value) {

        int k = searchForIndex(i);

        if (k < cardinality && indices[k] == i) {
            // if (Math.abs(value) > Vectors.EPS || value < 0.0) {
            if (value != 0.0) {
                values[k] = value;
            } else {
                remove(k);
            }
        } else {
            insert(k, i, value);
        }
    }

    @Override
    public void swap(int i, int j) {

        if (i == j) {
            return;
        }

        int ii = searchForIndex(i);
        int jj = searchForIndex(j);

        boolean iiNotZero = ii < cardinality && i == indices[ii];
        boolean jjNotZero = jj < cardinality && j == indices[jj];

        if (iiNotZero && jjNotZero) {

            double sd = values[ii];
            values[ii] = values[jj];
            values[jj] = sd;

        } else {

            double notZero = values[iiNotZero ? ii : jj];

            int leftIndex = (ii < jj) ? ii : jj;
            int rightIndex = (ii > jj) ? ii : jj;

            if (((iiNotZero && (leftIndex == ii))
                 || (jjNotZero && (leftIndex == jj))) && (ii != jj)) {

                System.arraycopy(values, leftIndex + 1, values, leftIndex,
                        cardinality - leftIndex);
                System.arraycopy(values, rightIndex - 1, values, rightIndex,
                        cardinality - rightIndex);

                values[rightIndex - 1] = notZero;

                System.arraycopy(indices, leftIndex + 1, indices, leftIndex,
                        cardinality - leftIndex);
                System.arraycopy(indices, rightIndex - 1, indices, rightIndex,
                        cardinality - rightIndex);

                indices[rightIndex -1] = jjNotZero ? i : j;

            } else if((iiNotZero && (rightIndex == ii))
                      || (jjNotZero && (rightIndex == jj))) {

                System.arraycopy(values, rightIndex + 1, values, rightIndex,
                        cardinality - rightIndex);
                System.arraycopy(values, leftIndex, values, leftIndex + 1,
                        cardinality - leftIndex);

                values[leftIndex] = notZero;

                System.arraycopy(indices, rightIndex + 1, indices, rightIndex,
                        cardinality - rightIndex);
                System.arraycopy(indices, leftIndex, indices, leftIndex + 1,
                        cardinality - leftIndex);

                indices[leftIndex] = jjNotZero ? i : j;
            }
        }
    }

    @Override
    public Vector resize(int length) {
        ensureLengthIsCorrect(length);

        int $cardinality = (length > this.length) ?
                           cardinality : searchForIndex(length);

        double $values[] = new double[align(length, $cardinality)];
        int $indices[] = new int[align(length, $cardinality)];

        System.arraycopy(values, 0, $values, 0, $cardinality);
        System.arraycopy(indices, 0, $indices, 0, $cardinality);

        return new CompressedVector(length, $cardinality, $values, $indices);
    }

    @Override
    public void each(VectorProcedure procedure) {
        int k = 0;
        for (int i = 0; i < length; i++) {
            if (k < cardinality && indices[k] == i) {
                procedure.apply(i, values[k++]);
            } else {
                procedure.apply(i, 0.0);
            }
        }
    }

    @Override
    public void eachNonZero(VectorProcedure procedure) {
        for (int i = 0; i < cardinality; i++) {
            procedure.apply(indices[i], values[i]);
        }
    }

    @Override
    public void update(int i, VectorFunction function) {

        int k = searchForIndex(i);

        if (k < cardinality && indices[k] == i) {

            double value = function.evaluate(i, values[k]);

            // if (Math.abs(value) > Vectors.EPS || value < 0.0) {
            if (value != 0.0) {
                values[k] = value;
            } else {
                remove(k);
            }
        } else {
            insert(k, i, function.evaluate(i, 0.0));
        }
    }

    @Override
    public void writeExternal(ObjectOutput out) throws IOException {

        out.writeInt(length);
        out.writeInt(cardinality);

        for (int i = 0; i < cardinality; i++) {
            out.writeInt(indices[i]);
            out.writeDouble(values[i]);
        }
    }

    @Override
    public void readExternal(ObjectInput in) throws IOException,
            ClassNotFoundException {

        length = in.readInt();
        cardinality = in.readInt();

        int alignedSize = align(length, cardinality);

        values = new double[alignedSize];
        indices = new int[alignedSize];

        for (int i = 0; i < cardinality; i++) {
            indices[i] = in.readInt();
            values[i] = in.readDouble();
        }
    }

    @Override
    public boolean nonZeroAt(int i) {
        int k = searchForIndex(i);
        return k < cardinality && indices[k] == i;
    }

    private int searchForIndex(int i) {

        // TODO: add the same check for CRS/CCS matrices
        if (cardinality == 0 || i > indices[cardinality - 1]) {
            return cardinality;
        }

        int left = 0;
        int right = cardinality;

        while (left < right) {
            int p = (left + right) / 2;
            if (indices[p] > i) {
                right = p;
            } else if (indices[p] < i) {
                left = p + 1;
            } else {
                return p;
            }
        }

        return left;
    }

    private void insert(int k, int i, double value) {

        // if (Math.abs(value) < Vectors.EPS && value >= 0.0) {
        if (value == 0.0) {
            return;
        }

        if (values.length < cardinality + 1) {
            growup();
        }

        // TODO: revise other system.arraycopy() calls
        if (cardinality - k > 0) {
            System.arraycopy(values, k, values, k + 1, cardinality - k);
            System.arraycopy(indices, k, indices, k + 1, cardinality - k);
        }

//        for (int kk = cardinality; kk > k; kk--) {
//            values[kk] = values[kk - 1];
//            indices[kk] = indices[kk - 1];
//        }

        values[k] = value;
        indices[k] = i;

        cardinality++;
    }

    private void remove(int k) {
        // TODO: https://github.com/vkostyukov/la4j/issues/87
        cardinality--;

        System.arraycopy(values, k + 1, values, k, cardinality - k);
        System.arraycopy(indices, k + 1, indices, k, cardinality - k);

//        for (int kk = k; kk < cardinality; kk++) {
//            values[kk] = values[kk + 1];
//            indices[kk] = indices[kk + 1];
//        }
    }

    // TODO: better name
    private void growup() {

        if (values.length == length) {
            // This should never happen
            throw new IllegalStateException("This vector can't grow up.");
        }

        int capacity = Math.min(length, (cardinality * 3) / 2 + 1);

        double $values[] = new double[capacity];
        int $indices[] = new int[capacity];

        System.arraycopy(values, 0, $values, 0, cardinality);
        System.arraycopy(indices, 0, $indices, 0, cardinality);

        values = $values;
        indices = $indices;
    }

    private int align(int length, int capacity) {
        if (capacity < 0) {
            fail("Cardinality should be positive: " + capacity + ".");
        }
        if (capacity > length) {
            fail("Cardinality should be less then or equal to capacity: " + capacity + ".");
        }
        return Math.min(length, ((capacity / MINIMUM_SIZE) + 1) * MINIMUM_SIZE);
    }

    @Override
    public VectorIterator nonZeroIterator() {
        return new VectorIterator(length) {
            private boolean currentIsRemoved = false;
            private int k = -1;
            private int removedIndex = -1;

            @Override
            public int index() {
                return currentIsRemoved ? removedIndex : indices[k];
            }

            @Override
            public double get() {
                return currentIsRemoved ? 0.0 : values[k];
            }

            @Override
            public void set(double value) {
                if (value == 0.0 && !currentIsRemoved) {
                    currentIsRemoved = true;
                    removedIndex = indices[k];
                    CompressedVector.this.remove(k--);
                } else if (value != 0.0 && !currentIsRemoved) {
                    values[k] = value;
                } else {
                    currentIsRemoved = false;
                    CompressedVector.this.insert(++k, removedIndex, value);
                }
            }

            @Override
            public boolean hasNext() {
                return k + 1 < cardinality;
            }

            @Override
            public Double next() {
                currentIsRemoved = false;
                return values[++k];
            }

            @Override
            protected int innerCursor() {
                return k;
            }
        };
    }

    @Override
    public VectorIterator iterator() {
        return new VectorIterator(length) {
            private int k = 0;
            private int i = -1;

            @Override
            public int index() {
                return i;
            }

            @Override
            public double get() {
                if (k < cardinality && indices[k] == i) {
                    return values[k];
                }
                return 0.0;
            }

            @Override
            public void set(double value) {
                if (k < cardinality && indices[k] == i) {
                    if (value == 0.0) {
                        CompressedVector.this.remove(k);
                    } else {
                        values[k] = value;
                    }
                } else {
                    CompressedVector.this.insert(k, i, value);
                }
            }

            @Override
            public boolean hasNext() {
                return i + 1 < length;
            }

            @Override
            public Double next() {
                i++;
                if (k < cardinality && indices[k] == i - 1) {
                    k++;
                }
                return get();
            }

            @Override
            protected int innerCursor() {
                return k;
            }
        };
    }
}


text:
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;

namespace Facturapi.Wrappers
{
    public class OrganizationWrapper : BaseWrapper
    {
        public OrganizationWrapper(string apiKey) : base (apiKey) { }

        public async Task<SearchResult<Organization>> ListAsync(Dictionary<string, object> query = null)
        {
            var response = await client.GetAsync(Router.ListOrganizations(query));
            var resultString = await response.Content.ReadAsStringAsync();

            if (!response.IsSuccessStatusCode)
            {
                var error = JsonConvert.DeserializeObject<JObject>(resultString);
                throw new FacturapiException(error["message"].ToString());
            }

            var searchResult = JsonConvert.DeserializeObject<SearchResult<Organization>>(resultString, this.jsonSettings);
            return searchResult;
        }

        public async Task<Organization> CreateAsync(Dictionary<string, object> data)
        {
            var response = await client.PostAsync(Router.CreateOrganization(), new StringContent(JsonConvert.SerializeObject(data), Encoding.UTF8, "application/json"));
            var resultString = await response.Content.ReadAsStringAsync();
            if (!response.IsSuccessStatusCode)
            {
                var error = JsonConvert.DeserializeObject<JObject>(resultString);
                throw new FacturapiException(error["message"].ToString());
            }
            var organization = JsonConvert.DeserializeObject<Organization>(resultString, this.jsonSettings);
            return organization;
        }

        public async Task<Organization> RetrieveAsync(string id)
        {
            var response = await client.GetAsync(Router.RetrieveOrganization(id));
            var resultString = await response.Content.ReadAsStringAsync();
            if (!response.IsSuccessStatusCode)
            {
                var error = JsonConvert.DeserializeObject<JObject>(resultString);
                throw new FacturapiException(error["message"].ToString());
            }
            var organization = JsonConvert.DeserializeObject<Organization>(resultString, this.jsonSettings);
            return organization;
        }

        public async Task<Organization> DeleteAsync(string id)
        {
            var response = await client.DeleteAsync(Router.DeleteOrganization(id));
            var resultString = await response.Content.ReadAsStringAsync();
            if (!response.IsSuccessStatusCode)
            {
                var error = JsonConvert.DeserializeObject<JObject>(resultString);
                throw new FacturapiException(error["message"].ToString());
            }
            var organization = JsonConvert.DeserializeObject<Organization>(resultString, this.jsonSettings);
            return organization;
        }

        public async Task<Organization> UploadLogoAsync(string id, Stream file)
        {
            var form = new MultipartFormDataContent();
            form.Add(new StreamContent(file), "file", "logo.jpg");
            var response = await client.PutAsync(Router.UploadLogo(id), form);
            var resultString = await response.Content.ReadAsStringAsync();
            if (!response.IsSuccessStatusCode)
            {
                var error = JsonConvert.DeserializeObject<JObject>(resultString);
                throw new FacturapiException(error["message"].ToString());
            }
            var organization = JsonConvert.DeserializeObject<Organization>(resultString, this.jsonSettings);
            return organization;
        }

        public async Task<Organization> UploadCertificateAsync(string id, Stream cerFile, Stream keyFile, string password)
        {
            var form = new MultipartFormDataContent();
            form.Add(new StreamContent(cerFile), "cer", "certificate.cer");
            form.Add(new StreamContent(keyFile), "key", "key.key");
            form.Add(new StringContent(password), "password");
            var response = await client.PutAsync(Router.UploadCertificate(id), form);
            var resultString = await response.Content.ReadAsStringAsync();
            if (!response.IsSuccessStatusCode)
            {
                var error = JsonConvert.DeserializeObject<JObject>(resultString);
                throw new FacturapiException(error["message"].ToString());
            }
            var organization = JsonConvert.DeserializeObject<Organization>(resultString, this.jsonSettings);
            return organization;
        }

        public async Task<Organization> UpdateLegalAsync(string id, Dictionary<string, object> data)
        {
            var response = await client.PutAsync(Router.UpdateLegal(id), new StringContent(JsonConvert.SerializeObject(data), Encoding.UTF8, "application/json"));
            var resultString = await response.Content.ReadAsStringAsync();
			if (!response.IsSuccessStatusCode)
			{
				var error = JsonConvert.DeserializeObject<JObject>(resultString);
				throw new FacturapiException(error["message"].ToString());
			}
			var organization = JsonConvert.DeserializeObject<Organization>(resultString, this.jsonSettings);
			return organization;
        }

        public async Task<Organization> UpdateCustomizationAsync(string id, Dictionary<string, object> data)
        {
            var response = await client.PutAsync(Router.UpdateCustomization(id), new StringContent(JsonConvert.SerializeObject(data), Encoding.UTF8, "application/json"));
            var resultString = await response.Content.ReadAsStringAsync();
            if (!response.IsSuccessStatusCode)
            {
                var error = JsonConvert.DeserializeObject<JObject>(resultString);
                throw new FacturapiException(error["message"].ToString());
            }
            var organization = JsonConvert.DeserializeObject<Organization>(resultString, this.jsonSettings);
            return organization;
        }

        public async Task<string> GetTestApiKeyAsync(string id)
        {
            var response = await client.GetAsync(Router.GetTestApiKey(id));
            var resultString = await response.Content.ReadAsStringAsync();
            if (!response.IsSuccessStatusCode)
            {
                var error = JsonConvert.DeserializeObject<JObject>(resultString);
                throw new FacturapiException(error["message"].ToString());
            }
            return resultString;
        }

        public async Task<string> RenewTestApiKeyAsync(string id)
        {
            var response = await client.PutAsync(Router.RenewTestApiKey(id), new StringContent(""));
            var resultString = await response.Content.ReadAsStringAsync();
            if (!response.IsSuccessStatusCode)
            {
                var error = JsonConvert.DeserializeObject<JObject>(resultString);
                throw new FacturapiException(error["message"].ToString());
            }
            return resultString;
        }

        public async Task<string> RenewLiveApiKeyAsync(string id)
        {
            var response = await client.PutAsync(Router.RenewLiveApiKey(id), new StringContent(""));
            var resultString = await response.Content.ReadAsStringAsync();
            if (!response.IsSuccessStatusCode)
            {
                var error = JsonConvert.DeserializeObject<JObject>(resultString);
                throw new FacturapiException(error["message"].ToString());
            }
            return resultString;
        }
    }
}


text:
using Octoposh.Model;
using System.Management.Automation;

namespace Octoposh.Cmdlets
{
    ///
    /// <para type="synopsis">This cmdlet sets a version of Octo.exe as default. To get the value of the current default Octo.exe version run Get-OctopusToolPath or simply use $env:OctoExe</para>
    /// <para type="synopsis">In the background [Get-OctopusToolPath] and [Set-OctopusToolPath] simply Get/Set the value of the environment variable $env:OctoExe</para>
    ///
    ///
    /// <para type="description">This cmdlet sets a version of Octo.exe as default. To get the value of the current default Octo.exe version run Get-OctopusToolPath or simply use $env:OctoExe</para>
    /// <para type="description">In the background [Get-OctopusToolPath] and [Set-OctopusToolPath] simply Get/Set the value of the environment variable $env:OctoExe</para>
    ///
    /// <example>
    ///   PS C:\> Set-OctopusToolPath -path C:\tools\1.0.0\Octo.exe
    ///   <para>Sets C:\Tools\1.0.0\Octo.exe as the current default Octo.exe version</para>
    /// </example>
    /// <example>
    ///   PS C:\> Set-OctopusToolPath -version 1.0.0
    ///   <para>Uses Get-OctopusToolVersion to look for Octo.exe version 1.0.0 and then sets its path as the current default version</para>
    /// </example>
    /// <example>
    ///   PS C:\>Get-OctopusToolsVersion -latest | Set-OctopusToolPath
    ///   <para>Gets the latest version of Octo.exe installed on the machine using Get-OctopusToolsVersion and sets $env:OctoExe with its path</para>
    /// </example>
    /// <para type="link" uri="http://Octoposh.net">WebSite: </para>
    /// <para type="link" uri="https://github.com/Dalmirog/OctoPosh/">Github Project: </para>
    /// <para type="link" uri="http://octoposh.readthedocs.io">Wiki: </para>
    /// <para type="link" uri="https://gitter.im/Dalmirog/OctoPosh#initial">QA and Feature requests: </para>
    [Cmdlet("Set", "OctopusToolPath",DefaultParameterSetName = ByPath)]
    [OutputType(typeof(void))]
    public class SetOctopusToolPath : PSCmdlet
    {

        private const string ByPath = "ByPath";
        private const string ByVersion = "ByVersion";
        ///
        /// <para type="description">Sets the value of the default Octo.exe based on the version of it found by Get-OctopustoolsVersion</para>
        ///
        [Parameter(Mandatory = true, ParameterSetName = ByVersion)]
        public string Version { get; set; }

        ///
        /// <para type="description">Sets the value of the default Octo.exe using a literal path. The cmdlet won't validate if the path leads to an existing octo.exe file</para>
        ///
        [Parameter(Mandatory = true, ParameterSetName = ByPath ,ValueFromPipelineByPropertyName = true, Position = 0)]
        public string Path { get; set; }

        protected override void ProcessRecord()
        {
            var OctopusTools = new OctopusToolsHandler();

            if (ParameterSetName == ByPath)
            {
                OctopusTools.SetOctoExePath(Path);
            }
            else
            {
                var tool = OctopusTools.GetToolByVersion(Version);
                OctopusTools.SetOctoExePath(tool.Path);
            }
        }
    }
}


text:
package org.uberfire.provisioning.services.api.backend;

import java.util.List;

import org.jboss.errai.bus.server.annotations.Remote;
import org.uberfire.provisioning.services.exceptions.BusinessException;
import org.uberfire.provisioning.pipeline.Pipeline;

@Remote
public interface PipelineServiceBackend {

    List<Pipeline> getAllPipelines() throws BusinessException;

    String newPipeline( final Pipeline pipeline ) throws BusinessException;

    void runPipeline( final String id ) throws BusinessException;

}


text:
package com.camilstaps.bar;

/**
 * A tap can fill glasses
 * @author Camil Staps, s4498062
 */
public class Tap {

    private static final int CC_PER_GLASS = 200, DRAW_TIME_PER_CC = 1;

    /**
     * Fill a glass. This method can fill one glass at a time.
     * @param glass the glass to fill
     * @return the glass itself
     */
    public synchronized Glass fillUp(Glass glass) {
        System.err.println("Tap fills glass " + glass.toString());
        try {
            Thread.sleep(DRAW_TIME_PER_CC * (CC_PER_GLASS - glass.getVolume()));
        } catch (InterruptedException e) {}
        glass.fill(CC_PER_GLASS);
        System.err.println("Tap finished filling glass " + glass.toString());
        return glass;
    }

}


text:
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>
  <groupId>MSZJPA</groupId>
  <artifactId>MSZJPA</artifactId>
  <version>0.0.1-SNAPSHOT</version>

  <dependencies>
   <dependency>
        <groupId>junit</groupId>
        <artifactId>junit</artifactId>
        <version>3.8.1</version>
        <scope>test</scope>
    </dependency>
	<dependency>
		<groupId>org.jboss.weld</groupId>
		<artifactId>weld-core</artifactId>
		<version>2.1.2.Final</version>
		<scope>provided</scope>
	</dependency>
	<dependency>
		<groupId>org.postgresql</groupId>
		<artifactId>postgresql</artifactId>
		<version>9.3-1100-jdbc41</version>
	</dependency>

	<dependency>
	    <groupId>org.hibernate</groupId>
	    <artifactId>hibernate-core</artifactId>
	    <version>4.3.4.Final</version>
		<scope>provided</scope>
	</dependency>
	<dependency>
	    <groupId>org.hibernate</groupId>
	    <artifactId>hibernate-entitymanager</artifactId>
	    <version>4.3.4.Final</version>
		<scope>provided</scope>
	</dependency>
  </dependencies>
  <build>
    <sourceDirectory>src</sourceDirectory>
    <resources>
      <resource>
        <directory>src</directory>
        <excludes>
          <exclude>**/*.java</exclude>
        </excludes>
      </resource>
    </resources>
    <plugins>
      <plugin>
        <artifactId>maven-compiler-plugin</artifactId>
        <version>3.1</version>
        <configuration>
          <source>1.7</source>
          <target>1.7</target>
        </configuration>
      </plugin>
    </plugins>
  </build>
</project>


text:
using Base.Test, Lumberjack
#import Mocking: mend TODO

modes = ["debug", "info", "notice", "warning", "err", "crit", "alert", "emerg"]
configure(; modes=[modes..., "invalid-syslog-level"])
Lumberjack.add_truck(LumberjackTruck(Syslog(:local0, "julia")))

# Syslog uses an external call to logger to do its legwork. Because the syslog itself can be
# essentially anywhere (we might not have permission to read it, and it might not even be on
# the same machine), we'll just make sure that the external call to logger itself is right.
# This requires that the call to run to be overwritten has the @mendable macro.
history = []
# mend(run, command::Cmd -> push!(history, string(command))) do
#     for mode in modes
#         log(mode, "Message")
#         @test history[end] == string(`logger -t julia -p local0.$(mode) "$(mode): Message"`)
#     end
#
#     # Syslog only accepts certain predefined loglevels.
#     @test_throws ErrorException log("invalid-syslog-level", "Message")
# end


text:
Whisk is a collection of the functional operation helpers (underscore-like)
for working with map, filter, reduce, etc.

[![NPM](https://nodei.co/npm/whisk.png)](https://nodei.co/npm/whisk/)

[![Build Status](https://img.shields.io/travis/DamonOehlman/whisk.svg?branch=master)](https://travis-ci.org/DamonOehlman/whisk)

## flatten

Flatten an array using `[].reduce`

```js
var flatten = require('whisk/flatten');

console.log([1, [2, 3], 4, [5]].reduce(flatten));
// --> [ 1, 2, 3, 4, 5 ]
```

## length

Get the length of the target.

```js
var length = require('whisk/length');

console.log(length([1, 2, 3]));
// --> 3

console.log(length('Hello'));
// --> 5

console.log(['Hi', 'there'].map(length));
// --> [ 2, 5 ]
```

## not

Designed to be used in combination with an `[].filter` the `not` function
can be used to exlude items from an array.

```js
var not = require('whisk/not');
var items = ['a', 'b', 'c', 'd', 'e'];

console.log(items.filter(not('a')));
// --> [ 'b', 'c', 'd', 'e' ]

console.log(items.filter(not(['a', 'b'])));
// --> [ 'c', 'd', 'e' ]

console.log(items.filter(not('a', 'b')));
// --> [ 'c', 'd', 'e' ]
```

## nub

Return only the unique elements of the list.

```js
var nub = require('whisk/nub');

console.log(nub([ 1, 2, 3, 2, 3, 4 ]));
// --> [ 1, 2, 3, 4 ]

console.log(nub([ 'red', 'blue', 'red' ]));
// --> [ 'red', 'blue' ]

console.log(nub([ 4, 6, 6, 8, 3, 4, 1 ]));
// --> [ 4, 6, 8, 3, 1 ]
```

## pluck

Extract targeted properties from a source object. When a single property
value is requested, then just that value is returned.

In the case where multiple properties are requested (in a varargs calling
style) a new object will be created with the requested properties copied
across.

__NOTE:__ In the second form extraction of nested properties is
not supported.

```js
var pluck = require('whisk/pluck');
var people = [
  { name: 'Bob', age: 35, address: { country: 'Australia' } },
  { name: 'Thelma', age: 32, address: { country: 'New Zealand' } },
  { name: 'Roger', age: 50, address: { country: 'Fiji' } }
];

console.log(people.map(pluck('name')));
// --> [ 'Bob', 'Thelma', 'Roger' ]

console.log(people.map(pluck('address.country')));
// --> [ 'Australia', 'New Zealand', 'Fiji' ]

console.log(people.map(pluck('name', 'age')));
// --> [ { name: 'Bob', age: 35 }, { name: 'Thelma', age: 32 }, { name: 'Roger', age: 50 } ]
```

## range

Create an array of elements from x -> y (inclusive)

```js
var pluck = require('whisk/range');

console.log(range(0, 3));
// --> [ 0, 1, 2, 3 ]
```

## sum

Sum an input array of values

```js
var sum = require('whisk/sum');
var range = require('whisk/range');

console.log(sum([1, 2]));
// --> 3

console.log(sum(range(1, 10)));
// --> 55

console.log([1, 2].reduce(sum));
// --> 3

console.log(range(1, 10).reduce(sum));
// --> 55

```

## times

Create an element of arrays that can be iterated over n times:

```js
var times = require('whisk/times');

times(3).forEach(function() {
  console.log('hello world');
});

// --> hello world
// --> hello world
// --> hello world

```

## zip

zip one array with other arrays

```js
var zip = require('whisk/zip');

console.log([1, 2, 3].map(zip(['a', 'b', 'c'])));
// --> [ [1, 'a'], [2, 'b'], [3, 'c'] ]

console.log([1, 2, 3].map(zip(['a', 'b', 'c'], ['x', 'y', 'z'])));
// --> [ [1, 'a', 'x'], [2, 'b', 'y'], [3, 'c', 'z'] ]
```

### zip todo

- tests

## License(s)

### MIT

Copyright (c) 2014 Damon Oehlman <damon.oehlman@gmail.com>

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.


text:
FROM bitnami/nginx:1.12

# built by running:
# $ docker-compose run --rm ui ng build -t production -o rootfs/dist
COPY dist/ /app


text:
@interface DroiFeedbackModel : NSObject

@property (copy, nonatomic)NSString *content;   //反馈内容

@property (copy, nonatomic)NSString *createTime;//创建时间

@property (copy, nonatomic)NSString *reply;     //回复内容

@property (copy, nonatomic)NSString *replyTime; //回复时间

@property (strong, nonatomic)NSMutableArray *imageList;//图片 url 列表,string数组
@property (strong, nonatomic)NSArray *objList;//objId 数组 ,根据objId去查询对应的图片 url。
@end


text:
module ForemanSentry
  VERSION = '0.1.3'.freeze
end


text:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
                      "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">

    <meta http-equiv="content-type" content="text/html; charset=UTF-8"/>
    <title>Zend_Service_Amazon_Ec2: Reservierte Instanzen - Zend Framework Manual</title>

                    Zend_Service_Amazon_Ec2: Windows Instanzen

Zend_Service

                        Programmer's Reference Guide

Zend_Service_Amazon_Ec2: CloudWatch Monitoring

Zend_Service_Amazon_Ec2: Reservierte Instanzen

        Mit Amazon <acronym class="acronym">EC2</acronym> Reservierte Instanzen, kann man eine geringe
        Einmalzahlung für jede zu reservierende Instanz tätigen und einen signifikanten Rabatt auf
        einer Stundenbasierenden Verwendung für diese Instanz erhalten.

        Amazon <acronym class="acronym">EC2</acronym> Reservierte Instanzen basieren auf Instanz Typ und Ort
        (Region und Vorhandene Zone) für eine spezifizierte Zeitperiode (z.B. 1 Jahr oder 3 Jahre)
        und sind nur für Linux oder UNIX Instanzen erhältlich.

Wie werden Reservierte Instanzen angehängt

            Reservierte Instanzen werden an Instanzen angehängt welche den Typen- und Ortskriterien
            wärend der spezifizierten Periode entsprechen. In diesem Beispiel verwendet ein Benutzer
            die folgenden Instanzen:

(4) m1.small Instanzen in der Vorhandenen Zone us-east-1a

(4) c1.medium Instanzen in der Vorhandenen Zone us-east-1b

(2) c1.xlarge Instanzen ind er Vorhandenen Zone us-east-1b

            Der Benutzer erwirbt anschließend die folgenden Reservierten Instanzen.

(2) m1.small Instanzen in der Vorhandenen Zone us-east-1a

(2) c1.medium Instanzen in der Vorhandenen Zone us-east-1a

(2) m1.xlarge Instanzen in der Vorhandenen Zone us-east-1a

            Amazon <acronym class="acronym">EC2</acronym> fügt die zwei m1.small Reservierten Instanzen den zwei
            Instanzen in der Vorhandenen Zone us-east-1a hinzu. Amazon <acronym class="acronym">EC2</acronym>
            fügt die zwei c1.medium Reservierten Instanzen nicht hinzu weil die c1.medium Instanzen
            in einer anderen Vorhandenen Zone sind und es fügt auch nicht die m1.xlarge
            Reservierten Instanzen hinzu weil es keine laufenden m1.xlarge Instanzen gibt.

Verwendung Reservierter Instanzen

Example #1 Beschreibt Reservierte Instanzen die man gekauft hat

                 describeInstances() gibt Informationen über eine
                reservierte Instanz oder Instanzen zurück die man gekauft hat.

                 describeInstances() gibt ein mehrdimensionales Array
                zurück welches folgendes enthält: reservedInstancesId, instanceType,
                availabilityZone, duration, fixedPrice, usagePrice, productDescription,
                instanceCount und state.

$ec2_instance = new Zend_Service_Amazon_Ec2_Instance_Reserved('aws_key',

                                                     'aws_secret_key');

$return = $ec2_instance->describeInstances('instanceId');

Example #2 Beschreiben der aktuell vorhandenen Reservierten Instanz Angebote

                 describeOfferings() beschreibt Angebote für Reservierte
                Instanzen die für einen Kauf vorhanden sind. Mit Amazon <acronym class="acronym">EC2</acronym>
                Reservierten Instanzen kauft man das Recht amazon <acronym class="acronym">EC2</acronym> Instanzen
                für eine bestimmte Zeitdauer zu starten (ohne Fehler wegen unzureichender Kapazität
                zu erhalten) und einen geringeren Preis für die Verwendung der wirklich verwendeten
                Zeit zu erhalten.

                 describeOfferings() gibt ein mehrdimensionales Array
                zurück das die folgenden Daten enthält: reservedInstancesId, instanceType,
                availabilityZone, duration, fixedPrice, usagePrice und productDescription.

$ec2_instance = new Zend_Service_Amazon_Ec2_Instance_Reserved('aws_key',

                                                     'aws_secret_key');

$return = $ec2_instance->describeOfferings();

Example #3 Das CloudWatch Monitoring bei Instanzen ausschalten

                 purchaseOffering() erwirbt eine Reservierte Instanz für
                die Verwendung mit dem eigenen Account. Mit Amazon <acronym class="acronym">EC2</acronym>
                Reservierten Instanzen kauft man das Recht amazon <acronym class="acronym">EC2</acronym> Instanzen
                für eine bestimmte Zeitdauer zu starten (ohne Fehler wegen unzureichender Kapazität
                zu erhalten) und einen geringeren Preis für die Verwendung der wirklich verwendeten
                Zeit zu erhalten.

                 purchaseOffering() gibt die reservedInstanceId zurück.

$ec2_instance = new Zend_Service_Amazon_Ec2_Instance_Reserved('aws_key',

                                                     'aws_secret_key');

$return = $ec2_instance->purchaseOffering('offeringId', 'instanceCount');

                    Zend_Service_Amazon_Ec2: Windows Instanzen

Zend_Service

                        Programmer's Reference Guide

Zend_Service_Amazon_Ec2: CloudWatch Monitoring

Programmer's Reference Guide

Programmer's Reference Guide

Zend Framework Reference

Zend_Service

Einführung

Zend_Service_Akismet

Zend_Service_Amazon

Zend_Service_Amazon_Ec2

Zend_Service_Amazon_Ec2: Instanzen

Zend_Service_Amazon_Ec2: Windows Instanzen

Zend_Service_Amazon_Ec2: Reservierte Instanzen

Zend_Service_Amazon_Ec2: CloudWatch Monitoring

Zend_Service_Amazon_Ec2: Amazon Maschinen Images (AMI)

Zend_Service_Amazon_Ec2: Elastischer Block Speicher (EBS)

Zend_Service_Amazon_Ec2: Elastische IP Adressen

Zend_Service_Amazon_Ec2: Schlüsselpaare

Zend_Service_Amazon_Ec2: Regionen und Availability Zones

Zend_Service_Amazon_Ec2: Sicherheitsgruppen

Zend_Service_Amazon_S3

Zend_Service_Amazon_Sqs

Zend_Service_Audioscrobbler

Zend_Service_Delicious

Zend_Service_DeveloperGarden

Zend_Service_Ebay

Zend_Service_Ebay_Finding

Zend_Service_Flickr

Zend_Service_LiveDocx

Zend_Service_Nirvanix

Zend_Service_ReCaptcha

Zend_Service_ShortUrl

Zend_Service_Simpy

Zend_Service_SlideShare

Zend_Service_StrikeIron

Zend_Service_StrikeIron: Mitgelieferte Services

Zend_Service_StrikeIron: Erweiterte Verwendung

Zend_Service_Technorati

Zend_Service_Twitter

Zend_Service_WindowsAzure

Zend_Service_WindowsAzure_Storage_Blob

Zend_Service_WindowsAzure_Diagnostics_Manager

Zend_Service_WindowsAzure_Storage_Queue

Zend_Service_WindowsAzure_Storage_Table

Zend_Service_Yahoo