问:
Python: use mysqldb to import a MySQL table as a dictionary?
Anyone know how I can use mysqldb to turn a MySQL table, with lots of rows, into a list of dictionary objects in Python?

I mean turning a set of MySQL rows, with columns 'a', 'b', and 'c', into a Python object that that looks like this:

```<code>data = [ { 'a':'A', 'b':(2, 4), 'c':3.0 }, { 'a':'Q', 'b':(1, 4), 'c':5.0 }, { 'a':'T', 'b':(2, 8), 'c':6.1 } ]
</code>```

Thanks :)

答:
using PYTHON >= 3.6; here it works by doing this:

OBS.: here I'm using 2 databases types ORACLE 12g and MYSQL 5.6 ; and the main server is the ORACLE, mysql is used only by some parts of the software ... then ... the code of my connection class:

here is comming from shellscript code... then i just bring a string to show here...

myp3 = 'XXXXXXXXXXXXXXXXXXXXXXXXXX PASSWD MYSQL XXXXXXXXXXXXXXXXXXXXXXXXXXX'

```<code>import cx_Oracle
import MySQLdb
import MySQLdb.cursors

class oracle(object):
    def __init__(self, serverORACLE=3, MYSQL='N', serverMYSQL=3):
        ## ORACLE connection!
        try:

        if serverORACLE == 1:
            self.db = cx_Oracle.connect('sys/[xxxxPASSWORDxxxxx]@[xxxxxIP/HOSTxxxxxx]:1521/DATABASE_X')
            print('ORACLE [ system/[xxxxPASSWORDxxxxx]@[xxxxxIP/HOSTxxxxxx]:1521 ] ===> CONNECTED')

        if serverORACLE == 2:
            self.db = cx_Oracle.connect('system/[xxxxPASSWORDxxxxx]@[xxxxxIP/HOSTxxxxxx]:1521/DATABASE_X')
            print('ORACLE [ system/[xxxxPASSWORDxxxxx]@[xxxxxIP/HOSTxxxxxx]:1521 ] ===> CONNECTED')

        if serverORACLE == 3:
            self.db = cx_Oracle.connect('userLEVEL1/[xxxxPASSWORDxxxxx]@[xxxxxIP/HOSTxxxxxx]:1521/DATABASE_X')
            print('ORACLE [ userLEVEL1/[xxxxPASSWORDxxxxx]@[xxxxxIP/HOSTxxxxxx]:1521 ] ===> CONNECTED')

        if serverORACLE == 4:
            self.db = cx_Oracle.connect('userLEVEL2/[xxxxPASSWORDxxxxx]@[xxxxxIP/HOSTxxxxxx]:1521/DATABASE_X')
            print('ORACLE [ userLEVEL2/[xxxxPASSWORDxxxxx]@[xxxxxIP/HOSTxxxxxx]:1521 ] ===> CONNECTED')

        self.cursor = self.db.cursor()

    except Exception as e:
        count = 0
        S1 = ''
        for W in str(e):
            S1+=W
            count+=1
            if count >= 40:
                S1+=' \n'
                count = 0
        print('\n\n ORACLE DATABASE ===> CONECTION FAILED!',
                    '\n error - module: ', S1)

    ##conexao MYSQL
    if MYSQL=='S':
        try:
            if serverMYSQL == 1:
                self.dbMySQL = MySQLdb.connect(user='root', host='XXXXXX HOST XXXXX', use_unicode=True, cursorclass=MySQLdb.cursors.DictCursor,
                                                charset='utf8', port=3306, passwd=myp3, db='XXXX')
                print('MySQL [ root / XXXXXX HOST XXXXX:3306 ] ===> CONNECTED')

            if serverMYSQL == 2:
                self.dbMySQL = MySQLdb.connect(user='XXXX USER XXXXX', host='XXXXXX HOST XXXXX', use_unicode=True, cursorclass=MySQLdb.cursors.DictCursor,
                                                charset='utf8', port=3306, passwd=myp3, db='XXXX')
                print('MySQL [ XXXX USER XXXXX / XXXXXX HOST XXXXX:3306 ] ===> CONNECTED')

            self.cursorMYSQL = self.dbMySQL.cursor()

        except Exception as e:
            count = 0
            S1 = ''
            for W in str(e):
                S1+=W
                count+=1
                if count >= 40:
                    S1+=' \n'
                    count = 0
            print('\n\n MYSQL DATABASE ===> CONECTION FAILED!',
                    '\n error - module: ', S1)
</code>```

"""

ContentLicense: CC BY-SA 2.5

Body:
Anyone know how I can use mysqldb to turn a MySQL table, with lots of rows, into a list of dictionary objects in Python?

I mean turning a set of MySQL rows, with columns 'a', 'b', and 'c', into a Python object that that looks like this:

data = [ { 'a':'A', 'b':(2, 4), 'c':3.0 }, { 'a':'Q', 'b':(1, 4), 'c':5.0 }, { 'a':'T', 'b':(2, 8), 'c':6.1 } ]

Thanks :)

Body:
using PYTHON >= 3.6; here it works by doing this:

OBS.: here I'm using 2 databases types ORACLE 12g and MYSQL 5.6 ; and the main server is the ORACLE, mysql is used only by some parts of the software ... then ... the code of my connection class:

here is comming from shellscript code... then i just bring a string to show here...

myp3 = 'XXXXXXXXXXXXXXXXXXXXXXXXXX PASSWD MYSQL XXXXXXXXXXXXXXXXXXXXXXXXXXX'

import cx_Oracle
import MySQLdb
import MySQLdb.cursors

class oracle(object):
    def __init__(self, serverORACLE=3, MYSQL='N', serverMYSQL=3):
        ## ORACLE connection!
        try:

        if serverORACLE == 1:
            self.db = cx_Oracle.connect('sys/[xxxxPASSWORDxxxxx]@[xxxxxIP/HOSTxxxxxx]:1521/DATABASE_X')
            print('ORACLE [ system/[xxxxPASSWORDxxxxx]@[xxxxxIP/HOSTxxxxxx]:1521 ] ===> CONNECTED')

        if serverORACLE == 2:
            self.db = cx_Oracle.connect('system/[xxxxPASSWORDxxxxx]@[xxxxxIP/HOSTxxxxxx]:1521/DATABASE_X')
            print('ORACLE [ system/[xxxxPASSWORDxxxxx]@[xxxxxIP/HOSTxxxxxx]:1521 ] ===> CONNECTED')

        if serverORACLE == 3:
            self.db = cx_Oracle.connect('userLEVEL1/[xxxxPASSWORDxxxxx]@[xxxxxIP/HOSTxxxxxx]:1521/DATABASE_X')
            print('ORACLE [ userLEVEL1/[xxxxPASSWORDxxxxx]@[xxxxxIP/HOSTxxxxxx]:1521 ] ===> CONNECTED')

        if serverORACLE == 4:
            self.db = cx_Oracle.connect('userLEVEL2/[xxxxPASSWORDxxxxx]@[xxxxxIP/HOSTxxxxxx]:1521/DATABASE_X')
            print('ORACLE [ userLEVEL2/[xxxxPASSWORDxxxxx]@[xxxxxIP/HOSTxxxxxx]:1521 ] ===> CONNECTED')

        self.cursor = self.db.cursor()

    except Exception as e:
        count = 0
        S1 = ''
        for W in str(e):
            S1+=W
            count+=1
            if count >= 40:
                S1+=' \n'
                count = 0
        print('\n\n ORACLE DATABASE ===> CONECTION FAILED!',
                    '\n error - module: ', S1)

    ##conexao MYSQL
    if MYSQL=='S':
        try:
            if serverMYSQL == 1:
                self.dbMySQL = MySQLdb.connect(user='root', host='XXXXXX HOST XXXXX', use_unicode=True, cursorclass=MySQLdb.cursors.DictCursor,
                                                charset='utf8', port=3306, passwd=myp3, db='XXXX')
                print('MySQL [ root / XXXXXX HOST XXXXX:3306 ] ===> CONNECTED')

            if serverMYSQL == 2:
                self.dbMySQL = MySQLdb.connect(user='XXXX USER XXXXX', host='XXXXXX HOST XXXXX', use_unicode=True, cursorclass=MySQLdb.cursors.DictCursor,
                                                charset='utf8', port=3306, passwd=myp3, db='XXXX')
                print('MySQL [ XXXX USER XXXXX / XXXXXX HOST XXXXX:3306 ] ===> CONNECTED')

            self.cursorMYSQL = self.dbMySQL.cursor()

        except Exception as e:
            count = 0
            S1 = ''
            for W in str(e):
                S1+=W
                count+=1
                if count >= 40:
                    S1+=' \n'
                    count = 0
            print('\n\n MYSQL DATABASE ===> CONECTION FAILED!',
                    '\n error - module: ', S1)

"""


来源: stackexchange

问:
How can I select only unordered factors from my data frame?
I cannot find a simple way to select only columns of nominal (unordered factor) variables from a data frame.

I've tried using the expression "!is.ordered" to grab factor variables that are not ordered, but that throws an error.

```<code>df=mtcars
df$am=as.factor(df$am)
df$carb=as.ordered(df$carb)
df2=df[,lapply(df,(is.factor & !is.ordered))]
</code>```

Error in !is.ordered : invalid argument type

This doesn't work either:

```<code>df=mtcars
df$am=as.factor(df$am)
df$carb=as.ordered(df$carb)
df2=df[,sapply(df, is.factor)]
ords=unlist(lapply(df2,is.ordered))
df2=df2[,-ords]
names(df2)
</code>```

NULL

答:
Try it with dplyr:

```<code>dplyr::select_if(df, ~ !is.ordered(.))
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I cannot find a simple way to select only columns of nominal (unordered factor) variables from a data frame.

I've tried using the expression "!is.ordered" to grab factor variables that are not ordered, but that throws an error.

df=mtcars
df$am=as.factor(df$am)
df$carb=as.ordered(df$carb)
df2=df[,lapply(df,(is.factor & !is.ordered))]

Error in !is.ordered : invalid argument type

This doesn't work either:

df=mtcars
df$am=as.factor(df$am)
df$carb=as.ordered(df$carb)
df2=df[,sapply(df, is.factor)]
ords=unlist(lapply(df2,is.ordered))
df2=df2[,-ords]
names(df2)

NULL

Body:
Try it with dplyr:

dplyr::select_if(df, ~ !is.ordered(.))


问:
Oracle - How to get date from YEAR, WEEKNUM and WEEKDAY?
I need to find the date of particular year, week, and weekday in oracle.
Is there a built-in function for this in oracle? or how can I achieve this?

Ex: If Year=2019, Week=22, Day=2(Tuesday), Then date should be '28-05-2019'.

答:
Logically, the ISO week number is the occurrence of Thursdays in that (Gregorian) calendar year. The ISO year of an ISO week, is the Gregorian year in which the Thursday of that ISO week falls.

In the ISO schema, weeks always contain 7 days. Weeks start on a Monday, finish on a Sunday, and the days of that week are numbered 1-7.

This weekday numbering scheme often differs from that returned from built-in WEEKDAY functions and similar in different software packages (or requires particular database settings), which is something to be aware of. You will need available a function that returns the weekday of a particular date according to the ISO numbering scheme.

The first Thursday of the year can occur anywhere in the range 01-Jan to 07-Jan.

If the first Thursday falls on 01-Jan, then the first ISO week of that year will include days (29/31-Dec) from the previous Gregorian year.

If the first Thursday falls on 07-Jan, then the last ISO week of the previous Gregorian year will include days (01/03-Jan) from the current Gregorian year.

If the first Thursday falls on 04-Jan, then by implication the first ISO week of the year runs from Monday 01-Jan.

To devise an algorithm, the easiest approach is probably to establish on what weekday the 04-Jan falls in the given year, then apply the following calculation 4 - weekday. If the weekday of 04-Jan is found to be Thursday, the result will be 0. If it is Monday, the result will be 3 (4-1). If it is Sunday, the result will be -3 (4-7). We will store this offset for use after the next step.

We can derive a provisional day-of-year-offset from the ISO week and day numbers as follows: (((iso_week - 1) * 7) - (4 - iso_day)).

We then apply the offset derived in the first stage for the final day-of-year-offset. This is an offset from 04-Jan of the given Gregorian year. This offset may be a minus figure, if the relevant day falls prior to 04-Jan of the given year.

Given that day-of-year-offset, we can then use built-in functions to produce 04-Jan of the given year, and apply the day-of-year-offset to produce the final Gregorian date.

For example, given 2019-W01-1.

2019-01-04 is a Friday, so it's weekday is 5. The result of the first step is -1 (4-5). The result of the second step is -3 (((1-1)*7) - (4-1)). Added together they produce a day-of-year-offset of -4. 04-Jan-2019 offset by -4 results in 31-Dec-2018.

And that is our result: 2019-W01-1 = 2018-12-31.


问:
How to compare and sort the variables that include the name of the teams and the chance of goals in percent
I have a few variables. The first variable always contains the name of the football club, and the next one – the chance of a goal as a percentage.

Example:

a="Man City", b=45.55%, c="Barcelona", d=57.6%, e="Everton", f=38.53%; etc.

I need to compare the chances of goal among all the teams, and sort them in descending order, with an indication of which team this or that chance belongs to.

When I use alert() command, I want that the output be similar to:

```<code>1.Barcelona: Chance 57.6%
2.Man City: Chance 45.55%
3.Everton: Chance 38.53%
</code>```

答:
This data would be better off structured as an array of objects, and your life will be much simpler with the javascript console (press F12 in your browser and in the pane that appears click "console"), such as:

```<code>var array = [
    {city: "Man City", chance: .4555},
    {city: "Barcelona", chance: .576},
    {city: "Everton", chance: .3853}
];

array.sort((a,b) => (a.chance < b.chance) ? 1 : ((b.chance < a.chance) ? -1 : 0));

for (var item of array) {
    console.log(item);
}
</code>```

You'll still have to format chance as percent, and this would be more usable going into an element on the page, but this will give you a start.

Body:
I have a few variables. The first variable always contains the name of the football club, and the next one – the chance of a goal as a percentage.

Example:

a="Man City", b=45.55%, c="Barcelona", d=57.6%, e="Everton", f=38.53%; etc.

I need to compare the chances of goal among all the teams, and sort them in descending order, with an indication of which team this or that chance belongs to.

When I use alert() command, I want that the output be similar to:

1.Barcelona: Chance 57.6%
2.Man City: Chance 45.55%
3.Everton: Chance 38.53%

Body:
This data would be better off structured as an array of objects, and your life will be much simpler with the javascript console (press F12 in your browser and in the pane that appears click "console"), such as:

var array = [
    {city: "Man City", chance: .4555},
    {city: "Barcelona", chance: .576},
    {city: "Everton", chance: .3853}
];

array.sort((a,b) => (a.chance < b.chance) ? 1 : ((b.chance < a.chance) ? -1 : 0));

for (var item of array) {
    console.log(item);
}

You'll still have to format chance as percent, and this would be more usable going into an element on the page, but this will give you a start.


问:
Temporaries problem in C++
I have this piece of code that prints the content of a directory using Boost.Filesystem:

```<code>class Shell {
private:
    const string& command;
    const path& firstPath;
    const path& secondPath;
public:
    // constructor
    Shell(const string& _command, const path& _firstPath, const path& _secondPath = path()): command(_command), firstPath(_firstPath), secondPath(_secondPath) {}

    //destructor
    ~Shell() {}

    //execute commands
    void executeCommand()
    {
        if(command.compare("ls"))
        {
            ls();
        }
    }

    void ls()
    {
        if(exists(firstPath))
        {
            vector<path> vecPath;

            copy(directory_iterator(firstPath), directory_iterator(), back_inserter(vecPath));
            sort(vecPath.begin(), vecPath.end());
            for(vector<path>::iterator it = vecPath.begin(); it != vecPath.end(); ++it)
            {
                cout << *it << endl;
            }
        }
    }
};

int main(int argc, char** argv)
{
    path Path = "c:\\workspace";
    Shell shell("ls", Path); // GOOD
    // Shell shell("ls", "c:\\workspace");  BAD creates temporary !!
    shell.executeCommand();
}
</code>```

If I send my second argument direclty as a const char* I know that it will create a temporary and my constructor argument will only be visible in the constructor, then its lost, because of the reference to temporary.

My question is, why isnt the same thing happening to the first argument, the string, because I am sending him also as a const char* directly, but the value isnt lost outside of the constructor ?

答:
```<code>std::string *ref;

{
    std::string tmp("temp");
    ref = &ref;  // risky, need to keep lifetime of tmp in mind

    const char* const rawptr = ref->c_str(); // equivalent to tmp.c_str()

    tmp = "altered"; // *ref also modified, rawptr completely invalid
}
// *ref _and_ rawptr completely invalid.
</code>```

ContentLicense: CC BY-SA 3.0

Title: Temporaries problem in C++

Body:
I have this piece of code that prints the content of a directory using Boost.Filesystem:

class Shell {
private:
    const string& command;
    const path& firstPath;
    const path& secondPath;
public:
    // constructor
    Shell(const string& _command, const path& _firstPath, const path& _secondPath = path()): command(_command), firstPath(_firstPath), secondPath(_secondPath) {}

    //destructor
    ~Shell() {}

    //execute commands
    void executeCommand()
    {
        if(command.compare("ls"))
        {
            ls();
        }
    }

    void ls()
    {
        if(exists(firstPath))
        {
            vector<path> vecPath;

            copy(directory_iterator(firstPath), directory_iterator(), back_inserter(vecPath));
            sort(vecPath.begin(), vecPath.end());
            for(vector<path>::iterator it = vecPath.begin(); it != vecPath.end(); ++it)
            {
                cout << *it << endl;
            }
        }
    }
};

int main(int argc, char** argv)
{
    path Path = "c:\\workspace";
    Shell shell("ls", Path); // GOOD
    // Shell shell("ls", "c:\\workspace");  BAD creates temporary !!
    shell.executeCommand();
}

If I send my second argument direclty as a const char* I know that it will create a temporary and my constructor argument will only be visible in the constructor, then its lost, because of the reference to temporary.

My question is, why isnt the same thing happening to the first argument, the string, because I am sending him also as a const char* directly, but the value isnt lost outside of the constructor ?


问:
Correctly scale DOT graphic
Please,

I need to create an SVG graphic with D3-GraphViz that size fits perfectly to a DIV area. I tried many this but without success.

Here is a sample code:

<!DOCTYPE html>
<meta charset="utf-8">

```

I saw on D3 website that is a ".fit(true)" property but it simply doesn't work. Any ideas or examples?

答:
I had the same issue. Just realised the source js was so out-of-date (I copied that line from an example as well). Simply change the reference to

```<code><script src="https://unpkg.com/d3-graphviz@2.6.1/build/d3-graphviz.min.js"></script>
</code>```

After that all functionalities listed in README.md of the github repo became available.

Title: Correctly scale DOT graphic

Body:
Please,

I need to create an SVG graphic with D3-GraphViz that size fits perfectly to a DIV area. I tried many this but without success.

Here is a sample code:

<!DOCTYPE html>
<meta charset="utf-8">

I saw on D3 website that is a ".fit(true)" property but it simply doesn't work. Any ideas or examples?

Body:
I had the same issue. Just realised the source js was so out-of-date (I copied that line from an example as well). Simply change the reference to

<script src="https://unpkg.com/d3-graphviz@2.6.1/build/d3-graphviz.min.js"></script>

After that all functionalities listed in README.md of the github repo became available.


问:
How is size of record size set for each record in kafka partition?
I want to know if each record within a kafka topic occupies same size irrespective actual size of the message?

I am aware of the following property -> max.message.bytes=1000012, this will make size of a record upto 1000012 bytes.

My question is if incoming record is less than these bytes , what will be the actual size of the space which is set aside for it?

答:
According to Kafka Docs,

max.message.bytes: The largest record batch size allowed by Kafka. If this is increased
  and there are consumers older than 0.10.2, the consumers' fetch size
  must also be increased so that the they can fetch record batches this
  large.

As far as I understand you are asking whether every message will reserve a space equal to max.message.bytes.

The answer is no. max.message.bytes defines the maximum permitted size of a message and not the size of every message.


问:
How do I make my plugins work with `set encoding=utf-8` in Vim run from Windows PowerShell?

What I want

I want to use the a plugin for Vim and I use the famous plugin manager pathogen for this (https://github.com/tpope/vim-pathogen).

The plugin is vim-ps1 (https://github.com/PProvost/vim-ps1) and provides syntax coloring for Windows Powershell files whose file extension is *.ps1.

My config

In order to install my plugin, I just cloned it into the bundle directory. I'm on my office computer which runs Windows, so my vimfiles directory (instead of the .vim linux version) looks like this:

```<code>    vimfiles
     ├── autoload
     │    └── pathogen.vim
     ├── bundle
     │    ├── nerdtree
     │    └── vim-ps1
     ├── spell
     ├── template
     └── vimrc
</code>```

So there are two plugins, vim-ps1 which I want to install, and nerdtree, added there only to be sure my problems aren't from the plugin (I made the assumption that there is particular problem with nerdtree).

The vimrc file is loaded by the _vimrc file because I want to version my settings. More information about this here https://stackoverflow.com/a/18203545/7964523

```<code>    runtime vimrc
</code>```

The problem

With set encoding=utf-8, I can't use plugins

When I open a *.sp1 nothing happens. Here is the content of my vimrc file for the debugging:

```<code>    runtime! debian.vim
    set nocompatible

    execute pathogen#infect("~/vimfiles/bundle/{}")
    syntax on
    filetype plugin indent on

    set encoding=utf-8
</code>```

The output of :scriptnames is

```<code>      1: ~\_vimrc
      2: ~\vimfiles\vimrc
      3: ~\vimfiles\autoload\pathogen.vim
      4: C:\Program Files (x86)\Vim\vim81\syntax\syntax.vim
      5: C:\Program Files (x86)\Vim\vim81\syntax\synload.vim
      6: C:\Program Files (x86)\Vim\vim81\syntax\syncolor.vim
      7: C:\Program Files (x86)\Vim\vim81\filetype.vim
      8: ~\vimfiles\bundle\vim-ps1\ftdetect\ps1.vim
      9: ~\vimfiles\bundle\vim-ps1\ftdetect\ps1xml.vim
     10: ~\vimfiles\bundle\vim-ps1\ftdetect\xml.vim
     11: C:\Program Files (x86)\Vim\vim81\ftplugin.vim
     12: C:\Program Files (x86)\Vim\vim81\indent.vim
     13: C:\Program Files (x86)\Vim\vim81\plugin\getscriptPlugin.vim
     14: C:\Program Files (x86)\Vim\vim81\plugin\gzip.vim
     15: C:\Program Files (x86)\Vim\vim81\plugin\logiPat.vim
     16: C:\Program Files (x86)\Vim\vim81\plugin\manpager.vim
     17: C:\Program Files (x86)\Vim\vim81\plugin\matchparen.vim
     18: C:\Program Files (x86)\Vim\vim81\plugin\netrwPlugin.vim
     19: C:\Program Files (x86)\Vim\vim81\plugin\rrhelper.vim
     20: C:\Program Files (x86)\Vim\vim81\plugin\spellfile.vim
     21: C:\Program Files (x86)\Vim\vim81\plugin\tarPlugin.vim
     22: C:\Program Files (x86)\Vim\vim81\plugin\tohtml.vim
     23: C:\Program Files (x86)\Vim\vim81\plugin\vimballPlugin.vim
     24: C:\Program Files (x86)\Vim\vim81\plugin\zipPlugin.vim
     25: C:\Program Files (x86)\Vim\vim81\scripts.vim
     26: C:\Program Files (x86)\Vim\vim81\syntax\vim.vim
     27: C:\Program Files (x86)\Vim\vim81\ftplugin\vim.vim
     28: C:\Program Files (x86)\Vim\vim81\indent\vim.vim
</code>```

You can see that there are some files from the vim-ps1 directory loaded. The output of ":set runtimepath? is

```<code>    runtimepath=
    ~\vimfiles\bundle\nerdtree,
    ~\vimfiles\bundle\vim-ps1,
    ~/vimfiles,
    C:\Program Files (x86)\Vim/vimfiles,
    C:\Program Files (x86)\Vim\vim81,
    C:\Program Files (x86)\Vim/vimfiles/after,
    ~/vimfiles/after
</code>```

You can also see that nerdtree and vim-sp1 folders are there, but none of them works.

Without set encoding=utf-8, I have trouble with characters display

Now I remove the line set encoding=utf-8 from my vimrcfile. I open the *.sp1, and the syntax coloring feature works! Nerdtree works too.

But I now have trouble with the display of some characters, like the character code ac (checked with the vim command ga) interpreted as ¬ in utf-8 and ¼ in latin-1.

The output of :scriptnames provides more lines including those related to the syntax plugin (see 46, 47, 48):

```<code>      1: ~\_vimrc
      2: ~\vimfiles\vimrc
      3: ~\vimfiles\autoload\pathogen.vim
      4: C:\Program Files (x86)\Vim\vim81\syntax\syntax.vim
      5: C:\Program Files (x86)\Vim\vim81\syntax\synload.vim
      6: C:\Program Files (x86)\Vim\vim81\syntax\syncolor.vim
      7: C:\Program Files (x86)\Vim\vim81\filetype.vim
      8: ~\vimfiles\bundle\vim-ps1\ftdetect\ps1.vim
      9: ~\vimfiles\bundle\vim-ps1\ftdetect\ps1xml.vim
     10: ~\vimfiles\bundle\vim-ps1\ftdetect\xml.vim
     11: C:\Program Files (x86)\Vim\vim81\ftplugin.vim
     12: C:\Program Files (x86)\Vim\vim81\indent.vim
     13: ~\vimfiles\bundle\nerdtree\plugin\NERD_tree.vim
     14: ~\vimfiles\bundle\nerdtree\autoload\nerdtree.vim
     15: ~\vimfiles\bundle\nerdtree\lib\nerdtree\path.vim
     16: ~\vimfiles\bundle\nerdtree\lib\nerdtree\menu_controller.vim
     17: ~\vimfiles\bundle\nerdtree\lib\nerdtree\menu_item.vim
     18: ~\vimfiles\bundle\nerdtree\lib\nerdtree\key_map.vim
     19: ~\vimfiles\bundle\nerdtree\lib\nerdtree\bookmark.vim
     20: ~\vimfiles\bundle\nerdtree\lib\nerdtree\tree_file_node.vim
     21: ~\vimfiles\bundle\nerdtree\lib\nerdtree\tree_dir_node.vim
     22: ~\vimfiles\bundle\nerdtree\lib\nerdtree\opener.vim
     23: ~\vimfiles\bundle\nerdtree\lib\nerdtree\creator.vim
     24: ~\vimfiles\bundle\nerdtree\lib\nerdtree\flag_set.vim
     25: ~\vimfiles\bundle\nerdtree\lib\nerdtree\nerdtree.vim
     26: ~\vimfiles\bundle\nerdtree\lib\nerdtree\ui.vim
     27: ~\vimfiles\bundle\nerdtree\lib\nerdtree\event.vim
     28: ~\vimfiles\bundle\nerdtree\lib\nerdtree\notifier.vim
     29: ~\vimfiles\bundle\nerdtree\autoload\nerdtree\ui_glue.vim
     30: ~\vimfiles\bundle\nerdtree\nerdtree_plugin\exec_menuitem.vim
     31: ~\vimfiles\bundle\nerdtree\nerdtree_plugin\fs_menu.vim
     32: ~\vimfiles\bundle\nerdtree\nerdtree_plugin\vcs.vim
     33: C:\Program Files (x86)\Vim\vim81\plugin\getscriptPlugin.vim
     34: C:\Program Files (x86)\Vim\vim81\plugin\gzip.vim
     35: C:\Program Files (x86)\Vim\vim81\plugin\logiPat.vim
     36: C:\Program Files (x86)\Vim\vim81\plugin\manpager.vim
     37: C:\Program Files (x86)\Vim\vim81\plugin\matchparen.vim
     38: C:\Program Files (x86)\Vim\vim81\plugin\netrwPlugin.vim
     39: C:\Program Files (x86)\Vim\vim81\plugin\rrhelper.vim
     40: C:\Program Files (x86)\Vim\vim81\plugin\spellfile.vim
     41: C:\Program Files (x86)\Vim\vim81\plugin\tarPlugin.vim
     42: C:\Program Files (x86)\Vim\vim81\plugin\tohtml.vim
     43: C:\Program Files (x86)\Vim\vim81\plugin\vimballPlugin.vim
     44: C:\Program Files (x86)\Vim\vim81\plugin\zipPlugin.vim
     45: C:\Program Files (x86)\Vim\vim81\scripts.vim
     46: ~\vimfiles\bundle\vim-ps1\syntax\ps1.vim
     47: ~\vimfiles\bundle\vim-ps1\ftplugin\ps1.vim
     48: ~\vimfiles\bundle\vim-ps1\indent\ps1.vim
</code>```

No change of the output of :set runtimepath?

What I  try to overcome this

I manage to identify the trigger (see above).

I moved the line set encoding=utf-8

the problem remains the same whatever its position after the line that executes pathogen

above the line that executes pathogen, I got this error:

```<code>E117: Unknown function: pathogen#infect
E15: Invalid expression: pathogen#infect("~/vimfiles/bundle/{}")
</code>```

so it is worst.

How do I make my plugins work with set encoding=utf-8?

Edit1

As I'm running Vim 8.1, I applied the solution suggested by @Matt. The problem is still here but is not linked to pathogen.

Adding set fileencodings=utf-8,default changed nothing.

I ran from my terminal vim -Vdebug and analysed the output file debug. My user name contains the letter é coded e9 in hexadecimal unicode, and at some point in the debugging file I've got

```<code>    Searching for "C:\Users\Aur<e9>lien/vimfiles/pack/*/start/*"
</code>```

See the <e9> part. It is four separate characters <, e, 9 and > (I can put my cursor over each of them).

Without set fileencodings=utf-8,default and set encoding=utf-8, the output of the debugging file is correct (except the slashes and backslashes but it works):

```<code>    Searching for "C:\Users\Aurélien/vimfiles/pack/*/start/*"
</code>```

This explains why it doesn't work with set encoding=utf-8, but I can't explain this behaviour.

答:
Look like you're running Vim 8, so you don't need Pathogen at all. Just move your plugins under ~/vimfiles/pack/bundle/start and you're done. Read :help packages for more info.

Also, in my experience setting set encoding=utf-8 as the very first line (not counting comments) in your config saves many troubles.

Body:
What I want

I want to use the a plugin for Vim and I use the famous plugin manager pathogen for this (https://github.com/tpope/vim-pathogen).

The plugin is vim-ps1 (https://github.com/PProvost/vim-ps1) and provides syntax coloring for Windows Powershell files whose file extension is *.ps1.

My config

In order to install my plugin, I just cloned it into the bundle directory. I'm on my office computer which runs Windows, so my vimfiles directory (instead of the .vim linux version) looks like this:

    vimfiles
     ├── autoload
     │    └── pathogen.vim
     ├── bundle
     │    ├── nerdtree
     │    └── vim-ps1
     ├── spell
     ├── template
     └── vimrc

So there are two plugins, vim-ps1 which I want to install, and nerdtree, added there only to be sure my problems aren't from the plugin (I made the assumption that there is particular problem with nerdtree).

The vimrc file is loaded by the _vimrc file because I want to version my settings. More information about this here https://stackoverflow.com/a/18203545/7964523

    runtime vimrc

The problem

With set encoding=utf-8, I can't use plugins

When I open a *.sp1 nothing happens. Here is the content of my vimrc file for the debugging:

    runtime! debian.vim
    set nocompatible

    execute pathogen#infect("~/vimfiles/bundle/{}")
    syntax on
    filetype plugin indent on

    set encoding=utf-8

The output of :scriptnames is

      1: ~\_vimrc
      2: ~\vimfiles\vimrc
      3: ~\vimfiles\autoload\pathogen.vim
      4: C:\Program Files (x86)\Vim\vim81\syntax\syntax.vim
      5: C:\Program Files (x86)\Vim\vim81\syntax\synload.vim
      6: C:\Program Files (x86)\Vim\vim81\syntax\syncolor.vim
      7: C:\Program Files (x86)\Vim\vim81\filetype.vim
      8: ~\vimfiles\bundle\vim-ps1\ftdetect\ps1.vim
      9: ~\vimfiles\bundle\vim-ps1\ftdetect\ps1xml.vim
     10: ~\vimfiles\bundle\vim-ps1\ftdetect\xml.vim
     11: C:\Program Files (x86)\Vim\vim81\ftplugin.vim
     12: C:\Program Files (x86)\Vim\vim81\indent.vim
     13: C:\Program Files (x86)\Vim\vim81\plugin\getscriptPlugin.vim
     14: C:\Program Files (x86)\Vim\vim81\plugin\gzip.vim
     15: C:\Program Files (x86)\Vim\vim81\plugin\logiPat.vim
     16: C:\Program Files (x86)\Vim\vim81\plugin\manpager.vim
     17: C:\Program Files (x86)\Vim\vim81\plugin\matchparen.vim
     18: C:\Program Files (x86)\Vim\vim81\plugin\netrwPlugin.vim
     19: C:\Program Files (x86)\Vim\vim81\plugin\rrhelper.vim
     20: C:\Program Files (x86)\Vim\vim81\plugin\spellfile.vim
     21: C:\Program Files (x86)\Vim\vim81\plugin\tarPlugin.vim
     22: C:\Program Files (x86)\Vim\vim81\plugin\tohtml.vim
     23: C:\Program Files (x86)\Vim\vim81\plugin\vimballPlugin.vim
     24: C:\Program Files (x86)\Vim\vim81\plugin\zipPlugin.vim
     25: C:\Program Files (x86)\Vim\vim81\scripts.vim
     26: C:\Program Files (x86)\Vim\vim81\syntax\vim.vim
     27: C:\Program Files (x86)\Vim\vim81\ftplugin\vim.vim
     28: C:\Program Files (x86)\Vim\vim81\indent\vim.vim

You can see that there are some files from the vim-ps1 directory loaded. The output of ":set runtimepath? is

    runtimepath=
    ~\vimfiles\bundle\nerdtree,
    ~\vimfiles\bundle\vim-ps1,
    ~/vimfiles,
    C:\Program Files (x86)\Vim/vimfiles,
    C:\Program Files (x86)\Vim\vim81,
    C:\Program Files (x86)\Vim/vimfiles/after,
    ~/vimfiles/after

You can also see that nerdtree and vim-sp1 folders are there, but none of them works.

Without set encoding=utf-8, I have trouble with characters display

Now I remove the line set encoding=utf-8 from my vimrcfile. I open the *.sp1, and the syntax coloring feature works! Nerdtree works too.

But I now have trouble with the display of some characters, like the character code ac (checked with the vim command ga) interpreted as ¬ in utf-8 and ¼ in latin-1.

The output of :scriptnames provides more lines including those related to the syntax plugin (see 46, 47, 48):

      1: ~\_vimrc
      2: ~\vimfiles\vimrc
      3: ~\vimfiles\autoload\pathogen.vim
      4: C:\Program Files (x86)\Vim\vim81\syntax\syntax.vim
      5: C:\Program Files (x86)\Vim\vim81\syntax\synload.vim
      6: C:\Program Files (x86)\Vim\vim81\syntax\syncolor.vim
      7: C:\Program Files (x86)\Vim\vim81\filetype.vim
      8: ~\vimfiles\bundle\vim-ps1\ftdetect\ps1.vim
      9: ~\vimfiles\bundle\vim-ps1\ftdetect\ps1xml.vim
     10: ~\vimfiles\bundle\vim-ps1\ftdetect\xml.vim
     11: C:\Program Files (x86)\Vim\vim81\ftplugin.vim
     12: C:\Program Files (x86)\Vim\vim81\indent.vim
     13: ~\vimfiles\bundle\nerdtree\plugin\NERD_tree.vim
     14: ~\vimfiles\bundle\nerdtree\autoload\nerdtree.vim
     15: ~\vimfiles\bundle\nerdtree\lib\nerdtree\path.vim
     16: ~\vimfiles\bundle\nerdtree\lib\nerdtree\menu_controller.vim
     17: ~\vimfiles\bundle\nerdtree\lib\nerdtree\menu_item.vim
     18: ~\vimfiles\bundle\nerdtree\lib\nerdtree\key_map.vim
     19: ~\vimfiles\bundle\nerdtree\lib\nerdtree\bookmark.vim
     20: ~\vimfiles\bundle\nerdtree\lib\nerdtree\tree_file_node.vim
     21: ~\vimfiles\bundle\nerdtree\lib\nerdtree\tree_dir_node.vim
     22: ~\vimfiles\bundle\nerdtree\lib\nerdtree\opener.vim
     23: ~\vimfiles\bundle\nerdtree\lib\nerdtree\creator.vim
     24: ~\vimfiles\bundle\nerdtree\lib\nerdtree\flag_set.vim
     25: ~\vimfiles\bundle\nerdtree\lib\nerdtree\nerdtree.vim
     26: ~\vimfiles\bundle\nerdtree\lib\nerdtree\ui.vim
     27: ~\vimfiles\bundle\nerdtree\lib\nerdtree\event.vim
     28: ~\vimfiles\bundle\nerdtree\lib\nerdtree\notifier.vim
     29: ~\vimfiles\bundle\nerdtree\autoload\nerdtree\ui_glue.vim
     30: ~\vimfiles\bundle\nerdtree\nerdtree_plugin\exec_menuitem.vim
     31: ~\vimfiles\bundle\nerdtree\nerdtree_plugin\fs_menu.vim
     32: ~\vimfiles\bundle\nerdtree\nerdtree_plugin\vcs.vim
     33: C:\Program Files (x86)\Vim\vim81\plugin\getscriptPlugin.vim
     34: C:\Program Files (x86)\Vim\vim81\plugin\gzip.vim
     35: C:\Program Files (x86)\Vim\vim81\plugin\logiPat.vim
     36: C:\Program Files (x86)\Vim\vim81\plugin\manpager.vim
     37: C:\Program Files (x86)\Vim\vim81\plugin\matchparen.vim
     38: C:\Program Files (x86)\Vim\vim81\plugin\netrwPlugin.vim
     39: C:\Program Files (x86)\Vim\vim81\plugin\rrhelper.vim
     40: C:\Program Files (x86)\Vim\vim81\plugin\spellfile.vim
     41: C:\Program Files (x86)\Vim\vim81\plugin\tarPlugin.vim
     42: C:\Program Files (x86)\Vim\vim81\plugin\tohtml.vim
     43: C:\Program Files (x86)\Vim\vim81\plugin\vimballPlugin.vim
     44: C:\Program Files (x86)\Vim\vim81\plugin\zipPlugin.vim
     45: C:\Program Files (x86)\Vim\vim81\scripts.vim
     46: ~\vimfiles\bundle\vim-ps1\syntax\ps1.vim
     47: ~\vimfiles\bundle\vim-ps1\ftplugin\ps1.vim
     48: ~\vimfiles\bundle\vim-ps1\indent\ps1.vim

No change of the output of :set runtimepath?

What I  try to overcome this

I manage to identify the trigger (see above).

I moved the line set encoding=utf-8

the problem remains the same whatever its position after the line that executes pathogen

above the line that executes pathogen, I got this error:

E117: Unknown function: pathogen#infect
E15: Invalid expression: pathogen#infect("~/vimfiles/bundle/{}")

so it is worst.

How do I make my plugins work with set encoding=utf-8?

Edit1

As I'm running Vim 8.1, I applied the solution suggested by @Matt. The problem is still here but is not linked to pathogen.

Adding set fileencodings=utf-8,default changed nothing.

I ran from my terminal vim -Vdebug and analysed the output file debug. My user name contains the letter é coded e9 in hexadecimal unicode, and at some point in the debugging file I've got

    Searching for "C:\Users\Aur<e9>lien/vimfiles/pack/*/start/*"

See the <e9> part. It is four separate characters <, e, 9 and > (I can put my cursor over each of them).

Without set fileencodings=utf-8,default and set encoding=utf-8, the output of the debugging file is correct (except the slashes and backslashes but it works):

    Searching for "C:\Users\Aurélien/vimfiles/pack/*/start/*"

This explains why it doesn't work with set encoding=utf-8, but I can't explain this behaviour.


问:
No results in record set
I have a temporary table being created from a query. From that table I am selecting the items and placing them in a specific order to display in a listbox. Everything works great until I try to add a where clause to my select statement.

What I'd like to do is, when I run the query that isn't working below, just have the variables return as "0".

I have tried to do an if statement that just makes my variable "0", but I still get the same "No Current Record" error.

The below query it works fine;

  strQuery = "SELECT * FROM " & currentTime & " Order By CVT, CVY, CVW,
  AdjusterName"
```

<p>But when I add in a where clause of <=1 then I get a "No Current Record" error. The second query is;</p>

<pre class="lang-vb prettyprint-override"><code>  strQuery = "SELECT * FROM " & currentTime & " WHERE CVT <=1 Order By
  CVT, CVY, CVW, AdjusterName"
</code>```

When I run this second query I get a "No Current Record" error. This is where I'd like it to just display a zero instead.

Just in case it's needed, here is the entire function;

    If ClaimTypeCB = "MO" Then
        strQuery = "SELECT * FROM " & currentTime & " WHERE CVT <=1 Order
        By CVT, CVY, CVW, AdjusterName"
    Else
        strQuery = "SELECT * FROM " & currentTime & " Order By CVT, CVY,
        CVW, AdjusterName"
    End If
        Set daoQueryResult = db.OpenRecordset(strQuery)

        daoQueryResult.MoveLast
        intRecordCount = daoQueryResult.RecordCount
        daoQueryResult.MoveFirst

    If intRecordCount = 0 Then
        intCVT = 0
    End If
```

<p>(The above If Statement is where I tried to insert an If statement, but it didn't work, and I still get a "No Current Record" error.)</p>

<pre class="lang-vb prettyprint-override"><code>    If intRecordCount <> 0 Then
        With daoQueryResult
            Do While Not .EOF

                If IsNull(!CVT) Then
                    intCVT = 0
                Else
                    intCVT = !CVT
                End If

                If IsNull(!CVY) Then
                    intCVY = 0
                Else
                    intCVY = !CVY
                End If

                If IsNull(!CVW) Then
                    intCVW = 0
                Else
                    intCVW = (!CVW)
                End If

                AvailAdjList.AddItem !AdjusterName & "," & intCVT & "," & intCVY & "," & intCVW
                .MoveNext
            Loop
        End With
    End If
</code>```

I really just want CVT to return as zero if it is 0 or 1.

答:
After this line:

Set daoQueryResult = db.OpenRecordset(strQuery)
```

<p>you need to check for Recordset.EOF</p>

<pre class="lang-vb prettyprint-override"><code>With daoQueryResult
    If .EOF Then
        intRecordCount = 0
    Else
        .MoveLast
        intRecordCount = .RecordCount
        .MoveFirst
    End If
End With
</code>```

Though from your code you don't seem to really need RecordCount.

You could simply start with Do While Not .EOF

Title: No results in record set

Body:
I have a temporary table being created from a query. From that table I am selecting the items and placing them in a specific order to display in a listbox. Everything works great until I try to add a where clause to my select statement.

What I'd like to do is, when I run the query that isn't working below, just have the variables return as "0".

I have tried to do an if statement that just makes my variable "0", but I still get the same "No Current Record" error.

The below query it works fine;

  strQuery = "SELECT * FROM " & currentTime & " Order By CVT, CVY, CVW,
  AdjusterName"

But when I add in a where clause of <=1 then I get a "No Current Record" error. The second query is;

  strQuery = "SELECT * FROM " & currentTime & " WHERE CVT <=1 Order By
  CVT, CVY, CVW, AdjusterName"

When I run this second query I get a "No Current Record" error. This is where I'd like it to just display a zero instead.

Just in case it's needed, here is the entire function;

    If ClaimTypeCB = "MO" Then
        strQuery = "SELECT * FROM " & currentTime & " WHERE CVT <=1 Order
        By CVT, CVY, CVW, AdjusterName"
    Else
        strQuery = "SELECT * FROM " & currentTime & " Order By CVT, CVY,
        CVW, AdjusterName"
    End If
        Set daoQueryResult = db.OpenRecordset(strQuery)

        daoQueryResult.MoveLast
        intRecordCount = daoQueryResult.RecordCount
        daoQueryResult.MoveFirst

    If intRecordCount = 0 Then
        intCVT = 0
    End If

(The above If Statement is where I tried to insert an If statement, but it didn't work, and I still get a "No Current Record" error.)

    If intRecordCount <> 0 Then
        With daoQueryResult
            Do While Not .EOF

                If IsNull(!CVT) Then
                    intCVT = 0
                Else
                    intCVT = !CVT
                End If

                If IsNull(!CVY) Then
                    intCVY = 0
                Else
                    intCVY = !CVY
                End If

                If IsNull(!CVW) Then
                    intCVW = 0
                Else
                    intCVW = (!CVW)
                End If

                AvailAdjList.AddItem !AdjusterName & "," & intCVT & "," & intCVY & "," & intCVW
                .MoveNext
            Loop
        End With
    End If

I really just want CVT to return as zero if it is 0 or 1.

Body:
After this line:

Set daoQueryResult = db.OpenRecordset(strQuery)

you need to check for Recordset.EOF

With daoQueryResult
    If .EOF Then
        intRecordCount = 0
    Else
        .MoveLast
        intRecordCount = .RecordCount
        .MoveFirst
    End If
End With

Though from your code you don't seem to really need RecordCount.

You could simply start with Do While Not .EOF


问:
Keep an object moving along the Y axis appear stationary at a point by moving its X and Z position
I need that the camera sees an object in the initial position after moving it on Y axis.
I use some images to explain myself better.
This is the initial position of the object. The main camera will not change position. At the coordinates (0, 0, 0) there is another camera I use for the background image. From this same point I draw Gizmo lines.

Now through my Editor I move a Plane on the Y axis from 0 to -2. The Y of my object is linked to the Y of the Plane, so it also goes down by 2 units.

Now comes the part I would like to automate. I want to move the object along the X and Z axis so that its feet appear to the camera as if they are in the same initial position. By manually moving it in Scene View on the X and Z axes, I put the feet in a place that looks like the same point as before and of course it is smaller as it is further away from the camera.

How can I calculate by code the X and Z coordinates to be assigned to my object's position at a given point on the Y axis, so that one point remains in the same position in screen space?

答:
You can use rays and planes to calculate this.

Before the object moves, create a Ray from the camera to the point on the object you need to keep in the same position:

```<code>// Where the "feet" are relative to the object's origin
public Vector3 cameraKeepOffset = new Vector3(0f,-1f,0f);

public Ray perspectiveRay;

...

Vector3 positionToKeep = transform.position + cameraKeepOffset;
Vector3 cameraPosition = Camera.main.transform.position;

perspectiveRay = new Ray(cameraPosition, positionToKeep - cameraPosition);
</code>```

The idea is that whenever the object moves, find where along that ray it can be placed. If we put a horizontal plane at the y position, wherever the ray intersects that plane is where the object should be placed.

So, when the object moves, create a Plane where the offset is, find where the perspectiveRay intersects it, then move the object so that its offset is at that point:

```<code>Plane yPlane = new Plane(Vector3.up, cameraKeepOffset + transform.position);
float distanceFromCam;
if ( !Raycast(perspectiveRay, out distanceFromCam)) {
    Debug.log("Camera is not pointing at plane");

    // Handle bugs here, return if necessary, etc.
} else {
    Vector3 intersectionPoint = Ray.GetPoint(distanceFromCam);
    transform.position = intersectionPoint - cameraKeepOffset;
}
</code>```

Body:
You can use rays and planes to calculate this.

Before the object moves, create a Ray from the camera to the point on the object you need to keep in the same position:

// Where the "feet" are relative to the object's origin
public Vector3 cameraKeepOffset = new Vector3(0f,-1f,0f);

public Ray perspectiveRay;

...

Vector3 positionToKeep = transform.position + cameraKeepOffset;
Vector3 cameraPosition = Camera.main.transform.position;

perspectiveRay = new Ray(cameraPosition, positionToKeep - cameraPosition);

The idea is that whenever the object moves, find where along that ray it can be placed. If we put a horizontal plane at the y position, wherever the ray intersects that plane is where the object should be placed.

So, when the object moves, create a Plane where the offset is, find where the perspectiveRay intersects it, then move the object so that its offset is at that point:

Plane yPlane = new Plane(Vector3.up, cameraKeepOffset + transform.position);
float distanceFromCam;
if ( !Raycast(perspectiveRay, out distanceFromCam)) {
    Debug.log("Camera is not pointing at plane");

    // Handle bugs here, return if necessary, etc.
} else {
    Vector3 intersectionPoint = Ray.GetPoint(distanceFromCam);
    transform.position = intersectionPoint - cameraKeepOffset;
}


问:
C# List<String> Print Items
very new to c# here and following tutorials on PluralSight.

i have the following files (Classes i think ?)

Program.cs

```<code>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Customers
{
    class Program
    {
        static void Main(string[] args)
        {
            CustomerList customers = new CustomerList();

            customers.AddCustomer("Apple");
            customers.AddCustomer("Microsoft");
        }
    }
}
</code>```

And CustomerList.cs

```<code>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Customers
{
    public class CustomerList
    {
        public CustomerList()
        {
            customers = new List<string>();
        }

        public void AddCustomer(string customer)
        {
            customers.Add(customer);
        }

        private List<String> customers;
    }
}
</code>```

The snag i'm hitting is i just want to list out the items within the list and doing so is stumping me. I did try to use a foreach statement as follows.

```<code>      foreach (string customer in customers)
        {
            Console.WriteLine(customer);
        }
</code>```

from within Program.cs but i'm unable to do so as it states

"foreach statement cannot operate on variables of type 'CustomerList' because 'CustomerList' does not contain a public instance definition for 'GetEnumerator'"

However if i keep all my code within Program.cs and use the following i am able to write out each item within list.

```<code>private List<string> customers;

static void Main(string[] args)
{
    customers = new List<String>();
    AddCustomers(customers);

    foreach(string customer in customers) {

         Console.WriteLine(customer);
    }

}

private void AddCustomers(List<string> customers)
    {
        customers.Add("Apple");
        customers.Add("Microsoft");
    }
</code>```

Like i say, very new, so please go easy one me.

答:
Try implementing the IEnumerable interface in your CustomerList class. By doing this, you have to add the method GetEnumerator() and that will allow you to iterate through your list of strings. Implement the interface like below (notice the : IEnumerable in the class definition):

```<code>public class CustomerList : IEnumerable
{
    ... // Your current code \\ ...

    public IEnumerator GetEnumerator()
    {
        return customers.GetEnumerator();
    }
}
</code>```

Title: C# List<String> Print Items

Body:
very new to c# here and following tutorials on PluralSight.

i have the following files (Classes i think ?)

Program.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Customers
{
    class Program
    {
        static void Main(string[] args)
        {
            CustomerList customers = new CustomerList();

            customers.AddCustomer("Apple");
            customers.AddCustomer("Microsoft");
        }
    }
}

And CustomerList.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Customers
{
    public class CustomerList
    {
        public CustomerList()
        {
            customers = new List<string>();
        }

        public void AddCustomer(string customer)
        {
            customers.Add(customer);
        }

        private List<String> customers;
    }
}

The snag i'm hitting is i just want to list out the items within the list and doing so is stumping me. I did try to use a foreach statement as follows.

      foreach (string customer in customers)
        {
            Console.WriteLine(customer);
        }

from within Program.cs but i'm unable to do so as it states

"foreach statement cannot operate on variables of type 'CustomerList' because 'CustomerList' does not contain a public instance definition for 'GetEnumerator'"

However if i keep all my code within Program.cs and use the following i am able to write out each item within list.

private List<string> customers;

static void Main(string[] args)
{
    customers = new List<String>();
    AddCustomers(customers);

    foreach(string customer in customers) {

         Console.WriteLine(customer);
    }

}

private void AddCustomers(List<string> customers)
    {
        customers.Add("Apple");
        customers.Add("Microsoft");
    }

Like i say, very new, so please go easy one me.

Body:
Try implementing the IEnumerable interface in your CustomerList class. By doing this, you have to add the method GetEnumerator() and that will allow you to iterate through your list of strings. Implement the interface like below (notice the : IEnumerable in the class definition):

public class CustomerList : IEnumerable
{
    ... // Your current code \\ ...

    public IEnumerator GetEnumerator()
    {
        return customers.GetEnumerator();
    }
}


问:
Python: 'ValueError: too many values to unpack (expected 2)' for a username password system
I am getting this error 'ValueError: too many values to unpack (expected 2)' when I am making a dictionary from a text file when there is more than 1 key and value in the text file.

```<code>database = {}  #creates an empty dictionary
with open("file.txt", "r") as infile:  #opens the dictionary
    for line in infile: #for each line
        name, ask = line.strip().split(':')
        database[name] = (ask)

name = input('Enter username: ')
ask = input('Enter pin: ')
if name in database:
    if ask in database[name]:
        print('Welcome', name)

    else:
        database.update( {name : ask} )
        print(database)
else:
    database.update( {name : ask} )
    print(database)

with open('file.txt', 'w') as file:
    file.write(json.dumps(database)) #updates the text file with the new databse
</code>```

I expect when the program runs and there is more than 1 key and value in the text file to run no matter which key is input. However if there is more than 1 key/value in the file, the text file can't be unpacked

答:
Why not just use a simple json file?</p>

```<code>with open("file.txt", "r") as infile:
    database = json.loads(infile.read())
</code>```

Body:
I am getting this error 'ValueError: too many values to unpack (expected 2)' when I am making a dictionary from a text file when there is more than 1 key and value in the text file.

database = {}  #creates an empty dictionary
with open("file.txt", "r") as infile:  #opens the dictionary
    for line in infile: #for each line
        name, ask = line.strip().split(':')
        database[name] = (ask)

name = input('Enter username: ')
ask = input('Enter pin: ')
if name in database:
    if ask in database[name]:
        print('Welcome', name)

    else:
        database.update( {name : ask} )
        print(database)
else:
    database.update( {name : ask} )
    print(database)

with open('file.txt', 'w') as file:
    file.write(json.dumps(database)) #updates the text file with the new databse

I expect when the program runs and there is more than 1 key and value in the text file to run no matter which key is input. However if there is more than 1 key/value in the file, the text file can't be unpacked

Body:
Why not just use a simple json file?

with open("file.txt", "r") as infile:
    database = json.loads(infile.read())


问:
How to set all columns not null while creating table
I'm trying to create table which should have not null constraint for all of columns.

Is there any way to set all of columns not null instead of placing it in front of each column's name?

答: Actually, there is a way to make it fast. You can type in many lines in the same type by using ALT + mouse or ALT + SHIFT + ARROWS. It's works nearly in every editor. See this post for more details. It's a very useful trick when you need to edit/add a lot of same words in consecutive lines i.e. NOT NULL as in your case.


问:
how to refresh fullcalendar v4 after change events object using ajax
i use fullcalendar v4 to show events.
 events shows in load normally ,but i need to add a filter using multiple checkboxes and refresh fullcalendar events after onchange checkbox with ajax .

after change i get the new object events but i need to refresh fullcalendar
 i try with calendar.render(); but not working

```<code>fullcalendar V4 !!
</code>```

fullcalendar script

```<code> var taskEvents = JSON.parse($("input[name=tasks_events]").val());
        var calendarEl = document.getElementById('tasks_calendar');
        var  calendar = new FullCalendar.Calendar(calendarEl, {
            locale: 'fr',
            plugins: [ 'interaction', 'dayGrid', 'timeGrid' ],
            header: {
                left: 'prev,next today',
                center: 'title',
                right: 'dayGridMonth,timeGridWeek'
            },
            defaultDate: new Date(),
            defaultView: 'timeGridWeek',
            minTime: "09:00:00",
            maxTime: "20:00:00",
            weekends:false,
            businessHours: true, // display business hours
            editable: true,
            selectable: true,
            droppable: true,
            //events:taskEvents ,
            select: function(info) {
                $('#newTaskFormLabel').html('Commence à '+"<b> " + moment(info.startStr).format('DD-MM-YYYY HH:mm') + "</b> "+" fin à " +"<b> " + moment(info.endStr).format('DD-MM-YYYY HH:m:m')) +"</b>"
                $('#newTaskForm').modal('show');
                $('#newTaskForm input[name=start_at]').val(info.startStr);
                $('#newTaskForm input[name=end_at]').val(info.endStr);
            },
            eventClick: function(info) {
                $('#editTaskForm').modal('show');
                console.log(info);
                editTask(info.event);
            },
            // dateClick: function(info) {
            //     alert('clicked ' + info.dateStr);
            // },
            eventResize: function(info) {
                $('.popover.in').remove();
                if (confirm("Êtes-vous sûr de vouloir appliquer ces modifications?")) {
                    submitTimeChanges(info.event);
                }else{
                    info.revert();
                }
            },
            eventDrop : function(info){
                $('.popover.in').remove();
                // $(info.el).removeAttr('aria-describedby');
                if (confirm("Êtes-vous sûr de vouloir appliquer ces modifications?")) {
                    submitTimeChanges(info.event);
                }else{
                    info.revert();
                }
            },
            eventRender: function(info) {

                $(info.el).append('<img src="'+document.location.origin+'/'+info.event.extendedProps.user_avatar+'" class="img-circle event-avatar" alt="User Image">');
                let state = function (state) {
                    if(state =="not_started") return "Pas encore commencé";
                    if(state =="started") return "Commencé";
                    if(state =="finish") return "Terminer";
                }
                $(info.el).popover({
                    title: info.event.title,
                    content: function () {
                        let html ="<p>"+moment(info.event.start).format('DD-MM-YYYY HH:mm')+' / '+moment(info.event.end).format('DD-MM-YYYY HH:mm')+"</P>"
                        +"<p>"+info.event.extendedProps.description+"</p>"
                        +"<p>"+"Utilisateur : "+info.event.extendedProps.user+"</p>"
                        +"<p>"+"Projet : "+info.event.extendedProps.project+"</p>"
                        +"<p>"+"Fonction : "+info.event.extendedProps.activity+"</p>"
                        +"<a class='btn btn-primary btn-xs'>"+state(info.event.extendedProps.state)+"</a>";
                        return html;
                    },
                    trigger: 'hover',
                    placement: 'top',
                    html: 'true',
                    container: 'body'
                    });
            },

        });
        calendar.addEventSource( taskEvents );
        calendar.render();
//--------------------------------------------------------
</code>```

ajax script

```<code>var getTasks = function (data){
            $.ajax({
                url:"/admin/get-users-tasks",
                type:"POST",
                data :{
                    users:data,
                },
                headers: {
                    'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
                },
                success: function (response) {
                    calendar.addEventSource( response );
                    calendar.refetchEvents();
                },
                error: function(response) {
                    new PNotify({
                        title: "Opération échoué",
                        text: response.message,
                        type: "error"
                      });
                }
              });
        }
</code>```

on change checkbox function

```<code> function onChangeUserCheckbox() {
        $("input[name*=selected_user]").on('change',function () {
            var selectedUsers = [];
            $.each($("input[name*='selected_user']:checked"), function(){
                selectedUsers.push($(this).val());
            });
            getTasks(selectedUsers);
            // getTasks(JSON.stringify(selectedUsers));
        })
    }
</code>```

答:
What I do : destroy calendar and re render it

do not load calendar as indicated in the doc, but :

function LoadCalendar() {
        if (typeof calendar != "undefined") {
            document.getElementById("calendar").innerHTML = "";
        }
        var calendarEl = document.getElementById('calendar');
        calendar = new FullCalendar.Calendar(calendarEl, {
        //... parameters
        });
        calendar.render();
    }
```

<ol start="2">
<li>Then at load : </li>
</ol>

<pre class="lang-js prettyprint-override"><code>function FirstCalendar() {
        MesEvents = "$events"; // Ajax script is executed and give $events
        LoadCalendar();
    }
        document.addEventListener('DOMContentLoaded', FirstCalendar);
</code>```

And finnaly, for Ajax update :

function makeRequest(event) {
        //... ajax instructions
        httpRequest.onreadystatechange = function() { changeContents(httpRequest); };
        httpRequest.open('POST', 'url/ajax.php', true);
        httpRequest.send(oData);
    }
    function changeContents(httpRequest) {
        try {
            if (httpRequest.readyState == XMLHttpRequest.DONE) {
                if (httpRequest.status == 200) {
                    reponse = JSON.parse(httpRequest.responseText);
                    MesEvents = JSON.parse(reponse.Events);
                    LoadCalendar();
                } else {
                    alert('Un problème est survenu avec la requête : ' + httpRequest.status);
                }
            }
        }
        catch( e ) {
            alert(\"Une exception s’est produite (changeContents) : \" + e.description);
        }
    }
```

Body:
i use fullcalendar v4 to show events.
 events shows in load normally ,but i need to add a filter using multiple checkboxes and refresh fullcalendar events after onchange checkbox with ajax .

after change i get the new object events but i need to refresh fullcalendar
 i try with calendar.render(); but not working

fullcalendar V4 !!

fullcalendar script

 var taskEvents = JSON.parse($("input[name=tasks_events]").val());
        var calendarEl = document.getElementById('tasks_calendar');
        var  calendar = new FullCalendar.Calendar(calendarEl, {
            locale: 'fr',
            plugins: [ 'interaction', 'dayGrid', 'timeGrid' ],
            header: {
                left: 'prev,next today',
                center: 'title',
                right: 'dayGridMonth,timeGridWeek'
            },
            defaultDate: new Date(),
            defaultView: 'timeGridWeek',
            minTime: "09:00:00",
            maxTime: "20:00:00",
            weekends:false,
            businessHours: true, // display business hours
            editable: true,
            selectable: true,
            droppable: true,
            //events:taskEvents ,
            select: function(info) {
                $('#newTaskFormLabel').html('Commence à '+" " + moment(info.startStr).format('DD-MM-YYYY HH:mm') + " "+" fin à " +" " + moment(info.endStr).format('DD-MM-YYYY HH:m:m')) +""
                $('#newTaskForm').modal('show');
                $('#newTaskForm input[name=start_at]').val(info.startStr);
                $('#newTaskForm input[name=end_at]').val(info.endStr);
            },
            eventClick: function(info) {
                $('#editTaskForm').modal('show');
                console.log(info);
                editTask(info.event);
            },
            // dateClick: function(info) {
            //     alert('clicked ' + info.dateStr);
            // },
            eventResize: function(info) {
                $('.popover.in').remove();
                if (confirm("Êtes-vous sûr de vouloir appliquer ces modifications?")) {
                    submitTimeChanges(info.event);
                }else{
                    info.revert();
                }
            },
            eventDrop : function(info){
                $('.popover.in').remove();
                // $(info.el).removeAttr('aria-describedby');
                if (confirm("Êtes-vous sûr de vouloir appliquer ces modifications?")) {
                    submitTimeChanges(info.event);
                }else{
                    info.revert();
                }
            },
            eventRender: function(info) {

                $(info.el).append('');
                let state = function (state) {
                    if(state =="not_started") return "Pas encore commencé";
                    if(state =="started") return "Commencé";
                    if(state =="finish") return "Terminer";
                }
                $(info.el).popover({
                    title: info.event.title,
                    content: function () {
                        let html ="
"+moment(info.event.start).format('DD-MM-YYYY HH:mm')+' / '+moment(info.event.end).format('DD-MM-YYYY HH:mm')+"
"
                        +"
"+info.event.extendedProps.description+"
"
                        +"
"+"Utilisateur : "+info.event.extendedProps.user+"
"
                        +"
"+"Projet : "+info.event.extendedProps.project+"
"
                        +"
"+"Fonction : "+info.event.extendedProps.activity+"
"
                        +""+state(info.event.extendedProps.state)+"";
                        return html;
                    },
                    trigger: 'hover',
                    placement: 'top',
                    html: 'true',
                    container: 'body'
                    });
            },

        });
        calendar.addEventSource( taskEvents );
        calendar.render();
//--------------------------------------------------------

ajax script

var getTasks = function (data){
            $.ajax({
                url:"/admin/get-users-tasks",
                type:"POST",
                data :{
                    users:data,
                },
                headers: {
                    'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
                },
                success: function (response) {
                    calendar.addEventSource( response );
                    calendar.refetchEvents();
                },
                error: function(response) {
                    new PNotify({
                        title: "Opération échoué",
                        text: response.message,
                        type: "error"
                      });
                }
              });
        }

on change checkbox function

 function onChangeUserCheckbox() {
        $("input[name*=selected_user]").on('change',function () {
            var selectedUsers = [];
            $.each($("input[name*='selected_user']:checked"), function(){
                selectedUsers.push($(this).val());
            });
            getTasks(selectedUsers);
            // getTasks(JSON.stringify(selectedUsers));
        })
    }

Body:
What I do : destroy calendar and re render it

do not load calendar as indicated in the doc, but :

function LoadCalendar() {
        if (typeof calendar != "undefined") {
            document.getElementById("calendar").innerHTML = "";
        }
        var calendarEl = document.getElementById('calendar');
        calendar = new FullCalendar.Calendar(calendarEl, {
        //... parameters
        });
        calendar.render();
    }

Then at load :

function FirstCalendar() {
        MesEvents = "$events"; // Ajax script is executed and give $events
        LoadCalendar();
    }
        document.addEventListener('DOMContentLoaded', FirstCalendar);

And finnaly, for Ajax update :

function makeRequest(event) {
        //... ajax instructions
        httpRequest.onreadystatechange = function() { changeContents(httpRequest); };
        httpRequest.open('POST', 'url/ajax.php', true);
        httpRequest.send(oData);
    }
    function changeContents(httpRequest) {
        try {
            if (httpRequest.readyState == XMLHttpRequest.DONE) {
                if (httpRequest.status == 200) {
                    reponse = JSON.parse(httpRequest.responseText);
                    MesEvents = JSON.parse(reponse.Events);
                    LoadCalendar();
                } else {
                    alert('Un problème est survenu avec la requête : ' + httpRequest.status);
                }
            }
        }
        catch( e ) {
            alert(\"Une exception s’est produite (changeContents) : \" + e.description);
        }
    }


问:
speed up mysql query with multiple subqueries
I'm wondering if there's a way to speed up a mysql query which is ordered by multiple subqueries.

On a music related site users can like different things like artists, songs, albums etc. These "likes" are all stored in the same table. Now I want to show a list of artists ordered by the number of "likes" by the users friends and all users. I want to show all artists, also those who have no likes at all.

I have the following query:

```<code>SELECT `artists`.*,

    // friend likes
    (SELECT COUNT(*)
     FROM `likes`
     WHERE like_type = 'artist'
     AND like_id = artists.id
     AND user_id IN (1,2,3,4, etc) // ids of friends
     GROUP BY like_id
    ) AS `friend_likes`,

    // all likes
    (SELECT COUNT(*)
     FROM `likes`
     WHERE like_type = 'artist'
     AND like_id = artists.id
     GROUP BY like_id
    ) AS `all_likes`

FROM artists
ORDER BY
    friend_likes DESC,
    all_likes DESC,
    artists.name ASC
</code>```

The query takes ± 1.5 seconds on an artist table with 2000 rows. I'm afraid that this takes longer and longer as the table gets bigger and bigger. I tried using JOINS by can't seem to get this working because the subqueries contain WHERE statements.

Any ideas in the right direction would be greatly appreciated!

答:
Try using JOINs instead of subqueries:

```<code>SELECT
  artists.*, -- do you really need all this?
  count(user_id) AS all_likes,
  sum(user_id IN (1, 2, 3, 4)) AS friend_likes
FROM artists a
LEFT JOIN likes l
  ON l.like_type = 'artist' AND l.like_id = a.id
GROUP BY a.id
ORDER BY
  friend_likes DESC,
  all_likes DESC,
  artists.name ASC;
</code>```

If this doesn't make the query faster, try adding indices, or consider selecting less fields.

Body:
I'm wondering if there's a way to speed up a mysql query which is ordered by multiple subqueries.

On a music related site users can like different things like artists, songs, albums etc. These "likes" are all stored in the same table. Now I want to show a list of artists ordered by the number of "likes" by the users friends and all users. I want to show all artists, also those who have no likes at all.

I have the following query:

SELECT `artists`.*,

    // friend likes
    (SELECT COUNT(*)
     FROM `likes`
     WHERE like_type = 'artist'
     AND like_id = artists.id
     AND user_id IN (1,2,3,4, etc) // ids of friends
     GROUP BY like_id
    ) AS `friend_likes`,

    // all likes
    (SELECT COUNT(*)
     FROM `likes`
     WHERE like_type = 'artist'
     AND like_id = artists.id
     GROUP BY like_id
    ) AS `all_likes`

FROM artists
ORDER BY
    friend_likes DESC,
    all_likes DESC,
    artists.name ASC

The query takes ± 1.5 seconds on an artist table with 2000 rows. I'm afraid that this takes longer and longer as the table gets bigger and bigger. I tried using JOINS by can't seem to get this working because the subqueries contain WHERE statements.

Any ideas in the right direction would be greatly appreciated!

Body:
Try using JOINs instead of subqueries:

SELECT
  artists.*, -- do you really need all this?
  count(user_id) AS all_likes,
  sum(user_id IN (1, 2, 3, 4)) AS friend_likes
FROM artists a
LEFT JOIN likes l
  ON l.like_type = 'artist' AND l.like_id = a.id
GROUP BY a.id
ORDER BY
  friend_likes DESC,
  all_likes DESC,
  artists.name ASC;

If this doesn't make the query faster, try adding indices, or consider selecting less fields.


问:
Rails 5 + MongoDB issue in production
I've just moved a Rails 5.2.2 app to production server and i'm having problem with MongoDB, none of the queries work. Here some info:

```<code>CentOS 7
Ruby 2.6.3
Rails (5.2.2)
Mongoid (7.0.2)

$ mongo --version
MongoDB shell version v4.0.9
git version: fc525e2d9b0e4bceff5c2201457e564362909765
OpenSSL version: OpenSSL 1.0.1e-fips 11 Feb 2013
allocator: tcmalloc
modules: none
build environment:
    distmod: rhel70
    distarch: x86_64
    target_arch: x86_64
</code>```

MongoDB authentication is enabled, user with proper permissions has been created, the DB is not empty (was restored from a local copy), here's the production section of the mongoid.yml file:

```<code>production:
  clients:
    default:
      database: mydb_production
      hosts:
        - localhost:27017
      username: myuser
      password: "mypass"
      options:
        auth_mech: :scram
        auth_source: admin
</code>```

I keep seeing these topology debug messages in the production log:

[rails_root]/log/production.log

```<code>D, [2019-05-27T20:01:58.272760 #27444] DEBUG -- : MONGODB | EVENT: #<TopologyOpening topology=Unknown[]>
D, [2019-05-27T20:01:58.272934 #27444] DEBUG -- : MONGODB | Topology type 'unknown' initializing.
D, [2019-05-27T20:01:58.273748 #27444] DEBUG -- : MONGODB | EVENT: #<TopologyChanged prev=Unknown[] new=Unknown[localhost:27017]>
D, [2019-05-27T20:01:58.273848 #27444] DEBUG -- : MONGODB | Topology type 'Unknown' changed to type 'Unknown'.
D, [2019-05-27T20:01:58.274028 #27444] DEBUG -- : MONGODB | EVENT: #<ServerOpening address=localhost:27017 topology=Unknown[localhost:27017]>
D, [2019-05-27T20:01:58.274091 #27444] DEBUG -- : MONGODB | Server localhost:27017 initializing.
D, [2019-05-27T20:01:58.365308 #27444] DEBUG -- : MONGODB | EVENT: #<ServerDescriptionChanged address=localhost:27017 topology=Single[localhost:27017] prev=#<Mongo::Server:Description:0x70049014837980 config={} average_round_trip_time=> new=#<Mongo::Server:Description:0x70048970460940 config={"ismaster"=>true, "maxBsonObjectSize"=>16777216, "maxMessageSizeBytes"=>48000000, "maxWriteBatchSize"=>100000, "localTime"=>2019-05-28 00:01:58 UTC, "logicalSessionTimeoutMinutes"=>30, "minWireVersion"=>0, "maxWireVersion"=>7, "readOnly"=>false, "ok"=>1.0} average_round_trip_time=0.088107942>>
D, [2019-05-27T20:01:58.365596 #27444] DEBUG -- : MONGODB | Server description for localhost:27017 changed from 'unknown' to 'standalone'.
D, [2019-05-27T20:01:58.365843 #27444] DEBUG -- : MONGODB | EVENT: #<TopologyChanged prev=Unknown[localhost:27017] new=Single[localhost:27017]>
D, [2019-05-27T20:01:58.366024 #27444] DEBUG -- : MONGODB | Topology type 'Unknown' changed to type 'Single'.
</code>```

connecting to the console, any attempt at reading or writing records throws the following error:

```<code>$ rails c production
Running via Spring preloader in process 3131
Loading production environment (Rails 5.2.2)
2.6.3 :001 > User.first
Traceback (most recent call last):
        1: from (irb):1
NoMethodError (undefined method `encode' for nil:NilClass)
</code>```

Any idea what's going on here? Connecting to the db either with a GUI remotely or via the mongo command line i can read the collections fine so i'm assuming it's a problem between rails and mongo, not mongo itself.

EDIT

Full stack trace of the error, seems to me that mongoid can't authenticate with MongoDB, no idea why though, i'm using the same configurations has when connecting via GUI or command line...

```<code>begin; User.first; rescue => e; puts e.backtrace.join("\n"); end
/home/tsh/.rvm/gems/ruby-2.6.3/gems/mongo-2.8.0/lib/mongo/auth/user.rb:96:in `encoded_name'
/home/tsh/.rvm/gems/ruby-2.6.3/gems/mongo-2.8.0/lib/mongo/auth/scram/conversation.rb:334:in `first_bare'
/home/tsh/.rvm/gems/ruby-2.6.3/gems/mongo-2.8.0/lib/mongo/auth/scram/conversation.rb:277:in `client_first_message'
/home/tsh/.rvm/gems/ruby-2.6.3/gems/mongo-2.8.0/lib/mongo/auth/scram/conversation.rb:184:in `start'
/home/tsh/.rvm/gems/ruby-2.6.3/gems/mongo-2.8.0/lib/mongo/auth/scram.rb:71:in `login'
/home/tsh/.rvm/gems/ruby-2.6.3/gems/mongo-2.8.0/lib/mongo/server/connection.rb:284:in `block in authenticate!'
/home/tsh/.rvm/gems/ruby-2.6.3/gems/mongo-2.8.0/lib/mongo/server.rb:361:in `handle_auth_failure!'
/home/tsh/.rvm/gems/ruby-2.6.3/gems/mongo-2.8.0/lib/mongo/server/connection.rb:282:in `authenticate!'
/home/tsh/.rvm/gems/ruby-2.6.3/gems/mongo-2.8.0/lib/mongo/server/connection.rb:135:in `connect!'
/home/tsh/.rvm/gems/ruby-2.6.3/gems/mongo-2.8.0/lib/mongo/server/connectable.rb:78:in `ensure_connected'
/home/tsh/.rvm/gems/ruby-2.6.3/gems/mongo-2.8.0/lib/mongo/server/connection_base.rb:97:in `deliver'
/home/tsh/.rvm/gems/ruby-2.6.3/gems/mongo-2.8.0/lib/mongo/server/connection.rb:299:in `deliver'
/home/tsh/.rvm/gems/ruby-2.6.3/gems/mongo-2.8.0/lib/mongo/server/connection_base.rb:90:in `dispatch'
/home/tsh/.rvm/gems/ruby-2.6.3/gems/mongo-2.8.0/lib/mongo/operation/shared/executable.rb:42:in `block in dispatch_message'
/home/tsh/.rvm/gems/ruby-2.6.3/gems/mongo-2.8.0/lib/mongo/server/connection_pool.rb:123:in `with_connection'
/home/tsh/.rvm/gems/ruby-2.6.3/gems/mongo-2.8.0/lib/mongo/server.rb:334:in `with_connection'
/home/tsh/.rvm/gems/ruby-2.6.3/gems/mongo-2.8.0/lib/mongo/operation/shared/executable.rb:41:in `dispatch_message'
/home/tsh/.rvm/gems/ruby-2.6.3/gems/mongo-2.8.0/lib/mongo/operation/shared/executable.rb:36:in `get_result'
/home/tsh/.rvm/gems/ruby-2.6.3/gems/mongo-2.8.0/lib/mongo/operation/shared/executable.rb:24:in `execute'
/home/tsh/.rvm/gems/ruby-2.6.3/gems/mongo-2.8.0/lib/mongo/operation/shared/executable_transaction_label.rb:27:in `execute'
/home/tsh/.rvm/gems/ruby-2.6.3/gems/mongo-2.8.0/lib/mongo/operation/shared/op_msg_or_find_command.rb:28:in `execute'
/home/tsh/.rvm/gems/ruby-2.6.3/gems/mongo-2.8.0/lib/mongo/collection/view/iterable.rb:82:in `send_initial_query'
/home/tsh/.rvm/gems/ruby-2.6.3/gems/mongo-2.8.0/lib/mongo/collection/view/iterable.rb:42:in `block in each'
/home/tsh/.rvm/gems/ruby-2.6.3/gems/mongo-2.8.0/lib/mongo/retryable.rb:43:in `read_with_retry'
/home/tsh/.rvm/gems/ruby-2.6.3/gems/mongo-2.8.0/lib/mongo/collection/view/iterable.rb:40:in `each'
/home/tsh/.rvm/gems/ruby-2.6.3/gems/mongoid-7.0.3/lib/mongoid/query_cache.rb:227:in `each'
/home/tsh/.rvm/gems/ruby-2.6.3/gems/mongoid-7.0.3/lib/mongoid/contextual/mongo.rb:258:in `first'
/home/tsh/.rvm/gems/ruby-2.6.3/gems/mongoid-7.0.3/lib/mongoid/contextual/mongo.rb:258:in `block in first'
/home/tsh/.rvm/gems/ruby-2.6.3/gems/mongoid-7.0.3/lib/mongoid/contextual/mongo.rb:531:in `try_cache'
/home/tsh/.rvm/gems/ruby-2.6.3/gems/mongoid-7.0.3/lib/mongoid/contextual/mongo.rb:256:in `first'
/home/tsh/.rvm/gems/ruby-2.6.3/gems/mongoid-7.0.3/lib/mongoid/contextual.rb:20:in `first'
/home/tsh/.rvm/gems/ruby-2.6.3/gems/mongoid-7.0.3/lib/mongoid/findable.rb:148:in `first'
(irb):1:in `irb_binding'
/home/tsh/.rvm/rubies/ruby-2.6.3/lib/ruby/2.6.0/irb/workspace.rb:85:in `eval'
/home/tsh/.rvm/rubies/ruby-2.6.3/lib/ruby/2.6.0/irb/workspace.rb:85:in `evaluate'
/home/tsh/.rvm/rubies/ruby-2.6.3/lib/ruby/2.6.0/irb/context.rb:385:in `evaluate'
/home/tsh/.rvm/rubies/ruby-2.6.3/lib/ruby/2.6.0/irb.rb:493:in `block (2 levels) in eval_input'
/home/tsh/.rvm/rubies/ruby-2.6.3/lib/ruby/2.6.0/irb.rb:647:in `signal_status'
/home/tsh/.rvm/rubies/ruby-2.6.3/lib/ruby/2.6.0/irb.rb:490:in `block in eval_input'
/home/tsh/.rvm/rubies/ruby-2.6.3/lib/ruby/2.6.0/irb/ruby-lex.rb:246:in `block (2 levels) in each_top_level_statement'
/home/tsh/.rvm/rubies/ruby-2.6.3/lib/ruby/2.6.0/irb/ruby-lex.rb:232:in `loop'
/home/tsh/.rvm/rubies/ruby-2.6.3/lib/ruby/2.6.0/irb/ruby-lex.rb:232:in `block in each_top_level_statement'
/home/tsh/.rvm/rubies/ruby-2.6.3/lib/ruby/2.6.0/irb/ruby-lex.rb:231:in `catch'
/home/tsh/.rvm/rubies/ruby-2.6.3/lib/ruby/2.6.0/irb/ruby-lex.rb:231:in `each_top_level_statement'
/home/tsh/.rvm/rubies/ruby-2.6.3/lib/ruby/2.6.0/irb.rb:489:in `eval_input'
/home/tsh/.rvm/rubies/ruby-2.6.3/lib/ruby/2.6.0/irb.rb:428:in `block in run'
/home/tsh/.rvm/rubies/ruby-2.6.3/lib/ruby/2.6.0/irb.rb:427:in `catch'
/home/tsh/.rvm/rubies/ruby-2.6.3/lib/ruby/2.6.0/irb.rb:427:in `run'
/home/tsh/.rvm/rubies/ruby-2.6.3/lib/ruby/2.6.0/irb.rb:383:in `start'
/home/tsh/.rvm/gems/ruby-2.6.3/gems/railties-5.2.2/lib/rails/commands/console/console_command.rb:64:in `start'
/home/tsh/.rvm/gems/ruby-2.6.3/gems/railties-5.2.2/lib/rails/commands/console/console_command.rb:19:in `start'
/home/tsh/.rvm/gems/ruby-2.6.3/gems/railties-5.2.2/lib/rails/commands/console/console_command.rb:96:in `perform'
/home/tsh/.rvm/gems/ruby-2.6.3/gems/thor-0.20.3/lib/thor/command.rb:27:in `run'
/home/tsh/.rvm/gems/ruby-2.6.3/gems/thor-0.20.3/lib/thor/invocation.rb:126:in `invoke_command'
/home/tsh/.rvm/gems/ruby-2.6.3/gems/thor-0.20.3/lib/thor.rb:387:in `dispatch'
/home/tsh/.rvm/gems/ruby-2.6.3/gems/railties-5.2.2/lib/rails/command/base.rb:65:in `perform'
/home/tsh/.rvm/gems/ruby-2.6.3/gems/railties-5.2.2/lib/rails/command.rb:46:in `invoke'
/home/tsh/.rvm/gems/ruby-2.6.3/gems/railties-5.2.2/lib/rails/commands.rb:18:in `<main>'
/home/tsh/.rvm/gems/ruby-2.6.3/gems/bootsnap-1.4.1/lib/bootsnap/load_path_cache/core_ext/kernel_require.rb:21:in `require'
/home/tsh/.rvm/gems/ruby-2.6.3/gems/bootsnap-1.4.1/lib/bootsnap/load_path_cache/core_ext/kernel_require.rb:21:in `block in require_with_bootsnap_lfi'
/home/tsh/.rvm/gems/ruby-2.6.3/gems/bootsnap-1.4.1/lib/bootsnap/load_path_cache/loaded_features_index.rb:83:in `register'
/home/tsh/.rvm/gems/ruby-2.6.3/gems/bootsnap-1.4.1/lib/bootsnap/load_path_cache/core_ext/kernel_require.rb:20:in `require_with_bootsnap_lfi'
/home/tsh/.rvm/gems/ruby-2.6.3/gems/bootsnap-1.4.1/lib/bootsnap/load_path_cache/core_ext/kernel_require.rb:29:in `require'
/home/tsh/.rvm/gems/ruby-2.6.3/gems/activesupport-5.2.2/lib/active_support/dependencies.rb:291:in `block in require'
/home/tsh/.rvm/gems/ruby-2.6.3/gems/activesupport-5.2.2/lib/active_support/dependencies.rb:257:in `load_dependency'
/home/tsh/.rvm/gems/ruby-2.6.3/gems/activesupport-5.2.2/lib/active_support/dependencies.rb:291:in `require'
/var/www/webtsh/bin/rails:9:in `<main>'
/home/tsh/.rvm/gems/ruby-2.6.3/gems/bootsnap-1.4.1/lib/bootsnap/load_path_cache/core_ext/kernel_require.rb:50:in `load'
/home/tsh/.rvm/gems/ruby-2.6.3/gems/bootsnap-1.4.1/lib/bootsnap/load_path_cache/core_ext/kernel_require.rb:50:in `load'
/home/tsh/.rvm/rubies/ruby-2.6.3/lib/ruby/2.6.0/rubygems/core_ext/kernel_require.rb:54:in `require'
/home/tsh/.rvm/rubies/ruby-2.6.3/lib/ruby/2.6.0/rubygems/core_ext/kernel_require.rb:54:in `require'
</code>```

答:
Start by obtaining a full stack trace for the exception, from there you can narrow the issue down to your application or a library it is using.

To obtain the full stack trace in an IRB console, you can use the following trick:

```<code>begin; <your code here>; rescue => e; puts e.backtrace.join("\n"); end
</code>```

Example:

```<code>averagest% irb
irb(main):001:0> hai
Traceback (most recent call last):
        2: from /home/w/.rbenv/versions/2.5.1/bin/irb:11:in `<main>'
        1: from (irb):1
NameError (undefined local variable or method `hai' for main:Object)
Did you mean?  hash

irb(main):003:0> begin; hai; rescue => e; puts e.backtrace.join("\n"); end
(irb):3:in `irb_binding'
/home/w/.rbenv/versions/2.5.1/lib/ruby/2.5.0/irb/workspace.rb:85:in `eval'
/home/w/.rbenv/versions/2.5.1/lib/ruby/2.5.0/irb/workspace.rb:85:in `evaluate'
/home/w/.rbenv/versions/2.5.1/lib/ruby/2.5.0/irb/context.rb:380:in `evaluate'
/home/w/.rbenv/versions/2.5.1/lib/ruby/2.5.0/irb.rb:491:in `block (2 levels) in eval_input'
/home/w/.rbenv/versions/2.5.1/lib/ruby/2.5.0/irb.rb:623:in `signal_status'
/home/w/.rbenv/versions/2.5.1/lib/ruby/2.5.0/irb.rb:488:in `block in eval_input'
/home/w/.rbenv/versions/2.5.1/lib/ruby/2.5.0/irb/ruby-lex.rb:246:in `block (2 levels) in each_top_level_statement'
/home/w/.rbenv/versions/2.5.1/lib/ruby/2.5.0/irb/ruby-lex.rb:232:in `loop'
/home/w/.rbenv/versions/2.5.1/lib/ruby/2.5.0/irb/ruby-lex.rb:232:in `block in each_top_level_statement'
/home/w/.rbenv/versions/2.5.1/lib/ruby/2.5.0/irb/ruby-lex.rb:231:in `catch'
/home/w/.rbenv/versions/2.5.1/lib/ruby/2.5.0/irb/ruby-lex.rb:231:in `each_top_level_statement'
/home/w/.rbenv/versions/2.5.1/lib/ruby/2.5.0/irb.rb:487:in `eval_input'
/home/w/.rbenv/versions/2.5.1/lib/ruby/2.5.0/irb.rb:428:in `block in run'
/home/w/.rbenv/versions/2.5.1/lib/ruby/2.5.0/irb.rb:427:in `catch'
/home/w/.rbenv/versions/2.5.1/lib/ruby/2.5.0/irb.rb:427:in `run'
/home/w/.rbenv/versions/2.5.1/lib/ruby/2.5.0/irb.rb:383:in `start'
/home/w/.rbenv/versions/2.5.1/bin/irb:11:in `<main>'
=> nil
irb(main):004:0>
</code>```

Title: Rails 5 + MongoDB issue in production

Body:
I've just moved a Rails 5.2.2 app to production server and i'm having problem with MongoDB, none of the queries work. Here some info:

CentOS 7
Ruby 2.6.3
Rails (5.2.2)
Mongoid (7.0.2)

$ mongo --version
MongoDB shell version v4.0.9
git version: fc525e2d9b0e4bceff5c2201457e564362909765
OpenSSL version: OpenSSL 1.0.1e-fips 11 Feb 2013
allocator: tcmalloc
modules: none
build environment:
    distmod: rhel70
    distarch: x86_64
    target_arch: x86_64

MongoDB authentication is enabled, user with proper permissions has been created, the DB is not empty (was restored from a local copy), here's the production section of the mongoid.yml file:

production:
  clients:
    default:
      database: mydb_production
      hosts:
        - localhost:27017
      username: myuser
      password: "mypass"
      options:
        auth_mech: :scram
        auth_source: admin

I keep seeing these topology debug messages in the production log:

[rails_root]/log/production.log

D, [2019-05-27T20:01:58.272760 #27444] DEBUG -- : MONGODB | EVENT: #<TopologyOpening topology=Unknown[]>
D, [2019-05-27T20:01:58.272934 #27444] DEBUG -- : MONGODB | Topology type 'unknown' initializing.
D, [2019-05-27T20:01:58.273748 #27444] DEBUG -- : MONGODB | EVENT: #<TopologyChanged prev=Unknown[] new=Unknown[localhost:27017]>
D, [2019-05-27T20:01:58.273848 #27444] DEBUG -- : MONGODB | Topology type 'Unknown' changed to type 'Unknown'.
D, [2019-05-27T20:01:58.274028 #27444] DEBUG -- : MONGODB | EVENT: #<ServerOpening address=localhost:27017 topology=Unknown[localhost:27017]>
D, [2019-05-27T20:01:58.274091 #27444] DEBUG -- : MONGODB | Server localhost:27017 initializing.
D, [2019-05-27T20:01:58.365308 #27444] DEBUG -- : MONGODB | EVENT: #<ServerDescriptionChanged address=localhost:27017 topology=Single[localhost:27017] prev=#<Mongo::Server:Description:0x70049014837980 config={} average_round_trip_time=> new=#<Mongo::Server:Description:0x70048970460940 config={"ismaster"=>true, "maxBsonObjectSize"=>16777216, "maxMessageSizeBytes"=>48000000, "maxWriteBatchSize"=>100000, "localTime"=>2019-05-28 00:01:58 UTC, "logicalSessionTimeoutMinutes"=>30, "minWireVersion"=>0, "maxWireVersion"=>7, "readOnly"=>false, "ok"=>1.0} average_round_trip_time=0.088107942>>
D, [2019-05-27T20:01:58.365596 #27444] DEBUG -- : MONGODB | Server description for localhost:27017 changed from 'unknown' to 'standalone'.
D, [2019-05-27T20:01:58.365843 #27444] DEBUG -- : MONGODB | EVENT: #<TopologyChanged prev=Unknown[localhost:27017] new=Single[localhost:27017]>
D, [2019-05-27T20:01:58.366024 #27444] DEBUG -- : MONGODB | Topology type 'Unknown' changed to type 'Single'.

connecting to the console, any attempt at reading or writing records throws the following error:

$ rails c production
Running via Spring preloader in process 3131
Loading production environment (Rails 5.2.2)
2.6.3 :001 > User.first
Traceback (most recent call last):
        1: from (irb):1
NoMethodError (undefined method `encode' for nil:NilClass)

Any idea what's going on here? Connecting to the db either with a GUI remotely or via the mongo command line i can read the collections fine so i'm assuming it's a problem between rails and mongo, not mongo itself.

EDIT

Full stack trace of the error, seems to me that mongoid can't authenticate with MongoDB, no idea why though, i'm using the same configurations has when connecting via GUI or command line...

begin; User.first; rescue => e; puts e.backtrace.join("\n"); end
/home/tsh/.rvm/gems/ruby-2.6.3/gems/mongo-2.8.0/lib/mongo/auth/user.rb:96:in `encoded_name'
/home/tsh/.rvm/gems/ruby-2.6.3/gems/mongo-2.8.0/lib/mongo/auth/scram/conversation.rb:334:in `first_bare'
/home/tsh/.rvm/gems/ruby-2.6.3/gems/mongo-2.8.0/lib/mongo/auth/scram/conversation.rb:277:in `client_first_message'
/home/tsh/.rvm/gems/ruby-2.6.3/gems/mongo-2.8.0/lib/mongo/auth/scram/conversation.rb:184:in `start'
/home/tsh/.rvm/gems/ruby-2.6.3/gems/mongo-2.8.0/lib/mongo/auth/scram.rb:71:in `login'
/home/tsh/.rvm/gems/ruby-2.6.3/gems/mongo-2.8.0/lib/mongo/server/connection.rb:284:in `block in authenticate!'
/home/tsh/.rvm/gems/ruby-2.6.3/gems/mongo-2.8.0/lib/mongo/server.rb:361:in `handle_auth_failure!'
/home/tsh/.rvm/gems/ruby-2.6.3/gems/mongo-2.8.0/lib/mongo/server/connection.rb:282:in `authenticate!'
/home/tsh/.rvm/gems/ruby-2.6.3/gems/mongo-2.8.0/lib/mongo/server/connection.rb:135:in `connect!'
/home/tsh/.rvm/gems/ruby-2.6.3/gems/mongo-2.8.0/lib/mongo/server/connectable.rb:78:in `ensure_connected'
/home/tsh/.rvm/gems/ruby-2.6.3/gems/mongo-2.8.0/lib/mongo/server/connection_base.rb:97:in `deliver'
/home/tsh/.rvm/gems/ruby-2.6.3/gems/mongo-2.8.0/lib/mongo/server/connection.rb:299:in `deliver'
/home/tsh/.rvm/gems/ruby-2.6.3/gems/mongo-2.8.0/lib/mongo/server/connection_base.rb:90:in `dispatch'
/home/tsh/.rvm/gems/ruby-2.6.3/gems/mongo-2.8.0/lib/mongo/operation/shared/executable.rb:42:in `block in dispatch_message'
/home/tsh/.rvm/gems/ruby-2.6.3/gems/mongo-2.8.0/lib/mongo/server/connection_pool.rb:123:in `with_connection'
/home/tsh/.rvm/gems/ruby-2.6.3/gems/mongo-2.8.0/lib/mongo/server.rb:334:in `with_connection'
/home/tsh/.rvm/gems/ruby-2.6.3/gems/mongo-2.8.0/lib/mongo/operation/shared/executable.rb:41:in `dispatch_message'
/home/tsh/.rvm/gems/ruby-2.6.3/gems/mongo-2.8.0/lib/mongo/operation/shared/executable.rb:36:in `get_result'
/home/tsh/.rvm/gems/ruby-2.6.3/gems/mongo-2.8.0/lib/mongo/operation/shared/executable.rb:24:in `execute'
/home/tsh/.rvm/gems/ruby-2.6.3/gems/mongo-2.8.0/lib/mongo/operation/shared/executable_transaction_label.rb:27:in `execute'
/home/tsh/.rvm/gems/ruby-2.6.3/gems/mongo-2.8.0/lib/mongo/operation/shared/op_msg_or_find_command.rb:28:in `execute'
/home/tsh/.rvm/gems/ruby-2.6.3/gems/mongo-2.8.0/lib/mongo/collection/view/iterable.rb:82:in `send_initial_query'
/home/tsh/.rvm/gems/ruby-2.6.3/gems/mongo-2.8.0/lib/mongo/collection/view/iterable.rb:42:in `block in each'
/home/tsh/.rvm/gems/ruby-2.6.3/gems/mongo-2.8.0/lib/mongo/retryable.rb:43:in `read_with_retry'
/home/tsh/.rvm/gems/ruby-2.6.3/gems/mongo-2.8.0/lib/mongo/collection/view/iterable.rb:40:in `each'
/home/tsh/.rvm/gems/ruby-2.6.3/gems/mongoid-7.0.3/lib/mongoid/query_cache.rb:227:in `each'
/home/tsh/.rvm/gems/ruby-2.6.3/gems/mongoid-7.0.3/lib/mongoid/contextual/mongo.rb:258:in `first'
/home/tsh/.rvm/gems/ruby-2.6.3/gems/mongoid-7.0.3/lib/mongoid/contextual/mongo.rb:258:in `block in first'
/home/tsh/.rvm/gems/ruby-2.6.3/gems/mongoid-7.0.3/lib/mongoid/contextual/mongo.rb:531:in `try_cache'
/home/tsh/.rvm/gems/ruby-2.6.3/gems/mongoid-7.0.3/lib/mongoid/contextual/mongo.rb:256:in `first'
/home/tsh/.rvm/gems/ruby-2.6.3/gems/mongoid-7.0.3/lib/mongoid/contextual.rb:20:in `first'
/home/tsh/.rvm/gems/ruby-2.6.3/gems/mongoid-7.0.3/lib/mongoid/findable.rb:148:in `first'
(irb):1:in `irb_binding'
/home/tsh/.rvm/rubies/ruby-2.6.3/lib/ruby/2.6.0/irb/workspace.rb:85:in `eval'
/home/tsh/.rvm/rubies/ruby-2.6.3/lib/ruby/2.6.0/irb/workspace.rb:85:in `evaluate'
/home/tsh/.rvm/rubies/ruby-2.6.3/lib/ruby/2.6.0/irb/context.rb:385:in `evaluate'
/home/tsh/.rvm/rubies/ruby-2.6.3/lib/ruby/2.6.0/irb.rb:493:in `block (2 levels) in eval_input'
/home/tsh/.rvm/rubies/ruby-2.6.3/lib/ruby/2.6.0/irb.rb:647:in `signal_status'
/home/tsh/.rvm/rubies/ruby-2.6.3/lib/ruby/2.6.0/irb.rb:490:in `block in eval_input'
/home/tsh/.rvm/rubies/ruby-2.6.3/lib/ruby/2.6.0/irb/ruby-lex.rb:246:in `block (2 levels) in each_top_level_statement'
/home/tsh/.rvm/rubies/ruby-2.6.3/lib/ruby/2.6.0/irb/ruby-lex.rb:232:in `loop'
/home/tsh/.rvm/rubies/ruby-2.6.3/lib/ruby/2.6.0/irb/ruby-lex.rb:232:in `block in each_top_level_statement'
/home/tsh/.rvm/rubies/ruby-2.6.3/lib/ruby/2.6.0/irb/ruby-lex.rb:231:in `catch'
/home/tsh/.rvm/rubies/ruby-2.6.3/lib/ruby/2.6.0/irb/ruby-lex.rb:231:in `each_top_level_statement'
/home/tsh/.rvm/rubies/ruby-2.6.3/lib/ruby/2.6.0/irb.rb:489:in `eval_input'
/home/tsh/.rvm/rubies/ruby-2.6.3/lib/ruby/2.6.0/irb.rb:428:in `block in run'
/home/tsh/.rvm/rubies/ruby-2.6.3/lib/ruby/2.6.0/irb.rb:427:in `catch'
/home/tsh/.rvm/rubies/ruby-2.6.3/lib/ruby/2.6.0/irb.rb:427:in `run'
/home/tsh/.rvm/rubies/ruby-2.6.3/lib/ruby/2.6.0/irb.rb:383:in `start'
/home/tsh/.rvm/gems/ruby-2.6.3/gems/railties-5.2.2/lib/rails/commands/console/console_command.rb:64:in `start'
/home/tsh/.rvm/gems/ruby-2.6.3/gems/railties-5.2.2/lib/rails/commands/console/console_command.rb:19:in `start'
/home/tsh/.rvm/gems/ruby-2.6.3/gems/railties-5.2.2/lib/rails/commands/console/console_command.rb:96:in `perform'
/home/tsh/.rvm/gems/ruby-2.6.3/gems/thor-0.20.3/lib/thor/command.rb:27:in `run'
/home/tsh/.rvm/gems/ruby-2.6.3/gems/thor-0.20.3/lib/thor/invocation.rb:126:in `invoke_command'
/home/tsh/.rvm/gems/ruby-2.6.3/gems/thor-0.20.3/lib/thor.rb:387:in `dispatch'
/home/tsh/.rvm/gems/ruby-2.6.3/gems/railties-5.2.2/lib/rails/command/base.rb:65:in `perform'
/home/tsh/.rvm/gems/ruby-2.6.3/gems/railties-5.2.2/lib/rails/command.rb:46:in `invoke'
/home/tsh/.rvm/gems/ruby-2.6.3/gems/railties-5.2.2/lib/rails/commands.rb:18:in `'
/home/tsh/.rvm/gems/ruby-2.6.3/gems/bootsnap-1.4.1/lib/bootsnap/load_path_cache/core_ext/kernel_require.rb:21:in `require'
/home/tsh/.rvm/gems/ruby-2.6.3/gems/bootsnap-1.4.1/lib/bootsnap/load_path_cache/core_ext/kernel_require.rb:21:in `block in require_with_bootsnap_lfi'
/home/tsh/.rvm/gems/ruby-2.6.3/gems/bootsnap-1.4.1/lib/bootsnap/load_path_cache/loaded_features_index.rb:83:in `register'
/home/tsh/.rvm/gems/ruby-2.6.3/gems/bootsnap-1.4.1/lib/bootsnap/load_path_cache/core_ext/kernel_require.rb:20:in `require_with_bootsnap_lfi'
/home/tsh/.rvm/gems/ruby-2.6.3/gems/bootsnap-1.4.1/lib/bootsnap/load_path_cache/core_ext/kernel_require.rb:29:in `require'
/home/tsh/.rvm/gems/ruby-2.6.3/gems/activesupport-5.2.2/lib/active_support/dependencies.rb:291:in `block in require'
/home/tsh/.rvm/gems/ruby-2.6.3/gems/activesupport-5.2.2/lib/active_support/dependencies.rb:257:in `load_dependency'
/home/tsh/.rvm/gems/ruby-2.6.3/gems/activesupport-5.2.2/lib/active_support/dependencies.rb:291:in `require'
/var/www/webtsh/bin/rails:9:in `'
/home/tsh/.rvm/gems/ruby-2.6.3/gems/bootsnap-1.4.1/lib/bootsnap/load_path_cache/core_ext/kernel_require.rb:50:in `load'
/home/tsh/.rvm/gems/ruby-2.6.3/gems/bootsnap-1.4.1/lib/bootsnap/load_path_cache/core_ext/kernel_require.rb:50:in `load'
/home/tsh/.rvm/rubies/ruby-2.6.3/lib/ruby/2.6.0/rubygems/core_ext/kernel_require.rb:54:in `require'
/home/tsh/.rvm/rubies/ruby-2.6.3/lib/ruby/2.6.0/rubygems/core_ext/kernel_require.rb:54:in `require'

Body:
Start by obtaining a full stack trace for the exception, from there you can narrow the issue down to your application or a library it is using.

To obtain the full stack trace in an IRB console, you can use the following trick:

begin; <your code here>; rescue => e; puts e.backtrace.join("\n"); end

Example:

averagest% irb
irb(main):001:0> hai
Traceback (most recent call last):
        2: from /home/w/.rbenv/versions/2.5.1/bin/irb:11:in `<main>'
        1: from (irb):1
NameError (undefined local variable or method `hai' for main:Object)
Did you mean?  hash

irb(main):003:0> begin; hai; rescue => e; puts e.backtrace.join("\n"); end
(irb):3:in `irb_binding'
/home/w/.rbenv/versions/2.5.1/lib/ruby/2.5.0/irb/workspace.rb:85:in `eval'
/home/w/.rbenv/versions/2.5.1/lib/ruby/2.5.0/irb/workspace.rb:85:in `evaluate'
/home/w/.rbenv/versions/2.5.1/lib/ruby/2.5.0/irb/context.rb:380:in `evaluate'
/home/w/.rbenv/versions/2.5.1/lib/ruby/2.5.0/irb.rb:491:in `block (2 levels) in eval_input'
/home/w/.rbenv/versions/2.5.1/lib/ruby/2.5.0/irb.rb:623:in `signal_status'
/home/w/.rbenv/versions/2.5.1/lib/ruby/2.5.0/irb.rb:488:in `block in eval_input'
/home/w/.rbenv/versions/2.5.1/lib/ruby/2.5.0/irb/ruby-lex.rb:246:in `block (2 levels) in each_top_level_statement'
/home/w/.rbenv/versions/2.5.1/lib/ruby/2.5.0/irb/ruby-lex.rb:232:in `loop'
/home/w/.rbenv/versions/2.5.1/lib/ruby/2.5.0/irb/ruby-lex.rb:232:in `block in each_top_level_statement'
/home/w/.rbenv/versions/2.5.1/lib/ruby/2.5.0/irb/ruby-lex.rb:231:in `catch'
/home/w/.rbenv/versions/2.5.1/lib/ruby/2.5.0/irb/ruby-lex.rb:231:in `each_top_level_statement'
/home/w/.rbenv/versions/2.5.1/lib/ruby/2.5.0/irb.rb:487:in `eval_input'
/home/w/.rbenv/versions/2.5.1/lib/ruby/2.5.0/irb.rb:428:in `block in run'
/home/w/.rbenv/versions/2.5.1/lib/ruby/2.5.0/irb.rb:427:in `catch'
/home/w/.rbenv/versions/2.5.1/lib/ruby/2.5.0/irb.rb:427:in `run'
/home/w/.rbenv/versions/2.5.1/lib/ruby/2.5.0/irb.rb:383:in `start'
/home/w/.rbenv/versions/2.5.1/bin/irb:11:in `<main>'
=> nil
irb(main):004:0>