问:
How to get the dimensions of an image from firebase storage in firebase functions?
I have an app having firebase back-end. and when i made i didn't thought about the dimensions of images as if they ll be useful in future so i just kept the images as they are and kept their URLs in firestore.

But now i m in need of dimensions of images before showing them to user so i have thought of making a function that i ll execute only once in order to set the files with their dimension in firestore and i ll also add some client side code in order to get the dimensions before uploading them.

So i have tried almost everything to get the file dimensions in functions but couldn't do it.

sample[abstract code]

this code works in node.js but fails in firebase functions

```<code>    const fs = require('fs')
    const request = require('request')
    import sizeOf from 'image-size'
    const FIRE = 'https://firebasestorage.googleapis.com/file....'
    const FILE = 'file.jpg';

    request.head(FIRE, (err, res, body) => {
        request(FIRE)
            .pipe(fs.createWriteStream(FILE))
            .on('close', () => {
                sizeOf(FILE, (err1, dimensions) => {
                    const result = {
                        "width": dimensions.width,
                        "height": dimensions.height
                    }
                    console.log(dimensions.width, dimensions.height);
                    fs.unlinkSync(FILE);
                    response.setHeader('Content-Type', 'application/json');
                    const responseData = {
                        'Error': false,
                        'Message': "result : " + result
                    };
                    response.send(JSON.stringify(responseData));
                })
            })
    })
</code>```

help me if someone knows something about this!

and moreover also tell me about how firebase keeps images, i mean in what manner ? whenever i open the url it doesnt show me the image instead it just downloads the image unline other urls on random websites.

I have got a trick to do it. It is quite prone to error, but will work for sure :

get all the urls of images using an api and do the stuff locally using node.js and post the result to another api, which will then feed the data to firestore ?

答:
Your code is trying to write to:

```<code>const FILE = 'file.jpg';
</code>```

Which is a file in the same directory as where your index.js is stored. This is (as the error message says) a read-only directory in the Cloud Functions container. If you want to write any files, they must be in /tmp (also known as tempfs). See Write temporary files from Google Cloud Function

Body:
I have an app having firebase back-end. and when i made i didn't thought about the dimensions of images as if they ll be useful in future so i just kept the images as they are and kept their URLs in firestore.

But now i m in need of dimensions of images before showing them to user so i have thought of making a function that i ll execute only once in order to set the files with their dimension in firestore and i ll also add some client side code in order to get the dimensions before uploading them.

So i have tried almost everything to get the file dimensions in functions but couldn't do it.

sample[abstract code]

this code works in node.js but fails in firebase functions

    const fs = require('fs')
    const request = require('request')
    import sizeOf from 'image-size'
    const FIRE = 'https://firebasestorage.googleapis.com/file....'
    const FILE = 'file.jpg';

    request.head(FIRE, (err, res, body) => {
        request(FIRE)
            .pipe(fs.createWriteStream(FILE))
            .on('close', () => {
                sizeOf(FILE, (err1, dimensions) => {
                    const result = {
                        "width": dimensions.width,
                        "height": dimensions.height
                    }
                    console.log(dimensions.width, dimensions.height);
                    fs.unlinkSync(FILE);
                    response.setHeader('Content-Type', 'application/json');
                    const responseData = {
                        'Error': false,
                        'Message': "result : " + result
                    };
                    response.send(JSON.stringify(responseData));
                })
            })
    })

help me if someone knows something about this!

and moreover also tell me about how firebase keeps images, i mean in what manner ? whenever i open the url it doesnt show me the image instead it just downloads the image unline other urls on random websites.

I have got a trick to do it. It is quite prone to error, but will work for sure :

get all the urls of images using an api and do the stuff locally using node.js and post the result to another api, which will then feed the data to firestore ?

Body:
Your code is trying to write to:

const FILE = 'file.jpg';

Which is a file in the same directory as where your index.js is stored. This is (as the error message says) a read-only directory in the Cloud Functions container. If you want to write any files, they must be in /tmp (also known as tempfs). See Write temporary files from Google Cloud Function


来源: stackexchange

问:
Git: How to list all branches that were created from a specific branch?
I need to generate a report with all branch names that were created from  develop branch (which was branched off master sometime in the past). My approach was to get the first and last commits in develop using git log --pretty=format:"%h" master..develop, then use the range of commits with git branch --contains <hash>.

However, the above approach has a few problems:

I need to run to commands to know the range of commits to consider in my query.

I'll have to repeat the git branch --contains command each hash in the range.

The output from git branch --contains commands will contain redundant results for most cases because of the fact that most commits are common between branches.

I'm hoping there is a better and more direct way of doing this. Below I'll try to illustrate the case of interest:

```<code>  master
    ^
    |                      develop
a---b                        ^
     \                       |
      --c--d---e---f---g--h--i
           \      \    \      \
            k-l    m    n      o--p
              ^    ^    ^         ^
              |    |    |         |
         branch_1  | branch_3     |
                 branch_2       branch_4

// Desired output:
branch_1
branch_2
branch_3
branch_4
</code>```

答:
You can get awfully close with one command:

```<code>git log --ancestry-path  --branches --not $(git merge-base --all master develop) \
        --pretty=%D  --simplify-by-decoration --decorate-refs=refs/heads
</code>```

That's "show me just the branch decorations in all branch-tip histories that trace back to the current merge base of master and develop".

You can get it prettier by piping the result through anything like awk '{print $NF}' RS=', |\n'.

Note that this (like @torek's answer) assumes you're doing this in a repo administered for archival-level stability like your production master, there's no necessary relation between branch names and commits at all, let alone a permanent, or global or unique one.   If you're trying to permanently tie commits to some external administrative record, do it in the commit message, not the branch name.

Edit: if you want a quick overview of the current branch structure since the master-develop split,

```<code>git log --graph --decorate-refs=refs/heads --oneline \
         --branches --simplify-by-decoration \
         --ancestry-path --boundary --not `git merge-base master develop`
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I need to generate a report with all branch names that were created from  develop branch (which was branched off master sometime in the past). My approach was to get the first and last commits in develop using git log --pretty=format:"%h" master..develop, then use the range of commits with git branch --contains <hash>.

However, the above approach has a few problems:

I need to run to commands to know the range of commits to consider in my query.

I'll have to repeat the git branch --contains command each hash in the range.

The output from git branch --contains commands will contain redundant results for most cases because of the fact that most commits are common between branches.

I'm hoping there is a better and more direct way of doing this. Below I'll try to illustrate the case of interest:

  master
    ^
    |                      develop
a---b                        ^
     \                       |
      --c--d---e---f---g--h--i
           \      \    \      \
            k-l    m    n      o--p
              ^    ^    ^         ^
              |    |    |         |
         branch_1  | branch_3     |
                 branch_2       branch_4

// Desired output:
branch_1
branch_2
branch_3
branch_4

Body:
You can get awfully close with one command:

git log --ancestry-path  --branches --not $(git merge-base --all master develop) \
        --pretty=%D  --simplify-by-decoration --decorate-refs=refs/heads

That's "show me just the branch decorations in all branch-tip histories that trace back to the current merge base of master and develop".

You can get it prettier by piping the result through anything like awk '{print $NF}' RS=', |\n'.

Note that this (like @torek's answer) assumes you're doing this in a repo administered for archival-level stability like your production master, there's no necessary relation between branch names and commits at all, let alone a permanent, or global or unique one.   If you're trying to permanently tie commits to some external administrative record, do it in the commit message, not the branch name.

Edit: if you want a quick overview of the current branch structure since the master-develop split,

git log --graph --decorate-refs=refs/heads --oneline \
         --branches --simplify-by-decoration \
         --ancestry-path --boundary --not `git merge-base master develop`


问:
Loading table view with data with 2 different prototype cells
I am trying to populate a tableView with different prototype cells at different times. The problem is any code after let cell = tableView.dequeueReusableCell(withIdentifier: "MeArticlesCell") as? MeArticlesCell else {return UITableViewCell()} isn't being called and I can't figure out why. Im returning the correct amount of rows.

```<code> func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

    if(postsSelected){
        guard let cell = tableView.dequeueReusableCell(withIdentifier: "messageCell") as? feedMessagesCell else {return UITableViewCell()}
        //the code in this part loads posts fine

    } else {
        guard let cell = tableView.dequeueReusableCell(withIdentifier: "messageCell") as? feedMessagesCell else {return UITableViewCell()}
        //this part never gets called
    }
}
</code>```

答:
Basically your guard statement fails and goes into the else part.

```<code>    guard let cell = tableView.dequeueReusableCell(withIdentifier: "messageCell") as? feedMessagesCell else { // this fails
       // enters here
       return UITableViewCell()
       // exist the function - nothing will be run after
    }
</code>```

My guess is it fails to cast your it as a feedMessagesCell, so tableView.dequeueReusableCell(withIdentifier: "messageCell") as? feedMessagesCell makes cell to be nil ( and then enter the else part )

Body:
I am trying to populate a tableView with different prototype cells at different times. The problem is any code after let cell = tableView.dequeueReusableCell(withIdentifier: "MeArticlesCell") as? MeArticlesCell else {return UITableViewCell()} isn't being called and I can't figure out why. Im returning the correct amount of rows.

 func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

    if(postsSelected){
        guard let cell = tableView.dequeueReusableCell(withIdentifier: "messageCell") as? feedMessagesCell else {return UITableViewCell()}
        //the code in this part loads posts fine

    } else {
        guard let cell = tableView.dequeueReusableCell(withIdentifier: "messageCell") as? feedMessagesCell else {return UITableViewCell()}
        //this part never gets called
    }
}

Body:
Basically your guard statement fails and goes into the else part.

    guard let cell = tableView.dequeueReusableCell(withIdentifier: "messageCell") as? feedMessagesCell else { // this fails
       // enters here
       return UITableViewCell()
       // exist the function - nothing will be run after
    }

My guess is it fails to cast your it as a feedMessagesCell, so tableView.dequeueReusableCell(withIdentifier: "messageCell") as? feedMessagesCell makes cell to be nil ( and then enter the else part )


问:
Warning: filter_var() expects parameter 2 to be long, string given in
In this code I get a warning

Warning: filter_var() expects parameter 2 to be long, string given in the last line

```<code>$check = filter_var($email, FILTER_SANITIZE_EMAIL);
$str = filter_var($name, FILTER_SANITIZE_STRING);
if (!filter_var($check, FILTER_VALIDATE_EMAIL) && !filter_var($str, FILTER_VALIDATE_STRING)) { //here
</code>```

The problem is this, because without it no exists any warning message

```<code> !filter_var($str, FILTER_VALIDATE_STRING)
</code>```

What is the reason of this error?

答:
As @TaylorOtwell mentioned: There is no filter FILTER_VALIDATE_STRING. Now, if you call

```<code>!filter_var($str, FILTER_VALIDATE_STRING)
</code>```

you would get a notice

```<code>PHP Notice:  Use of undefined constant FILTER_VALIDATE_STRING - assumed 'FILTER_VALIDATE_STRING'
</code>```

It seems, that your error_reporting doesnt include notices.

ContentLicense: CC BY-SA 3.0

Body:
In this code I get a warning

Warning: filter_var() expects parameter 2 to be long, string given in the last line

$check = filter_var($email, FILTER_SANITIZE_EMAIL);
$str = filter_var($name, FILTER_SANITIZE_STRING);
if (!filter_var($check, FILTER_VALIDATE_EMAIL) && !filter_var($str, FILTER_VALIDATE_STRING)) { //here

The problem is this, because without it no exists any warning message

 !filter_var($str, FILTER_VALIDATE_STRING)

What is the reason of this error?

Body:
As @TaylorOtwell mentioned: There is no filter FILTER_VALIDATE_STRING. Now, if you call

!filter_var($str, FILTER_VALIDATE_STRING)

you would get a notice

PHP Notice:  Use of undefined constant FILTER_VALIDATE_STRING - assumed 'FILTER_VALIDATE_STRING'

It seems, that your error_reporting doesnt include notices.


问:
How to stagger multiple animation delays in Sass?
I was wondering how I can calculate two animation delays (fade in and fade out) by using a for loop in Sass.

Came up with the following, but doesn't know how to calc the second animation delay.

```<code>@for $i from 1 through 2 {
    .text:nth-child(#{$i}) {
        animation-delay: ($i * 0.5s), 4s;
    }
}
</code>```

I would like to do the same for the fade in, so each text element will be slightly stagger.

Already tried something like this, but with no result.

```<code>@for $i from 1 through 2 {
    .text:nth-child(#{$i, $a}) {
        animation-delay: ($i * 0.5s), ($a * 0.5s);
    }
}
</code>```

And how can I use the last delay to start another delay of another animation?

答:
I'm not sure exactly what you're trying to accomplish.

The easy version

That said, the basic idea is to do the "in" and "out" animations as percentages of the same animation function. In this case the build in = 25%, static = 50%, and build out = 25%.

Then your duration controls how long each part takes to complete. In this case 2 seconds.

Next, the delay (calculated as part of the loop) offsets the animation. You could also multiply the duration in the loop to completely stagger the animation.

```<code>
$timeOffset: 0.5s;
$aniLength: 2s;
// 0.5s in, 1s solid, 0.5s out = 2sec

.item {
    opacity:0;
    animation-name: animation;
    animation-duration: $aniLength;
    animation-timing-function: ease-in-out;
}

@for $i from 1 through 20 {
    .item:nth-child(#{$i}){
        // units are in the variable so SCSS just does math
        animation-delay: $i * $timeOffset;
    }
}

@keyframes animation {
    0% {
        opacity: 0;
        transform: translatex(100%);
    }
    25% {
        opacity: 1;
        transform: translatex(0);
    }
    75% {
        opacity: 1;
        transform: translatex(0);
    }
    100% {
        opacity: 0;
        transform: translatex(-100%);
    }
}
</code>```

Here's a Codepen example since SO doesn't parse SCSS in the code sandbox available here.

More complex version with multiple delays

Your second example didn't work because you were building an odd selector in your nth-child code while using an undefined variable.

Also, you can do pretty complex math for each iteration. Just remember concepts like Order of Operations.

The correct way to specify two different delay values is like this:

```<code>@for $i from 1 through 20 {
        // the hash forces SCSS to create a string
    .item:nth-child(#{$i}){
        // you need to use $i for BOTH since its the only defined increment
        animation-delay: $i * $timeOffset, $i * $timeOffset + $aniLength;
        // delay #1 = iteration * 0.5s, delay #2 = iteration * 0.5s + 2s (run at end of animation plus the offset)
    }
}
</code>```

Body:
I was wondering how I can calculate two animation delays (fade in and fade out) by using a for loop in Sass.

Came up with the following, but doesn't know how to calc the second animation delay.

@for $i from 1 through 2 {
    .text:nth-child(#{$i}) {
        animation-delay: ($i * 0.5s), 4s;
    }
}

I would like to do the same for the fade in, so each text element will be slightly stagger.

Already tried something like this, but with no result.

@for $i from 1 through 2 {
    .text:nth-child(#{$i, $a}) {
        animation-delay: ($i * 0.5s), ($a * 0.5s);
    }
}

And how can I use the last delay to start another delay of another animation?

Body:
I'm not sure exactly what you're trying to accomplish.

The easy version

That said, the basic idea is to do the "in" and "out" animations as percentages of the same animation function. In this case the build in = 25%, static = 50%, and build out = 25%.

Then your duration controls how long each part takes to complete. In this case 2 seconds.

Next, the delay (calculated as part of the loop) offsets the animation. You could also multiply the duration in the loop to completely stagger the animation.

$timeOffset: 0.5s;
$aniLength: 2s;
// 0.5s in, 1s solid, 0.5s out = 2sec

.item {
    opacity:0;
    animation-name: animation;
    animation-duration: $aniLength;
    animation-timing-function: ease-in-out;
}

@for $i from 1 through 20 {
    .item:nth-child(#{$i}){
        // units are in the variable so SCSS just does math
        animation-delay: $i * $timeOffset;
    }
}

@keyframes animation {
    0% {
        opacity: 0;
        transform: translatex(100%);
    }
    25% {
        opacity: 1;
        transform: translatex(0);
    }
    75% {
        opacity: 1;
        transform: translatex(0);
    }
    100% {
        opacity: 0;
        transform: translatex(-100%);
    }
}

Here's a Codepen example since SO doesn't parse SCSS in the code sandbox available here.

More complex version with multiple delays

Your second example didn't work because you were building an odd selector in your nth-child code while using an undefined variable.

Also, you can do pretty complex math for each iteration. Just remember concepts like Order of Operations.

The correct way to specify two different delay values is like this:

@for $i from 1 through 20 {
        // the hash forces SCSS to create a string
    .item:nth-child(#{$i}){
        // you need to use $i for BOTH since its the only defined increment
        animation-delay: $i * $timeOffset, $i * $timeOffset + $aniLength;
        // delay #1 = iteration * 0.5s, delay #2 = iteration * 0.5s + 2s (run at end of animation plus the offset)
    }
}


问:
How to implement SQLITE_LIMIT_LENGTH?
I am using SQLite in my RN apps with help of react-native-sqlite-storage. Then, one of my table has a column which contain a very long string. When I try to insert the string, no error occured. But, when I select the row, it return null. This open issue is similar with my problem.

Then, I found this documentation. It said that

During part of SQLite's INSERT and SELECT processing, the complete
  content of each row in the database is encoded as a single BLOB. So
  the SQLITE_MAX_LENGTH parameter also determines the maximum number of
  bytes in a row.

The maximum string or BLOB length can be lowered at run-time using the
  sqlite3_limit(db,SQLITE_LIMIT_LENGTH,size) interface.

My question is, if I have this piece of working code to select data from a table:

```<code>const db = await SQLite.openDatabase('databasename', 'default');
db.executeSql('SELECT * FROM tablename', [], (res) => {
  console.log(res.rows.item(0));
}, err => console.log(err));
</code>```

How to implement sqlite3_limit(db, SQLITE_LIMIT_LENGTH, size) to above code in order to increase the SQLITE_LIMIT_LENGTH?

答:
You can't easily.  Android's default sqlite implementation doesn't provide access to it.  You would need to import your own version of the sqlite Java library (which is really a C library accessed via JNI), then provide your own RN module to access it in Java, then use only that module to access the db at all.  Its a lot of work.  How large is this string?  You may want to consider storing it in a file and putting the filename in the db.

The issue you linked particularly mentioned images.  Sqlite is not really a good solution for storing images, for a variety of reasons.  Use a file and store the filename for that.

Title: How to implement SQLITE_LIMIT_LENGTH?

Body:
I am using SQLite in my RN apps with help of react-native-sqlite-storage. Then, one of my table has a column which contain a very long string. When I try to insert the string, no error occured. But, when I select the row, it return null. This open issue is similar with my problem.

Then, I found this documentation. It said that

During part of SQLite's INSERT and SELECT processing, the complete
  content of each row in the database is encoded as a single BLOB. So
  the SQLITE_MAX_LENGTH parameter also determines the maximum number of
  bytes in a row.

The maximum string or BLOB length can be lowered at run-time using the
  sqlite3_limit(db,SQLITE_LIMIT_LENGTH,size) interface.

My question is, if I have this piece of working code to select data from a table:

const db = await SQLite.openDatabase('databasename', 'default');
db.executeSql('SELECT * FROM tablename', [], (res) => {
  console.log(res.rows.item(0));
}, err => console.log(err));

How to implement sqlite3_limit(db, SQLITE_LIMIT_LENGTH, size) to above code in order to increase the SQLITE_LIMIT_LENGTH?


问:
Spinner entries bindingadapter room livedata not working
I am working on room livedata databinding concept. I am setting list to spinner using custom binding adapter. But i am getting null livedata while retrieving from room firsttime.

code:

```<code>     @Query("select * from Student")
        LiveData<List<Student>> getAllItems();

        @BindingAdapter({"bind:entries"})
            public static void customSpinnerBinding(AppCompatSpinner appCompatSpinner,LiveData<List<Student>> listLiveData){
                if(listLiveData != null && listLiveData.getValue().size() > 0){
                    ArrayAdapter<Student> spinnerArrayAdapter = new ArrayAdapter<Student>
                            (appCompatSpinner.getContext(), android.R.layout.simple_spinner_item,
                                    listLiveData.getValue()); //selected item will look like a spinner set from XML
                    spinnerArrayAdapter.setDropDownViewResource(android.R.layout
                            .simple_spinner_dropdown_item);
                    appCompatSpinner.setAdapter(spinnerArrayAdapter);
                }
            }

        public LiveData<List<Student>> getListLiveData() {
            if(listLiveData == null){
               listLiveData = studentDB.studentDao().getAllItems();
            }
            return listLiveData;
        }

        <android.support.v7.widget.AppCompatSpinner
                    android:id="@+id/spinner"
                    android:layout_width="0dp"
                    bind:entries="@{viewmodel.listLiveData}"
                    android:layout_height="wrap_content"
                    android:layout_marginStart="16dp"
                    android:layout_marginLeft="16dp"
                    android:layout_marginTop="16dp"
                    android:layout_marginEnd="16dp"
                    android:layout_marginRight="16dp"
                    android:layout_marginBottom="16dp"
                    app:layout_constraintBottom_toBottomOf="parent"
                    app:layout_constraintEnd_toEndOf="parent"
                    app:layout_constraintStart_toStartOf="parent"
                    app:layout_constraintTop_toTopOf="parent" />

but if i observe livedata in activity this is working

  mainViewModel.getListLiveData().observe(this, new Observer<List<Student>>() {
           @Override
           public void onChanged(@Nullable List<Student> students) {
               if(students.size() > 0){
                   ArrayAdapter<Student> spinnerArrayAdapter = new ArrayAdapter<Student>
                    (MainActivity.this, android.R.layout.simple_spinner_item,
                            students); //selected item will look like a spinner set from XML
            spinnerArrayAdapter.setDropDownViewResource(android.R.layout
                    .simple_spinner_dropdown_item);
            activityMainBinding.appbar.contentid.spinner.setAdapter(spinnerArrayAdapter);
               }
           }
       });
</code>```

答:
Check these two things:

Change your .customSpinnerBinding to accept a List<Student> instead of LiveData<List<Student>>.

BindingAdapter accepts what goes inside of a LiveData , not the LiveData itself. LiveData is not the one that changes. Only the content of the LiveData notifications change.

Example BindingAdapter:

```<code>        @BindingAdapter({"bind:entries"})
        public static void customSpinnerBinding(AppCompatSpinner appCompatSpinner, List<Student> students) {

            ArrayAdapter<Student> spinnerArrayAdapter = new ArrayAdapter<Student>
                    (appCompatSpinner.getContext(), android.R.layout.simple_spinner_item,
                         students); //selected item will look like a spinner set from XML
            spinnerArrayAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
            appCompatSpinner.setAdapter(spinnerArrayAdapter);
        }
</code>```

Do not lazy load listLiveData

It looks like your view will need it anyway, what is the point of lazily loading it? It will only make your code more complex and harder to debug by making your viewmodel more stateful. Just eagerly load the student list, and declare it as final to make it even better.

```<code>public final LiveData listLiveData = studentDB.studentDao().getAllItems();
</code>```

If you must lazy load listLiveData then make sure it gets initialized. In your .xml:

```<code>    <android.support.v7.widget.AppCompatSpinner
                ...
                bind:entries="@{viewmodel.getListLiveData()}"
                ... />
</code>```

Body:
I am working on room livedata databinding concept. I am setting list to spinner using custom binding adapter. But i am getting null livedata while retrieving from room firsttime.

code:

     @Query("select * from Student")
        LiveData<List<Student>> getAllItems();

        @BindingAdapter({"bind:entries"})
            public static void customSpinnerBinding(AppCompatSpinner appCompatSpinner,LiveData<List<Student>> listLiveData){
                if(listLiveData != null && listLiveData.getValue().size() > 0){
                    ArrayAdapter<Student> spinnerArrayAdapter = new ArrayAdapter<Student>
                            (appCompatSpinner.getContext(), android.R.layout.simple_spinner_item,
                                    listLiveData.getValue()); //selected item will look like a spinner set from XML
                    spinnerArrayAdapter.setDropDownViewResource(android.R.layout
                            .simple_spinner_dropdown_item);
                    appCompatSpinner.setAdapter(spinnerArrayAdapter);
                }
            }

        public LiveData<List<Student>> getListLiveData() {
            if(listLiveData == null){
               listLiveData = studentDB.studentDao().getAllItems();
            }
            return listLiveData;
        }

        <android.support.v7.widget.AppCompatSpinner
                    android:id="@+id/spinner"
                    android:layout_width="0dp"
                    bind:entries="@{viewmodel.listLiveData}"
                    android:layout_height="wrap_content"
                    android:layout_marginStart="16dp"
                    android:layout_marginLeft="16dp"
                    android:layout_marginTop="16dp"
                    android:layout_marginEnd="16dp"
                    android:layout_marginRight="16dp"
                    android:layout_marginBottom="16dp"
                    app:layout_constraintBottom_toBottomOf="parent"
                    app:layout_constraintEnd_toEndOf="parent"
                    app:layout_constraintStart_toStartOf="parent"
                    app:layout_constraintTop_toTopOf="parent" />

but if i observe livedata in activity this is working

  mainViewModel.getListLiveData().observe(this, new Observer<List<Student>>() {
           @Override
           public void onChanged(@Nullable List<Student> students) {
               if(students.size() > 0){
                   ArrayAdapter<Student> spinnerArrayAdapter = new ArrayAdapter<Student>
                    (MainActivity.this, android.R.layout.simple_spinner_item,
                            students); //selected item will look like a spinner set from XML
            spinnerArrayAdapter.setDropDownViewResource(android.R.layout
                    .simple_spinner_dropdown_item);
            activityMainBinding.appbar.contentid.spinner.setAdapter(spinnerArrayAdapter);
               }
           }
       });

Body:
Check these two things:

Change your .customSpinnerBinding to accept a List<Student> instead of LiveData<List<Student>>.

BindingAdapter accepts what goes inside of a LiveData , not the LiveData itself. LiveData is not the one that changes. Only the content of the LiveData notifications change.

Example BindingAdapter:

        @BindingAdapter({"bind:entries"})
        public static void customSpinnerBinding(AppCompatSpinner appCompatSpinner, List<Student> students) {

            ArrayAdapter<Student> spinnerArrayAdapter = new ArrayAdapter<Student>
                    (appCompatSpinner.getContext(), android.R.layout.simple_spinner_item,
                         students); //selected item will look like a spinner set from XML
            spinnerArrayAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
            appCompatSpinner.setAdapter(spinnerArrayAdapter);
        }

Do not lazy load listLiveData

It looks like your view will need it anyway, what is the point of lazily loading it? It will only make your code more complex and harder to debug by making your viewmodel more stateful. Just eagerly load the student list, and declare it as final to make it even better.

public final LiveData listLiveData = studentDB.studentDao().getAllItems();

If you must lazy load listLiveData then make sure it gets initialized. In your .xml:

    <android.support.v7.widget.AppCompatSpinner
                ...
                bind:entries="@{viewmodel.getListLiveData()}"
                ... />


问:
I have the map set to rotate to the users location. How do I allow the user to interact with the map?
I have the map set to center and rotate to the user's location and direction but the map view is locked, as in, I can not interact with it.

```<code>extension MapScreen: CLLocationManagerDelegate {
    func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
        guard let location = locations.last else { return }
        let region = MKCoordinateRegion.init(center: location.coordinate, latitudinalMeters: regionInMeters, longitudinalMeters: regionInMeters)
        mapView.setRegion(region, animated: true)

    func locationManager(_ manager: CLLocationManager, didChangeAuthorization status: CLAuthorizationStatus) {
        checkLocationAuthorization()

    func locationManager(_ manager: CLLocationManager, didUpdateHeading newHeading: CLHeading) {
        mapView.camera.heading = newHeading.magneticHeading
        mapView.setCamera(mapView.camera, animated: true)
            }
        }
    }
}
</code>```

How do I allow the user to explore his surroundings; scroll, zoom, interact with pins, etcetera, while centering and rotating to the user?

答:
By using the didUpdateLocations delegate method you are continually updating the map view, overriding any changes made by the user.

The solution is not to use CLLocationManager delegate methods to update the map view.

Simply set userTrackingMode on the map to .followWithHeading and the map view will do the work for you.  As soon as the user interacts with the map the tracking mode will change to .none.

You can add a button to re-activate the .followWithHeading user tracking mode.

Body:
I have the map set to center and rotate to the user's location and direction but the map view is locked, as in, I can not interact with it.

extension MapScreen: CLLocationManagerDelegate {
    func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
        guard let location = locations.last else { return }
        let region = MKCoordinateRegion.init(center: location.coordinate, latitudinalMeters: regionInMeters, longitudinalMeters: regionInMeters)
        mapView.setRegion(region, animated: true)

    func locationManager(_ manager: CLLocationManager, didChangeAuthorization status: CLAuthorizationStatus) {
        checkLocationAuthorization()

    func locationManager(_ manager: CLLocationManager, didUpdateHeading newHeading: CLHeading) {
        mapView.camera.heading = newHeading.magneticHeading
        mapView.setCamera(mapView.camera, animated: true)
            }
        }
    }
}

How do I allow the user to explore his surroundings; scroll, zoom, interact with pins, etcetera, while centering and rotating to the user?


问:
How to fix pip error when installing requests
I was trying to use the Terminal on Ubuntu 16.04 to install Requests for API calls in Python and had this error. How would I go about fixing it?

I have already tried creating a virtualenv to install it only there but it did not work either.

I typed in "pip install requests"

```<code>Exception:
Traceback (most recent call last):

File "/usr/local/lib/python2.7/dist-packages/pip/basecommand.py", line 209, in main status = self.run(options, args)

  File "/usr/local/lib/python2.7/dist-packages/pip/commands/install.py", line 317, in run prefix=options.prefix_path,

  File "/usr/local/lib/python2.7/dist-packages/pip/req/req_set.py", line 726, in install requirement.uninstall(auto_confirm=True)

  File "/usr/local/lib/python2.7/dist-packages/pip/req/req_install.py", line 746, in uninstall paths_to_remove.remove(auto_confirm)

  File "/usr/local/lib/python2.7/dist-packages/pip/req/req_uninstall.py", line 115, in remove renames(path, new_path)

  File "/usr/local/lib/python2.7/dist-packages/pip/utils/__init__.py", line 267, in renames shutil.move(old, new)

  File "/usr/lib/python2.7/shutil.py", line 300, in move
    rmtree(src)

  File "/usr/lib/python2.7/shutil.py", line 252, in rmtree
    onerror(os.remove, fullname, sys.exc_info())

  File "/usr/lib/python2.7/shutil.py", line 250, in rmtree
    os.remove(fullname)

OSError: [Errno 13] Permission denied: '/usr/lib/python2.7/dist-packages/idna/codec.pyc'
</code>```

答:
Try installing using the sudo keyword to give yourself privilege evaluations. The following should work as long as you know your credentials.

```<code>sudo pip install requests
</code>```

Body:
I was trying to use the Terminal on Ubuntu 16.04 to install Requests for API calls in Python and had this error. How would I go about fixing it?

I have already tried creating a virtualenv to install it only there but it did not work either.

I typed in "pip install requests"

Exception:
Traceback (most recent call last):

File "/usr/local/lib/python2.7/dist-packages/pip/basecommand.py", line 209, in main status = self.run(options, args)

  File "/usr/local/lib/python2.7/dist-packages/pip/commands/install.py", line 317, in run prefix=options.prefix_path,

  File "/usr/local/lib/python2.7/dist-packages/pip/req/req_set.py", line 726, in install requirement.uninstall(auto_confirm=True)

  File "/usr/local/lib/python2.7/dist-packages/pip/req/req_install.py", line 746, in uninstall paths_to_remove.remove(auto_confirm)

  File "/usr/local/lib/python2.7/dist-packages/pip/req/req_uninstall.py", line 115, in remove renames(path, new_path)

  File "/usr/local/lib/python2.7/dist-packages/pip/utils/__init__.py", line 267, in renames shutil.move(old, new)

  File "/usr/lib/python2.7/shutil.py", line 300, in move
    rmtree(src)

  File "/usr/lib/python2.7/shutil.py", line 252, in rmtree
    onerror(os.remove, fullname, sys.exc_info())

  File "/usr/lib/python2.7/shutil.py", line 250, in rmtree
    os.remove(fullname)

OSError: [Errno 13] Permission denied: '/usr/lib/python2.7/dist-packages/idna/codec.pyc'

Body:
Try installing using the sudo keyword to give yourself privilege evaluations. The following should work as long as you know your credentials.

sudo pip install requests


问:
How to create a thumbnails page in WordPress
I'm creating a WordPress photoblog theme and I want to create a thumbnails page that sits between index.php and single.php.

The idea is that when someone clicks on a blog post, they go to the thumbnails page to see all photos attached to that post and they then click on an individual image to be redirected to the blog entry.  Does WP templating support this?

答:
WordPress just loads the files inside of the theme's directory, so you aren't limited by WP much.

If you want, why not just make the index.php file have a section which runs only when it receives a $_GET variable denoting that the user has requested the thumbnails page?

This is sort of what I mean:

single.php:

```<code><?php

if (isset($_GET['gallery']))
{
  // Show the gallery.
} else {
  // Show the main content instead
}

?>
</code>```

And on index.php, you could add the gallery parameter to the URLs:

```<code><a href="single.php?gallery=1&foo=bar">Title of Article</a>
</code>```

But that's just the way I'd do it.

Body:
WordPress just loads the files inside of the theme's directory, so you aren't limited by WP much.

If you want, why not just make the index.php file have a section which runs only when it receives a $_GET variable denoting that the user has requested the thumbnails page?

This is sort of what I mean:

single.php:

<?php

if (isset($_GET['gallery']))
{
  // Show the gallery.
} else {
  // Show the main content instead
}

?>

And on index.php, you could add the gallery parameter to the URLs:

<a href="single.php?gallery=1&foo=bar">Title of Article</a>

But that's just the way I'd do it.


问:
beberlei DoctrineExtensions in ZF2 working fine on Windows localhost but shows fatal error Linux production server
I want to use use Day, Week, Month and Year functions of DoctrineExtensions in ZF2 and am getting the below error message. The code works fine on my local machine running on Windows but the same code does not work on server running on Linux.

```<code>Fatal error: Uncaught Error: Class 'DoctrineExtensions\Query\Mysql\Day' not found
</code>```

Here is my module.config.php configuration

```<code>'configuration' => array(
        'orm_default' => array(
            'datetime_functions' => array(
                'day' => 'DoctrineExtensions\Query\MySql\Day',
                'week' => 'DoctrineExtensions\Query\MySql\Week',
                'month' => 'DoctrineExtensions\Query\MySql\Month',
                'Year' => 'DoctrineExtensions\Query\MySql\Year',
            ),
            'string_functions'   => array(),
        )
    ),
</code>```

I installed the module using composer.

答: "DoctrineExtensions\Query\MySql\" should be "DoctrineExtensions\Query\Mysql\" with small "s" not Capital "S". Linux are case sensitive that is why it cannot find the path of the classes. I have the same problem and this is how we solved it. Hope this helps.</p>

Body:
I want to use use Day, Week, Month and Year functions of DoctrineExtensions in ZF2 and am getting the below error message. The code works fine on my local machine running on Windows but the same code does not work on server running on Linux.

Fatal error: Uncaught Error: Class 'DoctrineExtensions\Query\Mysql\Day' not found

Here is my module.config.php configuration

'configuration' => array(
        'orm_default' => array(
            'datetime_functions' => array(
                'day' => 'DoctrineExtensions\Query\MySql\Day',
                'week' => 'DoctrineExtensions\Query\MySql\Week',
                'month' => 'DoctrineExtensions\Query\MySql\Month',
                'Year' => 'DoctrineExtensions\Query\MySql\Year',
            ),
            'string_functions'   => array(),
        )
    ),

I installed the module using composer.


问:
cant install bootstrap in new rails 6rc1 project - error in harmony-module.js
I've got a new rails project (6.0.0rc1) and I'm attempting to use the new webpack system to load bootstrap.

For reference, this is a mac running Mojave, with no known problems when doing any other dev work.

I've followed all relevant tutorials and always end up with the same error, and am unable to load either the js or the stylesheets.

```<code>yarn add bootstrap jquery popper.js
</code>```

config/webpack/environment:

const { environment } = require('@rails/webpacker')
const webpack = require('webpack')

environment.plugins.append('Provide', new webpack.ProvidePlugin({
    $: 'jquery',
    jQuery: 'jquery',
    Poppper: ['popper.js', 'default']
}))

module.exports = environment
```

<p>app/javascript/packs/application.js:</p>

<pre class="lang-rb prettyprint-override"><code>require("@rails/ujs").start()
require("turbolinks").start()
require("@rails/activestorage").start()
require("channels")

import "bootstrap"
import "../stylesheets/application"
</code>```

The error:

```<code>TypeError: __webpack_require__(/*! ./harmony-module.js */
"./node_modules/webpack/buildin/harmony-module.js") is not a
function.

(In '__webpack_require__(/*! ./harmony-module.js */
"./node_modules/webpack/buildin/harmony-module.js")(module)',
'__webpack_require__(/*! ./harmony-module.js */
"./node_modules/webpack/buildin/harmony-module.js")' is an instance
of Object)
</code>```

and, yes the webpack dev server is running and not complaining:

```<code>ℹ ｢wdm｣: Compiling...
ℹ ｢wdm｣: Hash: 1c7e3fa63a51751518ef
Version: webpack 4.32.2
Time: 610ms
Built at: 2019-05-29 2:43:34 p.m.
                                     Asset       Size       Chunks
Chunk Names
js/application-40d856ea775503923ce0.js   2.05 MiB  application
[emitted]  application
js/application-40d856ea775503923ce0.js.map   2.02 MiB  application
[emitted]  application
                         manifest.json  364 bytes
[emitted]
ℹ ｢wdm｣: Compiled successfully.
</code>```

答:
This is related to https://github.com/rails/webpacker/pull/2031 and not related to bootstrap in webpacker.

Removing the two references to corejs 3 in /babel.config.js solved the issue.

also see https://github.com/rails/webpacker/issues/2109

Body:
I've got a new rails project (6.0.0rc1) and I'm attempting to use the new webpack system to load bootstrap.

For reference, this is a mac running Mojave, with no known problems when doing any other dev work.

I've followed all relevant tutorials and always end up with the same error, and am unable to load either the js or the stylesheets.

yarn add bootstrap jquery popper.js

config/webpack/environment:

const { environment } = require('@rails/webpacker')
const webpack = require('webpack')

environment.plugins.append('Provide', new webpack.ProvidePlugin({
    $: 'jquery',
    jQuery: 'jquery',
    Poppper: ['popper.js', 'default']
}))

module.exports = environment

app/javascript/packs/application.js:

require("@rails/ujs").start()
require("turbolinks").start()
require("@rails/activestorage").start()
require("channels")

import "bootstrap"
import "../stylesheets/application"

The error:

TypeError: __webpack_require__(/*! ./harmony-module.js */
"./node_modules/webpack/buildin/harmony-module.js") is not a
function.

(In '__webpack_require__(/*! ./harmony-module.js */
"./node_modules/webpack/buildin/harmony-module.js")(module)',
'__webpack_require__(/*! ./harmony-module.js */
"./node_modules/webpack/buildin/harmony-module.js")' is an instance
of Object)

and, yes the webpack dev server is running and not complaining:

ℹ ｢wdm｣: Compiling...
ℹ ｢wdm｣: Hash: 1c7e3fa63a51751518ef
Version: webpack 4.32.2
Time: 610ms
Built at: 2019-05-29 2:43:34 p.m.
                                     Asset       Size       Chunks
Chunk Names
js/application-40d856ea775503923ce0.js   2.05 MiB  application
[emitted]  application
js/application-40d856ea775503923ce0.js.map   2.02 MiB  application
[emitted]  application
                         manifest.json  364 bytes
[emitted]
ℹ ｢wdm｣: Compiled successfully.


问:
Python: Select and move file based on criteria in a directory
I have about 10 minutes of video and just extracted into every frame so I have more than 100,000 of images in my folder and renamed them from 1 to 100,000. Now I want to select 1 of every 30 from 1 to 100,000 images and move them to another folder. For example : 1, 31,61,91,121,151,181 and so on.

This is my code so far:

```<code>import os
import shutil

PATH = './Folder1/'
DEST = './Folder2/'

file = 1

for file in os.listdir(PATH):
    file = file + 30
    shutil.copyfile(PATH, DEST)
</code>```

But it gave me following error:

```<code>---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-2-b08091703697> in <module>
      9 # Get a list of files in the current working directory
     10 for file in os.listdir(PATH):
---> 11     file = file + 30
     12     shutil.copyfile(PATH, DEST)

TypeError: can only concatenate str (not "int") to str
</code>```

Thanks in advance for any help!

答:
"file" in for file in os.listdir(PATH) is a string, so file = file + 30 is not valid.
you should try:

```<code>import os
import shutil

PATH = './Folder1/'
DEST = './Folder2/'

filenames = os.listdir(PATH)

for i in range(1, len(filenames), 30):
    shutil.copyfile(PATH + filenames[i], DEST)
</code>```

Body:
I have about 10 minutes of video and just extracted into every frame so I have more than 100,000 of images in my folder and renamed them from 1 to 100,000. Now I want to select 1 of every 30 from 1 to 100,000 images and move them to another folder. For example : 1, 31,61,91,121,151,181 and so on.

This is my code so far:

import os
import shutil

PATH = './Folder1/'
DEST = './Folder2/'

file = 1

for file in os.listdir(PATH):
    file = file + 30
    shutil.copyfile(PATH, DEST)

But it gave me following error:

---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-2-b08091703697> in <module>
      9 # Get a list of files in the current working directory
     10 for file in os.listdir(PATH):
---> 11     file = file + 30
     12     shutil.copyfile(PATH, DEST)

TypeError: can only concatenate str (not "int") to str

Thanks in advance for any help!

Body:
"file" in for file in os.listdir(PATH) is a string, so file = file + 30 is not valid.
you should try:

import os
import shutil

PATH = './Folder1/'
DEST = './Folder2/'

filenames = os.listdir(PATH)

for i in range(1, len(filenames), 30):
    shutil.copyfile(PATH + filenames[i], DEST)


问:
Fastest Dictionary lookup in c# .net Compact Framework 3.5
I'm looking for the fastest way to lookup if List, Set, Dictionary contains a specific Keyword (string). I don't need to store any data inside I just want to know if my Keyword is in the List.

I thought about some possibilities like:

```<code>Dictionary<string, bool> myDictionary = new Dictionary<string, bool>();
if (myDictionary.ContainsKey(valueToSearch))
{
    // do something
}
</code>```

but I don't need a value.

```<code>string[] myArray = {"key1", "key2", "key3"}
if (Array.IndexOf(myArray, valueToSearch) != -1)
{
    // do something
}
</code>```

Then I found:

```<code>List<string> list = new List<string>();
if (list.Contains(valueToSearch))
{
    // do something
}
</code>```

The lookup will happen very often and has to be very fast.
Any idea what's the fastest way to check if a value equals one of a given list of keys?

答: Of the standard collection types, Dictionary will be the fastest, since I don't think you have HashSet<T> in the compact framework. The other two do a sequential search.

Body:
I'm looking for the fastest way to lookup if List, Set, Dictionary contains a specific Keyword (string). I don't need to store any data inside I just want to know if my Keyword is in the List.

I thought about some possibilities like:

Dictionary<string, bool> myDictionary = new Dictionary<string, bool>();
if (myDictionary.ContainsKey(valueToSearch))
{
    // do something
}

but I don't need a value.

string[] myArray = {"key1", "key2", "key3"}
if (Array.IndexOf(myArray, valueToSearch) != -1)
{
    // do something
}

Then I found:

List<string> list = new List<string>();
if (list.Contains(valueToSearch))
{
    // do something
}

The lookup will happen very often and has to be very fast.
Any idea what's the fastest way to check if a value equals one of a given list of keys?


问:
How to offer scalars as coordinates of the data points for pyplot's plot function?
I am reading document of the pyplot's plot function here: https://matplotlib.org/api/_as_gen/matplotlib.pyplot.plot.html#matplotlib.pyplot.plot. It said the Parameters x, y: array-like or scalar.

I understand how to using array-like data, but not scalar. Can anyone give some examples to show how to use scalar x, y parameter? Thanks.

答:
```<code>plot(y)
</code>```

as plot(100) or some other number. It will plot a single point.

Body:
plot(y)

as plot(100) or some other number. It will plot a single point.


问:
How to Restore Default Settings for Virtual Machine Network Adapter in Azure manage console
How to Restore Default Settings for Virtual Machine Network Adapter in Azure manage console. I cannot connect the vm desktop remotely after I changed the Ip Address in Virtual Machine Network Adapter. then I restarted the vm in the manage console, but it still didn't work.</p>

答:
You could manually reset the network interface for Azure Windows VM to resolve issues when you cannot connect to Microsoft Azure Windows Virtual Machine (VM) after you disabled the default NIC or manually set a static IP for the NIC.

You could follow the above steps to reset the NIC. This works for me. Just a reminder, you need to re-RDP to the VM until the VM status is restored running. If it takes a long time, you could try to refresh the portal.

Let me know if this works on your side.


问:
php remove element from array using regular expression
i have the following array

```<code>(
[0] => DHL - 4857998880
[1] => DHL - 4858005666
[2] => COA - 485344322
)
</code>```

i want to loop through the array and if DHL found then i want to remove from the array. the numbers in front of DHL do not matter. any element with DHL in front i want to remove from the array.

i have created the following the regular expression to ignore the numbers in front but not sure how move forward from there.

```<code>foreach($result as $valDHL) {

   $s = preg_replace("/[^a-z-]/i", "", $valDHL);

}
</code>```

答:
You can use array_filter to strip out the entries in your array that start with DHL, using the regex ^DHL to see if the entry starts with DHL:

```<code>$array = array(
0 => 'DHL - 4857998880',
1 => 'DHL - 4858005666',
2 => 'COA - 485344322'
);
$array = array_filter($array, function ($v) { return !preg_match('/^DHL/', $v); });
print_r($array);
</code>```

Output:

```<code>Array (
  [2] => COA - 485344322
)
</code>```

Demo on 3v4l.org

Body:
i have the following array

(
[0] => DHL - 4857998880
[1] => DHL - 4858005666
[2] => COA - 485344322
)

i want to loop through the array and if DHL found then i want to remove from the array. the numbers in front of DHL do not matter. any element with DHL in front i want to remove from the array.

i have created the following the regular expression to ignore the numbers in front but not sure how move forward from there.

foreach($result as $valDHL) {

   $s = preg_replace("/[^a-z-]/i", "", $valDHL);

}

Body:
You can use array_filter to strip out the entries in your array that start with DHL, using the regex ^DHL to see if the entry starts with DHL:

$array = array(
0 => 'DHL - 4857998880',
1 => 'DHL - 4858005666',
2 => 'COA - 485344322'
);
$array = array_filter($array, function ($v) { return !preg_match('/^DHL/', $v); });
print_r($array);

Output:

Array (
  [2] => COA - 485344322
)

Demo on 3v4l.org


问:
Checking for an existing record in Sqlite in android?
Hii guys

Im trying to check for an existing record in android before inserting a record. i get an exception and when i check the logcat it says its  a syntax error. need some Urget help with this guys

thanks

```<code>DbConnection dbConnection = new DbConnection(EnterDetails.this);
db = dbConnection.getReadableDatabase();
Cursor cursor = db.rawQuery("SELECT 1 FROM" + DbConnection.TABLE + " WHERE "+ DbConnection.C_MNUMBER + " = " +EditTextMobileNumber.getText().toString().trim(),null);
boolean flag = (cursor.getCount() > 0);
Toast.makeText(EnterDetails.this,"Record Found",Toast.LENGTH_LONG).show();
return false;
</code>```

答:
Change:

```<code>"SELECT 1 FROM"
</code>```

to

```<code>"SELECT 1 FROM "
</code>```

Body:
Hii guys

Im trying to check for an existing record in android before inserting a record. i get an exception and when i check the logcat it says its  a syntax error. need some Urget help with this guys

thanks

DbConnection dbConnection = new DbConnection(EnterDetails.this);
db = dbConnection.getReadableDatabase();
Cursor cursor = db.rawQuery("SELECT 1 FROM" + DbConnection.TABLE + " WHERE "+ DbConnection.C_MNUMBER + " = " +EditTextMobileNumber.getText().toString().trim(),null);
boolean flag = (cursor.getCount() > 0);
Toast.makeText(EnterDetails.this,"Record Found",Toast.LENGTH_LONG).show();
return false;

Body:
Change:

"SELECT 1 FROM"

to

"SELECT 1 FROM "


问:
How to properly connect to MongoDB with Spring?
I'm total beginner in Spring. I want to create simple Spring app connecting to MongoDB. I generated Spring Boot with Spring Initializer and I created necessery files following a guide.

MongoDB is working. When I run the app I got the following error:

SpringFramework 2.2.0 M3
MongoDB 4.0
Dependencies (chosen in Spring Initializer): Web, MongoDB

DatabaseConfiguration.java

```<code>package com.talkingflashcards.server.TalkingFlashcards.config;

import com.mongodb.client.MongoClient;
import com.mongodb.client.MongoClients;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.mongodb.config.AbstractMongoClientConfiguration;
import org.springframework.data.mongodb.repository.config.EnableMongoRepositories;

@EnableMongoRepositories(basePackages = "com.talkingflashcards.server.TalkingFlashcards.repository")

@Configuration
public class DatabaseConfiguration extends AbstractMongoClientConfiguration {

    @Value("${spring.data.mongodb.host}")
    private String host;

    @Value("${spring.data.mongodb.port}")
    private String port;

    @Value("${spring.data.mongodb.username}")
    private String username;

    @Value("${spring.data.mongodb.password}")
    private String password;

    @Value("${spring.data.mongodb.database}")
    private String database;

    @Override
    public MongoClient mongoClient() {
        return MongoClients.create(host + ":" + port);
    }

    @Override
    protected String getDatabaseName() {
        return database;
    }
}

Error starting ApplicationContext. To display the conditions report re-run your application with 'debug' enabled.
    2019-05-29 23:52:19.955 ERROR 10144 --- [           main] o.s.boot.SpringApplication               : Application run failed

    org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'mongoTemplate' defined in class path resource [com/talkingflashcards/server/TalkingFlashcards/config/DatabaseConfiguration.class]: Bean instantiation via factory method failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [org.springframework.data.mongodb.core.MongoTemplate]: Factory method 'mongoTemplate' threw exception; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'mongoDbFactory' defined in class path resource [com/talkingflashcards/server/TalkingFlashcards/config/DatabaseConfiguration.class]: Bean instantiation via factory method failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [org.springframework.data.mongodb.MongoDbFactory]: Factory method 'mongoDbFactory' threw exception; nested exception is java.lang.IllegalArgumentException: The connection string is invalid. Connection strings must start with either 'mongodb://' or 'mongodb+srv://
        at org.springframework.beans.factory.support.ConstructorResolver.instantiate(ConstructorResolver.java:638) ~[spring-beans-5.2.0.M2.jar:5.2.0.M2]
        at org.springframework.beans.factory.support.ConstructorResolver.instantiateUsingFactoryMethod(ConstructorResolver.java:468) ~[spring-beans-5.2.0.M2.jar:5.2.0.M2]
        at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.instantiateUsingFactoryMethod(AbstractAutowireCapableBeanFactory.java:1325) ~[spring-beans-5.2.0.M2.jar:5.2.0.M2]
        at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBeanInstance(AbstractAutowireCapableBeanFactory.java:1164) ~[spring-beans-5.2.0.M2.jar:5.2.0.M2]
        at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:555) ~[spring-beans-5.2.0.M2.jar:5.2.0.M2]
        at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:515) ~[spring-beans-5.2.0.M2.jar:5.2.0.M2]
        at org.springframework.beans.factory.support.AbstractBeanFactory.lambda$doGetBean$0(AbstractBeanFactory.java:320) ~[spring-beans-5.2.0.M2.jar:5.2.0.M2]
        at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:222) ~[spring-beans-5.2.0.M2.jar:5.2.0.M2]
        at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:318) ~[spring-beans-5.2.0.M2.jar:5.2.0.M2]
        at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:199) ~[spring-beans-5.2.0.M2.jar:5.2.0.M2]
        at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:868) ~[spring-beans-5.2.0.M2.jar:5.2.0.M2]
        at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:877) ~[spring-context-5.2.0.M2.jar:5.2.0.M2]
        at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:549) ~[spring-context-5.2.0.M2.jar:5.2.0.M2]
        at org.springframework.boot.web.servlet.context.ServletWebServerApplicationContext.refresh(ServletWebServerApplicationContext.java:142) ~[spring-boot-2.2.0.M3.jar:2.2.0.M3]
        at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:782) [spring-boot-2.2.0.M3.jar:2.2.0.M3]
        at org.springframework.boot.SpringApplication.refreshContext(SpringApplication.java:404) [spring-boot-2.2.0.M3.jar:2.2.0.M3]
        at org.springframework.boot.SpringApplication.run(SpringApplication.java:319) [spring-boot-2.2.0.M3.jar:2.2.0.M3]
        at org.springframework.boot.SpringApplication.run(SpringApplication.java:1275) [spring-boot-2.2.0.M3.jar:2.2.0.M3]
        at org.springframework.boot.SpringApplication.run(SpringApplication.java:1263) [spring-boot-2.2.0.M3.jar:2.2.0.M3]
        at com.talkingflashcards.server.TalkingFlashcards.TalkingFlashcardsApplication.main(TalkingFlashcardsApplication.java:14) [classes/:na]
    Caused by: org.springframework.beans.BeanInstantiationException: Failed to instantiate [org.springframework.data.mongodb.core.MongoTemplate]: Factory method 'mongoTemplate' threw exception; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'mongoDbFactory' defined in class path resource [com/talkingflashcards/server/TalkingFlashcards/config/DatabaseConfiguration.class]: Bean instantiation via factory method failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [org.springframework.data.mongodb.MongoDbFactory]: Factory method 'mongoDbFactory' threw exception; nested exception is java.lang.IllegalArgumentException: The connection string is invalid. Connection strings must start with either 'mongodb://' or 'mongodb+srv://
        at org.springframework.beans.factory.support.SimpleInstantiationStrategy.instantiate(SimpleInstantiationStrategy.java:185) ~[spring-beans-5.2.0.M2.jar:5.2.0.M2]
        at org.springframework.beans.factory.support.ConstructorResolver.instantiate(ConstructorResolver.java:633) ~[spring-beans-5.2.0.M2.jar:5.2.0.M2]
        ... 19 common frames omitted
    Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'mongoDbFactory' defined in class path resource [com/talkingflashcards/server/TalkingFlashcards/config/DatabaseConfiguration.class]: Bean instantiation via factory method failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [org.springframework.data.mongodb.MongoDbFactory]: Factory method 'mongoDbFactory' threw exception; nested exception is java.lang.IllegalArgumentException: The connection string is invalid. Connection strings must start with either 'mongodb://' or 'mongodb+srv://
        at org.springframework.beans.factory.support.ConstructorResolver.instantiate(ConstructorResolver.java:638) ~[spring-beans-5.2.0.M2.jar:5.2.0.M2]
        at org.springframework.beans.factory.support.ConstructorResolver.instantiateUsingFactoryMethod(ConstructorResolver.java:468) ~[spring-beans-5.2.0.M2.jar:5.2.0.M2]
        at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.instantiateUsingFactoryMethod(AbstractAutowireCapableBeanFactory.java:1325) ~[spring-beans-5.2.0.M2.jar:5.2.0.M2]
        at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBeanInstance(AbstractAutowireCapableBeanFactory.java:1164) ~[spring-beans-5.2.0.M2.jar:5.2.0.M2]
        at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:555) ~[spring-beans-5.2.0.M2.jar:5.2.0.M2]
        at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:515) ~[spring-beans-5.2.0.M2.jar:5.2.0.M2]
        at org.springframework.beans.factory.support.AbstractBeanFactory.lambda$doGetBean$0(AbstractBeanFactory.java:320) ~[spring-beans-5.2.0.M2.jar:5.2.0.M2]
        at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:222) ~[spring-beans-5.2.0.M2.jar:5.2.0.M2]
        at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:318) ~[spring-beans-5.2.0.M2.jar:5.2.0.M2]
        at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:199) ~[spring-beans-5.2.0.M2.jar:5.2.0.M2]
        at org.springframework.context.annotation.ConfigurationClassEnhancer$BeanMethodInterceptor.resolveBeanReference(ConfigurationClassEnhancer.java:394) ~[spring-context-5.2.0.M2.jar:5.2.0.M2]
        at org.springframework.context.annotation.ConfigurationClassEnhancer$BeanMethodInterceptor.intercept(ConfigurationClassEnhancer.java:366) ~[spring-context-5.2.0.M2.jar:5.2.0.M2]
        at com.talkingflashcards.server.TalkingFlashcards.config.DatabaseConfiguration$$EnhancerBySpringCGLIB$$7a79cc38.mongoDbFactory(<generated>) ~[classes/:na]
        at org.springframework.data.mongodb.config.AbstractMongoClientConfiguration.mongoTemplate(AbstractMongoClientConfiguration.java:58) ~[spring-data-mongodb-2.2.0.M4.jar:2.2.0.M4]
        at com.talkingflashcards.server.TalkingFlashcards.config.DatabaseConfiguration$$EnhancerBySpringCGLIB$$7a79cc38.CGLIB$mongoTemplate$3(<generated>) ~[classes/:na]
        at com.talkingflashcards.server.TalkingFlashcards.config.DatabaseConfiguration$$EnhancerBySpringCGLIB$$7a79cc38$$FastClassBySpringCGLIB$$5311e25d.invoke(<generated>) ~[classes/:na]
        at org.springframework.cglib.proxy.MethodProxy.invokeSuper(MethodProxy.java:244) ~[spring-core-5.2.0.M2.jar:5.2.0.M2]
        at org.springframework.context.annotation.ConfigurationClassEnhancer$BeanMethodInterceptor.intercept(ConfigurationClassEnhancer.java:363) ~[spring-context-5.2.0.M2.jar:5.2.0.M2]
        at com.talkingflashcards.server.TalkingFlashcards.config.DatabaseConfiguration$$EnhancerBySpringCGLIB$$7a79cc38.mongoTemplate(<generated>) ~[classes/:na]
        at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[na:1.8.0_191]
        at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) ~[na:1.8.0_191]
        at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) ~[na:1.8.0_191]
        at java.lang.reflect.Method.invoke(Method.java:498) ~[na:1.8.0_191]
        at org.springframework.beans.factory.support.SimpleInstantiationStrategy.instantiate(SimpleInstantiationStrategy.java:154) ~[spring-beans-5.2.0.M2.jar:5.2.0.M2]
        ... 20 common frames omitted
    Caused by: org.springframework.beans.BeanInstantiationException: Failed to instantiate [org.springframework.data.mongodb.MongoDbFactory]: Factory method 'mongoDbFactory' threw exception; nested exception is java.lang.IllegalArgumentException: The connection string is invalid. Connection strings must start with either 'mongodb://' or 'mongodb+srv://
        at org.springframework.beans.factory.support.SimpleInstantiationStrategy.instantiate(SimpleInstantiationStrategy.java:185) ~[spring-beans-5.2.0.M2.jar:5.2.0.M2]
        at org.springframework.beans.factory.support.ConstructorResolver.instantiate(ConstructorResolver.java:633) ~[spring-beans-5.2.0.M2.jar:5.2.0.M2]
        ... 43 common frames omitted
    Caused by: java.lang.IllegalArgumentException: The connection string is invalid. Connection strings must start with either 'mongodb://' or 'mongodb+srv://
        at com.mongodb.ConnectionString.<init>(ConnectionString.java:288) ~[mongodb-driver-core-3.11.0-beta3.jar:na]
        at com.mongodb.client.MongoClients.create(MongoClients.java:61) ~[mongodb-driver-3.11.0-beta3.jar:na]
        at com.talkingflashcards.server.TalkingFlashcards.config.DatabaseConfiguration.mongoClient(DatabaseConfiguration.java:32) ~[classes/:na]
        at org.springframework.data.mongodb.config.AbstractMongoClientConfiguration.mongoDbFactory(AbstractMongoClientConfiguration.java:71) ~[spring-data-mongodb-2.2.0.M4.jar:2.2.0.M4]
        at com.talkingflashcards.server.TalkingFlashcards.config.DatabaseConfiguration$$EnhancerBySpringCGLIB$$7a79cc38.CGLIB$mongoDbFactory$2(<generated>) ~[classes/:na]
        at com.talkingflashcards.server.TalkingFlashcards.config.DatabaseConfiguration$$EnhancerBySpringCGLIB$$7a79cc38$$FastClassBySpringCGLIB$$5311e25d.invoke(<generated>) ~[classes/:na]
        at org.springframework.cglib.proxy.MethodProxy.invokeSuper(MethodProxy.java:244) ~[spring-core-5.2.0.M2.jar:5.2.0.M2]
        at org.springframework.context.annotation.ConfigurationClassEnhancer$BeanMethodInterceptor.intercept(ConfigurationClassEnhancer.java:363) ~[spring-context-5.2.0.M2.jar:5.2.0.M2]
        at com.talkingflashcards.server.TalkingFlashcards.config.DatabaseConfiguration$$EnhancerBySpringCGLIB$$7a79cc38.mongoDbFactory(<generated>) ~[classes/:na]
        at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[na:1.8.0_191]
        at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) ~[na:1.8.0_191]
        at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) ~[na:1.8.0_191]
        at java.lang.reflect.Method.invoke(Method.java:498) ~[na:1.8.0_191]
        at org.springframework.beans.factory.support.SimpleInstantiationStrategy.instantiate(SimpleInstantiationStrategy.java:154) ~[spring-beans-5.2.0.M2.jar:5.2.0.M2]
        ... 44 common frames omitted

    Disconnected from the target VM, address: '127.0.0.1:60940', transport: 'socket'

    Process finished with exit code 1
</code>```

答:
I believe the key to the answer is towards the end of the stack trace where it says:

```<code>java.lang.IllegalArgumentException: The connection string is invalid. Connection strings must start with either 'mongodb://' or 'mongodb+srv://'
</code>```

Check that the host + ":" + port passed in the MongoClients.create method begins with either mongodb:// or mongodb+srv://. By looking at what you've posted, I can't tell what the host value is.

Body:
I'm total beginner in Spring. I want to create simple Spring app connecting to MongoDB. I generated Spring Boot with Spring Initializer and I created necessery files following a guide.

MongoDB is working. When I run the app I got the following error:

SpringFramework 2.2.0 M3
MongoDB 4.0
Dependencies (chosen in Spring Initializer): Web, MongoDB

DatabaseConfiguration.java

package com.talkingflashcards.server.TalkingFlashcards.config;

import com.mongodb.client.MongoClient;
import com.mongodb.client.MongoClients;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.mongodb.config.AbstractMongoClientConfiguration;
import org.springframework.data.mongodb.repository.config.EnableMongoRepositories;

@EnableMongoRepositories(basePackages = "com.talkingflashcards.server.TalkingFlashcards.repository")

@Configuration
public class DatabaseConfiguration extends AbstractMongoClientConfiguration {

    @Value("${spring.data.mongodb.host}")
    private String host;

    @Value("${spring.data.mongodb.port}")
    private String port;

    @Value("${spring.data.mongodb.username}")
    private String username;

    @Value("${spring.data.mongodb.password}")
    private String password;

    @Value("${spring.data.mongodb.database}")
    private String database;

    @Override
    public MongoClient mongoClient() {
        return MongoClients.create(host + ":" + port);
    }

    @Override
    protected String getDatabaseName() {
        return database;
    }
}

Error starting ApplicationContext. To display the conditions report re-run your application with 'debug' enabled.
    2019-05-29 23:52:19.955 ERROR 10144 --- [           main] o.s.boot.SpringApplication               : Application run failed

    org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'mongoTemplate' defined in class path resource [com/talkingflashcards/server/TalkingFlashcards/config/DatabaseConfiguration.class]: Bean instantiation via factory method failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [org.springframework.data.mongodb.core.MongoTemplate]: Factory method 'mongoTemplate' threw exception; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'mongoDbFactory' defined in class path resource [com/talkingflashcards/server/TalkingFlashcards/config/DatabaseConfiguration.class]: Bean instantiation via factory method failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [org.springframework.data.mongodb.MongoDbFactory]: Factory method 'mongoDbFactory' threw exception; nested exception is java.lang.IllegalArgumentException: The connection string is invalid. Connection strings must start with either 'mongodb://' or 'mongodb+srv://
        at org.springframework.beans.factory.support.ConstructorResolver.instantiate(ConstructorResolver.java:638) ~[spring-beans-5.2.0.M2.jar:5.2.0.M2]
        at org.springframework.beans.factory.support.ConstructorResolver.instantiateUsingFactoryMethod(ConstructorResolver.java:468) ~[spring-beans-5.2.0.M2.jar:5.2.0.M2]
        at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.instantiateUsingFactoryMethod(AbstractAutowireCapableBeanFactory.java:1325) ~[spring-beans-5.2.0.M2.jar:5.2.0.M2]
        at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBeanInstance(AbstractAutowireCapableBeanFactory.java:1164) ~[spring-beans-5.2.0.M2.jar:5.2.0.M2]
        at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:555) ~[spring-beans-5.2.0.M2.jar:5.2.0.M2]
        at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:515) ~[spring-beans-5.2.0.M2.jar:5.2.0.M2]
        at org.springframework.beans.factory.support.AbstractBeanFactory.lambda$doGetBean$0(AbstractBeanFactory.java:320) ~[spring-beans-5.2.0.M2.jar:5.2.0.M2]
        at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:222) ~[spring-beans-5.2.0.M2.jar:5.2.0.M2]
        at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:318) ~[spring-beans-5.2.0.M2.jar:5.2.0.M2]
        at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:199) ~[spring-beans-5.2.0.M2.jar:5.2.0.M2]
        at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:868) ~[spring-beans-5.2.0.M2.jar:5.2.0.M2]
        at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:877) ~[spring-context-5.2.0.M2.jar:5.2.0.M2]
        at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:549) ~[spring-context-5.2.0.M2.jar:5.2.0.M2]
        at org.springframework.boot.web.servlet.context.ServletWebServerApplicationContext.refresh(ServletWebServerApplicationContext.java:142) ~[spring-boot-2.2.0.M3.jar:2.2.0.M3]
        at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:782) [spring-boot-2.2.0.M3.jar:2.2.0.M3]
        at org.springframework.boot.SpringApplication.refreshContext(SpringApplication.java:404) [spring-boot-2.2.0.M3.jar:2.2.0.M3]
        at org.springframework.boot.SpringApplication.run(SpringApplication.java:319) [spring-boot-2.2.0.M3.jar:2.2.0.M3]
        at org.springframework.boot.SpringApplication.run(SpringApplication.java:1275) [spring-boot-2.2.0.M3.jar:2.2.0.M3]
        at org.springframework.boot.SpringApplication.run(SpringApplication.java:1263) [spring-boot-2.2.0.M3.jar:2.2.0.M3]
        at com.talkingflashcards.server.TalkingFlashcards.TalkingFlashcardsApplication.main(TalkingFlashcardsApplication.java:14) [classes/:na]
    Caused by: org.springframework.beans.BeanInstantiationException: Failed to instantiate [org.springframework.data.mongodb.core.MongoTemplate]: Factory method 'mongoTemplate' threw exception; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'mongoDbFactory' defined in class path resource [com/talkingflashcards/server/TalkingFlashcards/config/DatabaseConfiguration.class]: Bean instantiation via factory method failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [org.springframework.data.mongodb.MongoDbFactory]: Factory method 'mongoDbFactory' threw exception; nested exception is java.lang.IllegalArgumentException: The connection string is invalid. Connection strings must start with either 'mongodb://' or 'mongodb+srv://
        at org.springframework.beans.factory.support.SimpleInstantiationStrategy.instantiate(SimpleInstantiationStrategy.java:185) ~[spring-beans-5.2.0.M2.jar:5.2.0.M2]
        at org.springframework.beans.factory.support.ConstructorResolver.instantiate(ConstructorResolver.java:633) ~[spring-beans-5.2.0.M2.jar:5.2.0.M2]
        ... 19 common frames omitted
    Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'mongoDbFactory' defined in class path resource [com/talkingflashcards/server/TalkingFlashcards/config/DatabaseConfiguration.class]: Bean instantiation via factory method failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [org.springframework.data.mongodb.MongoDbFactory]: Factory method 'mongoDbFactory' threw exception; nested exception is java.lang.IllegalArgumentException: The connection string is invalid. Connection strings must start with either 'mongodb://' or 'mongodb+srv://
        at org.springframework.beans.factory.support.ConstructorResolver.instantiate(ConstructorResolver.java:638) ~[spring-beans-5.2.0.M2.jar:5.2.0.M2]
        at org.springframework.beans.factory.support.ConstructorResolver.instantiateUsingFactoryMethod(ConstructorResolver.java:468) ~[spring-beans-5.2.0.M2.jar:5.2.0.M2]
        at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.instantiateUsingFactoryMethod(AbstractAutowireCapableBeanFactory.java:1325) ~[spring-beans-5.2.0.M2.jar:5.2.0.M2]
        at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBeanInstance(AbstractAutowireCapableBeanFactory.java:1164) ~[spring-beans-5.2.0.M2.jar:5.2.0.M2]
        at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:555) ~[spring-beans-5.2.0.M2.jar:5.2.0.M2]
        at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:515) ~[spring-beans-5.2.0.M2.jar:5.2.0.M2]
        at org.springframework.beans.factory.support.AbstractBeanFactory.lambda$doGetBean$0(AbstractBeanFactory.java:320) ~[spring-beans-5.2.0.M2.jar:5.2.0.M2]
        at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:222) ~[spring-beans-5.2.0.M2.jar:5.2.0.M2]
        at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:318) ~[spring-beans-5.2.0.M2.jar:5.2.0.M2]
        at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:199) ~[spring-beans-5.2.0.M2.jar:5.2.0.M2]
        at org.springframework.context.annotation.ConfigurationClassEnhancer$BeanMethodInterceptor.resolveBeanReference(ConfigurationClassEnhancer.java:394) ~[spring-context-5.2.0.M2.jar:5.2.0.M2]
        at org.springframework.context.annotation.ConfigurationClassEnhancer$BeanMethodInterceptor.intercept(ConfigurationClassEnhancer.java:366) ~[spring-context-5.2.0.M2.jar:5.2.0.M2]
        at com.talkingflashcards.server.TalkingFlashcards.config.DatabaseConfiguration$$EnhancerBySpringCGLIB$$7a79cc38.mongoDbFactory(<generated>) ~[classes/:na]
        at org.springframework.data.mongodb.config.AbstractMongoClientConfiguration.mongoTemplate(AbstractMongoClientConfiguration.java:58) ~[spring-data-mongodb-2.2.0.M4.jar:2.2.0.M4]
        at com.talkingflashcards.server.TalkingFlashcards.config.DatabaseConfiguration$$EnhancerBySpringCGLIB$$7a79cc38.CGLIB$mongoTemplate$3(<generated>) ~[classes/:na]
        at com.talkingflashcards.server.TalkingFlashcards.config.DatabaseConfiguration$$EnhancerBySpringCGLIB$$7a79cc38$$FastClassBySpringCGLIB$$5311e25d.invoke(<generated>) ~[classes/:na]
        at org.springframework.cglib.proxy.MethodProxy.invokeSuper(MethodProxy.java:244) ~[spring-core-5.2.0.M2.jar:5.2.0.M2]
        at org.springframework.context.annotation.ConfigurationClassEnhancer$BeanMethodInterceptor.intercept(ConfigurationClassEnhancer.java:363) ~[spring-context-5.2.0.M2.jar:5.2.0.M2]
        at com.talkingflashcards.server.TalkingFlashcards.config.DatabaseConfiguration$$EnhancerBySpringCGLIB$$7a79cc38.mongoTemplate(<generated>) ~[classes/:na]
        at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[na:1.8.0_191]
        at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) ~[na:1.8.0_191]
        at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) ~[na:1.8.0_191]
        at java.lang.reflect.Method.invoke(Method.java:498) ~[na:1.8.0_191]
        at org.springframework.beans.factory.support.SimpleInstantiationStrategy.instantiate(SimpleInstantiationStrategy.java:154) ~[spring-beans-5.2.0.M2.jar:5.2.0.M2]
        ... 20 common frames omitted
    Caused by: org.springframework.beans.BeanInstantiationException: Failed to instantiate [org.springframework.data.mongodb.MongoDbFactory]: Factory method 'mongoDbFactory' threw exception; nested exception is java.lang.IllegalArgumentException: The connection string is invalid. Connection strings must start with either 'mongodb://' or 'mongodb+srv://
        at org.springframework.beans.factory.support.SimpleInstantiationStrategy.instantiate(SimpleInstantiationStrategy.java:185) ~[spring-beans-5.2.0.M2.jar:5.2.0.M2]
        at org.springframework.beans.factory.support.ConstructorResolver.instantiate(ConstructorResolver.java:633) ~[spring-beans-5.2.0.M2.jar:5.2.0.M2]
        ... 43 common frames omitted
    Caused by: java.lang.IllegalArgumentException: The connection string is invalid. Connection strings must start with either 'mongodb://' or 'mongodb+srv://
        at com.mongodb.ConnectionString.<init>(ConnectionString.java:288) ~[mongodb-driver-core-3.11.0-beta3.jar:na]
        at com.mongodb.client.MongoClients.create(MongoClients.java:61) ~[mongodb-driver-3.11.0-beta3.jar:na]
        at com.talkingflashcards.server.TalkingFlashcards.config.DatabaseConfiguration.mongoClient(DatabaseConfiguration.java:32) ~[classes/:na]
        at org.springframework.data.mongodb.config.AbstractMongoClientConfiguration.mongoDbFactory(AbstractMongoClientConfiguration.java:71) ~[spring-data-mongodb-2.2.0.M4.jar:2.2.0.M4]
        at com.talkingflashcards.server.TalkingFlashcards.config.DatabaseConfiguration$$EnhancerBySpringCGLIB$$7a79cc38.CGLIB$mongoDbFactory$2(<generated>) ~[classes/:na]
        at com.talkingflashcards.server.TalkingFlashcards.config.DatabaseConfiguration$$EnhancerBySpringCGLIB$$7a79cc38$$FastClassBySpringCGLIB$$5311e25d.invoke(<generated>) ~[classes/:na]
        at org.springframework.cglib.proxy.MethodProxy.invokeSuper(MethodProxy.java:244) ~[spring-core-5.2.0.M2.jar:5.2.0.M2]
        at org.springframework.context.annotation.ConfigurationClassEnhancer$BeanMethodInterceptor.intercept(ConfigurationClassEnhancer.java:363) ~[spring-context-5.2.0.M2.jar:5.2.0.M2]
        at com.talkingflashcards.server.TalkingFlashcards.config.DatabaseConfiguration$$EnhancerBySpringCGLIB$$7a79cc38.mongoDbFactory(<generated>) ~[classes/:na]
        at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[na:1.8.0_191]
        at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) ~[na:1.8.0_191]
        at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) ~[na:1.8.0_191]
        at java.lang.reflect.Method.invoke(Method.java:498) ~[na:1.8.0_191]
        at org.springframework.beans.factory.support.SimpleInstantiationStrategy.instantiate(SimpleInstantiationStrategy.java:154) ~[spring-beans-5.2.0.M2.jar:5.2.0.M2]
        ... 44 common frames omitted

    Disconnected from the target VM, address: '127.0.0.1:60940', transport: 'socket'

    Process finished with exit code 1

Body:
I believe the key to the answer is towards the end of the stack trace where it says:

java.lang.IllegalArgumentException: The connection string is invalid. Connection strings must start with either 'mongodb://' or 'mongodb+srv://'

Check that the host + ":" + port passed in the MongoClients.create method begins with either mongodb:// or mongodb+srv://. By looking at what you've posted, I can't tell what the host value is.


问:
Webjob application vs web api app triggered by console app as a web job
I have a web api(.netcore) which I have hosted in Azure under an app service.

I have another app related to the above api(in the same resource group) which need to be triggered every few minutes.

My confusion is what is the best practise?

1) Write a webjob app(.net framework) for the second app.

2) Write the second app as an api and write a console app to call the api. Then call the console app from the webjobs in Azure. But that would mean a second app service in the same resource group(for second API).

Is there any pricing difference between the two?

Is there any advantage of one over the other?

Is there any better way?

Update

I have gone with the second option.

Is there any advantage if I go with the below(cost and code vice).So in the same app service there will be a wep app, a webjob to trigger the api and another webjob to read message from queue do the processing.

答:
There are a few options for writing a service that is triggered on a timer:

WebJobs - These are essentially console apps that run behind the scenes to do related jobs that users of your API don't need to wait on (photo processing is a common example) or need to be run on a schedule, like your use case.

Azure Functions - Functions are similar to WebJobs, but make it easier to scale and abstract away the necessity of coding up connections to a lot of other services. They also can have billing advantages if you are creating an App Service just to run them.

Azure Logic Apps - I think you want either WebJobs or Functions, but Logic Apps can also run a job on a schedule. In this case, you are designing your workflow either in JSON file or more likely in a GUI. If your job doesn't require much custom code, using a Logic App means that development time is reduced and you have one less piece of custom code to maintain.

For pricing:

Both Webjobs and Functions can be attached to the same App Service account as your API as long as you have sufficient resources there to handle the additional load. So no additional costs there.

You could pay for a separate App Service account for the Webjob if you want, but usually they are kept on the same App Service account as the API.

Functions apps can run on a special type of App Service account that has a consumption plan. What that means that instead of a monthly fee, you pay for the resources that you actually use.

Logic Apps aren't connected to App Services, and have consumption based billing similar to Functions.


问:
Gitlab merge request with --no-ff
Does Gitlab support merge request with --no-ff?

I found in Gitlab, it only supports fast-forward mode. While in Github, we're provided with 2 options: To merge or squash (--no-ff).

I'd like to discard verbose commit messages in Gitlab master branch on approving a merge request. That's why I wish there's squash option in Gitlab.

答:
Squashing is not really related to --no-ff (no fast forward)

If all you want to do is remove noise commit messages. You want to squash your commits. If you want to remove merge commits you fast forward (achieved by doing a rebase).

To squash, you can do this through command line with

git rebase -i HEAD~[NUMBER OF COMMITS]

or

git reset --soft HEAD~3
git commit -m "New message for the combined commit"

(There are other ways to achieve this as well)

There is also an option on gitlab to squash your commits for you on merge. It uses the title of the merge request as the commit message.

An example

You open a merge request with the Title

"WAR-132: Display confirmation dialogue when document uploaded"

This merge request contains three commits

```<code>WAR-132: Make code more concise.
War-132: Add missing specs (and reorder, reformat of tests)
WAR-132: Display a confirmation dialogue when the document is uploaded
</code>```

By ticking the squash commits option (found next to the merge button).

You will end up with the following commit being added to the branch you are merging to.

```<code>WAR-132: Display confirmation dialogue when document uploaded
</code>```

Title: Gitlab merge request with --no-ff

Body:
Squashing is not really related to --no-ff (no fast forward)

If all you want to do is remove noise commit messages. You want to squash your commits. If you want to remove merge commits you fast forward (achieved by doing a rebase).

To squash, you can do this through command line with

git rebase -i HEAD~[NUMBER OF COMMITS]

or

git reset --soft HEAD~3
git commit -m "New message for the combined commit"

(There are other ways to achieve this as well)

There is also an option on gitlab to squash your commits for you on merge. It uses the title of the merge request as the commit message.

An example

You open a merge request with the Title

"WAR-132: Display confirmation dialogue when document uploaded"

This merge request contains three commits

WAR-132: Make code more concise.
War-132: Add missing specs (and reorder, reformat of tests)
WAR-132: Display a confirmation dialogue when the document is uploaded

By ticking the squash commits option (found next to the merge button).

You will end up with the following commit being added to the branch you are merging to.

WAR-132: Display confirmation dialogue when document uploaded