text:
namespace pthash {

template <typename Hasher>
struct external_memory_builder_single_phf {
    typedef Hasher hasher_type;

    external_memory_builder_single_phf() : m_pilots_filename(""), m_free_slots_filename("") {}
    // non construction-copyable
    external_memory_builder_single_phf(external_memory_builder_single_phf const&) = delete;
    // non copyable
    external_memory_builder_single_phf& operator=(external_memory_builder_single_phf const&) =
        delete;

    ~external_memory_builder_single_phf() {
        if (m_pilots_filename != "") std::remove(m_pilots_filename.c_str());
        m_pilots_filename = "";
        if (m_free_slots_filename != "") std::remove(m_free_slots_filename.c_str());
        m_free_slots_filename = "";
    }

    template <typename Iterator>
    build_timings build_from_keys(Iterator keys, uint64_t num_keys,
                                  build_configuration const& config) {
        assert(num_keys > 1);
        if (config.alpha == 0 or config.alpha > 1.0) {
            throw std::invalid_argument("load factor must be > 0 and <= 1.0");
        }

        build_timings time;
        uint64_t table_size = static_cast<double>(num_keys) / config.alpha;
        if ((table_size & (table_size - 1)) == 0) table_size += 1;
        uint64_t num_buckets = std::ceil((config.c * num_keys) / std::log2(num_keys));

        if (sizeof(bucket_id_type) != sizeof(uint64_t) and
            num_buckets > (1ULL << (sizeof(bucket_id_type) * 8))) {
            throw std::runtime_error(
                "using too many buckets: change bucket_id_type to uint64_t or use a smaller c");
        }

        m_num_keys = num_keys;
        m_table_size = table_size;
        m_num_buckets = num_buckets;
        m_seed = config.seed == constants::invalid_seed ? random_value() : config.seed;
        m_bucketer.init(num_buckets);

        uint64_t ram = config.ram;

        uint64_t bitmap_taken_bytes = 8 * ((table_size + 63) / 64);
        uint64_t hashed_pilots_cache_bytes = search_cache_size * sizeof(uint64_t);
        if (bitmap_taken_bytes + hashed_pilots_cache_bytes >= ram) {
            std::stringstream ss;
            ss << "not enough RAM available, the bitmap alone takes "
               << static_cast<double>(bitmap_taken_bytes) / 1000000000 << " GB of space.";
            throw std::runtime_error(ss.str());
        }

        if (config.verbose_output) {
            constexpr uint64_t GB = 1000000000;
            uint64_t peak = num_keys * (sizeof(bucket_payload_pair) + sizeof(uint64_t)) +
                            (num_keys + num_buckets) * sizeof(uint64_t);
            std::cout << "c = " << config.c << std::endl;
            std::cout << "alpha = " << config.alpha << std::endl;
            std::cout << "num_keys = " << num_keys << std::endl;
            std::cout << "table_size = " << table_size << std::endl;
            std::cout << "num_buckets = " << num_buckets << std::endl;
            std::cout << "using " << static_cast<double>(ram) / GB << " GB of RAM"
                      << " (" << static_cast<double>(bitmap_taken_bytes) / GB
                      << " GB occupied by the bitmap)" << std::endl;
            std::cout << "using a peak of " << static_cast<double>(peak) / GB << " GB of disk space"
                      << std::endl;
        }

        uint64_t run_identifier = clock_type::now().time_since_epoch().count();
        temporary_files_manager tfm(config.tmp_dir, run_identifier);

        uint64_t num_non_empty_buckets = 0;

        try {
            auto start = clock_type::now();
            {
                auto start = clock_type::now();
                std::vector<pairs_t> pairs_blocks;
                map(keys, num_keys, pairs_blocks, tfm, config);
                auto stop = clock_type::now();
                if (config.verbose_output) {
                    std::cout << " == map+sort " << tfm.get_num_pairs_files()
                              << " files(s) took: " << seconds(stop - start) << " seconds"
                              << std::endl;
                }
                start = clock_type::now();
                buckets_t buckets = tfm.buckets(config);
                merge(pairs_blocks, buckets, config.verbose_output);
                buckets.flush();
                for (auto& pairs_block : pairs_blocks) pairs_block.close();
                num_non_empty_buckets = buckets.num_buckets();
                tfm.remove_all_pairs_files();
                stop = clock_type::now();
                if (config.verbose_output) {
                    std::cout << " == merge+check took: " << seconds(stop - start) << " seconds"
                              << std::endl;
                    std::cout << " == max bucket size = " << int(tfm.max_bucket_size())
                              << std::endl;
                }
            }
            auto stop = clock_type::now();
            time.mapping_ordering_seconds = seconds(stop - start);
            if (config.verbose_output) {
                std::cout << " == map+ordering took " << time.mapping_ordering_seconds << " seconds"
                          << std::endl;
            }
        } catch (...) {
            tfm.remove_all_pairs_files();
            tfm.remove_all_merge_files();
            throw;
        }

        try {
            auto start = clock_type::now();
            bit_vector_builder taken(m_table_size);

            {  // search
                auto buckets_iterator = tfm.buckets_iterator();

                // write all bucket-pilot pairs to files
                uint64_t ram_for_pilots = ram - bitmap_taken_bytes - hashed_pilots_cache_bytes;
                auto pilots =
                    tfm.get_multifile_pairs_writer(num_non_empty_buckets, ram_for_pilots, 1, 0);

                search(m_num_keys, m_num_buckets, num_non_empty_buckets, m_seed, config,
                       buckets_iterator, taken, pilots);

                pilots.flush();
                buckets_iterator.close();
                // merge all sorted bucket-pilot pairs on a single file, saving only the pilot
                pilots_merger_t pilots_merger(tfm.get_pilots_filename(), ram);
                merge(tfm.pairs_blocks(), pilots_merger, false);
                pilots_merger.finalize_and_close(m_num_buckets);

                if (m_pilots_filename != "") std::remove(m_pilots_filename.c_str());
                m_pilots_filename = tfm.get_pilots_filename();

                // remove unused temporary files
                tfm.remove_all_pairs_files();
                tfm.remove_all_merge_files();
            }

            if (config.minimal_output) {  // fill free slots
                // write all free slots to file
                buffered_file_t<uint64_t> writer(tfm.get_free_slots_filename(),
                                                 ram - bitmap_taken_bytes);
                fill_free_slots(taken, num_keys, writer);
                writer.close();
                if (m_free_slots_filename != "") std::remove(m_free_slots_filename.c_str());
                m_free_slots_filename = tfm.get_free_slots_filename();
            }

            auto stop = clock_type::now();
            time.searching_seconds = seconds(stop - start);
            if (config.verbose_output) {
                std::cout << " == search took " << time.searching_seconds << " seconds"
                          << std::endl;
            }
        } catch (...) {
            tfm.remove_all_pairs_files();
            tfm.remove_all_merge_files();
            throw;
        }

        return time;
    }

    uint64_t seed() const {
        return m_seed;
    }

    uint64_t num_keys() const {
        return m_num_keys;
    }

    uint64_t table_size() const {
        return m_table_size;
    }

    skew_bucketer bucketer() const {
        return m_bucketer;
    }

    mm::file_source<uint64_t> pilots() const {
        return mm::file_source<uint64_t>(m_pilots_filename);
    }

    mm::file_source<uint64_t> free_slots() const {
        return mm::file_source<uint64_t>(m_free_slots_filename);
    }

private:
    uint64_t m_seed;
    uint64_t m_num_keys;
    uint64_t m_table_size;
    uint64_t m_num_buckets;
    skew_bucketer m_bucketer;
    std::string m_pilots_filename;
    std::string m_free_slots_filename;

    template <typename T>
    struct buffer_t {
        buffer_t(uint64_t ram) : m_buffer_capacity(ram / sizeof(T)) {
            m_buffer.reserve(m_buffer_capacity);
            assert(m_buffer_capacity > 0);
        }

        template <class... _Args>
        void emplace_back(_Args&&... __args) {
            m_buffer.emplace_back(std::forward<_Args>(__args)...);
            if (--m_buffer_capacity == 0) flush();
        }

        void flush() {
            if (!m_buffer.empty()) {
                uint64_t buffer_size = m_buffer.size();
                flush_impl(m_buffer);
                m_buffer_capacity += buffer_size;
                m_buffer.clear();
            }
        }

    protected:
        virtual void flush_impl(std::vector<T>& buffer) = 0;

    private:
        uint64_t m_buffer_capacity;
        std::vector<T> m_buffer;
    };

    template <typename T>
    struct buffered_file_t : buffer_t<T> {
        buffered_file_t(std::string const& filename, uint64_t ram) : buffer_t<T>(ram) {
            m_out.open(filename, std::ofstream::out | std::ofstream::binary);
            if (!m_out.is_open()) throw std::runtime_error("cannot open binary file in write mode");
        }

        void close() {
            buffer_t<T>::flush();
            m_out.close();
        }

    protected:
        void flush_impl(std::vector<T>& buffer) {
            m_out.write(reinterpret_cast<char const*>(buffer.data()), buffer.size() * sizeof(T));
        }

    private:
        std::ofstream m_out;
    };

    template <typename T>
    struct memory_view {
        typedef T* iterator;
        typedef const T* const_iterator;

        memory_view() : m_begin(nullptr), m_end(nullptr){};
        memory_view(T* begin, uint64_t size) : m_begin(begin), m_end(begin + size) {}

        inline T* begin() const {
            return m_begin;
        }
        inline T* end() const {
            return m_end;
        }
        inline T& operator[](uint64_t pos) const {
            return *(m_begin + pos);
        }
        inline uint64_t size() const {
            return std::distance(m_begin, m_end);
        }

    protected:
        T *m_begin, *m_end;
    };

    template <typename T>
    struct reader_t : memory_view<const T> {
        void open(std::string const& filename) {
            if (m_is.is_open()) m_is.close();
            m_is.open(filename, mm::advice::sequential);
            if (!m_is.is_open()) throw std::runtime_error("cannot open temporary file (read)");
            memory_view<const T>::m_begin = m_is.data();
            memory_view<const T>::m_end = m_is.data() + m_is.size();
        }

        void close() {
            m_is.close();
        }

    private:
        mm::file_source<T> m_is;
    };

    typedef reader_t<bucket_payload_pair> pairs_t;

    struct pairs_merger_t {
        pairs_merger_t(std::string const& filename, uint64_t ram) : m_buffer(filename, ram) {}

        template <typename HashIterator>
        void add(bucket_id_type bucket_id, bucket_size_type bucket_size, HashIterator hashes) {
            for (uint64_t k = 0; k != bucket_size; ++k, ++hashes) {
                m_buffer.emplace_back(bucket_id, *hashes);
            }
        }

        void close() {
            m_buffer.close();
        }

    private:
        buffered_file_t<bucket_payload_pair> m_buffer;
    };

    struct buckets_t {  // merger
        buckets_t(std::vector<std::string> const& filenames, uint64_t ram,
                  std::vector<bool>& used_bucket_sizes)
            : m_filenames(filenames)
            , m_buffers(filenames.size())
            , m_buffer_capacity(ram / (sizeof(uint64_t) * 2))
            , m_ram(ram / (sizeof(uint64_t) * 2))
            , m_used_bucket_sizes(used_bucket_sizes)
            , m_outs(filenames.size())
            , m_num_buckets(0) {
            assert(m_filenames.size() == m_used_bucket_sizes.size());
            m_non_empty_buckets.reserve(filenames.size());
            for (uint64_t i = 0; i != filenames.size(); ++i) {
                if (m_used_bucket_sizes[i]) {
                    throw std::runtime_error("One of the output files is already open");
                }
            }
        }

        template <typename HashIterator>
        void add(bucket_id_type bucket_id, bucket_size_type bucket_size, HashIterator hashes) {
            assert(bucket_size > 0 and bucket_size <= MAX_BUCKET_SIZE);
            ensure_capacity(bucket_size);
            uint64_t i = bucket_size - 1;
            if (m_buffers[i].empty()) m_non_empty_buckets.push_back(bucket_size - 1);
            m_buffers[i].push_back(bucket_id);
            for (uint64_t k = 0; k != bucket_size; ++k, ++hashes) m_buffers[i].push_back(*hashes);
            m_buffer_capacity -= bucket_size + 1;
            ++m_num_buckets;
        }

        uint64_t num_buckets() const {
            return m_num_buckets;
        };

        void flush() {
            for (uint64_t i = 0; i != m_buffers.size(); ++i) flush_i(i);
            m_non_empty_buckets.clear();
        }

    private:
        void ensure_capacity(uint64_t bucket_size) {
            if (bucket_size + 1 > m_buffer_capacity) {
                std::sort(m_non_empty_buckets.begin(), m_non_empty_buckets.end(),
                          [&](uint64_t i, uint64_t j) {
                              return m_buffers[i].size() < m_buffers[j].size();
                          });

                uint64_t target = std::max((uint64_t)std::ceil(0.999 * m_ram), bucket_size + 1);
                while (m_buffer_capacity < target) {
                    flush_i(m_non_empty_buckets.back());
                    m_non_empty_buckets.pop_back();
                }
            }
        }

        void flush_i(uint64_t i) {
            if (m_buffers[i].size() == 0) return;
            if (!m_used_bucket_sizes[i]) {
                m_outs[i].open(m_filenames[i].c_str(), std::ofstream::out | std::ofstream::binary);
                if (!m_outs[i].is_open()) {
                    throw std::runtime_error("cannot open temporary file (write)");
                }
                m_used_bucket_sizes[i] = true;
            }
            m_outs[i].write(reinterpret_cast<char const*>(m_buffers[i].data()),
                            m_buffers[i].size() * sizeof(uint64_t));
            m_buffer_capacity += m_buffers[i].size();
            std::vector<uint64_t>().swap(m_buffers[i]);
        }

        std::vector<std::string> m_filenames;
        std::vector<std::vector<uint64_t>> m_buffers;
        uint64_t m_buffer_capacity;
        uint64_t m_ram;
        std::vector<uint64_t> m_non_empty_buckets;
        std::vector<bool>& m_used_bucket_sizes;
        std::vector<std::ofstream> m_outs;
        uint64_t m_num_buckets;
    };

    struct buckets_iterator_t {
        buckets_iterator_t(
            std::vector<std::pair<bucket_size_type, std::string>> const& sizes_filenames)
            : m_sizes(sizes_filenames.size()), m_sources(sizes_filenames.size()) {
            m_pos = sizes_filenames.size();
            for (uint64_t i = 0, i_end = m_pos; i < i_end; ++i) {
                m_sizes[i] = sizes_filenames[i].first;
                m_sources[i].open(sizes_filenames[i].second, mm::advice::sequential);
                assert(i == 0 or m_sizes[i - 1] < m_sizes[i]);
            }
            read_next_file();
        }

        void close() {
            for (auto& is : m_sources) is.close();
        }

        inline bucket_t operator*() {
            bucket_t bucket;
            bucket.init(m_it, m_bucket_size);
            return bucket;
        }

        void operator++() {
            m_it += m_bucket_size + 1;
            if (m_it >= m_end) read_next_file();
        }

    private:
        void read_next_file() {
            if (m_pos == 0) {
                m_it = m_end;
                return;
            }
            --m_pos;
            m_bucket_size = m_sizes[m_pos];
            m_it = m_sources[m_pos].data();
            m_end = m_it + m_sources[m_pos].size();
        }

        uint64_t m_pos;
        std::vector<bucket_size_type> m_sizes;
        std::vector<mm::file_source<uint64_t>> m_sources;
        bucket_size_type m_bucket_size;
        uint64_t const* m_it;
        uint64_t const* m_end;
    };

    struct pilots_merger_t {
        pilots_merger_t(std::string const& filename, uint64_t ram)
            : m_buffer(filename, ram), m_next_bucket_id(0) {}

        template <typename HashIterator>
        void add(bucket_id_type bucket_id, bucket_size_type bucket_size, HashIterator hashes) {
            assert(bucket_size == 1);
            (void)bucket_size;  // avoid unused warning in release mode
            emplace_back_and_fill(bucket_id, *hashes);
        }

        void finalize_and_close(uint64_t num_buckets) {
            if (m_next_bucket_id < num_buckets) emplace_back_and_fill(num_buckets - 1, 0);
            m_buffer.close();
        }

    private:
        inline void emplace_back_and_fill(bucket_id_type bucket_id, uint64_t pilot) {
            assert(m_next_bucket_id <= bucket_id);

            while (m_next_bucket_id++ < bucket_id) { m_buffer.emplace_back(0); }
            m_buffer.emplace_back(pilot);
        }

        buffered_file_t<uint64_t> m_buffer;
        uint64_t m_next_bucket_id;
    };

    struct multifile_pairs_writer : buffer_t<bucket_payload_pair> {
        multifile_pairs_writer(std::vector<std::string> const& filenames, uint64_t& num_pairs_files,
                               uint64_t num_pairs, uint64_t ram, uint64_t num_threads_sort = 1,
                               uint64_t ram_parallel_merge = 0)
            : buffer_t<bucket_payload_pair>(get_balanced_ram(num_pairs, ram))
            , m_filenames(filenames)
            , m_num_pairs_files(num_pairs_files)
            , m_num_threads_sort(num_threads_sort)
            , m_ram_parallel_merge(ram_parallel_merge) {
            assert(num_threads_sort > 1 or ram_parallel_merge == 0);
        }

    protected:
        void flush_impl(std::vector<bucket_payload_pair>& buffer) {
            const uint64_t size = buffer.size();

            if (m_num_threads_sort > 1) {  // parallel
                std::vector<memory_view<bucket_payload_pair>> blocks;
                uint64_t num_keys_per_thread = (size + m_num_threads_sort - 1) / m_num_threads_sort;
                auto exe = [&](uint64_t tid) { std::sort(blocks[tid].begin(), blocks[tid].end()); };

                std::vector<std::thread> threads(m_num_threads_sort);
                for (uint64_t i = 0; i != m_num_threads_sort; ++i) {
                    auto begin = buffer.data() + i * num_keys_per_thread;
                    auto end = buffer.data() + std::min((i + 1) * num_keys_per_thread, size);
                    uint64_t block_size = std::distance(begin, end);

                    blocks.emplace_back(begin, block_size);
                    threads[i] = std::thread(exe, i);
                }
                for (uint64_t i = 0; i != m_num_threads_sort; ++i) {
                    if (threads[i].joinable()) threads[i].join();
                }
                pairs_merger_t pairs_merger(m_filenames[m_num_pairs_files], m_ram_parallel_merge);
                ++m_num_pairs_files;
                merge(blocks, pairs_merger, false);
                pairs_merger.close();
            } else {  // sequential
                std::ofstream out(m_filenames[m_num_pairs_files],
                                  std::ofstream::out | std::ofstream::binary);
                if (!out.is_open()) throw std::runtime_error("cannot open temporary file (write)");
                ++m_num_pairs_files;
                std::sort(buffer.begin(), buffer.end());
                out.write(reinterpret_cast<char const*>(buffer.data()),
                          size * sizeof(bucket_payload_pair));
                out.close();
            }
        }

    private:
        std::vector<std::string> m_filenames;
        uint64_t& m_num_pairs_files;
        uint64_t m_num_threads_sort;
        uint64_t m_ram_parallel_merge;

        static uint64_t get_balanced_ram(uint64_t num_pairs, uint64_t ram) {
            uint64_t num_pairs_per_file = ram / sizeof(bucket_payload_pair);
            uint64_t num_temporary_files =
                (num_pairs + num_pairs_per_file - 1) / num_pairs_per_file;
            uint64_t balanced_num_pairs_per_temporary_file =
                (num_pairs + num_temporary_files - 1) / num_temporary_files;
            uint64_t balanced_ram =
                balanced_num_pairs_per_temporary_file * sizeof(bucket_payload_pair);
            assert(balanced_ram <= ram);

            return balanced_ram;
        }
    };

    struct temporary_files_manager {
        temporary_files_manager(std::string const& dir_name, uint64_t run_identifier)
            : m_dir_name(dir_name)
            , m_run_identifier(run_identifier)
            , m_num_pairs_files(0)
            , m_used_bucket_sizes(MAX_BUCKET_SIZE) {
            std::fill(m_used_bucket_sizes.begin(), m_used_bucket_sizes.end(), false);
        }

        multifile_pairs_writer get_multifile_pairs_writer(uint64_t num_pairs, uint64_t ram,
                                                          uint64_t num_threads_sort = 1,
                                                          uint64_t ram_parallel_merge = 0) {
            uint64_t num_pairs_per_file = ram / sizeof(bucket_payload_pair);
            uint64_t num_temporary_files =
                (num_pairs + num_pairs_per_file - 1) / num_pairs_per_file;
            std::vector<std::string> filenames;
            filenames.reserve(num_temporary_files);
            for (uint64_t i = 0; i < num_temporary_files; ++i) {
                filenames.emplace_back(get_pairs_filename(m_num_pairs_files + i));
            }
            return multifile_pairs_writer(filenames, m_num_pairs_files, num_pairs, ram,
                                          num_threads_sort, ram_parallel_merge);
        }

        uint64_t get_num_pairs_files() const {
            return m_num_pairs_files;
        }

        void remove_all_pairs_files() {
            while (m_num_pairs_files > 0) {
                std::remove(get_pairs_filename(--m_num_pairs_files).c_str());
            }
        }

        void remove_all_merge_files() {
            for (uint64_t i = 0; i != MAX_BUCKET_SIZE; ++i) {
                if (m_used_bucket_sizes[i]) {
                    std::remove(get_buckets_filename(i + 1).c_str());
                    m_used_bucket_sizes[i] = false;
                }
            }
        }

        std::vector<pairs_t> pairs_blocks() const {
            std::vector<pairs_t> result(m_num_pairs_files);
            for (uint64_t i = 0; i != m_num_pairs_files; ++i) result[i].open(get_pairs_filename(i));
            return result;
        };

        buckets_t buckets(build_configuration const& config) {
            std::vector<std::string> filenames;
            filenames.reserve(MAX_BUCKET_SIZE);
            for (uint64_t bucket_size = 1; bucket_size <= MAX_BUCKET_SIZE; ++bucket_size) {
                filenames.emplace_back(get_buckets_filename(bucket_size));
            }
            return buckets_t(filenames, config.ram, m_used_bucket_sizes);
        }

        buckets_iterator_t buckets_iterator() {
            std::vector<std::pair<bucket_size_type, std::string>> sizes_filenames;
            for (uint64_t i = 0; i != MAX_BUCKET_SIZE; ++i) {
                if (m_used_bucket_sizes[i]) {
                    uint64_t bucket_size = i + 1;
                    sizes_filenames.emplace_back(bucket_size, get_buckets_filename(bucket_size));
                }
            }
            assert(sizes_filenames.size() > 0);
            return buckets_iterator_t(sizes_filenames);
        }

        bucket_size_type max_bucket_size() {
            bucket_size_type bucket_size = 0;
            for (uint64_t i = 0, i_end = m_used_bucket_sizes.size(); i < i_end; ++i) {
                if (m_used_bucket_sizes[i]) bucket_size = i;
            }
            return bucket_size + 1;
        }

        std::string get_pilots_filename() const {
            std::stringstream filename;
            filename << m_dir_name << "/pthash.tmp.run" << m_run_identifier << ".pilots"
                     << ".bin";
            return filename.str();
        }

        std::string get_free_slots_filename() const {
            std::stringstream filename;
            filename << m_dir_name << "/pthash.tmp.run" << m_run_identifier << ".free_slots"
                     << ".bin";
            return filename.str();
        }

    private:
        std::string get_pairs_filename(uint32_t file_id) const {
            std::stringstream filename;
            filename << m_dir_name << "/pthash.tmp.run" << m_run_identifier << ".pairs" << file_id
                     << ".bin";
            return filename.str();
        }

        std::string get_buckets_filename(bucket_size_type bucket_size) const {
            std::stringstream filename;
            filename << m_dir_name << "/pthash.tmp.run" << m_run_identifier << ".size"
                     << static_cast<uint32_t>(bucket_size) << ".bin";
            return filename.str();
        }

        std::string m_dir_name;
        uint64_t m_run_identifier;
        uint64_t m_num_pairs_files;
        std::vector<bool> m_used_bucket_sizes;
    };

    template <typename Iterator>
    void map(Iterator keys, uint64_t num_keys, std::vector<pairs_t>& pairs_blocks,
             temporary_files_manager& tfm, build_configuration const& config) {
        progress_logger logger(num_keys, " == processed ", " keys from input",
                               config.verbose_output);

        uint64_t ram = config.ram;
        uint64_t ram_parallel_merge = 0;
        if (config.num_threads > 1) {
            ram_parallel_merge = ram * 0.01;
            assert(ram_parallel_merge >= MAX_BUCKET_SIZE * sizeof(bucket_payload_pair));
        }

        auto writer = tfm.get_multifile_pairs_writer(num_keys, ram - ram_parallel_merge,
                                                     config.num_threads, ram_parallel_merge);
        try {
            for (uint64_t i = 0; i != num_keys; ++i, ++keys) {
                auto const& key = *keys;
                auto hash = hasher_type::hash(key, m_seed);
                bucket_id_type bucket_id = m_bucketer.bucket(hash.first());
                writer.emplace_back(bucket_id, hash.second());
                logger.log();
            }
            writer.flush();
            logger.finalize();
        } catch (std::runtime_error const& e) { throw e; }

        auto tmp = tfm.pairs_blocks();
        pairs_blocks.swap(tmp);
    }
};

}  // namespace pthash


text:
import { Component, Input } from '@angular/core';
import { ChangeDetectionStrategy } from '@angular/core';
import { User } from '../shared/user';

@Component({
  selector: 'app-change-detect',
  template: `
    <div>

    </div>`,
  changeDetection: ChangeDetectionStrategy.OnPush,
  styleUrls: ['./change-detect.component.css']
})
export class ChangeDetectComponent {

  title = "Change Detection";
  @Input() user: User;

  constructor() { }

}

redpajama_set_name: RedPajamaGithub


text:
package com.dexvis.javafx.scene.control;

import javafx.event.Event;
import javafx.event.EventTarget;
import javafx.event.EventType;

/**
 *
 * A custom event to house events for the JsonGuiPane.
 *
 * @author Patrick Martin
 *
 */
public class JsonGuiEvent extends Event
{
  public static final EventType<JsonGuiEvent> ROOT_EVENT = new EventType<>(
      Event.ANY, "ROOT_EVENT");
  public static final EventType<JsonGuiEvent> CHANGE_EVENT = new EventType<>(
      ROOT_EVENT, "CHANGE ");

  private JsonGuiEventPayload payload = null;
  private static final long serialVersionUID = 1L;

  public JsonGuiEvent(Object source, EventTarget target,
      EventType<JsonGuiEvent> eventType)
  {
    super(source, target, eventType);
    payload = (JsonGuiEventPayload) source;
  }

  public JsonGuiEventPayload getPayload()
  {
    return payload;
  }
}


text:
ES5Harness.registerTest( {

    id: "15.4.4.15-3-8",

    path: "TestCases/chapter15/15.4/15.4.4/15.4.4.15/15.4.4.15-3-8.js",

    description: "Array.prototype.lastIndexOf when value of 'length' is a number (value is Infinity)",

    test: function testcase() {

        var obj = { 0: 0, length: Infinity };

        return Array.prototype.lastIndexOf.call(obj, 0) === -1;
    },

    precondition: function prereq() {
        return fnExists(Array.prototype.lastIndexOf);
    }

});


text:
using System;
using IbanLib.Countries;
using IbanLib.Domain;
using IbanLib.Domain.Splitters;
using IbanLib.Exceptions;
using IbanLib.Test.Common;
using Moq;
using NUnit.Framework;

namespace IbanLib.Test.IbanTests
{
    public class IbanThrowExceptionTest : AIbanTest
    {
        private static readonly IBban NotNullBban = new Mock<IBban>().Object;
        private static readonly ICountryResolver NotNullCountryResolver = new Mock<ICountryResolver>().Object;
        private static readonly IValidators NotNullValidators = new Mock<IValidators>().Object;
        private static readonly IIbanSplitter NotNullIbanSplitter = new Mock<IIbanSplitter>().Object;
        private static readonly IBbanSplitter NotNullBbanSplitter = new Mock<IBbanSplitter>().Object;

        [Test]
        public void Constructo_Splitterr_Null_Country_Resolver_Expected_InvalidIbanException()
        {
            Action action = () => new Iban(
                GetIban(),
                null, NotNullBban,
                NotNullValidators, NotNullIbanSplitter, NotNullBbanSplitter);
            TestUtil.ExpectedException<InvalidIbanException>(action);
        }

        [Test]
        public void Constructor_Parameters_Bban_Is_Null_Expected_InvalidIbanException()
        {
            Action action = () => new Iban(TestUtil.MockNotNullCountry, null);
            TestUtil.ExpectedException<InvalidIbanException>(action);
        }

        [Test]
        public void Constructor_Parameters_Country_Is_Null_Expected_InvalidCountryException()
        {
            Action action = () => new Iban(null, NotNullBban);
            TestUtil.ExpectedException<InvalidCountryException>(action);
        }

        [Test]
        public void Constructor_Parameters_Country_National_Check_Digits_Is_Not_Valid_Expected_InvalidIbanException()
        {
            Action action = () =>
            {
                var country = new Mock<ICountry>();
                country
                    .Setup(x => x.CalculateNationalCheckDigits(It.IsAny<string>()))
                    .Returns("INVALID_LENGHT");

                new Iban(country.Object, NotNullBban);
            };
            TestUtil.ExpectedException<InvalidIbanException>(action);
        }

        [Test]
        public void Constructor_Parameters_Country_National_Check_Digits_Is_Null_Expected_InvalidIbanException()
        {
            Action action = () =>
            {
                var country = new Mock<ICountry>();
                country
                    .Setup(x => x.CalculateNationalCheckDigits(It.IsAny<string>()))
                    .Returns(string.Empty);

                new Iban(country.Object, NotNullBban);
            };
            TestUtil.ExpectedException<InvalidIbanException>(action);
        }

        [Test]
        public void Constructor_Splitter_Country_Code_Validator_Return_False_Expected_InvalidIbanException()
        {
            Action action = () => new Iban(
                GetIban(),
                NotNullCountryResolver, NotNullBban,
                GetValidators(false), NotNullIbanSplitter, NotNullBbanSplitter);
            TestUtil.ExpectedException<InvalidIbanException>(action);
        }

        [Test]
        public void Constructor_Splitter_Country_Resolver_Return_Null_Expected_InvalidIbanException()
        {
            var countryResovler = new Mock<ICountryResolver>();
            countryResovler
                .Setup(x => x.GetCountry(It.IsAny<string>()))
                .Returns(() => null);

            Action action = () => new Iban(
                GetIban(),
                countryResovler.Object, NotNullBban,
                GetValidators(true), NotNullIbanSplitter, NotNullBbanSplitter);
            TestUtil.ExpectedException<InvalidIbanException>(action);
        }

        [Test]
        public void Constructor_Splitter_Null_Bban_Generator_Expected_InvalidIbanException()
        {
            Action action = () => new Iban(
                GetIban(),
                NotNullCountryResolver, null,
                NotNullValidators, NotNullIbanSplitter, NotNullBbanSplitter);
            TestUtil.ExpectedException<InvalidIbanException>(action);
        }

        [Test]
        public void Constructor_Splitter_Null_Bban_Splitter_Expected_InvalidIbanException()
        {
            Action action = () => new Iban(
                GetIban(),
                NotNullCountryResolver, NotNullBban,
                NotNullValidators, NotNullIbanSplitter, null);
            TestUtil.ExpectedException<InvalidIbanException>(action);
        }

        [Test]
        public void Constructor_Splitter_Null_Iban_Splitter_Expected_InvalidIbanException()
        {
            Action action = () => new Iban(
                GetIban(),
                NotNullCountryResolver, NotNullBban,
                NotNullValidators, null, NotNullBbanSplitter);
            TestUtil.ExpectedException<InvalidIbanException>(action);
        }

        [Test]
        public void Constructor_Splitter_Null_Validators_Expected_InvalidIbanException()
        {
            Action action = () => new Iban(
                GetIban(),
                NotNullCountryResolver, NotNullBban,
                null, NotNullIbanSplitter, NotNullBbanSplitter);
            TestUtil.ExpectedException<InvalidIbanException>(action);
        }
    }
}


text:
package com.google.javascript.jscomp.deps;

/**
 * An exception thrown by the compilation service.
 */
public final class ServiceException extends Exception {
  public ServiceException(String message) {
    super(message);
  }
}


text:
#include "config.h"
#include "GCThreadSharedData.h"

#include "CopyVisitor.h"
#include "CopyVisitorInlines.h"
#include "GCThread.h"
#include "VM.h"
#include "MarkStack.h"
#include "SlotVisitor.h"
#include "SlotVisitorInlines.h"

namespace JSC {

#if ENABLE(PARALLEL_GC)
void GCThreadSharedData::resetChildren()
{
    for (size_t i = 0; i < m_gcThreads.size(); ++i)
        m_gcThreads[i]->slotVisitor()->reset();
}

size_t GCThreadSharedData::childVisitCount()
{
    unsigned long result = 0;
    for (unsigned i = 0; i < m_gcThreads.size(); ++i)
        result += m_gcThreads[i]->slotVisitor()->visitCount();
    return result;
}

size_t GCThreadSharedData::childBytesVisited()
{
    size_t result = 0;
    for (unsigned i = 0; i < m_gcThreads.size(); ++i)
        result += m_gcThreads[i]->slotVisitor()->bytesVisited();
    return result;
}

size_t GCThreadSharedData::childBytesCopied()
{
    size_t result = 0;
    for (unsigned i = 0; i < m_gcThreads.size(); ++i)
        result += m_gcThreads[i]->slotVisitor()->bytesCopied();
    return result;
}
#endif

GCThreadSharedData::GCThreadSharedData(VM* vm)
    : m_vm(vm)
    , m_copiedSpace(&vm->heap.m_storageSpace)
    , m_shouldHashCons(false)
    , m_sharedMarkStack(vm->heap.blockAllocator())
    , m_numberOfActiveParallelMarkers(0)
    , m_parallelMarkersShouldExit(false)
    , m_copyIndex(0)
    , m_numberOfActiveGCThreads(0)
    , m_gcThreadsShouldWait(false)
    , m_currentPhase(NoPhase)
{
    m_copyLock.Init();
#if ENABLE(PARALLEL_GC)
    // Grab the lock so the new GC threads can be properly initialized before they start running.
    MutexLocker locker(m_phaseLock);
    for (unsigned i = 1; i < Options::numberOfGCMarkers(); ++i) {
        m_numberOfActiveGCThreads++;
        SlotVisitor* slotVisitor = new SlotVisitor(*this);
        CopyVisitor* copyVisitor = new CopyVisitor(*this);
        GCThread* newThread = new GCThread(*this, slotVisitor, copyVisitor);
        ThreadIdentifier threadID = createThread(GCThread::gcThreadStartFunc, newThread, "JavaScriptCore::Marking");
        newThread->initializeThreadID(threadID);
        m_gcThreads.append(newThread);
    }

    // Wait for all the GCThreads to get to the right place.
    while (m_numberOfActiveGCThreads)
        m_activityCondition.wait(m_phaseLock);
#endif
}

GCThreadSharedData::~GCThreadSharedData()
{
#if ENABLE(PARALLEL_GC)
    // Destroy our marking threads.
    {
        MutexLocker markingLocker(m_markingLock);
        MutexLocker phaseLocker(m_phaseLock);
        ASSERT(m_currentPhase == NoPhase);
        m_parallelMarkersShouldExit = true;
        m_gcThreadsShouldWait = false;
        m_currentPhase = Exit;
        m_phaseCondition.broadcast();
    }
    for (unsigned i = 0; i < m_gcThreads.size(); ++i) {
        waitForThreadCompletion(m_gcThreads[i]->threadID());
        delete m_gcThreads[i];
    }
#endif
}

void GCThreadSharedData::reset()
{
    ASSERT(m_sharedMarkStack.isEmpty());

#if ENABLE(PARALLEL_GC)
    m_opaqueRoots.clear();
#else
    ASSERT(m_opaqueRoots.isEmpty());
#endif
    m_weakReferenceHarvesters.removeAll();

    if (m_shouldHashCons) {
        m_vm->resetNewStringsSinceLastHashCons();
        m_shouldHashCons = false;
    }
}

void GCThreadSharedData::startNextPhase(GCPhase phase)
{
    MutexLocker phaseLocker(m_phaseLock);
    ASSERT(!m_gcThreadsShouldWait);
    ASSERT(m_currentPhase == NoPhase);
    m_gcThreadsShouldWait = true;
    m_currentPhase = phase;
    m_phaseCondition.broadcast();
}

void GCThreadSharedData::endCurrentPhase()
{
    ASSERT(m_gcThreadsShouldWait);
    MutexLocker locker(m_phaseLock);
    m_currentPhase = NoPhase;
    m_gcThreadsShouldWait = false;
    m_phaseCondition.broadcast();
    while (m_numberOfActiveGCThreads)
        m_activityCondition.wait(m_phaseLock);
}

void GCThreadSharedData::didStartMarking()
{
    MutexLocker markingLocker(m_markingLock);
    m_parallelMarkersShouldExit = false;
    startNextPhase(Mark);
}

void GCThreadSharedData::didFinishMarking()
{
    {
        MutexLocker markingLocker(m_markingLock);
        m_parallelMarkersShouldExit = true;
        m_markingCondition.broadcast();
    }

    ASSERT(m_currentPhase == Mark);
    endCurrentPhase();
}

void GCThreadSharedData::didStartCopying()
{
    {
        SpinLockHolder locker(&m_copyLock);
        WTF::copyToVector(m_copiedSpace->m_blockSet, m_blocksToCopy);
        m_copyIndex = 0;
    }

    // We do this here so that we avoid a race condition where the main thread can
    // blow through all of the copying work before the GCThreads fully wake up.
    // The GCThreads then request a block from the CopiedSpace when the copying phase
    // has completed, which isn't allowed.
    for (size_t i = 0; i < m_gcThreads.size(); i++)
        m_gcThreads[i]->copyVisitor()->startCopying();

    startNextPhase(Copy);
}

void GCThreadSharedData::didFinishCopying()
{
    ASSERT(m_currentPhase == Copy);
    endCurrentPhase();
}

} // namespace JSC


text:
package org.apache.cassandra.utils;

import java.io.IOException;
import java.util.*;

import com.google.common.base.Objects;

import org.apache.cassandra.db.TypeSizes;
import org.apache.cassandra.io.ISerializer;
import org.apache.cassandra.io.util.DataInputPlus;
import org.apache.cassandra.io.util.DataOutputPlus;

/**
 * Histogram that can be constructed from streaming of data.
 *
 * The algorithm is taken from following paper:
 * Yael Ben-Haim and Elad Tom-Tov, "A Streaming Parallel Decision Tree Algorithm" (2010)
 * http://jmlr.csail.mit.edu/papers/volume11/ben-haim10a/ben-haim10a.pdf
 */
public class StreamingHistogram
{
    public static final StreamingHistogramSerializer serializer = new StreamingHistogramSerializer();

    // TreeMap to hold bins of histogram.
    // The key is a numeric type so we can avoid boxing/unboxing streams of different key types
    // The value is a unboxed long array always of length == 1
    // Serialized Histograms always writes with double keys for backwards compatibility
    private final TreeMap<Number, long[]> bin;

    // Keep a second, larger buffer to spool data in, before finalizing it into `bin`
    private final TreeMap<Number, long[]> spool;

    // maximum bin size for this histogram
    private final int maxBinSize;

    // maximum size of the spool
    private final int maxSpoolSize;

    // voluntarily give up resolution for speed
    private final int roundSeconds;

    /**
     * Creates a new histogram with max bin size of maxBinSize
     * @param maxBinSize maximum number of bins this histogram can have
     */
    public StreamingHistogram(int maxBinSize, int maxSpoolSize, int roundSeconds)
    {
        this.maxBinSize = maxBinSize;
        this.maxSpoolSize = maxSpoolSize;
        this.roundSeconds = roundSeconds;
        bin = new TreeMap<>((o1, o2) -> {
            if (o1.getClass().equals(o2.getClass()))
                return ((Comparable)o1).compareTo(o2);
            else
            	return Double.compare(o1.doubleValue(), o2.doubleValue());
        });
        spool = new TreeMap<>((o1, o2) -> {
            if (o1.getClass().equals(o2.getClass()))
                return ((Comparable)o1).compareTo(o2);
            else
                return Double.compare(o1.doubleValue(), o2.doubleValue());
        });

    }

    private StreamingHistogram(int maxBinSize, int maxSpoolSize,  int roundSeconds, Map<Double, Long> bin)
    {
        this(maxBinSize, maxSpoolSize, roundSeconds);
        for (Map.Entry<Double, Long> entry : bin.entrySet())
            this.bin.put(entry.getKey(), new long[]{entry.getValue()});
    }

    /**
     * Adds new point p to this histogram.
     * @param p
     */
    public void update(Number p)
    {
        update(p, 1L);
    }

    /**
     * Adds new point p with value m to this histogram.
     * @param p
     * @param m
     */
    public void update(Number p, long m)
    {
        Number d = p.longValue() % this.roundSeconds;
        if (d.longValue() > 0)
            p =p.longValue() + (this.roundSeconds - d.longValue());

        long[] mi = spool.get(p);
        if (mi != null)
        {
            // we found the same p so increment that counter
            mi[0] += m;
        }
        else
        {
            mi = new long[]{m};
            spool.put(p, mi);
        }

        // If spool has overflowed, compact it
        if(spool.size() > maxSpoolSize)
            flushHistogram();
    }

    /**
     * Drain the temporary spool into the final bins
     */
    public void flushHistogram()
    {
        if (spool.size() > 0)
        {
            long[] spoolValue;
            long[] binValue;

            // Iterate over the spool, copying the value into the primary bin map
            // and compacting that map as necessary
            for (Map.Entry<Number, long[]> entry : spool.entrySet())
            {
                Number key = entry.getKey();
                spoolValue = entry.getValue();
                binValue = bin.get(key);

                // If this value is already in the final histogram bins
                // Simply increment and update, otherwise, insert a new long[1] value
                if(binValue != null)
                {
                    binValue[0] += spoolValue[0];
                    bin.put(key, binValue);
                }
                else
                {
                    bin.put(key, new long[]{spoolValue[0]});
                }

                if (bin.size() > maxBinSize)
                {
                    // find points p1, p2 which have smallest difference
                    Iterator<Number> keys = bin.keySet().iterator();
                    double p1 = keys.next().doubleValue();
                    double p2 = keys.next().doubleValue();
                    double smallestDiff = p2 - p1;
                    double q1 = p1, q2 = p2;
                    while (keys.hasNext())
                    {
                        p1 = p2;
                        p2 = keys.next().doubleValue();
                        double diff = p2 - p1;
                        if (diff < smallestDiff)
                        {
                            smallestDiff = diff;
                            q1 = p1;
                            q2 = p2;
                        }
                    }
                    // merge those two
                    long[] a1 = bin.remove(q1);
                    long[] a2 = bin.remove(q2);
                    long k1 = a1[0];
                    long k2 = a2[0];

                    a1[0] += k2;
                    bin.put((q1 * k1 + q2 * k2) / (k1 + k2), a1);

                }
            }
            spool.clear();
        }
    }

    /**
     * Merges given histogram with this histogram.
     *
     * @param other histogram to merge
     */
    public void merge(StreamingHistogram other)
    {
        if (other == null)
            return;

        other.flushHistogram();

        for (Map.Entry<Number, long[]> entry : other.getAsMap().entrySet())
            update(entry.getKey(), entry.getValue()[0]);
    }

    /**
     * Calculates estimated number of points in interval [-inf,b].
     *
     * @param b upper bound of a interval to calculate sum
     * @return estimated number of points in a interval [-inf,b].
     */
    public double sum(double b)
    {
        flushHistogram();
        double sum = 0;
        // find the points pi, pnext which satisfy pi <= b < pnext
        Map.Entry<Number, long[]> pnext = bin.higherEntry(b);
        if (pnext == null)
        {
            // if b is greater than any key in this histogram,
            // just count all appearance and return
            for (long[] value : bin.values())
                sum += value[0];
        }
        else
        {
            Map.Entry<Number, long[]> pi = bin.floorEntry(b);
            if (pi == null)
                return 0;
            // calculate estimated count mb for point b
            double weight = (b - pi.getKey().doubleValue()) / (pnext.getKey().doubleValue() - pi.getKey().doubleValue());
            double mb = pi.getValue()[0] + (pnext.getValue()[0] - pi.getValue()[0]) * weight;
            sum += (pi.getValue()[0] + mb) * weight / 2;

            sum += pi.getValue()[0] / 2.0;
            for (long[] value : bin.headMap(pi.getKey(), false).values())
                sum += value[0];
        }
        return sum;
    }

    public Map<Number, long[]> getAsMap()
    {
        flushHistogram();
        return Collections.unmodifiableMap(bin);
    }

    public static class StreamingHistogramSerializer implements ISerializer<StreamingHistogram>
    {
        public void serialize(StreamingHistogram histogram, DataOutputPlus out) throws IOException
        {
            histogram.flushHistogram();
            out.writeInt(histogram.maxBinSize);
            Map<Number, long[]> entries = histogram.getAsMap();
            out.writeInt(entries.size());
            for (Map.Entry<Number, long[]> entry : entries.entrySet())
            {
                out.writeDouble(entry.getKey().doubleValue());
                out.writeLong(entry.getValue()[0]);
            }
        }

        public StreamingHistogram deserialize(DataInputPlus in) throws IOException
        {
            int maxBinSize = in.readInt();
            int size = in.readInt();
            Map<Double, Long> tmp = new HashMap<>(size);
            for (int i = 0; i < size; i++)
            {
                tmp.put(in.readDouble(), in.readLong());
            }

            return new StreamingHistogram(maxBinSize, maxBinSize, 1, tmp);
        }

        public long serializedSize(StreamingHistogram histogram)
        {
            long size = TypeSizes.sizeof(histogram.maxBinSize);
            Map<Number, long[]> entries = histogram.getAsMap();
            size += TypeSizes.sizeof(entries.size());
            // size of entries = size * (8(double) + 8(long))
            size += entries.size() * (8L + 8L);
            return size;
        }
    }

    @Override
    public boolean equals(Object o)
    {
        if (this == o)
            return true;

        if (!(o instanceof StreamingHistogram))
            return false;

        StreamingHistogram that = (StreamingHistogram) o;
        return maxBinSize == that.maxBinSize &&
               spool.equals(that.spool) &&
               bin.equals(that.bin);
    }

    @Override
    public int hashCode()
    {
        return Objects.hashCode(bin.hashCode(), spool.hashCode(), maxBinSize);
    }

}


text:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:id="@+id/activity_tui_chu_zhang_hao"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="com.example.c.denglizimeijunqi.TuiChuZhangHaoActivity">
    <!--xmlns:app="http://schemas.android.com/apk/res-auto"-->
    <android.support.v7.widget.Toolbar
        android:id="@+id/toolbar"
        android:layout_width="match_parent"
        android:layout_height="?attr/actionBarSize"
        android:background="?attr/colorPrimary"
        android:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar"
        app:popupTheme="@style/ThemeOverlay.AppCompat.Light"
        app:contentInsetStart="0dp"
        app:contentInsetLeft="0dp">

        <TextView
            android:id="@+id/title_text"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="账号管理"
            android:textSize="24sp"
            android:textColor="#FFFFFF"
            android:layout_centerInParent="true"
            android:layout_gravity="center"/>
        <Button
            android:layout_width="100dp"
            android:layout_height="?attr/actionBarSize"
            android:drawableLeft="@drawable/back"
            android:textSize="24sp"
            android:background="#4052B5"
            android:id="@+id/guanli_button"/>
    </android.support.v7.widget.Toolbar>
    <Button
        android:layout_below="@+id/toolbar"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="退出当前账号"
        android:textColor="#000000"
        android:background="#FF3F5A"
        android:textSize="24sp"
        android:id="@+id/tui123_Button"/>
</RelativeLayout>


text:
package com.evolveum.midpoint.model.impl.sync.action;

import java.util.Map;

import javax.xml.namespace.QName;

import com.evolveum.midpoint.model.impl.lens.LensContext;
import com.evolveum.midpoint.model.impl.lens.LensFocusContext;
import com.evolveum.midpoint.model.impl.sync.Action;
import com.evolveum.midpoint.model.impl.sync.SynchronizationSituation;
import com.evolveum.midpoint.prism.PrismContext;
import com.evolveum.midpoint.prism.PrismObject;
import com.evolveum.midpoint.prism.PrismObjectDefinition;
import com.evolveum.midpoint.prism.delta.ObjectDelta;
import com.evolveum.midpoint.schema.result.OperationResult;
import com.evolveum.midpoint.task.api.Task;
import com.evolveum.midpoint.util.exception.SchemaException;
import com.evolveum.midpoint.util.logging.Trace;
import com.evolveum.midpoint.util.logging.TraceManager;
import com.evolveum.midpoint.xml.ns._public.common.common_3.FocusType;

/**
 * @author semancik
 *
 */
public class AddFocusAction implements Action {

	private static final Trace LOGGER = TraceManager.getTrace(AddFocusAction.class);

	/* (non-Javadoc)
	 * @see com.evolveum.midpoint.model.sync.Action#handle(com.evolveum.midpoint.model.lens.LensContext, com.evolveum.midpoint.model.sync.SynchronizationSituation, java.util.Map, com.evolveum.midpoint.task.api.Task, com.evolveum.midpoint.schema.result.OperationResult)
	 */
	@Override
	public <F extends FocusType> void handle(LensContext<F> context, SynchronizationSituation<F> situation,
			Map<QName, Object> parameters, Task task, OperationResult parentResult) throws SchemaException {

		if (context == null) {
			throw new UnsupportedOperationException("addFocus action is not supported with synchronize=false");
		}

		PrismContext prismContext = context.getPrismContext();

		LensFocusContext<F> focusContext = context.createFocusContext();
		Class<F> focusClass = focusContext.getObjectTypeClass();
		LOGGER.trace("addFocus action: add delta for {}", focusClass);
		PrismObjectDefinition<F> focusDefinition = prismContext.getSchemaRegistry().findObjectDefinitionByCompileTimeClass(focusClass);
		PrismObject<F> emptyFocus = focusDefinition.instantiate();
		ObjectDelta<F> delta = emptyFocus.createAddDelta();
        delta.setObjectToAdd(emptyFocus);
        focusContext.setPrimaryDelta(delta);
	}

}


text:
# Apatite

Object persistence framework for Node.js. ORM framework supports: MySQL, Oracle, Postgres, SQL Server, Sqlite.

[![npm](https://img.shields.io/npm/v/apatite.svg)](https://npmjs.org/package/apatite)
[![Windows Build](https://img.shields.io/appveyor/ci/apatitejs/apatite/master.svg?label=windows)](https://ci.appveyor.com/project/apatitejs/apatite)
[![Coverage Status](https://coveralls.io/repos/github/apatitejs/apatite/badge.svg?branch=master)](https://coveralls.io/github/apatitejs/apatite?branch=master)

## Features

  * Based on object oriented principles.
  * Zero dependencies.
  * Transaction based.
  * Generate (or execute) SQL scripts to create tables/columns for models/attributes.
  * Apart from standard mappings, supports inheritence mapping too.
  * Optional objects session cache management.

## Prerequisites

  * Node version >=12.13.1.
  * [oracledb](https://github.com/oracle/node-oracledb) if you plan to use Oracle: $ npm install oracledb@4.1.0
  * [pg](https://github.com/brianc/node-postgres) if you plan to use Postgres: $ npm install pg@6.1.5
  * [mysql](https://github.com/mysqljs/mysql) if you plan to use Mysql: $ npm install mysql@2.17.1
  * [tedious](https://github.com/tediousjs/tedious) if you plan to use Microsoft SQL Server: $ npm install tedious@2.0.0, optionally for connection pool: [tedious-connection-pool](https://github.com/tediousjs/tedious-connection-pool) : $ npm install tedious-connection-pool@1.0.5
  * [sqlite3](https://github.com/mapbox/node-sqlite3) if you plan to use Sqlite: $ npm install sqlite3@3.1.8

## Installation

```bash
C:\my-project> npm install apatite
```

## Quick Start

* Install the prerequisites.

* Create your class and define a static method getModelDescriptor which takes apatite as an argument.

```js
class Department {
	constructor() {
		this.oid = 0;
		this.name = '';
	}

	printName() {
		console.log(this.name);
	}

	static getModelDescriptor(apatite) {
		var table = apatite.newTable('DEPT');
		var modelDescriptor = apatite.newModelDescriptor(this, table);

		var column = table.addNewColumn('OID', apatite.dialect.newSerialType());
		column.bePrimaryKey();
		modelDescriptor.newSimpleMapping('oid', column);

		column = table.addNewColumn('NAME', apatite.dialect.newVarCharType(100));
		modelDescriptor.newSimpleMapping('name', column);

		return modelDescriptor;
	}
}
```
You could also create descriptor from a simple object:

```js
static getModelDescriptor(apatite) {
	var object = {
		table: 'DEPT',
		model: this,
		mappings: [
			{attr: 'oid', col: 'OID', pk: true, type: 'serial'},
			{attr: 'name', col: 'NAME', type: 'varchar', length: 100}
		]
	}
	return apatite.newDescriptorFromObject(object);
}
```

* Register your models.

```js
// Oracle
var connOptions = { userName: 'apatite', password: 'apatite', connectionInfo: 'localhost/apatite' };
var apatite = require('apatite').forOracle(connOptions);
```

```js
// Postgres
var connOptions = { userName: 'apatite', password: 'apatite', connectionInfo: 'localhost/apatite' };
var apatite = require('apatite').forPostgres(connOptions);
```

```js
// Mysql
var connOptions = { userName: 'apatite', password: 'apatite', connectionInfo: 'localhost/apatite' };
var apatite = require('apatite').forMysql(connOptions);
```

```js
// Mssql
var connOptions = { userName: 'apatite', password: 'apatite', connectionInfo: 'localhost/apatite' };
var apatite = require('apatite').forMssql(connOptions);
```

```js
// Sqlite
var connOptions = { connectionInfo: ':memory:' };
var apatite = require('apatite').forSqlite(connOptions);
```

```js
apatite.registerModel(Department);
```

* Create session and start querying your objects.

```js
// Creates a new session and database connection
apatite.newSession(function (err, session) {
	if (err) {
		console.error(err.message);
		return;
	}
	var query = session.newQuery(Department);
	query.execute(function(err, departments) {
		if (err) {
			console.error(err.message);
			return;
		}
		console.log(JSON.stringify(departments));
		if (departments.length)
			departments[0].printName();
		endSession(session);
	});
});

//closes the database connection
function endSession(session) {
	session.end(function(err) {
		if (err)
			console.error(err.message);
	})
}
```

```js
// Using promise to execute queries
// Creates a new session and database connection
apatite.newSession(function (err, session) {
	if (err) {
		console.error(err.message);
		return;
	}
	var query = session.newQuery(Department);
	var promise = query.execute();
	promise.then(function(departments) {
		console.log(JSON.stringify(departments));
		if (departments.length)
			departments[0].printName();
		endSession(session);
	}, function(err) {
		console.error(err.message);
		endSession(session);
	});
});

//closes the database connection
function endSession(session) {
	session.end(function(err) {
		if (err)
			console.error(err.message);
	})
}
```

```js
//query results from cursor stream
apatite.newSession(function (err, session) {
	var query = session.newQuery(Department)
	query.returnCursorStream = true

	query.execute(function (err, cursorStream) {
		if (err) {
			console.log(err)
			return endSession(session)
		}

		cursorStream.on('error', function(cursorStreamErr) {
			console.log(cursorStreamErr)
			endSession(session)
		})
		cursorStream.on('result', function(department) {
			console.log(JSON.stringify(department))
		})
		cursorStream.on('end', function() {
			endSession(session)
		})
	})
})

function endSession(session) {
	session.end(function (endConnErr) {
		if (endConnErr)
			return console.log(endConnErr)
		console.log('Connection ended.')
	})
}
```

* Do changes to your objects and save.

```js
...
	// Create new department
	var department = new Department();
	department.name = 'Sales';
	// Register it to session
	var changesToDo = function (changesDone) {
		session.registerNew(department);
		changesDone(); // must be called when you are done with all changes
	}

	session.doChangesAndSave(changesToDo, function (saveErr) {
		if (saveErr)
			console.error(saveErr.message);
	});
...
```

```js
...
	// Change an existing department
	var query = session.newQuery(Department);
    query.attr('name').eq('Sales');
    // Or you could create query from an array
    // const query = session.newQueryFromArray(Department, [['name', '=', 'Sales']])
	query.execute(function(executeErr, departments) {
		if (executeErr) {
			return console.error(executeErr);
		}
		var changesToDo = function (changesDone) {
			departments[0].name = 'Pre-Sales';
			changesDone(); // must be called when you are done with all changes
		}
		session.doChangesAndSave(changesToDo, function (saveErr) {
			if (saveErr)
				console.error(saveErr.message);
		});
	});
...
```

```js
...
	// Delete an existing department
	var changesToDo = function (changesDone) {
		var query = session.newQuery(Department);
        query.attr('name').eq('Pre-Sales');
        // Or you could create query from an array
        // const query = session.newQueryFromArray(Department, [['name', '=', 'Pre-Sales']])
		query.execute(function(executeErr, departments) {
			if (executeErr) {
				changesDone(executeErr);
				return;
			}
			session.registerDelete(departments[0]);
			changesDone(); // must be called when you are done with all changes
		});
	}

	session.doChangesAndSave(changesToDo, function (saveErr) {
		if (saveErr)
			console.error(saveErr.message);
	});
...
```

* Below is a complete example which can be run multiple times. All you need to do is create a postgres DB with user name/db name/password as apatite

```js
const connOptions = { userName: 'apatite', password: 'apatite', connectionInfo: 'localhost/apatite' }

const apatite = require('apatite').forPostgres(connOptions)

class Department {
    constructor() {
        this.oid = 0
        this.name = ''
    }

    printName() {
        console.log(this.name)
    }

    static getModelDescriptor(apatite) {
        const table = apatite.newTable('DEPT')
        const modelDescriptor = apatite.newModelDescriptor(this, table)

        let column = table.addNewColumn('OID', apatite.dialect.newSerialType())
        column.bePrimaryKey()
        modelDescriptor.newSimpleMapping('oid', column)

        column = table.addNewColumn('NAME', apatite.dialect.newVarCharType(100))
        modelDescriptor.newSimpleMapping('name', column)

        return modelDescriptor
    }
}

apatite.registerModel(Department)

apatite.newSession((sessionErr, session) => {
    if (sessionErr) {
        return console.error(sessionErr)
    }
    session.existsDBTable('dept', (existsErr, tableInfo) => {
        if (existsErr) {
            endSession(session)
            return console.error(existsErr)
        }
        if (tableInfo.rows.length === 0) {
            session.createDBTablesForAllModels((creationErr) => {
                if (creationErr) {
                    return console.error(creationErr)
                }
                createDepartments(session)
            })
        } else {
            queryDepartments(session)
        }
    })
})

function createDepartments(session) {
    let changesToDo = (changesDone) => {
        for(let i = 0; i < 50; i++) {
            let department = new Department()
            department.name = `Department ${`000${i + 1}`.slice(-3)}`
            session.registerNew(department)
        }
        changesDone()
    }
    session.doChangesAndSave(changesToDo, (saveErr) => {
        if (saveErr) {
            endSession(session)
            return console.error(saveErr)
        }
        queryDepartments(session)
    })
}

function queryDepartments(session) {
    const query = session.newQueryFromArray(Department, [['oid', '>', 0]])
    query.execute((executeErr, departments) => {
        if (executeErr) {
            console.error(executeErr)
        }
        console.log(JSON.stringify(departments))
        endSession(session)
    })
}

function endSession(session) {
    session.end((endSessionErr) => {
        if (endSessionErr) {
            console.error(endSessionErr)
        }
    })
}
```

## Contributions

Welcome.

## Links

  - [Documentation](https://github.com/apatitejs/apatite-doc/blob/master/doc.md)

## Tests

Install all supported databases and then install dependencies:

```bash
C:\my-project> npm install
```

Run the tests:

```bash
C:\my-project> npm test
```

## License

  [MIT](LICENCE)


text:
<?php

use CSSPrites\ImageProcessor\ImagineImageProcessor;
use CSSPrites\ImagesCollection;

class ImageTest extends AbstractBaseTest
{
    protected $processor;
    protected $directory;
    protected $mask;
    protected $filename;

    protected $collection;

    public function __construct()
    {
        $this->processor = new ImagineImageProcessor();
        $this->processor->setConfig(['driver' => 'gd']);

        $this->directory = './tests/stubs';
        $this->mask      = 'test-*.png';
        $this->filename  = 'sprite.png';

        $this->collection = new ImagesCollection(
            $this->processor,
            $this->directory,
            $this->mask,
            $this->filename
        );
    }

    public function testGetSimpleName()
    {
        $image = $this->collection->get(0);

        $this->assertSame('test-ico-cross-32', $image->getSimpleName());
    }

    public function testGetFilepath()
    {
        $image = $this->collection->get(0);
        $path  = realpath('./tests/stubs').'/'.$image->getSimpleName().'.png';

        $this->assertSame($path, $image->getFilepath());
    }

    public function testGetImage()
    {
        $image = $this->collection->get(0);

        $this->assertInstanceOf('CSSPrites\ImageProcessor\ImagineImageProcessor', $image->getImage());
    }

    public function testGetX()
    {
        $image = $this->collection->get(0);

        $this->assertSame(null, $image->getX());
    }

    public function testGetY()
    {
        $image = $this->collection->get(0);

        $this->assertSame(null, $image->getY());
    }

    public function testGetSurface()
    {
        $image = $this->collection->get(0);

        $this->assertSame(32 * 32, $image->getSurface());
    }

    public function testSetX()
    {
        $image  = $this->collection->get(0);
        $return = $image->setX(12);

        $this->assertInstanceOf('CSSPrites\Image', $return);
        $this->assertSame(12, $return->getX());
    }

    public function testSetY()
    {
        $image  = $this->collection->get(0);
        $return = $image->setY(24);

        $this->assertInstanceOf('CSSPrites\Image', $return);

        $this->assertSame(24, $return->getY());
    }
}


text:
package org.arquillian.cube.kubernetes.reporter;

import io.fabric8.kubernetes.clnt.v4_0.KubernetesClient;
import java.io.File;
import java.io.IOException;
import java.net.URL;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.List;
import org.arquillian.cube.kubernetes.api.Configuration;
import org.arquillian.cube.kubernetes.api.DependencyResolver;
import org.arquillian.cube.kubernetes.api.KubernetesResourceLocator;
import org.arquillian.cube.kubernetes.api.Session;
import org.arquillian.cube.kubernetes.impl.event.AfterStart;
import org.arquillian.cube.kubernetes.impl.event.Start;
import org.arquillian.reporter.api.builder.Reporter;
import org.arquillian.reporter.api.builder.report.ReportBuilder;
import org.arquillian.reporter.api.event.SectionEvent;
import org.arquillian.reporter.api.model.entry.FileEntry;
import org.jboss.arquillian.core.api.Event;
import org.jboss.arquillian.core.api.Instance;
import org.jboss.arquillian.core.api.annotation.Inject;
import org.jboss.arquillian.core.api.annotation.Observes;

import static org.arquillian.cube.kubernetes.reporter.KubernetesReportKey.CONFIGURATION;
import static org.arquillian.cube.kubernetes.reporter.KubernetesReportKey.KUBERNETES_SECTION_NAME;
import static org.arquillian.cube.kubernetes.reporter.KubernetesReportKey.MASTER_URL;
import static org.arquillian.cube.kubernetes.reporter.KubernetesReportKey.NAMESPACE;
import static org.arquillian.cube.kubernetes.reporter.KubernetesReportKey.SESSION_STATUS;

public class TakeKubernetesResourcesInformation {

    @Inject
    Event<SectionEvent> sectionEvent;

    @Inject
    Instance<DependencyResolver> dependencyResolver;

    @Inject
    Instance<KubernetesResourceLocator> resourceLocator;

    public void reportKubernetesConfiguration(@Observes Start start, Configuration configuration,
        org.arquillian.reporter.config.ReporterConfiguration reporterConfiguration) throws IOException {
        final ReportBuilder reportBuilder = Reporter.createReport(CONFIGURATION);
        Session session = start.getSession();
        if (configuration != null) {
            reportBuilder.addEntries(getFilesForResourcesConfiguration(session, configuration, reporterConfiguration));
        }

        Reporter.createReport(KUBERNETES_SECTION_NAME)
            .addReport(reportBuilder)
            .inSection(new KubernetesSection()).fire(sectionEvent);
    }

    public void reportSessionStatus(@Observes AfterStart afterStart, KubernetesClient kubernetesClient) {

        Session session = afterStart.getSession();
        if (session != null) {
            String namespace = session.getNamespace();

            Reporter.createReport(SESSION_STATUS)
                .addKeyValueEntry(NAMESPACE, namespace)
                .addKeyValueEntry(MASTER_URL, String.valueOf(kubernetesClient.getMasterUrl()))
                .inSection(new KubernetesSection())
                .asSubReport()
                .fire(sectionEvent);
        }
    }
/*
    private TableEntry getTableForReplicationControllers(KubernetesClient kubernetesClient, String namespace) {

        TableEntry tableEntry = createTableEntryWithTHead(REPLICATION_CONTROLLER, REPLICATION_CONTROLLER, REPLICAS);

        for (ReplicationController replicationController : kubernetesClient.replicationControllers().inNamespace(namespace).list().getItems()) {
            TableRowEntry tableRowEntry = new TableRowEntry();
            tableRowEntry.addCells(new TableCellEntry(replicationController.getMetadata().getName()), new TableCellEntry(String.valueOf(replicationController.getSpec().getReplicas())));
            tableEntry.getTableBody().getRows().add(tableRowEntry);

        }

        return tableEntry;
    }

    private TableEntry getTableForServices(KubernetesClient kubernetesClient, String namespace) {

        TableEntry tableEntry = createTableEntryWithTHead(SERVICE, SERVICE, CLUSTER_IP, PORTS);

        for (Service service : kubernetesClient.services().inNamespace(namespace).list().getItems()) {
            TableRowEntry tableRowEntry = new TableRowEntry();
            tableRowEntry.addCells(
                    new TableCellEntry(service.getMetadata().getName()),
                    new TableCellEntry(String.valueOf(service.getSpec().getClusterIP())),
                    new TableCellEntry(getPortsForService(service)));

            tableEntry.getTableBody().getRows().add(tableRowEntry);
        }

        return tableEntry;
    }

    private TableEntry getTableForPods(KubernetesClient kubernetesClient, String namespace) {

        TableEntry tableEntry = createTableEntryWithTHead(POD, POD, STATUS);

        for (Pod pod : kubernetesClient.pods().inNamespace(namespace).list().getItems()) {
            TableRowEntry tableRowEntry = new TableRowEntry();
            tableRowEntry.addCells(new TableCellEntry(pod.getMetadata().getName()), new TableCellEntry(pod.getStatus().getPhase()));
            tableEntry.getTableBody().getRows().add(tableRowEntry);

        }

        return tableEntry;
    }

    private TableEntry createTableEntryWithTHead(String name, String... heads) {
        TableEntry tableEntry = new TableEntry();
        tableEntry.setTableName(name);

        for (String head : heads) {
            tableEntry.getTableHead().getRow().addCell(new TableCellEntry(head));
        }

        return tableEntry;
    }*/

    private List<FileEntry> getFilesForResourcesConfiguration(Session session, Configuration configuration,
        org.arquillian.reporter.config.ReporterConfiguration reporterConfiguration) throws IOException {
        final List<FileEntry> fileEntries = new ArrayList<>();
        URL environmentConfigUrl = configuration.getEnvironmentConfigUrl();

        if (environmentConfigUrl == null) {
            KubernetesResourceLocator kubernetesResourceLocator = resourceLocator.get();
            if (kubernetesResourceLocator != null) {
                environmentConfigUrl = kubernetesResourceLocator.locate();
            }
        }

        if (environmentConfigUrl != null) {
            fileEntries.add(getFileForResourcesConfiguration(environmentConfigUrl, reporterConfiguration));
        }

        if (configuration.isEnvironmentInitEnabled()) {
            List<URL> dependencyUrls =
                !configuration.getEnvironmentDependencies().isEmpty() ? configuration.getEnvironmentDependencies()
                    : dependencyResolver.get().resolve(session);

            for (URL dependencyUrl : dependencyUrls) {
                fileEntries.add(getFileForResourcesConfiguration(dependencyUrl, reporterConfiguration));
            }
        }

        return fileEntries;
    }

    private FileEntry getFileForResourcesConfiguration(URL url,
        org.arquillian.reporter.config.ReporterConfiguration reporterConfiguration) throws IOException {

        final Path rootDir = Paths.get(reporterConfiguration.getRootDirectory());
        final String filePath = relativizePath(url, rootDir);

        return new org.arquillian.reporter.api.model.entry.FileEntry(filePath);
    }

    private String relativizePath(URL url, Path rootDir) {
        String filePath;
        final String pathURL = url.toString();
        final String absoluteRootDir = new File(rootDir.toString()).getAbsolutePath();

        if (pathURL.contains(absoluteRootDir)) {
            final Path rootDirPath = Paths.get(absoluteRootDir);
            final Path configFilePath = Paths.get(url.getFile());

            final Path relativize = rootDirPath.relativize(configFilePath);
            filePath = relativize.toString();
        } else {
            filePath = pathURL;
        }

        return filePath;
    }

    /*private String getPortsForService(Service service) {
        StringBuilder sb = new StringBuilder();

        for (ServicePort servicePort : service.getSpec().getPorts()) {
            sb.append(servicePort.getPort()).append(" ");
        }

        return sb.toString();
    }
*/
}


text:
/* global Module */

/* Magic Mirror
 * Module: MMM-vvsDeparture
 *
 * By niklaskappler
 * MIT Licensed.
 */
Module.register("MMM-vvsDeparture", {

	defaults: {
		station_id: 'de:08111:6112',
		station_name: "",
		maximumEntries: 6,
		reloadInterval: 1 * 60 * 1000, // every minute
		colorDelay: true,
		colorNoDelay: true,
		number: undefined,
		direction: undefined,
		offset: undefined
	},

	requiresVersion: "2.1.0", // Required version of MagicMirror

	// Define required scripts.
	getStyles: function () {
		return ["MMM-vvsDeparture.css"];
	},

	// Define required scripts.
	getScripts: function () {
		return ["moment.js"];
	},

	// Load translations files
	getTranslations: function() {
		return {
			en: "translations/en.json",
			de: "translations/de.json"
		};
	},

	// Overrides start function.
	start: function () {
		var self = this;
		Log.log("Starting module: " + self.name + "as" + self.identifier);

		self.departure = [];
		self.sendSocketNotification("GET_DEPARTURES",
			{
				"config": self.config,
				"identifier": this.identifier,
			});
	},

	// socketNotificationReceived from helper
	socketNotificationReceived: function (notification, payload) {
		var self = this;
		if (notification === this.identifier+"_NEW_DEPARTURES") {
			self.departure = payload.stopEvents;
			self.station_name = self.config.station_name ? self.config.station_name : payload.locations[0].disassembledName;
			self.updateDom();
		}
	},

	// Override dom generator.
	getDom: function () {
		var self = this;

		var wrapper = document.createElement("div");

		wrapper.appendChild(self.getHeaderDom());

		var tableWrapper = document.createElement("table");
		tableWrapper.className = "departure";

		var added = 0;
		for (var i in self.departure) {
			// If the maximum number of entries is reached
			// stop adding and attach table
			if (added >= self.config.maximumEntries) {
				wrapper.appendChild(tableWrapper);
				return wrapper;
			}

			var currentValue = self.departure[i];

			// Skip if the configuration should hide this
			if(!self.showNumber(currentValue.transportation.number) || !self.showDirection(currentValue.transportation.destination.name)) {
				continue;
			}

			// Row
			var trWrapper = document.createElement("tr");

			// Clock
			var clockWrapper = document.createElement("td");
			clockWrapper.className = "time";

			var date = new Date(currentValue.departureTimePlanned);
			clockWrapper.innerHTML = moment(date.getHours() + ":" + date.getMinutes(), "HH:mm")
				.subtract(currentValue.delay, "m")
				.format("HH:mm");
			trWrapper.appendChild(clockWrapper);

			// Delay
			var delayWrapper = document.createElement("td");
			if("isRealtimeControlled" in currentValue && currentValue.isRealtimeControlled == true){
				var delay = this.calculateDelay(currentValue.departureTimePlanned, currentValue.departureTimeEstimated);
			}
			if (delay.getMinutes() != 0) {
				delayWrapper.className = "delay";
				if (self.config.colorDelay) {
					delayWrapper.className += " color";
				}
			} else {
				delayWrapper.className = "nodelay";
				if (self.config.colorNoDelay) {
					delayWrapper.className += " color";
				}
			}
			if(isNaN(delay.getMinutes())){
				delayWrapper.innerHTML = self.translate("CANCELED");
			} else {
				delayWrapper.innerHTML = "+" +delay.getMinutes();
			}
			trWrapper.appendChild(delayWrapper);

			// Lane
			var laneWrapper = document.createElement("td");
			laneWrapper.className = "number";
			laneWrapper.innerHTML = currentValue.transportation.number;
			trWrapper.appendChild(laneWrapper);

			// Direction
			var directionWrapper = document.createElement("td");
			directionWrapper.className = "direction";
			directionWrapper.innerHTML = currentValue.transportation.destination.name;
			trWrapper.appendChild(directionWrapper);

			trWrapper.className = "small dimmed";
			tableWrapper.appendChild(trWrapper);
			added++;
		}

		wrapper.appendChild(tableWrapper);
		return wrapper;
	},

	stringTemplateParser: function (expression, valueObj) {
		const templateMatcher = /{{\s?([^{}\s]*)\s?}}/g;
		let text = expression.replace(templateMatcher, (substring, value, index) => {
			value = valueObj[value];
			return value;
		});
		return text
	},

	getHeaderDom: function () {
		var self = this;

		var headerWrappper = document.createElement("header");
		if(self.config.offset && self.config.offset >= 0){
			headerWrappper.innerHTML = self.stringTemplateParser(
				self.translate("DIRECTIONS_FROM_WITH_OFFSET"),
				{
					STATION: self.station_name,
					OFFSET: self.config.offset,
				});
		}else {
			headerWrappper.innerHTML = self.stringTemplateParser(
				self.translate("DIRECTIONS_FROM"),
				{STATION: self.station_name});
		}
		return headerWrappper;
	},

	calculateDelay(departureTimePlanned, departureTimeEstimated){
		timePlanned = new Date(departureTimePlanned);
		timeEstimated = new Date(departureTimeEstimated);
		var timeDiff = new Date(timeEstimated.getTime() - timePlanned.getTime());
		return timeDiff
	},

	showNumber : function(number) {
		var self = this;
		return self.isValue(number, self.config.number);
	},

	showDirection : function(direction) {
		var self = this;
		return self.isValue(direction, self.config.direction);
	},

	isValue : function(input, value) {
		if(!value || !input) {
			return true;
		} else if(value instanceof Array) {
			return value.indexOf(input) >= 0;
		} else if (typeof value === "string" || value instanceof String) {
			return value === input;
		} else if(typeof value === "function" || value instanceof Function) {
			return value(input);
		}
		return false;
	}

});


text:
'use strict';

// A place to hold default settings. Useful so environments can reference the defaults when they override

var _ = require('lodash');
var fs = require('fs');
var url = require('url');
var bunyan = require('bunyan');
var PrettyStream = require('bunyan-prettystream');

var prettyStdOut = new PrettyStream({
  mode: 'short' // 'long' is useful if you want to see PID and/or hostname
});
prettyStdOut.pipe(process.stdout);

var env = process.env.NODE_ENV || 'development';

var createLogger = function (options) {
  var serializers = _.assign({
    user: function userSerializer (user) {
      if (!user) {
        return null;
      }
      if (typeof user.codexModel === 'function') {
        user = user.doc;
      }

      return {
        id: user.id,
        username: user.username,
        roles: user.roles
        // possibly more fields we deem useful...
      };
    }
  }, bunyan.stdSerializers);

  options = _.assign({
    name: 'fracas',
    serializers: serializers,
    streams: [
      // human-readable output on stdout
      {
        // we don't want any noise besides the red/green lights when we run tests
        level: env === 'test' ? 'warn' : 'debug',
        type: 'raw',
        stream: prettyStdOut
      }

      // TODO machine-readable output in log file
      // We need log rotation, but bunyan's implementation has issues
      // (see https://github.com/trentm/node-bunyan/pull/97 for example). Log rotation is a big enough problem that
      // it should be handled independently, e.g. by logrotate on Linux. All the more reason to deploy to a managed
      // container.
    ]
  }, options);

  return bunyan.createLogger(options);
};

function ElasticSearchLogger () {
  var logger = createLogger({name: 'elasticsearch.js'});

  this.error = logger.error.bind(logger);
  this.warning = logger.warn.bind(logger);
  this.info = logger.info.bind(logger);
  this.debug = logger.debug.bind(logger);
  this.trace = function (method, requestUrl, body, responseBody, responseStatus) {
    logger.trace({
      method: method,
      requestUrl: requestUrl,
      body: body,
      responseBody: responseBody,
      responseStatus: responseStatus
    });
  };
  this.close = function () {};
}

var certPath = process.env.SSL_CERT || __dirname + '/../../cert.pem';
var keyPath = process.env.SSL_KEY || __dirname + '/../../key.pem';
var sessionStore = process.env.SESSION_STORE || 'memory'; // 'redis' is also accepted

module.exports = {
  env: env,
  createLogger: createLogger,

  // the default logger
  logger: createLogger(),

  appName: process.env.APP_NAME || 'Fracas',

  ssl: {
    enabled: fs.existsSync(certPath) && fs.existsSync(keyPath),
    certPath: certPath,
    keyPath: keyPath
    // more properties are defined in ./index.js
  },

  // Number of Fracas worker processes. Note that the default session store saves sessions in memory, and thus
  // will not work with more than one worker. A shared session store like Redis should therefore be used in production.
  workers: (function () {
    var workers = process.env.WORKERS || (sessionStore === 'memory' ? 1 : 2);
    if (workers === 'NUM_CPUS') {
      workers = require('os').cpus().length;
    } else {
      workers = parseInt(workers, 10);
    }

    return workers;
  })(),

  phantom: {
    enabled: process.env.PHANTOM !== 'false',

    // URL for Phantom HTTP proxy. The proxy provides an HTTP API to submit requests to PhantomJS.
    // This settings has two purposes: if phantom is enabled, it specifies what hostname and port to listen on;
    // and even if phantom is disabled (e.g. because it's running on another host), it specifies the URL requests
    // should be routed to. The default port of 23680 is just a random available port we picked.
    url: process.env.PHANTOM_URL || 'http://localhost:23680'
  },

  // Define extra users. The auth layers checks if a user is defined here first and then checks if the user is in the
  // data store. This is useful for development: instead of every Fracas instance having a known set of test users,
  // e.g. "admin", "test", etc. and having to make sure those accounts are disabled or their passwords changed before
  // deployment, you can include them in conf instead. Settings users to `false` will disable the pre-registration
  // requirement and grant all Persona users admin privileges.
  users: process.env.USERS === 'false' ? false : {
    // example local user
//    admin: {
//      roles: ['admin']
//    }

    // example Persona user
//    'foo@bar.com' : {
//      roles: ['entry']
//    }
  },

  persona: {
    enabled: process.env.PERSONA !== 'false'
  },

  proxy: {
    // true if Fracas is running behind a reverse proxy
    enabled: !!process.env.PROXY || false
  },

  session: {
    // Session store. Accepted values are currently 'memory' and 'redis'. Memory is fine for development, but Redis
    // should be used in production to provide persistence and the ability to scale past a single web server process.
    store: sessionStore,

    // Secret used to sign cookies
    secret: process.env.SESSION_SECRET
  },

  redis: {
    url: process.env.REDIS_URL || (function () {
      if (process.env.REDISCLOUD_URL) {
        // Heroku addons automatically add environment variables. We might as well use them to make installation
        // easier. There are a number of Redis providers, but Redis Cloud offers 25MB free and Redis 2.8 instances.
        // Redis To Go is the only other free Redis provider (as of Sept. 2014) but they put free customers on Redis
        // 2.4 instances. We need 2.6.12+ for our locks.
        return process.env.REDISCLOUD_URL;
      }

      if (process.env.REDIS_PORT) {
        // If we're running in a Docker container that's linked against a container with alias `redis`, then Docker will
        // set REDIS_PORT to be the tcp port of the linked container

        var parsedRedisPort = url.parse(process.env.REDIS_PORT);
        if (parsedRedisPort.protocol === 'tcp:') {
          // Docker sets the protocol of the port to be tcp since it operates below the application layer. You can
          // also tell Docker to use UDP instead, but Redis speaks TCP, so why would we ever do that?
          parsedRedisPort.protocol = 'redis:';
        }

        return url.format(parsedRedisPort);
      }

      // Fallback to Redis's default
      return 'redis://localhost:6379';
    })(),
    password: process.env.REDIS_PASSWORD // Redis doesn't use usernames, just tokens
  },

  // elasticsearch settings, duh
  elasticsearch: {
    // Found.no is nice since they give you unlimited indices. But they're (currently) $40/month. Bonsai has fewer
    // features and limits the number of indices, but they do have a free tier.
    host: process.env.ELASTICSEARCH_URL || process.env.FOUNDELASTICSEARCH_URL || process.env.BONSAI_URL ||
      (function () {
        if (process.env.ELASTICSEARCH_PORT) {
          // If we're running in a Docker container that's linked against a container with alias `elasticsearch`, then
          // Docker will set ELASTICSEARCH_PORT to be the tcp port of the linked container

          var parsedElasticsearchPort = url.parse(process.env.ELASTICSEARCH_PORT);
          if (parsedElasticsearchPort.protocol === 'tcp:') {
            // Docker sets the protocol of the port to be tcp since it operates below the application layer. You can
            // also tell Docker to use UDP instead, but Elasticsearch speaks TCP (via HTTP), so why would we ever do that?
            parsedElasticsearchPort.protocol = 'http:';
          }

          return url.format(parsedElasticsearchPort);
        }

        // Fallback to Elasticsearch's default
        return 'http://localhost:9200';
      })(),
    log: ElasticSearchLogger,
    apiVersion: '1.1'
  },

  // Database settings. Fracas doesn't use a relational database, but we still need connection info for things like
  // importing data. If you're not using a features that require connecting to a DB, then you can skip this.
  db: {
    url: 'jdbc:postgresql://localhost:5432/fracas',
    user: 'postgres',
    password: '',
    driver: 'org.postgresql.Driver'
  }
};


text:
ACCEPTED

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

#### Published in
Mycologia 38(1): 107 (1946)

#### Original name
Rozella chytriomycetis Karling, 1946

### Remarks
null


text:
CKEDITOR.dialog.add('button', function(editor) {
  function commitAttributes(element) {
    var val = this.getValue();
    if (val) {
      element.attributes[ this.id ] = val;
      if (this.id == 'name')
        element.attributes[ 'data-cke-saved-name' ] = val;
    }
    else {
      delete element.attributes[ this.id ];
      if (this.id == 'name')
        delete element.attributes[ 'data-cke-saved-name' ];
    }
  }

  return {
    title : editor.lang.button.title,
    minWidth : 350,
    minHeight : 150,
    onShow : function() {
      delete this.button;
      var element = this.getParentEditor().getSelection().getSelectedElement();
      if (element && element.is('input')) {
        var type = element.getAttribute('type');
        if (type in { button:1, reset:1, submit:1 }) {
          this.button = element;
          this.setupContent(element);
        }
      }
    },
    onOk : function() {
      var editor = this.getParentEditor(),
          element = this.button,
          isInsertMode = !element;

      var fake = element ? CKEDITOR.htmlParser.fragment.fromHtml(element.getOuterHtml()).children[ 0 ]
          : new CKEDITOR.htmlParser.element('input');
      this.commitContent(fake);

      var writer = new CKEDITOR.htmlParser.basicWriter();
      fake.writeHtml(writer);
      var newElement = CKEDITOR.dom.element.createFromHtml(writer.getHtml(), editor.document);

      if (isInsertMode)
        editor.insertElement(newElement);
      else {
        newElement.replace(element);
        editor.getSelection().selectElement(newElement);
      }
    },
    contents : [
      {
        id : 'info',
        label : editor.lang.button.title,
        title : editor.lang.button.title,
        elements : [
          {
            id : 'name',
            type : 'text',
            label : editor.lang.common.name,
            'default' : '',
            setup : function(element) {
              this.setValue(
                  element.data('cke-saved-name') ||
                      element.getAttribute('name') ||
                      '');
            },
            commit : commitAttributes
          },
          {
            id : 'value',
            type : 'text',
            label : editor.lang.button.text,
            accessKey : 'V',
            'default' : '',
            setup : function(element) {
              this.setValue(element.getAttribute('value') || '');
            },
            commit : commitAttributes
          },
          {
            id : 'type',
            type : 'select',
            label : editor.lang.button.type,
            'default' : 'button',
            accessKey : 'T',
            items :
                [
                  [ editor.lang.button.typeBtn, 'button' ],
                  [ editor.lang.button.typeSbm, 'submit' ],
                  [ editor.lang.button.typeRst, 'reset' ]
                ],
            setup : function(element) {
              this.setValue(element.getAttribute('type') || '');
            },
            commit : commitAttributes
          }
        ]
      }
    ]
  };
});


text:
set -o errexit
set -o pipefail
set -o nounset
set -o xtrace

rm -f './celerybeat.pid'
celery -A awesome_app.taskapp beat -l INFO


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

    <artifactId>visualiser</artifactId>
    <name>Hazelcast Simulator Visualiser</name>

    <parent>
        <groupId>com.hazelcast.simulator</groupId>
        <artifactId>simulator-root</artifactId>
        <version>0.6-SNAPSHOT</version>
    </parent>

    <properties>
        <main.basedir>${project.parent.basedir}</main.basedir>
    </properties>

    <dependencies>
        <dependency>
            <groupId>com.hazelcast.simulator</groupId>
            <artifactId>probes</artifactId>
            <version>${project.parent.version}</version>
        </dependency>

        <dependency>
            <groupId>org.jfree</groupId>
            <artifactId>jfreechart</artifactId>
            <version>${jfreechart.version}</version>
        </dependency>

        <dependency>
            <groupId>org.apache.commons</groupId>
            <artifactId>commons-lang3</artifactId>
            <version>${commons-lang.version}</version>
        </dependency>
    </dependencies>
</project>


text:
package org.odata4j.test.unit.format.json;

import org.junit.BeforeClass;
import org.odata4j.format.FormatType;
import org.odata4j.test.unit.format.AbstractErrorFormatWriterTest;

public class JsonErrorFormatWriterTest extends AbstractErrorFormatWriterTest {

  @BeforeClass
  public static void setupClass() throws Exception {
    createFormatWriter(FormatType.JSONVERBOSE);
  }

  @Override
  protected String buildRegex(String code, String message, String innerError) {
    StringBuilder regex = new StringBuilder();
    regex.append("\\{\\s*\"error\"\\s*:\\s*\\{\\s*");
    regex.append("\"code\"\\s*:\\s*\"" + code + "\"\\s*,\\s*");
    regex.append("\"message\"\\s*:\\s*\\{\\s*");
    regex.append("\"lang\"\\s*:\\s*\".+\"\\s*,\\s*");
    regex.append("\"value\"\\s*:\\s*\"" + message + "\"\\s*");
    regex.append("\\}\\s*");
    if (innerError != null)
      regex.append(",\\s*\"innererror\"\\s*:\\s*\"" + innerError + "\"\\s*");
    regex.append("\\}\\s*");
    regex.append("\\}");
    return regex.toString();
  }
}


text:
<?php
	require_once ("TnLFunctions.php");
?>

<?php TnLHeader(); ?>

Discuss Learning Objectives

Discuss Learning Objectives Poster

Discuss Learning Objectives Poster

PDF

Download

Resources (scrollable list)

	<?php TnLFooter(); ?>