text:
threads_count = ENV.fetch('RAILS_MAX_THREADS') { 5 }
threads threads_count, threads_count

# Specifies the `port` that Puma will listen on to receive requests, default is 3000.
#
port        ENV.fetch('PORT') { 3000 }

# Specifies the `environment` that Puma will run in.
#
environment ENV.fetch('RAILS_ENV') { 'development' }

# Specifies the number of `workers` to boot in clustered mode.
# Workers are forked webserver processes. If using threads and workers together
# the concurrency of the application would be max `threads` * `workers`.
# Workers do not work on JRuby or Windows (both of which do not support
# processes).
#
# workers ENV.fetch("WEB_CONCURRENCY") { 2 }

# Use the `preload_app!` method when specifying a `workers` number.
# This directive tells Puma to first boot the application and load code
# before forking the application. This takes advantage of Copy On Write
# process behavior so workers use less memory. If you use this option
# you need to make sure to reconnect any threads in the `on_worker_boot`
# block.
#
# preload_app!

# Allow puma to be restarted by `rails restart` command.
plugin :tmp_restart

redpajama_set_name: RedPajamaGithub


text:
#include "log.h"

using namespace lus;
/*
 * <one line to give the library's name and an idea of what it does.>
 * Copyright (C) 2017  Serge Lussier <lussier.serge@gmail.com>
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 *
 */

#include "Journal.h"

#include <unistd.h>
#include <errno.h>

namespace Tea{

    String          Journal::m_Journal_header="";
    String          Journal::m_arrows[8] = {
        "➜ ", // append space char becauwse the redering is cut if we have no space between the unicode and the next char...
        "⬅ ",
        "⬆ ",
        "⬇ ",
        "⬈ ",
        "⬉ ",
        "⬊ ",
        "⬋ "
    };

    String              Journal::m_filename = "";    ///< ...filename - empty if stdout is to be used.
    std::ofstream       Journal::m_file_output; ///< the instance of file.
    std::ostream*       Journal::m_file = 0;        ///< pointer to the ofstream { stdout; or file stream}.
    std::map<int32_t, String> Journal::m_code_type_dictionary;

    String              Journal::m_tstamp = "";      ///< holds the configured date-time format for normal line ouputs.
    bool                Journal::m_stdout = false;      ///< if i am unable to find the way to assign stdout to m_file_output, a flag set to true...
    bool                Journal::m_code_mode = false;

    String              Journal::m_fn_prefix  = "";   ///< saved text attributes/style for the function name { __function__ }.
    String              Journal::m_long_fn_prefix = ""; ///< saved text attributes/style for the long function name. { __pretty_function__ }.

    Journal::mode_t     Journal::m_mode = Journal::plain;

    String::list_t      Journal::m_attr_table;  ///< text attributes/style list built from the mode;
    String::list_t      Journal::m_type_table;  ///< message types list including their attributes/style.
    String::list_t      Journal::m_objects_prefix_table;

    String              Journal::m_eol = "\n";  ///< line break for the mode.
    int                 Journal::m_indent = 0;

    Journal::Journal(const Journal& l)
    {
        // -- break - no copy -- and copy what ?
        if(!Journal::m_file){
            Journal::SetFile("");
            Journal::Init(Journal::ansi, ":", false);
            Journal::ResetStamp();
            return;
        }
        //     if(!Journal::m_tstamp.empty())
        //         (*Journal::m_file) << String().datetime(Journal::m_tstamp) << ' ';

        if(Journal::m_indent > 0 ){
            //m_text.clear(); // cleared in attributes definitions.
            m_text.insert(0, Journal::m_indent*4, ' ');
            (*Journal::m_file) << m_text;
        }
    }

    Journal::Journal()
    {
        if(!Journal::m_file){
            Journal::SetFile("");
            Journal::Init(Journal::ansi, ":", false);
            Journal::ResetStamp();
            return;
        }
        //     if(!Journal::m_tstamp.empty())
        //         (*Journal::m_file) << String().datetime(Journal::m_tstamp) << ' ';

        if(Journal::m_indent > 0 ){
            //m_text.clear(); // cleared in attributes definitions.
            m_text.insert(0, Journal::m_indent*4, ' ');
            (*Journal::m_file) << m_text;
        }
    }

    Journal::Journal(const char* a_function_name, int aline, const char* filename)
    {
        if(!Journal::m_file){
            Journal::Init(Journal::ansi, ":", false);
            Journal::ResetStamp();
            return;
        }
        if(!Journal::m_tstamp.empty())
            (*Journal::m_file) << String().DateTime(Journal::m_tstamp) << ' ';

        if(Journal::m_indent > 0 ){
            //m_text.clear(); // cleared in attributes definitions.
            m_text.insert(0, Journal::m_indent*4, ' ');
            (*Journal::m_file) << m_text;
        }

        if(!a_function_name)
            return;

        (*Journal::m_file) << Journal::m_attr_table[(int)Journal::reset];

        if(filename)
            (*Journal::m_file) << filename << " ";
        if(aline)
            (*Journal::m_file) << "line:" << aline << Journal::m_attr_table[(int)Journal::reset] << ' ';
        if(a_function_name)
            (*Journal::m_file) << " " << Journal::m_fn_prefix << a_function_name << Journal::m_attr_table[(int)Journal::reset] << ' ';
    }

    Journal::Journal(Journal::type_t t, const char* a_function_name, int aline, const char* filename)
    {
        if(!Journal::m_file){
            Journal::Init(Journal::ansi, ":", false);
            Journal::ResetStamp();
            return;
        }
        if(!Journal::m_tstamp.empty())
            (*Journal::m_file) << String().DateTime(Journal::m_tstamp) << ' ';

        (*Journal::m_file) << Journal::m_type_table[(int)t] << Journal::m_attr_table[(int)Journal::reset];

        if(Journal::m_indent > 0 ){
            //m_text.clear(); // cleared in attributes definitions.
            m_text.insert(0, Journal::m_indent*4, ' ');
            (*Journal::m_file) << m_text;
        }

        if(!a_function_name)
            return;

        (*Journal::m_file) << Journal::m_attr_table[(int)Journal::reset];

        if(filename)
            (*Journal::m_file) << filename << " ";
        if(aline)
            (*Journal::m_file) << "line:" << aline << Journal::m_attr_table[(int)Journal::reset] << ' ';
        if(a_function_name)
            (*Journal::m_file) << " " << Journal::m_fn_prefix << a_function_name << Journal::m_attr_table[(int)Journal::reset] << ' ';
    }

    Journal::~Journal()
    {
        if(Journal::m_file)
            Journal::m_file->flush();
    }

    /*!
     *    @brief creates and opens file for output.
     *
     *    @param afilename the complete path and name of the file to be used for output.
     *
 if \c afilename is empty, then stdout will be used as the output file.

     *
     *    @author © 2015,2017, serge lussier (bretzelus), lussier.serge@gmail.com
     *
     */
    void Journal::SetFile(const String& afilename)
    {
        Journal::m_filename = afilename;
        if(Journal::m_filename.empty()){
            Journal::m_stdout = true;
            Journal::m_file = &std::cout; // duh ?
            return;
        }
        Journal::m_file_output.open(Journal::m_filename.c_str(),std::ios::out);
        if(!Journal::m_file_output.good()){
            String msg = "error (#%d) openning \"%s\" for output : `%s` - falling back to std out.";
            msg.Arg(errno);
            msg.Arg(Journal::m_filename);
            String e = strerror(errno);
            msg.Arg(e);

            Journal::m_stdout = true;
            Journal::m_file = &std::cout; // duh ?
            //throw msg.c_str();
            return ;
        }
        Journal::m_file = &Journal::m_file_output;
    }

    bool Journal::Close()
    {
        Journal::m_attr_table.clear();
        Journal::m_fn_prefix.clear();
        Journal::m_objects_prefix_table.clear();
        Journal::m_type_table.clear();

        if(Journal::m_file_output.is_open()){
            (*Journal::m_file) << Journal::m_eol<< "} end" << Journal::m_eol ;
            if(!Journal::m_stdout)
                Journal::m_file_output.close();
        }
        else{
            if(Journal::m_stdout)
                (*Journal::m_file) << Journal::m_eol<< "} end" << Journal::m_eol ;
            else
                return false;
        }
        return true;
    }

    /*!
     *    @brief clears \c Journal::m_tstamp static String contents.
     *        this static method resets the date-time stamp and then returns an anonymous instance that is to be used as the construction of a new date-time using Journal's comma operator.
     *        the `stamp` is part of the prefix of each line. if \c Journal::ResetStamp() if used alone without any further construction, then there will be no date-time stamp on the line.
     *        @code
     *            // example of usage:
     *            Journal::ResetStamp(), Journal::hour24, ':', Journal::minutes, ',', Journal::seconds;
     *        @endcode
     *    @return an anounymous instance of Journal to be used for Journal::operators
     */
    Journal Journal::ResetStamp()
    {
        Journal::m_tstamp = "";
        return Journal();
    }

    /*!
     *
     *    @brief appends time-date object to the stamp
     *
     *
 Journal++ follows and uses the posix time date format to be given to std::strftime :
     *
     *  the characters of ordinary character sequences (including the null byte) are copied verbatim from format to s. however, the characters of conversion specifications are replaced as follows:
     *  @li %a  the abbreviated name of the day of the week according to the current locale.
     *  @li %A  the full name of the day of the week according to the current locale.
     *  @li %b  the abbreviated month name according to the current locale.
     *  @li %B  the full month name according to the current locale.
     *  @li %c  the preferred date and time representation for the current locale.
     *  @li %C  the century number (year/100) as a 2-digit integer. (su)
     *  @li %d  the day of the month as a decimal number (range 01 to 31).
     *  @li %D  equivalent to %m/%d/%y. (yecch—for americans only. americans should note that in other countries %d/%m/%y is rather common. this means that in international context this format is ambiguous and should not be used.) (su)
     *  @li %e  like %d, the day of the month as a decimal number, but a leading zero is replaced by a space. (su)
     *  @li %e  modifier: use alternative format, see below. (su)
     *  @li %f  equivalent to %y-%m-%d (the iso 8601 date format). (c99)
     *  @li %g  the iso 8601 week-based year (see notes) with century as a decimal number. the 4-digit year corresponding to the iso week number (see %v). this has the same format and value as %y, except that if the iso week number belongs to the previous or next year, that year is used insTead. (tz)
     *  @li %g  like %g, but without century, that is, with a 2-digit year (00-99). (tz)
     *  @li %h  equivalent to %b. (su)
     *  @li %H  the hour as a decimal number using a 24-hour clock (range 00 to 23).
     *  @li %i  the hour as a decimal number using a 12-hour clock (range 01 to 12).
     *  @li %j  the day of the year as a decimal number (range 001 to 366).
     *  @li %k  the hour (24-hour clock) as a decimal number (range 0 to 23); single digits are preceded by a blank. (see also %h.) (tz)
     *  @li %l  the hour (12-hour clock) as a decimal number (range 1 to 12); single digits are preceded by a blank. (see also %i.) (tz)
     *  @li %m  the month as a decimal number (range 01 to 12).
     *  @li %m  the minute as a decimal number (range 00 to 59).
     *  @li %n  a newline character. (su)
     *  @li %o  modifier: use alternative format, see below. (su)
     *  @li %P  either "am" or "pm" according to the given time value, or the corresponding strings for the current locale. noon is treated as "pm" and midnight as "am".
     *  @li %p  like %p but in lowercase: "am" or "pm" or a corresponding string for the current locale. (gnu)
     *  @li %r  the time in a.m. or p.m. notation. in the posix locale this is equivalent to %i:%m:%s %p. (su)
     *  @li %r  the time in 24-hour notation (%h:%m). (su) for a version including the seconds, see %t below.
     *  @li %s  the number of seconds since the epoch, 1970-01-01 00:00:00 +0000 (utc). (tz)
     *  @li %S  the second as a decimal number (range 00 to 60). (the range is up to 60 to allow for occasional leap seconds.)
     *  @li %t  a tab character. (su)
     *  @li %T  the time in 24-hour notation (%h:%m:%s). (su)
     *  @li %u  the day of the week as a decimal, range 1 to 7, monday being 1. see also %w. (su)
     *  @li %u  the week number of the current year as a decimal number, range 00 to 53, starting with the first sunday as the first day of week 01. see also %v and %w.
     *  @li %v  the iso 8601 week number (see notes) of the current year as a decimal number, range 01 to 53, where week 1 is the first week that has at least 4 days in the new year. see also %u and %w. (su)
     *  @li %w  the day of the week as a decimal, range 0 to 6, sunday being 0. see also %u.
     *  @li %w  the week number of the current year as a decimal number, range 00 to 53, starting with the first monday as the first day of week 01.
     *  @li %x  the preferred date representation for the current locale without the time.
     *  @li %x  the preferred time representation for the current locale without the date.
     *  @li %y  the year as a decimal number without a century (range 00 to 99).
     *  @li %y  the year as a decimal number including the century.
     *  @li %z  the +hhmm or -hhmm numeric timezone (that is, the hour and minute offset from utc). (su)
     *  @li %z  the timezone name or abbreviation.
     *  @li %+  the date and time in date(1) format. (tz) (not supported in glibc2.)
     *  @li %%  a literal '%' character.
     *
     *  @param dt_obj an Journal::object enumerator value / valeur énumératrice
     *
     *

     *    usage:

     *    @code
     *        // ...
     *        Journal::ResetStamp(), Journal::hour24 , Journal::minute, Journal::seconds ;
     *        //...
     *
     *    @endcode
     *  @note not all format modifiers are used. / tous les modifiants format ne sont pas utilisés
     */

    Journal& Journal::operator,(Journal::object dt_obj)
    {

        switch(dt_obj){
            case Journal::lday:
                Journal::m_tstamp << "%A";
                break;
            case Journal::day:
                Journal::m_tstamp << "%d";
                break;
            case Journal::yday:
                Journal::m_tstamp << "%j";
                break;
            case Journal::month_num:
                Journal::m_tstamp << "%m";
                break;
            case Journal::month_name_short:
                Journal::m_tstamp << "%b";
                break;
            case Journal::month_name_long:
                Journal::m_tstamp << "%B";
                break;
            case Journal::year_short:
                Journal::m_tstamp << "%y";
                break;
            case Journal::year_long:
                Journal::m_tstamp << "%Y";
                break;
            case Journal::hour:
                Journal::m_tstamp << "%I";
                break;
            case Journal::ampm:
                Journal::m_tstamp << "%P";
                break;
            case Journal::hour24:
                Journal::m_tstamp << "%H";
                break;
            case Journal::minute:
                Journal::m_tstamp << "%M";
                break;
            case Journal::seconds:
                Journal::m_tstamp << "%S";
                break;
            default: return *this;
        }

        //Journal::m_tstamp << Journal()[Journal::reset];
        return *this;

    }

    Journal& Journal::operator,(Journal::attr_t attr)
    {
        Journal::m_tstamp << Journal::m_attr_table[(int)attr];
        return *this;
    }

    //disabled, but left there to prevent the the compiler to make full copy....
    Journal& Journal::operator=(const Journal& other)
    {

        return *this;
    }

    // --
    bool Journal::operator==(const Journal& other) const
    {
        return false;
    }

    Journal& Journal::operator<<(Journal::attr_t attr)
    {
        (*Journal::m_file) << Journal::m_attr_table[(int)attr];
        return *this;
    }

    Journal& Journal::operator<<(Journal::tail til)
    {
        switch(til){
            case Journal::lf:
                (*Journal::m_file) << Journal::m_eol;
                break;
            case Journal::end:
                (*Journal::m_file) << Journal::m_eol << Journal::m_attr_table[(int)Journal::reset];
                break;
        }
        return *this;
    }

    Journal& Journal::operator<<(Journal::object obj)
    {
        m_text.clear();
        switch(obj){
            case Journal::stamp:
                m_text.DateTime(Journal::m_tstamp);
                (*Journal::m_file) << m_text << Journal::m_attr_table[(int)Journal::reset];
                m_text.clear();
                break;
            case Journal::fn:
                (*Journal::m_file) << Journal::m_fn_prefix << Journal::m_attr_table[(int)Journal::reset];
                break;
            case Journal::fname:
                (*Journal::m_file) << Journal::m_long_fn_prefix << Journal::m_attr_table[(int)Journal::reset];
                break;
                // ...
            case Journal::inc:
                ++Journal::m_indent;
                break;
            case Journal::dec:
                //Journal::m_indent = --Journal::m_indent < 0 ? 0 : Journal::m_indent;
                --Journal::m_indent;
                if(Journal::m_indent < 0) Journal::m_indent = 0;
                break;
            case Journal::code:
                Journal::m_code_mode = true;
                break;
            case Journal::endcode:
                Journal::m_code_mode = false;
                break;
            case Journal::para:
                (*Journal::m_file) << "
n";
                break;
            case Journal::endpara:
                (*Journal::m_file) << "
";
                break;
            default:
                break;
        };
        return *this;
    }

    Journal& Journal::operator<<(Journal::type_t t)
    {
        (*Journal::m_file) << Journal::m_type_table[(int)t] << Journal::m_attr_table[(int)Journal::reset];
        return *this;
    }

    Journal& Journal::operator << (Journal::arrow arr)
    {
        //  ➜ ⬅ ⬆ ⬇ ⬈ ⬉ ⬊ ⬋
        //     switch(arr){
        //         case Journal::arrow::arrow_down:
        //             (*Journal::m_file) << "⬇ ";
        //             break;
        //         case Journal::arrow::arrow_down_left:
        //             (*Journal::m_file) << "⬋ ";
        //             break;
        //         case Journal::arrow::arrow_down_right:
        //             (*Journal::m_file) << "⬊ ";
        //             break;
        //         case Journal::arrow::arrow_left:
        //             (*Journal::m_file) << "⬅ ";
        //             break;
        //         case Journal::arrow::arrow_right:
        //             (*Journal::m_file) << "➜ ";
        //             break;
        //         case Journal::arrow::arrow_up:
        //             (*Journal::m_file) << "⬆ ";
        //             break;
        //         case Journal::arrow::arrow_up_left:
        //             (*Journal::m_file) << "⬉ ";
        //             break;
        //         case Journal::arrow::arrow_up_right:
        //             (*Journal::m_file) << "⬈ ";
        //             break;
        //     }
        //     return *this;

        (*Journal::m_file) << Journal::m_arrows[(int)arr];
        return *this;
    }

    String Journal::operator[](Journal::attr_t attr)
    {
        return Journal::m_attr_table[(int)attr];
    }

    String Journal::operator[](Journal::type_t tclass)
    {
        return Journal::m_type_table[(int)tclass];
    }

    String Journal::operator[](Journal::object obj)
    {
        // thinking ...
        return Journal::m_objects_prefix_table[(int)obj];
    }

    int Journal::Init(Journal::mode_t mode, const String& lname, bool use_pid)
    {
        Journal::m_mode = mode;
        std::map<Journal::mode_t, String> names;

        String mode_name;
        switch (Journal::m_mode){

            case Journal::mode_t::ansi: mode_name = "ansi256 unicode console format output" ; Journal::_init_ansi();  break;
            case Journal::mode_t::html: mode_name = "html format output" ; Journal::_init_html();  break;
            case Journal::mode_t::none: mode_name = "unformatted output" ; Journal::_init_plain(); break;
            case Journal::mode_t::nsml: mode_name = "sml  format output" ; Journal::_init_sml();   break;
            case Journal::mode_t::plain:mode_name = "unformatted output" ; Journal::_init_plain(); break;
            default : mode_name = "unformatted output"; Journal::_init_plain(); break;
        }

        // setup full date-time for the Journal header:
        Journal::ResetStamp(),  Journal::white, Journal::lday, ',',
        Journal::month_name_long, ' ',
        Journal::day, ' ',
        Journal::year_long, "  ",
        Journal::hour, ':',
        Journal::minute, ':',
        Journal::seconds;
        //Journal::ampm;

        Journal::m_Journal_header.clear();
        Journal::m_Journal_header.DateTime(Journal::m_tstamp);
        Journal::m_Journal_header << "%s Journal [Journal 1.0] name '%s%s%s' format: '%s%s' "; // %s
        if(use_pid)
            Journal::m_Journal_header << " pid:%s%d%s ";

        Journal::m_Journal_header << " -- begin {" << Journal::m_eol;

        Journal::m_Journal_header.Arg(Journal::m_attr_table[(int)Journal::white]);
        //name:
        Journal::m_Journal_header.Arg(Journal::m_attr_table[(int)Journal::hcyan]);
        Journal::m_Journal_header.Arg(lname);
        Journal::m_Journal_header.Arg(Journal::m_attr_table[(int)Journal::white]);
        Journal::m_Journal_header.Arg(Journal::m_attr_table[(int)Journal::hcyan]);
        Journal::m_Journal_header.Arg(mode_name);
        Journal::m_Journal_header.Arg(Journal::m_attr_table[(int)Journal::white]);
        if(use_pid){
            Journal::m_Journal_header.Arg(Journal::m_attr_table[(int)Journal::hcyan]);
            Journal::m_Journal_header.Arg(getpid());
            Journal::m_Journal_header.Arg(Journal::m_attr_table[(int)Journal::white]);
        }

        (*Journal::m_file) << Journal::m_Journal_header;
        Journal::m_Journal_header.clear();

        // init text attributes/style for type/class of messages:
        // info=0, err, critical, fatal, debug, excep, notice, warnings
        Journal::m_type_table.push_back(Journal::m_attr_table[(int)hblue]  + "⚫ information: "); // information : light blue
        Journal::m_type_table.push_back(Journal::m_attr_table[(int)red]    + "✘ error: "); // error
        Journal::m_type_table.push_back(Journal::m_attr_table[(int)hred]   + "⚒ critical:  "); // critical
        Journal::m_type_table.push_back(Journal::m_attr_table[(int)hmagenta]  + "☠ fatal:     "); // fatal hihihihi!
        Journal::m_type_table.push_back(Journal::m_attr_table[(int)hgreen] + "➤ debug:     "); // debug
        Journal::m_type_table.push_back(Journal::m_attr_table[(int)hcyan]  + "⚡ exception: "); // exceptions
        Journal::m_type_table.push_back(Journal::m_attr_table[(int)yellow] + "✎ notice:    "); // notice / notes
        Journal::m_type_table.push_back(Journal::m_attr_table[(int)yellow] + "⚑ warning:   "); // and ...warnings ... :-) ⚠
        Journal::m_type_table.push_back(Journal::m_attr_table[(int)hgreen] + "✔ succes:    "); // and ...succes ... :-)

        // now the text attributres/style for function signature...
        Journal::m_fn_prefix = Journal()[Journal::cyan];
        Journal::m_long_fn_prefix = Journal()[Journal::magenta];

        // attributes for the objects

        Journal::m_objects_prefix_table.push_back(Journal::m_attr_table[(int)Journal::cyan]);
        Journal::m_objects_prefix_table.push_back(Journal::m_attr_table[(int)Journal::cyan]);
        Journal::m_objects_prefix_table.push_back(Journal::m_attr_table[(int)Journal::hgray]);

        // text attribute code tokens:
        //      Journal::m_code_type_dictionary[types::binary_op_t]  = Journal::m_attr_table[(int)Journal::white];
        //      Journal::m_code_type_dictionary[types::unary_op_t]   = Journal::m_attr_table[(int)Journal::hcyan];
        //      Journal::m_code_type_dictionary[types::identifier_t] = Journal::m_attr_table[(int)Journal::hgreen];
        //      Journal::m_code_type_dictionary[types::keyword_t]    = Journal::m_attr_table[(int)Journal::dgray];
        //      Journal::m_code_type_dictionary[types::punct_t]      = Journal::m_attr_table[(int)Journal::hgray];
        //      Journal::m_code_type_dictionary[types::const_number_t]=Journal::m_attr_table[(int)Journal::yellow];
        //      Journal::m_code_type_dictionary[types::const_text_t] = Journal::m_attr_table[(int)Journal::cyan];

        //      // considering if it worth it :
        //      Journal::m_objects_prefix_table[(int)Journal::lday               ]= "";
        //      Journal::m_objects_prefix_table[(int)Journal::day                ]= "";
        //      Journal::m_objects_prefix_table[(int)Journal::yday               ]= "";
        //      Journal::m_objects_prefix_table[(int)Journal::month_num          ]= "";
        //      Journal::m_objects_prefix_table[(int)Journal::month_name_short   ]= "";
        //      Journal::m_objects_prefix_table[(int)Journal::month_name_long    ]= "";
        //      Journal::m_objects_prefix_table[(int)Journal::year_short         ]= "";
        //      Journal::m_objects_prefix_table[(int)Journal::year_long          ]= "";
        //      Journal::m_objects_prefix_table[(int)Journal::hour               ]= "";
        //      Journal::m_objects_prefix_table[(int)Journal::ampm               ]= "";
        //      Journal::m_objects_prefix_table[(int)Journal::hour24             ]= "";
        //      Journal::m_objects_prefix_table[(int)Journal::minute             ]= "";
        //      Journal::m_objects_prefix_table[(int)Journal::seconds            ]= "";
        //      Journal::m_objects_prefix_table[(int)Journal::lbreak             ]= "";
        //      Journal::m_objects_prefix_table[(int)Journal::inc                ]= "";
        //      Journal::m_objects_prefix_table[(int)Journal::dec                ]= "";
        //      Journal::m_objects_prefix_table[(int)Journal::nil                ]= "";

        return 0;
    }

    void Journal::_init_ansi()
    {
        // init colors attributes

        //     enum attr_t{
        //         /* colors*/ black=0, red=1, green=2, amber=3,blue=4, magenta=5,cyan=6, hgray, dgray, hred, hgreen, yellow, hblue,hmagenta, hcyan, white,
        //         /* reset */ reset, ///< remise-à-zéro des attributs.
        //         /* html: */ italic, strong, sup, sub ///< styles supplémentaires du texte au format `html`
        //     };
        Journal::m_attr_table.push_back("\033[0;30m"); // Journal::black
        Journal::m_attr_table.push_back("\033[0;31m"); // Journal::red
        Journal::m_attr_table.push_back("\033[0;32m"); // Journal::green
        Journal::m_attr_table.push_back("\033[0;33m");// Journal::ambre
        Journal::m_attr_table.push_back("\033[0;34m"); // Journal::blue
        Journal::m_attr_table.push_back("\033[0;35m"); // Journal::magenta
        Journal::m_attr_table.push_back("\033[0;36m"); // Journal::cyan
        Journal::m_attr_table.push_back("\033[0;37m"); // Journal::hgray
        Journal::m_attr_table.push_back("\033[1;30m");  // Journal::drakgray
        Journal::m_attr_table.push_back("\033[1;31m"); // Journal::hred
        Journal::m_attr_table.push_back("\033[1;32m"); // Journal::hgreen
        Journal::m_attr_table.push_back("\033[1;33m"); // Journal::yellow
        Journal::m_attr_table.push_back("\033[1;34m"); // Journal::hblue
        Journal::m_attr_table.push_back("\033[1;35m"); // Journal::hmagenta
        Journal::m_attr_table.push_back("\033[1;36m"); // Journal::hcyan
        Journal::m_attr_table.push_back("\033[1;37m"); // Journal::white
        Journal::m_attr_table.push_back("\033[0m");// Journal::reset
        Journal::m_attr_table.push_back("\033[0m");// Journal::italic
        Journal::m_attr_table.push_back("\033[0m");// Journal::strong
        Journal::m_attr_table.push_back("\033[0m");// Journal::sup
        Journal::m_attr_table.push_back("\033[0m");// Journal::sub
        Journal::m_eol = "\n";
    }

    void Journal::_init_html()
    {
        Journal::m_attr_table.push_back(""); // Journal::black
        Journal::m_attr_table.push_back(""); // Journal::red
        Journal::m_attr_table.push_back(""); // Journal::green
        Journal::m_attr_table.push_back("");// Journal::ambre
        Journal::m_attr_table.push_back(""); // Journal::blue
        Journal::m_attr_table.push_back(""); // Journal::magenta
        Journal::m_attr_table.push_back(""); // Journal::cyan
        Journal::m_attr_table.push_back(""); // Journal::hgray
        Journal::m_attr_table.push_back("");  // Journal::drakgray
        Journal::m_attr_table.push_back(""); // Journal::hred
        Journal::m_attr_table.push_back(""); // Journal::hgreen
        Journal::m_attr_table.push_back(""); // Journal::yellow
        Journal::m_attr_table.push_back(""); // Journal::hblue
        Journal::m_attr_table.push_back(""); // Journal::hmagenta
        Journal::m_attr_table.push_back(""); // Journal::hcyan
        Journal::m_attr_table.push_back(""); // Journal::white
        Journal::m_attr_table.push_back("");// Journal::reset
        Journal::m_attr_table.push_back("");// Journal::italic
        Journal::m_attr_table.push_back("");// Journal::strong
        Journal::m_attr_table.push_back("");// Journal::sup
        Journal::m_attr_table.push_back("");// Journal::sub
        Journal::m_eol = "
";

    }

    void Journal::_init_plain()
    {
        Journal::m_attr_table.push_back(""); // Journal::black
        Journal::m_attr_table.push_back(""); // Journal::red
        Journal::m_attr_table.push_back(""); // Journal::green
        Journal::m_attr_table.push_back("");// Journal::ambre
        Journal::m_attr_table.push_back(""); // Journal::blue
        Journal::m_attr_table.push_back(""); // Journal::magenta
        Journal::m_attr_table.push_back(""); // Journal::cyan
        Journal::m_attr_table.push_back(""); // Journal::hgray
        Journal::m_attr_table.push_back("");  // Journal::drakgray
        Journal::m_attr_table.push_back(""); // Journal::hred
        Journal::m_attr_table.push_back(""); // Journal::hgreen
        Journal::m_attr_table.push_back(""); // Journal::yellow
        Journal::m_attr_table.push_back(""); // Journal::hblue
        Journal::m_attr_table.push_back(""); // Journal::hmagenta
        Journal::m_attr_table.push_back(""); // Journal::hcyan
        Journal::m_attr_table.push_back(""); // Journal::white
        Journal::m_attr_table.push_back("");// Journal::reset
        Journal::m_attr_table.push_back("");// Journal::italic
        Journal::m_attr_table.push_back("");// Journal::strong
        Journal::m_attr_table.push_back("");// Journal::sup
        Journal::m_attr_table.push_back("");// Journal::sub
    }

    void Journal::_init_sml()
    {

    }

    String Journal::operator[](Journal::arrow ar)
    {
        return Journal::m_arrows[(int)ar];
    }

}


text:
package edu.uw.zookeeper.proxy;

import java.util.List;

import com.google.common.collect.Lists;
import com.google.common.util.concurrent.Service;

import edu.uw.zookeeper.common.RuntimeModule;
import edu.uw.zookeeper.protocol.server.ServerConnectionsHandler;
import edu.uw.zookeeper.server.SimpleServerBuilder;

public class ProxyServerBuilder extends SimpleServerBuilder<ProxyServerExecutorBuilder> {

    public static ProxyServerBuilder defaults() {
        return new ProxyServerBuilder(
                ProxyServerExecutorBuilder.defaults(),
                ServerConnectionsHandler.Builder.defaults());
    }

    protected ProxyServerBuilder(
            ProxyServerExecutorBuilder server,
            ServerConnectionsHandler.Builder connections) {
        super(server, connections);
    }

    @Override
    public ProxyServerBuilder setRuntimeModule(RuntimeModule runtime) {
        return newInstance(
                TracingProxyServerBuilder.fromRuntimeModule(runtime),
                getConnectionsBuilder().setRuntimeModule(runtime));
    }

    @Override
    protected ProxyServerBuilder newInstance(
            ProxyServerExecutorBuilder server,
            ServerConnectionsHandler.Builder connections) {
        return new ProxyServerBuilder(server, connections);
    }

    @Override
    protected List<Service> doBuild() {
        List<Service> services = Lists.newLinkedList();
        if (getServerBuilder() instanceof TracingProxyServerBuilder) {
            services.add(((TracingProxyServerBuilder) getServerBuilder()).getTracingBuilder().build());
        }
        for (Service e: getServerBuilder().getClientBuilder().build()) {
            services.add(e);
        }
        for (Service e: super.doBuild()) {
            services.add(e);
        }
        return services;
    }

    @Override
    protected ServerConnectionsHandler.Builder getDefaultConnectionsBuilder() {
        ServerConnectionsHandler.Builder connections = getConnectionsBuilder();
        if (connections.getServerExecutor() == null) {
            connections = connections.setServerExecutor(getDefaultServerExecutor());
        }
        return connections
                .setConnectionBuilder(connections.getConnectionBuilder().setServerModule(getServerBuilder().getNetModule().servers()))
                .setTimeOut(getServerBuilder().getClientBuilder().getConnectionBuilder().getTimeOut())
                .setDefaults();
    }
}


text:
/*jslint white: true, vars: true, undef: true, newcap: true, regexp: true, browser: true,
    forin: true, continue: true, nomen: true, bitwise: true, maxerr: 100, indent: 4 */

var fs = require("fs"),
    url = require("url"),
    fluid = fluid || require("infusion"),
    flock = fluid.registerNamespace("flock"),
    Speaker = require("speaker"),
    Readable = require("stream").Readable,
    midi = require("midi");

(function () {
    "use strict";

    /*********************************************************
     * Override default clocks with same-thread alternatives *
     *********************************************************/

    fluid.demands("flock.scheduler.webWorkerIntervalClock", ["flock.platform.nodejs", "flock.scheduler.async"], {
        funcName: "flock.scheduler.intervalClock"
    });

    fluid.demands("flock.scheduler.webWorkerScheduleClock", ["flock.platform.nodejs", "flock.scheduler.async"], {
        funcName: "flock.scheduler.scheduleClock"
    });

    /********************************************
     * Override buffer loading implementations. *
     ********************************************/

    fluid.registerNamespace("flock.file");

    flock.file.readFromPath = function (options) {
        var path = options.src;

        fs.exists(path, function (exists) {
            if (!exists && options.error) {
                options.error(path + " doesn't exist.");
                return;
            }

            fs.stat(path, function (error, stats) {
                fs.open(path, "r", function (error, fd) {
                    var buf = new Buffer(stats.size);

                    fs.read(fd, buf, 0, buf.length, null, function () {
                        var type = flock.file.parseFileExtension(path);
                        var arr = new Int8Array(buf);
                        options.success(arr.buffer, type);
                    });
                });
            });
        });
    };

    fluid.registerNamespace("flock.net");

    flock.net.readBufferFromUrl = function () {
        throw new Error("Loading files from URLs is not currently supported in Node.js.");
    };

    fluid.registerNamespace("flock.audio.loadBuffer");

    flock.audio.loadBuffer.readerForSource = function (src) {
        if (typeof (src) !== "string") {
            throw new Error("Flocking error: Can't load a buffer from an unknown type of source. " +
                "Only paths and URLs are currently supported on Node.js.");
        }
        var parsed = url.parse(src);
        return parsed.protocol === "data:" ? flock.file.readBufferFromDataUrl :
            !parsed.protocol ? flock.file.readFromPath : flock.net.readBufferFromUrl;
    };

    fluid.registerNamespace("flock.audio.decode");

    // TODO: Use a stream-style interface for decoding rather than just dumping the whole job on nextTick().
    flock.audio.decode.node = function (options) {
        process.nextTick(function () {
            flock.audio.decode.sync(options);
        });
    };

    flock.audio.registerDecoderStrategy({
        "default": flock.audio.decode.node,
        "aiff": flock.audio.decode.node
    });

    /*********************************************
     * Node.js-based Environment implementation. *
     *********************************************/

    fluid.defaults("flock.audioStrategy.nodejs", {
        gradeNames: ["flock.audioStrategy", "autoInit"],

        bytesPerSample: 4, // Flocking uses Float32s, hence 4 bytes.

        model: {
            audioSettings: "{audioSystem}.model",
            bytesPerBlock: {
                expander: {
                    funcName: "flock.audioStrategy.nodejs.calcBlockBytes",
                    args: ["{audioSystem}.model", "{that}.options.bytesPerSample"]
                }
            }
        },

        members: {
            speaker: "@expand:flock.audioStrategy.nodejs.createSpeaker({that}.model.audioSettings)",
            outputStream: {
                expander: {
                    funcName: "flock.audioStrategy.nodejs.createOutputStream",
                    args: "{that}.model.audioSettings"
                }
            }
        },

        invokers: {
            start: {
                funcName: "flock.audioStrategy.nodejs.startGeneratingSamples",
                args: ["{that}.outputStream", "{that}.speaker", "{that}.writeSamples"]
            },

            stop: {
                funcName: "flock.audioStrategy.nodejs.stopGeneratingSamples",
                args: ["{that}.outputStream", "{that}.speaker"]
            },

            // TODO: De-thatify.
            writeSamples: {
                funcName: "flock.audioStrategy.nodejs.writeSamples",
                args: ["{arguments}.0", "{that}"]
            },

            startReadingAudioInput: {
                funcName: "flock.fail",
                args: "Audio input is not currently supported on Node.js"
            },

            stopReadingAudioInput: "{that}.startReadingAudioInput",

            saveBuffer: "flock.audioStrategy.nodejs.saveBuffer({arguments}.0)"
        },

        listeners: {
            onStart: ["{that}.start"],
            onStop: ["{that}.stop"]
        }
    });

    flock.audioStrategy.nodejs.calcBlockBytes = function (audioSettings, bytesPerSample) {
        return audioSettings.blockSize * audioSettings.chans * bytesPerSample;
    };

    flock.audioStrategy.nodejs.createSpeaker = function (audioSettings) {
        return new Speaker({
            channels: audioSettings.chans,
            bitDepth: 32,
            sampleRate: audioSettings.rates.audio,
            signed: true,
            float: true,
            samplesPerFrame: audioSettings.blockSize,
            endianness: "LE"
        });
    };

    flock.audioStrategy.nodejs.createOutputStream = function () {
        return new Readable();
    };

    flock.audioStrategy.nodejs.startGeneratingSamples = function (outputStream, speaker, writeFn) {
        outputStream._read = writeFn;
        outputStream.pipe(speaker);
    };

    flock.audioStrategy.nodejs.stopGeneratingSamples = function (outputStream, speaker) {
        outputStream.unpipe(speaker);
        outputStream._read = undefined;
    };

    flock.audioStrategy.nodejs.writeSamples = function (numBytes, that) {
        var s = that.model.audioSettings,
            m = that.model,
            bytesPerSample = that.options.bytesPerSample,
            blockSize = s.blockSize,
            chans = s.chans,
            krPeriods = numBytes / m.bytesPerBlock,
            evaluator = that.nodeEvaluator,
            buses = evaluator.buses,
            nodes = evaluator.nodes,
            outputStream = that.outputStream,
            out = new Buffer(numBytes);

        if (numBytes < m.bytesPerBlock) {
            return;
        }

        if (evaluator.nodes.length < 1) {
            // If there are no nodes providing samples, write out silence.
            flock.generate.silence(out);
        } else {
            for (var i = 0, offset = 0; i < krPeriods; i++, offset += m.bytesPerBlock) {
                flock.nodeEvaluator.clearBuses(s.numBuses, s.blockSize, buses);
                flock.nodeEvaluator.gen(nodes);

                // Interleave each output channel.
                for (var chan = 0; chan < chans; chan++) {
                    var bus = evaluator.buses[chan];
                    for (var sampIdx = 0; sampIdx < blockSize; sampIdx++) {
                        var frameIdx = (sampIdx * chans + chan) * bytesPerSample;
                        out.writeFloatLE(bus[sampIdx], offset + frameIdx);
                    }
                }
            }
        }

        outputStream.push(out);
    };

    flock.audioStrategy.nodejs.saveBuffer = function (o) {
        var encoded = flock.audio.encode.wav(o.buffer);

        fs.writeFile(o.path, encoded, function (err) {
            if (err) {
                if (!o.error) {
                    flock.fail("There was an error while writing a buffer named " +
                        o.buffer.id + " with the file path " + fileName + ". Error was: " + err);
                } else {
                    o.error(err);
                }

                return;
            }

            if (o.success) {
                o.success(encoded);
            }
        });
    };

    fluid.demands("flock.audioSystem.platform", "flock.platform.nodejs", {
        funcName: "flock.audioSystem"
    });

    fluid.demands("flock.audioStrategy.platform", "flock.platform.nodejs", {
        funcName: "flock.audioStrategy.nodejs"
    });

    /****************************
     * Web MIDI Pseudo-Polyfill *
     ****************************/

    fluid.registerNamespace("flock.midi.nodejs");

    /**
     * MIDIAccess represents access to the midi system.
     * @constructor
     */
    flock.midi.nodejs.MIDIAccess = function (options) {
        this.sysex = options.sysex !== undefined ? options.sysex : false;
        this.input = new midi.input();
        this.output = new midi.output();

        this.input.ignoreTypes(this.sysex, false, false);
    };

    var p = flock.midi.nodejs.MIDIAccess.prototype = {};
    p.constructor = flock.midi.nodejs.MIDIAccess;

    p.inputs = function () {
        return flock.midi.nodejs.getAllPorts("input", this.input);
    };

    p.outputs = function () {
        return flock.midi.nodejs.getAllPorts("output", this.output);
    };

    flock.midi.nodejs.getAllPorts = function (type, midi) {
        var numPorts = midi.getPortCount(),
            ports = new Array(numPorts);

        for (var i = 0; i < numPorts; i++) {
            ports[i] = new flock.midi.nodejs.MIDIPort(type, i);
        }

        return ports;
    };

    /**
     * MIDIPort represents a MIDI input or output port.
     * @constructor
     */
    flock.midi.nodejs.MIDIPort = function (type, portNum) {
        this.type = type;
        this.midi = new midi[this.type]();
        this.portNum = portNum;
        this.name = this.midi.getPortName(this.portNum);
        this.listeners = {};
    };

    p = flock.midi.nodejs.MIDIPort.prototype = {};
    p.constructor = flock.midi.nodejs.MIDIPort;

    p.addEventListener = function (evtName, fn) {
        flock.midi.nodejs.throwIfNotMIDIMessage(evtName);
        this.midi.on("message", flock.midi.nodejs.wrapMessageListener(this, fn));
    };

    p.removeEventListener = function (evtName, fn) {
        flock.midi.nodejs.throwIfNotMIDIMessage(evtName);
        var listenerGUID = fn.__flock_midi_id,
            wrapper = this.listeners[listenerGUID];

        if (wrapper) {
            this.midi.removeListener("message", wrapper);
            this.listeners[listenerGUID] = undefined;
        }

        // TODO: Should we close the port when we have no listeners?
    };

    p.open = function () {
        this.midi.openPort(this.portNum);
    };

    p.send = function (data) {
        if (this.type !== "output") {
            throw new Error("An input port can't be used to send MIDI messages.");
        }

        this.midi.sendMessage(data);
    };

    flock.midi.nodejs.throwIfNotMIDIMessage = function (evtName) {
        if (evtName !== "midimessage") {
            throw new Error("Port.addListener() only supports the midimessage event.");
        }
    };

    var listenerID = 0;
    flock.midi.nodejs.wrapMessageListener = function (that, fn) {
        var guid = "flock-guid-" + listenerID++;
        fn.__flock_midi_id = guid;

        var wrapper = function (deltaTime, data) {
            var e = {
                receivedTime: deltaTime,
                data: data
            };

            fn(e);
        };

        wrapper.__flock_midi_id = guid;
        that.listeners[guid] = wrapper;

        return wrapper;
    };

    flock.midi.nodejs.requestAccess = function (sysex, onAccessGranted, onError) {
        try {
            var access = new flock.midi.nodejs.MIDIAccess(sysex);
            onAccessGranted(access);
            return access;
        } catch (e) {
            onError(e);
        }
    };

    flock.midi.nodejs.openPort = function (port) {
        port.open();
    };

    // TODO: Replace this with something more civilized!
    flock.midi.requestAccess = flock.midi.nodejs.requestAccess;
    flock.midi.connection.openPort = flock.midi.nodejs.openPort;

}());


text:
using System;

namespace Azure.Messaging.EventGrid.SystemEvents
{
    /// <summary> The content of the event request message. </summary>
    public partial class ContainerRegistryEventData
    {
        /// <summary> Initializes a new instance of ContainerRegistryEventData. </summary>
        internal ContainerRegistryEventData()
        {
        }

        /// <summary> Initializes a new instance of ContainerRegistryEventData. </summary>
        /// <param name="id"> The event ID. </param>
        /// <param name="timestamp"> The time at which the event occurred. </param>
        /// <param name="action"> The action that encompasses the provided event. </param>
        /// <param name="target"> The target of the event. </param>
        /// <param name="request"> The request that generated the event. </param>
        /// <param name="actor"> The agent that initiated the event. For most situations, this could be from the authorization context of the request. </param>
        /// <param name="source"> The registry node that generated the event. Put differently, while the actor initiates the event, the source generates it. </param>
        internal ContainerRegistryEventData(string id, DateTimeOffset? timestamp, string action, ContainerRegistryEventTarget target, ContainerRegistryEventRequest request, ContainerRegistryEventActor actor, ContainerRegistryEventSource source)
        {
            Id = id;
            Timestamp = timestamp;
            Action = action;
            Target = target;
            Request = request;
            Actor = actor;
            Source = source;
        }

        /// <summary> The event ID. </summary>
        public string Id { get; }
        /// <summary> The time at which the event occurred. </summary>
        public DateTimeOffset? Timestamp { get; }
        /// <summary> The action that encompasses the provided event. </summary>
        public string Action { get; }
        /// <summary> The target of the event. </summary>
        public ContainerRegistryEventTarget Target { get; }
        /// <summary> The request that generated the event. </summary>
        public ContainerRegistryEventRequest Request { get; }
        /// <summary> The agent that initiated the event. For most situations, this could be from the authorization context of the request. </summary>
        public ContainerRegistryEventActor Actor { get; }
        /// <summary> The registry node that generated the event. Put differently, while the actor initiates the event, the source generates it. </summary>
        public ContainerRegistryEventSource Source { get; }
    }
}


text:
/**
 * Transition-end mapping
 */

var map = {
  'WebkitTransition' : 'webkitTransitionEnd',
  'MozTransition' : 'transitionend',
  'OTransition' : 'oTransitionEnd',
  'msTransition' : 'MSTransitionEnd',
  'transition' : 'transitionend'
};

/**
 * Expose `transitionend`
 */

var el = document.createElement('p');

for (var transition in map) {
  if (null != el.style[transition]) {
    module.exports = map[transition];
    break;
  }
}


text:
//  Copyright (c) 2011-present, Facebook, Inc.  All rights reserved.
//  This source code is licensed under both the GPLv2 (found in the
//  COPYING file in the root directory) and Apache 2.0 License
//  (found in the LICENSE.Apache file in the root directory).
//
// Copyright (c) 2011 The LevelDB Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file. See the AUTHORS file for names of contributors
#include <dirent.h>
#ifndef ROCKSDB_NO_DYNAMIC_EXTENSION
#include <dlfcn.h>
#endif
#include <errno.h>
#include <fcntl.h>

#if defined(OS_LINUX)
#include <linux/fs.h>
#endif
#include <pthread.h>
#include <signal.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/ioctl.h>
#include <sys/mman.h>
#include <sys/stat.h>
#if defined(OS_LINUX) || defined(OS_SOLARIS) || defined(OS_ANDROID)
#include <sys/statfs.h>
#include <sys/syscall.h>
#include <sys/sysmacros.h>
#endif
#include <sys/statvfs.h>
#include <sys/time.h>
#include <sys/types.h>
#include <time.h>
#include <algorithm>
// Get nano time includes
#if defined(OS_LINUX) || defined(OS_FREEBSD)
#elif defined(__MACH__)
#include <Availability.h>
#include <mach/clock.h>
#include <mach/mach.h>
#else
#include <chrono>
#endif
#include <deque>
#include <set>
#include <vector>

#include "env/io_posix.h"
#include "logging/logging.h"
#include "logging/posix_logger.h"
#include "monitoring/iostats_context_imp.h"
#include "monitoring/thread_status_updater.h"
#include "port/port.h"
#include "rocksdb/options.h"
#include "rocksdb/slice.h"
#include "test_util/sync_point.h"
#include "util/coding.h"
#include "util/compression_context_cache.h"
#include "util/random.h"
#include "util/string_util.h"
#include "util/thread_local.h"
#include "util/threadpool_imp.h"

#if !defined(TMPFS_MAGIC)
#define TMPFS_MAGIC 0x01021994
#endif
#if !defined(XFS_SUPER_MAGIC)
#define XFS_SUPER_MAGIC 0x58465342
#endif
#if !defined(EXT4_SUPER_MAGIC)
#define EXT4_SUPER_MAGIC 0xEF53
#endif

namespace ROCKSDB_NAMESPACE {

namespace {

inline mode_t GetDBFileMode(bool allow_non_owner_access) {
  return allow_non_owner_access ? 0644 : 0600;
}

// list of pathnames that are locked
// Only used for error message.
struct LockHoldingInfo {
  int64_t acquire_time;
  uint64_t acquiring_thread;
};
static std::map<std::string, LockHoldingInfo> locked_files;
static port::Mutex mutex_locked_files;

static int LockOrUnlock(int fd, bool lock) {
  errno = 0;
  struct flock f;
  memset(&f, 0, sizeof(f));
  f.l_type = (lock ? F_WRLCK : F_UNLCK);
  f.l_whence = SEEK_SET;
  f.l_start = 0;
  f.l_len = 0;  // Lock/unlock entire file
  int value = fcntl(fd, F_SETLK, &f);

  return value;
}

class PosixFileLock : public FileLock {
 public:
  int fd_;
  std::string filename;
};

int cloexec_flags(int flags, const EnvOptions* options) {
  // If the system supports opening the file with cloexec enabled,
  // do so, as this avoids a race condition if a db is opened around
  // the same time that a child process is forked
#ifdef O_CLOEXEC
  if (options == nullptr || options->set_fd_cloexec) {
    flags |= O_CLOEXEC;
  }
#endif
  return flags;
}

class PosixFileSystem : public FileSystem {
 public:
  PosixFileSystem();

  const char* Name() const override { return "Posix File System"; }

  ~PosixFileSystem() override {}

  void SetFD_CLOEXEC(int fd, const EnvOptions* options) {
    if ((options == nullptr || options->set_fd_cloexec) && fd > 0) {
      fcntl(fd, F_SETFD, fcntl(fd, F_GETFD) | FD_CLOEXEC);
    }
  }

  IOStatus NewSequentialFile(const std::string& fname,
                             const FileOptions& options,
                             std::unique_ptr<FSSequentialFile>* result,
                             IODebugContext* /*dbg*/) override {
    result->reset();
    int fd = -1;
    int flags = cloexec_flags(O_RDONLY, &options);
    FILE* file = nullptr;

    if (options.use_direct_reads && !options.use_mmap_reads) {
#ifdef ROCKSDB_LITE
      return IOStatus::IOError(fname,
                               "Direct I/O not supported in RocksDB lite");
#endif  // !ROCKSDB_LITE
#if !defined(OS_MACOSX) && !defined(OS_OPENBSD) && !defined(OS_SOLARIS)
      flags |= O_DIRECT;
#endif
    }

    do {
      IOSTATS_TIMER_GUARD(open_nanos);
      fd = open(fname.c_str(), flags, GetDBFileMode(allow_non_owner_access_));
    } while (fd < 0 && errno == EINTR);
    if (fd < 0) {
      return IOError("While opening a file for sequentially reading", fname,
                     errno);
    }

    SetFD_CLOEXEC(fd, &options);

    if (options.use_direct_reads && !options.use_mmap_reads) {
#ifdef OS_MACOSX
      if (fcntl(fd, F_NOCACHE, 1) == -1) {
        close(fd);
        return IOError("While fcntl NoCache", fname, errno);
      }
#endif
    } else {
      do {
        IOSTATS_TIMER_GUARD(open_nanos);
        file = fdopen(fd, "r");
      } while (file == nullptr && errno == EINTR);
      if (file == nullptr) {
        close(fd);
        return IOError("While opening file for sequentially read", fname,
                       errno);
      }
    }
    result->reset(new PosixSequentialFile(
        fname, file, fd, GetLogicalBlockSize(fname, fd), options));
    return IOStatus::OK();
  }

  IOStatus NewRandomAccessFile(const std::string& fname,
                               const FileOptions& options,
                               std::unique_ptr<FSRandomAccessFile>* result,
                               IODebugContext* /*dbg*/) override {
    result->reset();
    IOStatus s;
    int fd;
    int flags = cloexec_flags(O_RDONLY, &options);

    if (options.use_direct_reads && !options.use_mmap_reads) {
#ifdef ROCKSDB_LITE
      return IOStatus::IOError(fname,
                               "Direct I/O not supported in RocksDB lite");
#endif  // !ROCKSDB_LITE
#if !defined(OS_MACOSX) && !defined(OS_OPENBSD) && !defined(OS_SOLARIS)
      flags |= O_DIRECT;
      TEST_SYNC_POINT_CALLBACK("NewRandomAccessFile:O_DIRECT", &flags);
#endif
    }

    do {
      IOSTATS_TIMER_GUARD(open_nanos);
      fd = open(fname.c_str(), flags, GetDBFileMode(allow_non_owner_access_));
    } while (fd < 0 && errno == EINTR);
    if (fd < 0) {
      return IOError("While open a file for random read", fname, errno);
    }
    SetFD_CLOEXEC(fd, &options);

    if (options.use_mmap_reads && sizeof(void*) >= 8) {
      // Use of mmap for random reads has been removed because it
      // kills performance when storage is fast.
      // Use mmap when virtual address-space is plentiful.
      uint64_t size;
      IOOptions opts;
      s = GetFileSize(fname, opts, &size, nullptr);
      if (s.ok()) {
        void* base = mmap(nullptr, size, PROT_READ, MAP_SHARED, fd, 0);
        if (base != MAP_FAILED) {
          result->reset(
              new PosixMmapReadableFile(fd, fname, base, size, options));
        } else {
          s = IOError("while mmap file for read", fname, errno);
          close(fd);
        }
      }
    } else {
      if (options.use_direct_reads && !options.use_mmap_reads) {
#ifdef OS_MACOSX
        if (fcntl(fd, F_NOCACHE, 1) == -1) {
          close(fd);
          return IOError("while fcntl NoCache", fname, errno);
        }
#endif
      }
      result->reset(new PosixRandomAccessFile(
          fname, fd, GetLogicalBlockSize(fname, fd), options
#if defined(ROCKSDB_IOURING_PRESENT)
          ,
          thread_local_io_urings_.get()
#endif
              ));
    }
    return s;
  }

  virtual IOStatus OpenWritableFile(const std::string& fname,
                                    const FileOptions& options,
                                    bool reopen,
                                    std::unique_ptr<FSWritableFile>* result,
                                    IODebugContext* /*dbg*/) {
    result->reset();
    IOStatus s;
    int fd = -1;
    int flags = (reopen) ? (O_CREAT | O_APPEND) : (O_CREAT | O_TRUNC);
    // Direct IO mode with O_DIRECT flag or F_NOCAHCE (MAC OSX)
    if (options.use_direct_writes && !options.use_mmap_writes) {
      // Note: we should avoid O_APPEND here due to ta the following bug:
      // POSIX requires that opening a file with the O_APPEND flag should
      // have no affect on the location at which pwrite() writes data.
      // However, on Linux, if a file is opened with O_APPEND, pwrite()
      // appends data to the end of the file, regardless of the value of
      // offset.
      // More info here: https://linux.die.net/man/2/pwrite
#ifdef ROCKSDB_LITE
      return IOStatus::IOError(fname,
                               "Direct I/O not supported in RocksDB lite");
#endif  // ROCKSDB_LITE
      flags |= O_WRONLY;
#if !defined(OS_MACOSX) && !defined(OS_OPENBSD) && !defined(OS_SOLARIS)
      flags |= O_DIRECT;
#endif
      TEST_SYNC_POINT_CALLBACK("NewWritableFile:O_DIRECT", &flags);
    } else if (options.use_mmap_writes) {
      // non-direct I/O
      flags |= O_RDWR;
    } else {
      flags |= O_WRONLY;
    }

    flags = cloexec_flags(flags, &options);

    do {
      IOSTATS_TIMER_GUARD(open_nanos);
      fd = open(fname.c_str(), flags, GetDBFileMode(allow_non_owner_access_));
    } while (fd < 0 && errno == EINTR);

    if (fd < 0) {
      s = IOError("While open a file for appending", fname, errno);
      return s;
    }
    SetFD_CLOEXEC(fd, &options);

    if (options.use_mmap_writes) {
      if (!checkedDiskForMmap_) {
        // this will be executed once in the program's lifetime.
        // do not use mmapWrite on non ext-3/xfs/tmpfs systems.
        if (!SupportsFastAllocate(fname)) {
          forceMmapOff_ = true;
        }
        checkedDiskForMmap_ = true;
      }
    }
    if (options.use_mmap_writes && !forceMmapOff_) {
      result->reset(new PosixMmapFile(fname, fd, page_size_, options));
    } else if (options.use_direct_writes && !options.use_mmap_writes) {
#ifdef OS_MACOSX
      if (fcntl(fd, F_NOCACHE, 1) == -1) {
        close(fd);
        s = IOError("While fcntl NoCache an opened file for appending", fname,
                    errno);
        return s;
      }
#elif defined(OS_SOLARIS)
      if (directio(fd, DIRECTIO_ON) == -1) {
        if (errno != ENOTTY) {  // ZFS filesystems don't support DIRECTIO_ON
          close(fd);
          s = IOError("While calling directio()", fname, errno);
          return s;
        }
      }
#endif
      result->reset(new PosixWritableFile(
          fname, fd, GetLogicalBlockSize(fname, fd), options));
    } else {
      // disable mmap writes
      EnvOptions no_mmap_writes_options = options;
      no_mmap_writes_options.use_mmap_writes = false;
      result->reset(new PosixWritableFile(
          fname, fd, GetLogicalBlockSize(fname, fd), no_mmap_writes_options));
    }
    return s;
  }

  IOStatus NewWritableFile(const std::string& fname, const FileOptions& options,
                           std::unique_ptr<FSWritableFile>* result,
                           IODebugContext* dbg) override {
    return OpenWritableFile(fname, options, false, result, dbg);
  }

  IOStatus ReopenWritableFile(const std::string& fname,
                              const FileOptions& options,
                              std::unique_ptr<FSWritableFile>* result,
                              IODebugContext* dbg) override {
    return OpenWritableFile(fname, options, true, result, dbg);
  }

  IOStatus ReuseWritableFile(const std::string& fname,
                             const std::string& old_fname,
                             const FileOptions& options,
                             std::unique_ptr<FSWritableFile>* result,
                             IODebugContext* /*dbg*/) override {
    result->reset();
    IOStatus s;
    int fd = -1;

    int flags = 0;
    // Direct IO mode with O_DIRECT flag or F_NOCAHCE (MAC OSX)
    if (options.use_direct_writes && !options.use_mmap_writes) {
#ifdef ROCKSDB_LITE
      return IOStatus::IOError(fname,
                               "Direct I/O not supported in RocksDB lite");
#endif  // !ROCKSDB_LITE
      flags |= O_WRONLY;
#if !defined(OS_MACOSX) && !defined(OS_OPENBSD) && !defined(OS_SOLARIS)
      flags |= O_DIRECT;
#endif
      TEST_SYNC_POINT_CALLBACK("NewWritableFile:O_DIRECT", &flags);
    } else if (options.use_mmap_writes) {
      // mmap needs O_RDWR mode
      flags |= O_RDWR;
    } else {
      flags |= O_WRONLY;
    }

    flags = cloexec_flags(flags, &options);

    do {
      IOSTATS_TIMER_GUARD(open_nanos);
      fd = open(old_fname.c_str(), flags,
                GetDBFileMode(allow_non_owner_access_));
    } while (fd < 0 && errno == EINTR);
    if (fd < 0) {
      s = IOError("while reopen file for write", fname, errno);
      return s;
    }

    SetFD_CLOEXEC(fd, &options);
    // rename into place
    if (rename(old_fname.c_str(), fname.c_str()) != 0) {
      s = IOError("while rename file to " + fname, old_fname, errno);
      close(fd);
      return s;
    }

    if (options.use_mmap_writes) {
      if (!checkedDiskForMmap_) {
        // this will be executed once in the program's lifetime.
        // do not use mmapWrite on non ext-3/xfs/tmpfs systems.
        if (!SupportsFastAllocate(fname)) {
          forceMmapOff_ = true;
        }
        checkedDiskForMmap_ = true;
      }
    }
    if (options.use_mmap_writes && !forceMmapOff_) {
      result->reset(new PosixMmapFile(fname, fd, page_size_, options));
    } else if (options.use_direct_writes && !options.use_mmap_writes) {
#ifdef OS_MACOSX
      if (fcntl(fd, F_NOCACHE, 1) == -1) {
        close(fd);
        s = IOError("while fcntl NoCache for reopened file for append", fname,
                    errno);
        return s;
      }
#elif defined(OS_SOLARIS)
      if (directio(fd, DIRECTIO_ON) == -1) {
        if (errno != ENOTTY) {  // ZFS filesystems don't support DIRECTIO_ON
          close(fd);
          s = IOError("while calling directio()", fname, errno);
          return s;
        }
      }
#endif
      result->reset(new PosixWritableFile(
          fname, fd, GetLogicalBlockSize(fname, fd), options));
    } else {
      // disable mmap writes
      FileOptions no_mmap_writes_options = options;
      no_mmap_writes_options.use_mmap_writes = false;
      result->reset(new PosixWritableFile(
          fname, fd, GetLogicalBlockSize(fname, fd), no_mmap_writes_options));
    }
    return s;
  }

  IOStatus NewRandomRWFile(const std::string& fname, const FileOptions& options,
                           std::unique_ptr<FSRandomRWFile>* result,
                           IODebugContext* /*dbg*/) override {
    int fd = -1;
    int flags = cloexec_flags(O_RDWR, &options);

    while (fd < 0) {
      IOSTATS_TIMER_GUARD(open_nanos);

      fd = open(fname.c_str(), flags, GetDBFileMode(allow_non_owner_access_));
      if (fd < 0) {
        // Error while opening the file
        if (errno == EINTR) {
          continue;
        }
        return IOError("While open file for random read/write", fname, errno);
      }
    }

    SetFD_CLOEXEC(fd, &options);
    result->reset(new PosixRandomRWFile(fname, fd, options));
    return IOStatus::OK();
  }

  IOStatus NewMemoryMappedFileBuffer(
      const std::string& fname,
      std::unique_ptr<MemoryMappedFileBuffer>* result) override {
    int fd = -1;
    IOStatus status;
    int flags = cloexec_flags(O_RDWR, nullptr);

    while (fd < 0) {
      IOSTATS_TIMER_GUARD(open_nanos);
      fd = open(fname.c_str(), flags, 0644);
      if (fd < 0) {
        // Error while opening the file
        if (errno == EINTR) {
          continue;
        }
        status =
            IOError("While open file for raw mmap buffer access", fname, errno);
        break;
      }
    }
    uint64_t size;
    if (status.ok()) {
      IOOptions opts;
      status = GetFileSize(fname, opts, &size, nullptr);
    }
    void* base = nullptr;
    if (status.ok()) {
      base = mmap(nullptr, static_cast<size_t>(size), PROT_READ | PROT_WRITE,
                  MAP_SHARED, fd, 0);
      if (base == MAP_FAILED) {
        status = IOError("while mmap file for read", fname, errno);
      }
    }
    if (status.ok()) {
      result->reset(
          new PosixMemoryMappedFileBuffer(base, static_cast<size_t>(size)));
    }
    if (fd >= 0) {
      // don't need to keep it open after mmap has been called
      close(fd);
    }
    return status;
  }

  IOStatus NewDirectory(const std::string& name, const IOOptions& /*opts*/,
                        std::unique_ptr<FSDirectory>* result,
                        IODebugContext* /*dbg*/) override {
    result->reset();
    int fd;
    int flags = cloexec_flags(0, nullptr);
    {
      IOSTATS_TIMER_GUARD(open_nanos);
      fd = open(name.c_str(), flags);
    }
    if (fd < 0) {
      return IOError("While open directory", name, errno);
    } else {
      result->reset(new PosixDirectory(fd));
    }
    return IOStatus::OK();
  }

  IOStatus NewLogger(const std::string& /*fname*/, const IOOptions& /*opts*/,
                     std::shared_ptr<ROCKSDB_NAMESPACE::Logger>* /*ptr*/,
                     IODebugContext* /*dbg*/) override {
    return IOStatus::NotSupported();
  }

  IOStatus FileExists(const std::string& fname, const IOOptions& /*opts*/,
                      IODebugContext* /*dbg*/) override {
    int result = access(fname.c_str(), F_OK);

    if (result == 0) {
      return IOStatus::OK();
    }

    int err = errno;
    switch (err) {
      case EACCES:
      case ELOOP:
      case ENAMETOOLONG:
      case ENOENT:
      case ENOTDIR:
        return IOStatus::NotFound();
      default:
        assert(err == EIO || err == ENOMEM);
        return IOStatus::IOError("Unexpected error(" + ToString(err) +
                                 ") accessing file `" + fname + "' ");
    }
  }

  IOStatus GetChildren(const std::string& dir, const IOOptions& /*opts*/,
                       std::vector<std::string>* result,
                       IODebugContext* /*dbg*/) override {
    result->clear();
    DIR* d = opendir(dir.c_str());
    if (d == nullptr) {
      switch (errno) {
        case EACCES:
        case ENOENT:
        case ENOTDIR:
          return IOStatus::NotFound();
        default:
          return IOError("While opendir", dir, errno);
      }
    }
    struct dirent* entry;
    while ((entry = readdir(d)) != nullptr) {
      result->push_back(entry->d_name);
    }
    closedir(d);
    return IOStatus::OK();
  }

  IOStatus DeleteFile(const std::string& fname, const IOOptions& /*opts*/,
                      IODebugContext* /*dbg*/) override {
    IOStatus result;
    if (unlink(fname.c_str()) != 0) {
      result = IOError("while unlink() file", fname, errno);
    }
    return result;
  }

  IOStatus CreateDir(const std::string& name, const IOOptions& /*opts*/,
                     IODebugContext* /*dbg*/) override {
    IOStatus result;
    if (mkdir(name.c_str(), 0755) != 0) {
      result = IOError("While mkdir", name, errno);
    }
    return result;
  }

  IOStatus CreateDirIfMissing(const std::string& name,
                              const IOOptions& /*opts*/,
                              IODebugContext* /*dbg*/) override {
    IOStatus result;
    if (mkdir(name.c_str(), 0755) != 0) {
      if (errno != EEXIST) {
        result = IOError("While mkdir if missing", name, errno);
      } else if (!DirExists(name)) {  // Check that name is actually a
                                      // directory.
        // Message is taken from mkdir
        result =
            IOStatus::IOError("`" + name + "' exists but is not a directory");
      }
    }
    return result;
  }

  IOStatus DeleteDir(const std::string& name, const IOOptions& /*opts*/,
                     IODebugContext* /*dbg*/) override {
    IOStatus result;
    if (rmdir(name.c_str()) != 0) {
      result = IOError("file rmdir", name, errno);
    }
    return result;
  }

  IOStatus GetFileSize(const std::string& fname, const IOOptions& /*opts*/,
                       uint64_t* size, IODebugContext* /*dbg*/) override {
    IOStatus s;
    struct stat sbuf;
    if (stat(fname.c_str(), &sbuf) != 0) {
      *size = 0;
      s = IOError("while stat a file for size", fname, errno);
    } else {
      *size = sbuf.st_size;
    }
    return s;
  }

  IOStatus GetFileModificationTime(const std::string& fname,
                                   const IOOptions& /*opts*/,
                                   uint64_t* file_mtime,
                                   IODebugContext* /*dbg*/) override {
    struct stat s;
    if (stat(fname.c_str(), &s) != 0) {
      return IOError("while stat a file for modification time", fname, errno);
    }
    *file_mtime = static_cast<uint64_t>(s.st_mtime);
    return IOStatus::OK();
  }

  IOStatus RenameFile(const std::string& src, const std::string& target,
                      const IOOptions& /*opts*/,
                      IODebugContext* /*dbg*/) override {
    IOStatus result;
    if (rename(src.c_str(), target.c_str()) != 0) {
      result = IOError("While renaming a file to " + target, src, errno);
    }
    return result;
  }

  IOStatus LinkFile(const std::string& src, const std::string& target,
                    const IOOptions& /*opts*/,
                    IODebugContext* /*dbg*/) override {
    IOStatus result;
    if (link(src.c_str(), target.c_str()) != 0) {
      if (errno == EXDEV) {
        return IOStatus::NotSupported("No cross FS links allowed");
      }
      result = IOError("while link file to " + target, src, errno);
    }
    return result;
  }

  IOStatus NumFileLinks(const std::string& fname, const IOOptions& /*opts*/,
                        uint64_t* count, IODebugContext* /*dbg*/) override {
    struct stat s;
    if (stat(fname.c_str(), &s) != 0) {
      return IOError("while stat a file for num file links", fname, errno);
    }
    *count = static_cast<uint64_t>(s.st_nlink);
    return IOStatus::OK();
  }

  IOStatus AreFilesSame(const std::string& first, const std::string& second,
                        const IOOptions& /*opts*/, bool* res,
                        IODebugContext* /*dbg*/) override {
    struct stat statbuf[2];
    if (stat(first.c_str(), &statbuf[0]) != 0) {
      return IOError("stat file", first, errno);
    }
    if (stat(second.c_str(), &statbuf[1]) != 0) {
      return IOError("stat file", second, errno);
    }

    if (major(statbuf[0].st_dev) != major(statbuf[1].st_dev) ||
        minor(statbuf[0].st_dev) != minor(statbuf[1].st_dev) ||
        statbuf[0].st_ino != statbuf[1].st_ino) {
      *res = false;
    } else {
      *res = true;
    }
    return IOStatus::OK();
  }

  IOStatus LockFile(const std::string& fname, const IOOptions& /*opts*/,
                    FileLock** lock, IODebugContext* /*dbg*/) override {
    *lock = nullptr;
    IOStatus result;

    LockHoldingInfo lhi;
    int64_t current_time = 0;
    // Ignore status code as the time is only used for error message.
    Env::Default()->GetCurrentTime(&current_time);
    lhi.acquire_time = current_time;
    lhi.acquiring_thread = Env::Default()->GetThreadID();

    mutex_locked_files.Lock();
    // If it already exists in the locked_files set, then it is already locked,
    // and fail this lock attempt. Otherwise, insert it into locked_files.
    // This check is needed because fcntl() does not detect lock conflict
    // if the fcntl is issued by the same thread that earlier acquired
    // this lock.
    // We must do this check *before* opening the file:
    // Otherwise, we will open a new file descriptor. Locks are associated with
    // a process, not a file descriptor and when *any* file descriptor is
    // closed, all locks the process holds for that *file* are released
    const auto it_success = locked_files.insert({fname, lhi});
    if (it_success.second == false) {
      mutex_locked_files.Unlock();
      errno = ENOLCK;
      LockHoldingInfo& prev_info = it_success.first->second;
      // Note that the thread ID printed is the same one as the one in
      // posix logger, but posix logger prints it hex format.
      return IOError("lock hold by current process, acquire time " +
                         ToString(prev_info.acquire_time) +
                         " acquiring thread " +
                         ToString(prev_info.acquiring_thread),
                     fname, errno);
    }

    int fd;
    int flags = cloexec_flags(O_RDWR | O_CREAT, nullptr);

    {
      IOSTATS_TIMER_GUARD(open_nanos);
      fd = open(fname.c_str(), flags, 0644);
    }
    if (fd < 0) {
      result = IOError("while open a file for lock", fname, errno);
    } else if (LockOrUnlock(fd, true) == -1) {
      // if there is an error in locking, then remove the pathname from
      // lockedfiles
      locked_files.erase(fname);
      result = IOError("While lock file", fname, errno);
      close(fd);
    } else {
      SetFD_CLOEXEC(fd, nullptr);
      PosixFileLock* my_lock = new PosixFileLock;
      my_lock->fd_ = fd;
      my_lock->filename = fname;
      *lock = my_lock;
    }

    mutex_locked_files.Unlock();
    return result;
  }

  IOStatus UnlockFile(FileLock* lock, const IOOptions& /*opts*/,
                      IODebugContext* /*dbg*/) override {
    PosixFileLock* my_lock = reinterpret_cast<PosixFileLock*>(lock);
    IOStatus result;
    mutex_locked_files.Lock();
    // If we are unlocking, then verify that we had locked it earlier,
    // it should already exist in locked_files. Remove it from locked_files.
    if (locked_files.erase(my_lock->filename) != 1) {
      errno = ENOLCK;
      result = IOError("unlock", my_lock->filename, errno);
    } else if (LockOrUnlock(my_lock->fd_, false) == -1) {
      result = IOError("unlock", my_lock->filename, errno);
    }
    close(my_lock->fd_);
    delete my_lock;
    mutex_locked_files.Unlock();
    return result;
  }

  IOStatus GetAbsolutePath(const std::string& db_path,
                           const IOOptions& /*opts*/, std::string* output_path,
                           IODebugContext* /*dbg*/) override {
    if (!db_path.empty() && db_path[0] == '/') {
      *output_path = db_path;
      return IOStatus::OK();
    }

    char the_path[256];
    char* ret = getcwd(the_path, 256);
    if (ret == nullptr) {
      return IOStatus::IOError(strerror(errno));
    }

    *output_path = ret;
    return IOStatus::OK();
  }

  IOStatus GetTestDirectory(const IOOptions& /*opts*/, std::string* result,
                            IODebugContext* /*dbg*/) override {
    const char* env = getenv("TEST_TMPDIR");
    if (env && env[0] != '\0') {
      *result = env;
    } else {
      char buf[100];
      snprintf(buf, sizeof(buf), "/tmp/rocksdbtest-%d", int(geteuid()));
      *result = buf;
    }
    // Directory may already exist
    {
      IOOptions opts;
      CreateDir(*result, opts, nullptr);
    }
    return IOStatus::OK();
  }

  IOStatus GetFreeSpace(const std::string& fname, const IOOptions& /*opts*/,
                        uint64_t* free_space,
                        IODebugContext* /*dbg*/) override {
    struct statvfs sbuf;

    if (statvfs(fname.c_str(), &sbuf) < 0) {
      return IOError("While doing statvfs", fname, errno);
    }

    // sbuf.bfree is total free space available to root
    // sbuf.bavail is total free space available to unprivileged user
    //  sbuf.bavail <= sbuf.bfree ... pick correct based upon effective user id
    if (geteuid()) {
      // non-zero user is unprivileged, or -1 if error.  take more conservative
      // size
      *free_space = ((uint64_t)sbuf.f_bsize * sbuf.f_bavail);
    } else {
      // root user can access all disk space
      *free_space = ((uint64_t)sbuf.f_bsize * sbuf.f_bfree);
    }
    return IOStatus::OK();
  }

  FileOptions OptimizeForLogWrite(const FileOptions& file_options,
                                 const DBOptions& db_options) const override {
    FileOptions optimized = file_options;
    optimized.use_mmap_writes = false;
    optimized.use_direct_writes = false;
    optimized.bytes_per_sync = db_options.wal_bytes_per_sync;
    // TODO(icanadi) it's faster if fallocate_with_keep_size is false, but it
    // breaks TransactionLogIteratorStallAtLastRecord unit test. Fix the unit
    // test and make this false
    optimized.fallocate_with_keep_size = true;
    optimized.writable_file_max_buffer_size =
        db_options.writable_file_max_buffer_size;
    return optimized;
  }

  FileOptions OptimizeForManifestWrite(
      const FileOptions& file_options) const override {
    FileOptions optimized = file_options;
    optimized.use_mmap_writes = false;
    optimized.use_direct_writes = false;
    optimized.fallocate_with_keep_size = true;
    return optimized;
  }
#ifdef OS_LINUX
  Status RegisterDbPaths(const std::vector<std::string>& paths) override {
    return logical_block_size_cache_.RefAndCacheLogicalBlockSize(paths);
  }
  Status UnregisterDbPaths(const std::vector<std::string>& paths) override {
    logical_block_size_cache_.UnrefAndTryRemoveCachedLogicalBlockSize(paths);
    return Status::OK();
  }
#endif
 private:
  bool checkedDiskForMmap_;
  bool forceMmapOff_;  // do we override Env options?

  // Returns true iff the named directory exists and is a directory.
  virtual bool DirExists(const std::string& dname) {
    struct stat statbuf;
    if (stat(dname.c_str(), &statbuf) == 0) {
      return S_ISDIR(statbuf.st_mode);
    }
    return false;  // stat() failed return false
  }

  bool SupportsFastAllocate(const std::string& path) {
#ifdef ROCKSDB_FALLOCATE_PRESENT
    struct statfs s;
    if (statfs(path.c_str(), &s)) {
      return false;
    }
    switch (s.f_type) {
      case EXT4_SUPER_MAGIC:
        return true;
      case XFS_SUPER_MAGIC:
        return true;
      case TMPFS_MAGIC:
        return true;
      default:
        return false;
    }
#else
    (void)path;
    return false;
#endif
  }

#if defined(ROCKSDB_IOURING_PRESENT)
  // io_uring instance
  std::unique_ptr<ThreadLocalPtr> thread_local_io_urings_;
#endif

  size_t page_size_;

  // If true, allow non owner read access for db files. Otherwise, non-owner
  //  has no access to db files.
  bool allow_non_owner_access_;

#ifdef OS_LINUX
  static LogicalBlockSizeCache logical_block_size_cache_;
#endif
  static size_t GetLogicalBlockSize(const std::string& fname, int fd);
};

#ifdef OS_LINUX
LogicalBlockSizeCache PosixFileSystem::logical_block_size_cache_;
#endif

size_t PosixFileSystem::GetLogicalBlockSize(const std::string& fname, int fd) {
#ifdef OS_LINUX
  return logical_block_size_cache_.GetLogicalBlockSize(fname, fd);
#else
  (void) fname;
  return PosixHelper::GetLogicalBlockSizeOfFd(fd);
#endif
}

PosixFileSystem::PosixFileSystem()
    : checkedDiskForMmap_(false),
      forceMmapOff_(false),
      page_size_(getpagesize()),
      allow_non_owner_access_(true) {
#if defined(ROCKSDB_IOURING_PRESENT)
  // Test whether IOUring is supported, and if it does, create a managing
  // object for thread local point so that in the future thread-local
  // io_uring can be created.
  struct io_uring* new_io_uring = CreateIOUring();
  if (new_io_uring != nullptr) {
    thread_local_io_urings_.reset(new ThreadLocalPtr(DeleteIOUring));
    delete new_io_uring;
  }
#endif
}

}  // namespace

//
// Default Posix FileSystem
//
std::shared_ptr<FileSystem> FileSystem::Default() {
  static PosixFileSystem default_fs;
  static std::shared_ptr<PosixFileSystem> default_fs_ptr(
      &default_fs, [](PosixFileSystem*) {});
  return default_fs_ptr;
}

}  // namespace ROCKSDB_NAMESPACE


text:
import unittest
from functools import partial

import hypothesis.strategies as st
import numpy as np
from auto_scan_test import PassAutoScanTest
from program_config import OpConfig, ProgramConfig, TensorConfig

class TestMulLstmFusePass(PassAutoScanTest):
    def is_program_valid(self, program_config: ProgramConfig) -> bool:
        return True

    def sample_program_config(self, draw):
        x_col = draw(st.sampled_from([1]))
        y_col = draw(st.sampled_from([1]))
        use_peepholes = draw(st.booleans())
        is_reverse = draw(st.booleans())
        gate_activation = draw(st.sampled_from(["sigmoid"]))
        cell_activation = draw(st.sampled_from(["tanh", "relu", "identity"]))
        candidate_activation = draw(
            st.sampled_from(["tanh", "relu", "identity"])
        )
        batch_size = draw(st.integers(min_value=1, max_value=40))

        def generate_input():
            shape = [batch_size, 128, 6, 120]
            return np.full(shape, 0.01).astype(np.float32)

        def generate_weight(shape):
            return np.full(shape, 0.0001).astype(np.float32)

        im2sequence_op = OpConfig(
            type="im2sequence",
            inputs={"X": ["input_data"]},
            outputs={"Out": ["seq_out"]},
            attrs={
                "kernels": [6, 1],
                "out_stride": [1, 1],
                "paddings": [0, 0, 0, 0],
                "strides": [1, 1],
            },
        )

        mul_op = OpConfig(
            type="mul",
            inputs={"X": ["seq_out"], "Y": ["mul_weight"]},
            outputs={"Out": ["mul_out"]},
            attrs={"x_num_col_dims": x_col, "y_num_col_dims": y_col},
        )

        lstm_op = OpConfig(
            type="lstm",
            inputs={
                "Input": ["mul_out"],
                "Weight": ["lstm_weight"],
                "Bias": ["lstm_bias"],
            },
            outputs={
                "Hidden": ["lstm_hidden"],
                "Cell": ["lstm_cell"],
                "BatchGate": ["lstm_gate"],
                "BatchCellPreAct": ["lstm_batch_cell"],
            },
            attrs={
                'use_peepholes': use_peepholes,
                'is_reverse': is_reverse,
                'gate_activation': gate_activation,
                'cell_activation': cell_activation,
                'candidate_activation': candidate_activation,
                'is_test': True,
            },
        )

        model_net = [im2sequence_op, mul_op, lstm_op]

        if use_peepholes:
            lstm_bias_shape = [1, 1050]
        else:
            lstm_bias_shape = [1, 600]

        program_config = ProgramConfig(
            ops=model_net,
            weights={
                "mul_weight": TensorConfig(
                    data_gen=partial(generate_weight, [768, 600])
                ),
                "lstm_weight": TensorConfig(
                    data_gen=partial(generate_weight, [150, 600])
                ),
                "lstm_bias": TensorConfig(
                    data_gen=partial(generate_weight, lstm_bias_shape)
                ),
            },
            inputs={
                "input_data": TensorConfig(data_gen=partial(generate_input)),
            },
            outputs=["lstm_hidden"],
        )

        return program_config

    def sample_predictor_configs(self, program_config):
        config = self.create_inference_config()
        yield config, ["im2sequence", "fusion_lstm"], (1e-5, 1e-5)

    def test(self):
        self.run_and_statis(
            quant=False, max_duration=300, passes=["mul_lstm_fuse_pass"]
        )

if __name__ == "__main__":
    unittest.main()


text:
<?php

namespace SilverStripe\GraphQL\Auth;

use SilverStripe\Control\HTTPRequest;
use SilverStripe\Core\ClassInfo;
use SilverStripe\Core\Config\Configurable;
use SilverStripe\Core\Injector\Injector;
use SilverStripe\ORM\ValidationException;
use SilverStripe\Security\Member;

/**
 * The authentication Handler is responsible for handling authentication requirements and providing a Member
 * to the Manager if required, so it can be used in request contexts.
 */
class Handler
{
    use Configurable;

    /**
     * @config
     * @var array
     *
     * @internal Experimental config:
     * @todo Move this to a per-schema configuration and refer to this schema from the current endpoint
     * @link https://github.com/silverstripe/silverstripe-graphql/issues/58
     * @link https://github.com/silverstripe/silverstripe-graphql/issues/52
     */
    private static $authenticators = [
        [
            'class' => MemberAuthenticator::class,
            'priority' => 10,
        ]
    ];

    /**
     * If required, enforce authentication for non-session authenticated requests. The Member returned from the
     * authentication method will returned for use in the OperationResolver context.
     *
     * Authenticators are defined in configuration. @see AuthenticatorInterface::authenticate.
     *
     * @param  HTTPRequest $request
     * @return Member|false         If authentication was successful the Member is returned. False if no
     *                              authenticators are configured.
     * @throws ValidationException  If authentication is attempted and fails
     */
    public function requireAuthentication(HTTPRequest $request)
    {
        $authenticator = $this->getAuthenticator($request);
        if (!$authenticator) {
            return false;
        }

        $member = $authenticator->authenticate($request);
        if ($member instanceof Member) {
            return $member;
        }
        // Note: The authenticator class itself may also throw an exception when called
        throw new ValidationException('Authentication failed.', 401);
    }

    /**
     * Returns the first configured authenticator by highest priority, or null if none are configured
     *
     * @param HTTPRequest $request
     * @return null|AuthenticatorInterface
     */
    public function getAuthenticator(HTTPRequest $request): ?AuthenticatorInterface
    {
        // Get list of default authenticators
        $authenticators = $this->config()->get('authenticators');
        if (empty($authenticators)) {
            return null;
        }

        // Build authenticator from first class
        $this->prioritiseAuthenticators($authenticators);
        foreach ($authenticators as $authenticatorConfig) {
            $authenticator = $this->buildAuthenticator($authenticatorConfig['class']);
            if ($authenticator->isApplicable($request)) {
                return $authenticator;
            }
        }
        return null;
    }

    /**
     * @param string $authenticator
     * @return AuthenticatorInterface
     * @throws ValidationException
     */
    protected function buildAuthenticator(string $authenticator): AuthenticatorInterface
    {
        if (!ClassInfo::classImplements($authenticator, AuthenticatorInterface::class)) {
            throw new ValidationException(
                sprintf('%s must implement %s!', $authenticator, AuthenticatorInterface::class)
            );
        }
        return Injector::inst()->get($authenticator);
    }

    /**
     * Sort the configured authenticators by their "priority" (highest to lowest). This allows modules to
     * contribute to the decision of which authenticator should be used first. Users can rewrite this in their
     * own configuration if necessary.
     *
     * @param array $authenticators
     */
    public function prioritiseAuthenticators(array &$authenticators): void
    {
        usort($authenticators, function ($a, $b) {
            // Set some default values
            if (!isset($a['priority'])) {
                $a['priority'] = 10;
            }
            if (!isset($b['priority'])) {
                $b['priority'] = 10;
            }

            return $b['priority'] - $a['priority'];
        });
    }
}


text:
package MainPack;

import RSSParser.Feed;
import javafx.application.Platform;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.geometry.Pos;
import javafx.scene.control.*;

import java.net.URL;
import java.util.ArrayList;
import java.util.ResourceBundle;

public class Controller
        implements Initializable {

    @FXML
    private Button searchButton, downloadButton, openButton;
    @FXML
    private ComboBox searchComboBox;
    @FXML
    private ComboBox torrentComboBox;
    @FXML
    private Label descriptionLabel;
    @FXML
    private ToggleButton autoToggle;

    private boolean isFeedRead = false;

    @Override // This method is called by the FXMLLoader when initialization is complete
    public void initialize(URL fxmlFileLocation, ResourceBundle resources) {

        setToolTips();
        setAutoButton();
        setSearchComboBox();
        setButtons();

        //Adds a shutdown hook that passes the state of the AutoMode Button to be written to a file
        Runtime.getRuntime().addShutdownHook(new Thread() {
            @Override
            public void run() {
                FileHandler file = new FileHandler();
                file.setAutoSettings(autoToggle.isSelected());
            }
        });
    }

    private void setButtons() {

        // A little hack to make the focused button trigger when the Enter key is pressed
        // Changes the default button to the one that is focused, which causes the button to change color too
        searchButton.defaultButtonProperty().bind(searchButton.focusedProperty());
        downloadButton.defaultButtonProperty().bind(downloadButton.focusedProperty());
        openButton.defaultButtonProperty().bind(openButton.focusedProperty());

        searchButton.setOnAction(event -> searchTorrent());
        downloadButton.setOnAction(event -> openMagnetLink(torrentComboBox.getSelectionModel().getSelectedIndex()));
        torrentComboBox.setOnAction(event -> {
            //Reads the description only when it's confirmed the feed has been read to prevent NullPointerExceptions
            if (isFeedRead) {
                showDescription();
            }
        });
        openButton.setOnAction(event -> openPageLink(torrentComboBox.getSelectionModel().getSelectedIndex()));
    }

    private void setAutoButton() {
        FileHandler file = new FileHandler();
        autoToggle.setSelected(file.getAutoSetting());
    }

    private void setSearchComboBox() {

        searchComboBox.getStyleClass().add("combo-box1");
        Platform.runLater(() -> searchComboBox.requestFocus());

        ObservableList<String> options =
                FXCollections.observableArrayList(
                        "Movies",
                        "Games",
                        "TV",
                        "Music"
                );

        searchComboBox.setItems(options);

        searchComboBox.setOnAction(new EventHandler<ActionEvent>() {
            @Override
            public void handle(ActionEvent event) {
                //Basically if anything from the list is selected this is triggered
                if (searchComboBox.getSelectionModel().getSelectedIndex() != -1) {
                    autoToggle.setSelected(false);
                    searchTorrent();
                }
            }
        });
    }

    public void searchTorrent() {

        try {
            String torrentName = searchComboBox.getSelectionModel().getSelectedItem().toString();
            isFeedRead = false;
            searchFeed(torrentName);
            Platform.runLater(() -> torrentComboBox.requestFocus());  //Giving focus to the ComboBox once the searching is completed.
            isFeedRead = true;
        } catch (NullPointerException e) {
            descriptionLabel.setText("I got nothing");
        }
    }

    private void setToolTips() {
        //There are tooltips in the app?!
        openButton.setTooltip(new Tooltip("Open the webpage for the torrent"));
        autoToggle.setTooltip(new Tooltip("Instantly add the best torrent to your BitTorrent client"));
        downloadButton.setTooltip(new Tooltip("Add selected torrent to your BitTorrent client"));
    }

    private void setTorrentComboBox(ObservableList torrentList) {
        if (torrentList.size() > 0) {
            torrentComboBox.setItems(torrentList);
            torrentComboBox.getSelectionModel().select(0);
            downloadButton.setDisable(false);
            openButton.setDisable(false);
            showDescription();
        } else {
            downloadButton.setDisable(true);
            openButton.setDisable(true);
        }
    }

    private void openMagnetLink(int selectedIndex) {
        ArrayList<String> tempList;
        TorrentData torrentData = TorrentData.getInstance();
        tempList = torrentData.getMagnetLinkList();
        String torrentName = tempList.get(selectedIndex);
        LinkHandler linkHandler = new LinkHandler();
        linkHandler.openMagnetLink(torrentName);
    }

    private void openPageLink(int selectedIndex) {
        ArrayList<String> tempList;
        TorrentData torrentData = TorrentData.getInstance();
        LinkHandler linkHandler = new LinkHandler();
        tempList = torrentData.getTorrentPageLinksList();
        String torrentName = tempList.get(selectedIndex);
        torrentName = linkHandler.addSuffix(torrentName);
        linkHandler.openWebLink(torrentName);
    }

    private void searchFeed(String torrentName) {
        FeedReader feedReader = new FeedReader();
        Feed feed = feedReader.getFeed(torrentName);
        feedReader.createTorrentDataLists(feed);
        TorrentData torrentData = TorrentData.getInstance();
        ObservableList<String> torrentList = FXCollections.observableArrayList(torrentData.getTorrentNameList());
        setTorrentComboBox(torrentList);
        // This is the amazing state of the art Independent Intelligent-O-TorrentPicker (IDIOT)
        // It opens the topmost torrent in the list
        if (autoToggle.isSelected()) {
            openMagnetLink(0);
        }
    }

    private void showDescription() {
        TorrentData torrentData = TorrentData.getInstance();
        int index = torrentComboBox.getSelectionModel().getSelectedIndex();
        descriptionLabel.setAlignment(Pos.CENTER);
        descriptionLabel.setText(torrentData.getTorrentDescriptionList().get(index));
    }

}


text:
CLASS({
  name: 'PersonCompleter',
  package: 'foam.apps.quickbug.model',
  properties: [
    { model_: 'foam.core.types.DAOProperty', name: 'autocompleteDao' }
  ],
  imports: [
    'issuePersonDAO'
  ],
  requires: [
    'foam.apps.quickbug.model.imported.IssuePerson'
  ],
  methods: {
    autocomplete: function(data) {
      var src = this.issuePersonDAO;
      var dao = src.where(
        data ?
          STARTS_WITH_IC(this.IssuePerson.NAME, data) :
          TRUE);

      var self = this;
      dao.limit(2).select()(function(objs) {
        if ( objs.length === 1 && self.f(objs[0]) === data ) {
          self.autocompleteDao = src.where(FALSE);
        } else {
          self.autocompleteDao = dao;
        }
      });
    },
    f: function(o) { return o.name; }
  }
});


text:
var app = angular.module("app", ['ui.bootstrap', 'ngCookies', 'ui.med']);

app.config(['$httpProvider', function ($httpProvider) {
    $httpProvider.defaults.headers.common['X-Requested-With'] = 'XMLHttpRequest';
    $httpProvider.defaults.xsrfCookieName = '__RequestVerificationToken';
    $httpProvider.defaults.cache = false;
    $httpProvider.interceptors.push(function () {
        return {
            'request': function (config) {
                if (config.method === 'POST') {
                    var antiForgery = angular.element('input[name="__RequestVerificationToken"]');
                    if (antiForgery.length > 0) {
                        config.headers['X-Request-Verification-Token'] = antiForgery.val();
                    }
                }
                return config;
            }
        };
    });

}]);

app.controller('rootController', [
    '$scope', function ($scope) {
        $scope.init = function(currentUserId) {
            $scope.currentUserId = currentUserId;
        }
    }
]);