问:
How do I execute a code only once all the queries inside a loop are done? (mongoose, express)
here is my router:

```<code>router.get('/questions/best', function(req,res,next){
  Question.aggregate([
    // Protect against missing fields with $ifNull
    // Protect against division by zero dislikes using max[1,size]
    {$project: {ratio: {$divide:[
    {$arrayElemAt:[{$ifNull:["$likes",[0]]}, 0]},
        {$max:[1, {$arrayElemAt:[{$ifNull:["$dislikes",[0]]}, 0]}]}
        ]}
    }},
    {$sort: {ratio:-1}},
    {$limit: 15}
  ]).exec(function(err,results){
    if(err) {return next(err)}
    top15 = []
    for(let i = 0; i < results.length; i++){
      Question.findOne({_id: results[i]._id}).exec(function(err,result){
        if(err){return next(err)}
        top15.push(result);
      })
    }
    res.render('content', { whichOne: 5, user: req.user, questions: top15 });
  });
});
</code>```

don't worry about the filtering stuff, it works good, the only problem is that the template at the end of the router get rendered automatically right after the queries start, not allowing them time to push the results into an array that gets rendered into the template.
I tried using set Timeout function, but the processing time changes drastically and it is impossible to find an exact time. I think I need to use async functions? but promises do not work for some reason?

can anybody make sure the template get rendered only after all the queries return and put their values in the array?
Thanks!

答:
From reading mongoose documentation, using promises makes this trivial

using Promises

```<code>router.get('/questions/best', (req,res,next) => {
    Question.aggregate([
        // Protect against missing fields with $ifNull
        // Protect against division by zero dislikes using max[1,size]
        {$project: {ratio: {$divide:[
        {$arrayElemAt:[{$ifNull:["$likes",[0]]}, 0]},
            {$max:[1, {$arrayElemAt:[{$ifNull:["$dislikes",[0]]}, 0]}]}
            ]}
        }},
        {$sort: {ratio:-1}},
        {$limit: 15}
    ]).exec()
    .then(results => Promise.all(results.map(({_id}) => Question.findOne({_id}).exec())))
    .then(questions => res.render('content', { whichOne: 5, user: req.user, questions}))
    .catch(next);
});
</code>```

or, using async/await

```<code>router.get('/questions/best', async (req,res,next) => {
    try {
        const results = await Question.aggregate([
            // Protect against missing fields with $ifNull
            // Protect against division by zero dislikes using max[1,size]
            {$project: {ratio: {$divide:[
            {$arrayElemAt:[{$ifNull:["$likes",[0]]}, 0]},
                {$max:[1, {$arrayElemAt:[{$ifNull:["$dislikes",[0]]}, 0]}]}
                ]}
            }},
            {$sort: {ratio:-1}},
            {$limit: 15}
        ]).exec();
        const questions = await Promise.all(results.map(({_id}) => Question.findOne({_id}).exec()));
        res.render('content', { whichOne: 5, user: req.user, questions});
    } catch(err) {
        next(err);
    }
});
</code>```

Body:
here is my router:

router.get('/questions/best', function(req,res,next){
  Question.aggregate([
    // Protect against missing fields with $ifNull
    // Protect against division by zero dislikes using max[1,size]
    {$project: {ratio: {$divide:[
    {$arrayElemAt:[{$ifNull:["$likes",[0]]}, 0]},
        {$max:[1, {$arrayElemAt:[{$ifNull:["$dislikes",[0]]}, 0]}]}
        ]}
    }},
    {$sort: {ratio:-1}},
    {$limit: 15}
  ]).exec(function(err,results){
    if(err) {return next(err)}
    top15 = []
    for(let i = 0; i < results.length; i++){
      Question.findOne({_id: results[i]._id}).exec(function(err,result){
        if(err){return next(err)}
        top15.push(result);
      })
    }
    res.render('content', { whichOne: 5, user: req.user, questions: top15 });
  });
});

don't worry about the filtering stuff, it works good, the only problem is that the template at the end of the router get rendered automatically right after the queries start, not allowing them time to push the results into an array that gets rendered into the template.
I tried using set Timeout function, but the processing time changes drastically and it is impossible to find an exact time. I think I need to use async functions? but promises do not work for some reason?

can anybody make sure the template get rendered only after all the queries return and put their values in the array?
Thanks!

Body:
From reading mongoose documentation, using promises makes this trivial

using Promises

router.get('/questions/best', (req,res,next) => {
    Question.aggregate([
        // Protect against missing fields with $ifNull
        // Protect against division by zero dislikes using max[1,size]
        {$project: {ratio: {$divide:[
        {$arrayElemAt:[{$ifNull:["$likes",[0]]}, 0]},
            {$max:[1, {$arrayElemAt:[{$ifNull:["$dislikes",[0]]}, 0]}]}
            ]}
        }},
        {$sort: {ratio:-1}},
        {$limit: 15}
    ]).exec()
    .then(results => Promise.all(results.map(({_id}) => Question.findOne({_id}).exec())))
    .then(questions => res.render('content', { whichOne: 5, user: req.user, questions}))
    .catch(next);
});

or, using async/await

router.get('/questions/best', async (req,res,next) => {
    try {
        const results = await Question.aggregate([
            // Protect against missing fields with $ifNull
            // Protect against division by zero dislikes using max[1,size]
            {$project: {ratio: {$divide:[
            {$arrayElemAt:[{$ifNull:["$likes",[0]]}, 0]},
                {$max:[1, {$arrayElemAt:[{$ifNull:["$dislikes",[0]]}, 0]}]}
                ]}
            }},
            {$sort: {ratio:-1}},
            {$limit: 15}
        ]).exec();
        const questions = await Promise.all(results.map(({_id}) => Question.findOne({_id}).exec()));
        res.render('content', { whichOne: 5, user: req.user, questions});
    } catch(err) {
        next(err);
    }
});


来源: stackexchange

问:
Rails 3 HTML 5/javascript free graphing recommendations
In doing searches for good rails 3 graphing options most of the things I can find are a couple of years old and some are not maintained anymore.  A few of the items I found are Bluff, D3, flotr, flotilla, and Highcharts, though Highcharts is not free for commercial use.  I am using prototype so I was looking for a solution with prototype.

I don't need anything too involved.  At the moment I am just planning line graphs but that could change.  Any recommendations on what I could use with prototype?  I would rather not switch my site over to jquery just so I can do graphing.

Thanks in advance for any recommendations.

答: Try using HTML5 canvas api. It has a complete drawing api.</p>

ContentLicense: CC BY-SA 3.0


ContentLicense: CC BY-SA 4.0

Title: Breaking up observations across multiple dates in R

Body:
I am hoping to find a data.table + lubridate solution to the following problem.

Suppose that I have the following dataset:

library(data.table)
library(lubridate)
library(magrittr)

sample <- data.table(start = c("2018-12-22 23:00:00",
                               "2018-12-23 06:00:00",
                               "2018-12-22 06:00:00",
                               "2018-12-23 06:00:00"),
                     end = c("2018-12-23 06:00:00",
                             "2018-12-23 13:00:00",
                             "2018-12-23 12:00:00",
                             "2018-12-24 01:00:00"),
                     store = c("A", "A", "B", "B"),
                     var = 1:4)

sample[, start:= ymd_hms(start)]
sample[, end := ymd_hms(end)]

The output looks like:

> sample
                 start                 end store var
1: 2018-12-22 23:00:00 2018-12-23 06:00:00     A   1
2: 2018-12-23 06:00:00 2018-12-23 13:00:00     A   2
3: 2018-12-22 06:00:00 2018-12-23 12:00:00     B   3
4: 2018-12-23 06:00:00 2018-12-24 01:00:00     B   4

Notice that on rows 1, 3, and 4, we have observations that span multiple dates. I would like to break up these observations so that they only take up one calendar date each. It is also possible that a start date and end date spans multiple days, but I would like to have one observation for each date. For the sample above, the data.table should look like:

                 start                 end store var
1: 2018-12-22 23:00:00 2018-12-22 23:59:59     A   1
2: 2018-12-23 00:00:00 2018-12-23 06:00:00     A   1
3: 2018-12-23 06:00:00 2018-12-23 13:00:00     A   2
4: 2018-12-22 06:00:00 2018-12-22 23:59:59     B   3
5: 2018-12-23 00:00:00 2018-12-23 12:00:00     B   3
6: 2018-12-23 06:00:00 2018-12-23 23:59:59     B   4
7: 2018-12-24 00:00:00 2018-12-24 01:00:00     B   4

It is important the var variable is the same when we break up the observation across multiple dates.

Thanks!

Body:
# expand the rows
sample = sample[sample[, .(date = seq(as.IDate(start),as.IDate(end),1)), by=var], on="var"]

# fix the times
sample[, `:=`(
  start = fifelse(as.IDate(start) == date,
                  ymd_hms(paste0(as.Date(start),as.ITime(start))),
                  ymd_hms(paste0(date,"00:00:00"))),
  end = fifelse(as.IDate(end) == date,
                ymd_hms(paste0(as.Date(end),as.ITime(end))),
                ymd_hms(paste0(date, "23:59:59"))),
  date = NULL
)]

Output:

                 start                 end store var
1: 2018-12-22 23:00:00 2018-12-22 23:59:59     A   1
2: 2018-12-23 00:00:00 2018-12-23 06:00:00     A   1
3: 2018-12-23 06:00:00 2018-12-23 13:00:00     A   2
4: 2018-12-22 06:00:00 2018-12-22 23:59:59     B   3
5: 2018-12-23 00:00:00 2018-12-23 12:00:00     B   3
6: 2018-12-23 06:00:00 2018-12-23 23:59:59     B   4
7: 2018-12-24 00:00:00 2018-12-24 01:00:00     B   4


问:
What is Sqlite used for?
I don't know how authoritative this is but I found this:

http://www.sqlite.org/cvstrac/wiki?p=PerformanceConsiderations

and it doesn't seem good to have a lot of connections to sqlite.  This seems to be bad for the web and most applications that have more than a few users.  I'm having a hard time thinking of what sqlite would be used for when you don't need that many connections.  Every program I can think of needs users, lots of them sometimes, so what would I use a database for that doesn't allow that many connections?  I thought about prototypes but why would I use that when I can just connect to a larger database?  Embedded apps maybe?

Thank you.

EDIT:  Thanks everyone.  I look at the page recommended below but an confused about something:

Under appropriate uses for sqlite it has:

Situations Where SQLite Works Well

•Websites

SQLite usually will work great as the database engine for low to medium traffic websites (which is to say, 99.9% of all websites). The amount of web traffic that SQLite can handle depends, of course, on how heavily the website uses its database. Generally speaking, any site that gets fewer than 100K hits/day should work fine with SQLite. The 100K hits/day figure is a conservative estimate, not a hard upper bound. SQLite has been demonstrated to work with 10 times that amount of traffic.

Situations Where Another RDBMS May Work Better

•Client/Server Applications

If you have many client programs accessing a common database over a network, you should consider using a client/server database engine instead of SQLite. SQLite will work over a network filesystem, but because of the latency associated with most network filesystems, performance will not be great. Also, the file locking logic of many network filesystems implementation contains bugs (on both Unix and Windows). If file locking does not work like it should, it might be possible for two or more client programs to modify the same part of the same database at the same time, resulting in database corruption. Because this problem results from bugs in the underlying filesystem implementation, there is nothing SQLite can do to prevent it.

A good rule of thumb is that you should avoid using SQLite in situations where the same database will be accessed simultaneously from many computers over a network filesystem.

The Question:

I'm going to show my ignorance here but what is the difference between these two?

答:
It's often used for embedded applications.

It can be very handy to use a database like storage when you have no access to a database service. So SQLite is used since it's just a file you store somewhere.

OwnerDisplayName: johnny

ContentLicense: CC BY-SA 2.5

Title: What is Sqlite used for?

LastEditorDisplayName: johnny

OwnerDisplayName: Ólafur Waage


问:
My indicator triggers alarm even though it doesn't satisfy the alarm condition
My Indicator

I have an indicator that gives signals. The working logic is if the background is light red and the price touches the blue bar, give a short signal. As you can see in the picture, there is no signal because

```<code>plot(long_short==-1 ? shortStop : na, style=plot.style_linebr, color=color.yellow, linewidth=3, title="Short Fixed SL")
plot(long_short==-1 ? shortTake : na, style=plot.style_linebr, color=color.blue, linewidth=3, title="Short Fixed TP")
...
alertcondition(condition=short_last, title="Short Alarm", message='Open a Short Trade @ ${{close}}')
...
if(short_last)
    l = label.new(bar_index, high)
    label.set_text(l, "sell@\n"+str.tostring(close))
    label.set_color(l, color.red)
    label.set_yloc(l, yloc.abovebar)
    label.set_style(l, label.style_arrowdown)
</code>```

If short_last was true, it should have tp/sl lines and the label like in the left signals, but it doesn't exist because short_last must be false. In other words, it should not have actually thrown a signal. What is the problem and how can I fix it?

答: I found what caused the problem. When adding an alarm in Tradingview, it is added according to the default inputs of the indicator. I changed the inputs later, but since the alarms remained according to the default values, it actually appears as a light-red zone for another input, and that's why it triggered an alarm. Now I have to set 40 alarms again.</p>

Body:
My Indicator

I have an indicator that gives signals. The working logic is if the background is light red and the price touches the blue bar, give a short signal. As you can see in the picture, there is no signal because

plot(long_short==-1 ? shortStop : na, style=plot.style_linebr, color=color.yellow, linewidth=3, title="Short Fixed SL")
plot(long_short==-1 ? shortTake : na, style=plot.style_linebr, color=color.blue, linewidth=3, title="Short Fixed TP")
...
alertcondition(condition=short_last, title="Short Alarm", message='Open a Short Trade @ ${{close}}')
...
if(short_last)
    l = label.new(bar_index, high)
    label.set_text(l, "sell@\n"+str.tostring(close))
    label.set_color(l, color.red)
    label.set_yloc(l, yloc.abovebar)
    label.set_style(l, label.style_arrowdown)

If short_last was true, it should have tp/sl lines and the label like in the left signals, but it doesn't exist because short_last must be false. In other words, it should not have actually thrown a signal. What is the problem and how can I fix it?


问:
Count the number of punctuation symbols in a string Kotlin
I have a question how can I count the number of punctuation symbols in a string.

Here is my code snippet

```<code>fun punctuationCount(stringValue: Editable): Int {
        val trimmedStr = stringValue.trim()
        return if (trimmedStr.isEmpty()) {
            0
        } else {
           return trimmedStr.split("[a-zA-Z&&[ \t]]".toRegex()).size
        }
    }
</code>```

答:
Another variation - the Unicode standard defines a bunch of categories (see 4.4) that a character can fall into, and those are present in Kotlin, so you could make use of those if you like

```<code>import kotlin.text.CharCategory.*

val punctuation = setOf(
    DASH_PUNCTUATION, START_PUNCTUATION, END_PUNCTUATION,
    CONNECTOR_PUNCTUATION, OTHER_PUNCTUATION
)

val testString = "Some string containing punctuation, like !, @, #, etc."

fun main() {
    testString.count { it.category in punctuation }.run(::println)
}

>>> 8
</code>```

You'd have to decide if those cover your needs, or which ones to include and exclude (and symbols are a different category class). Just throwing it out there as an option / something to know about!

Body:
I have a question how can I count the number of punctuation symbols in a string.

Here is my code snippet

fun punctuationCount(stringValue: Editable): Int {
        val trimmedStr = stringValue.trim()
        return if (trimmedStr.isEmpty()) {
            0
        } else {
           return trimmedStr.split("[a-zA-Z&&[ \t]]".toRegex()).size
        }
    }

Body:
Another variation - the Unicode standard defines a bunch of categories (see 4.4) that a character can fall into, and those are present in Kotlin, so you could make use of those if you like

import kotlin.text.CharCategory.*

val punctuation = setOf(
    DASH_PUNCTUATION, START_PUNCTUATION, END_PUNCTUATION,
    CONNECTOR_PUNCTUATION, OTHER_PUNCTUATION
)

val testString = "Some string containing punctuation, like !, @, #, etc."

fun main() {
    testString.count { it.category in punctuation }.run(::println)
}

>>> 8

You'd have to decide if those cover your needs, or which ones to include and exclude (and symbols are a different category class). Just throwing it out there as an option / something to know about!


问:
Python unittest does not run tests
I made a small project called demo, with a single test in it

```<code>import unittest

class Test(unittest.TestCase):

    def testName1(self):
        self.assertEqual(5+9, 14)

if __name__ == "__main__":
    #import sys;sys.argv = ['', 'Test.testName']
    unittest.main()
</code>```

However, from command line

```<code>ThinkPad-T520:~/workspacep/demo$ python -m unittest

----------------------------------------------------------------------
Ran 0 tests in 0.000s

OK
</code>```

Why doesn't this work? In general, how can I run all unit tests from command line with a single line?

The structure of the directory is

```<code>demo
    tests
          demo_test1.py  __init__.py
</code>```

答: I had a similar issue and figured out that I had to run python3 -m unittest instead as I had forgotten python defaults to Python 2 on my system

Title: Python unittest does not run tests

Body:
I made a small project called demo, with a single test in it

import unittest

class Test(unittest.TestCase):

    def testName1(self):
        self.assertEqual(5+9, 14)

if __name__ == "__main__":
    #import sys;sys.argv = ['', 'Test.testName']
    unittest.main()

However, from command line

ThinkPad-T520:~/workspacep/demo$ python -m unittest

----------------------------------------------------------------------
Ran 0 tests in 0.000s

OK

Why doesn't this work? In general, how can I run all unit tests from command line with a single line?

The structure of the directory is

demo
    tests
          demo_test1.py  __init__.py


问:
How to remove only one of repeated chars in string using JavaScript
I have a string with repeated chars like : 'CANADA'.

And I am trying to get the string which removed only one of repeated chars :

'CNADA', 'CANDA', 'CANAD'.

I've tried it with subString, but it returned the part of string removed.
Also I've tried it with reduce, but it ended up removing all the repeated chars ('CND').

What is the way of removing only one char at time?
The results can be stored in array. (results = ['CNADA', 'CANDA', 'CANAD'])

Thank you.

答:
You can first count all the occurrences in the string. Later you can iterate over the script and if the count is greater than 1 you can remove that character.

const theString = 'CANADA'
const letterCount = {}
const resultArr = []

for (var i = 0; i < theString.length; i++) {
  const theLetter = theString.charAt(i)
  if(letterCount[theLetter]){
    letterCount[theLetter] = letterCount[theLetter] + 1
  }
  else{
    letterCount[theLetter] = 1
  }
}
console.log(letterCount)
for (var i = 0; i < theString.length; i++) {
  const theLetter = theString.charAt(i)
  if(letterCount[theLetter] && letterCount[theLetter] > 1){
   resultArr.push(theString.substr(0, i) + theString.substr(i + 1))
  }
}

console.log(resultArr)```


问:
How can I Import a module from the working directory?
I have downloaded a module and moved it to my working directory, how can I import this module and all of its contents to use on my code?

a view of my working directory:
E:\myprojects\projectA

location of the downloaded module:
E:\myprojects\projectA\tweepy

NOTE:
I tried installing it using a CMD and I was unable to that's why I want to do it this way instead.

答:
Normally to import a module you need to install it first, not just download it. In almost every case, your IDE will help you to install it.

Once installed, all you need to do in your code is to add this line at the beginning of it:

```<code>import tweepy as name
</code>```

Where name is the name you would like to use for using that module functions.

Body:
Normally to import a module you need to install it first, not just download it. In almost every case, your IDE will help you to install it.

Once installed, all you need to do in your code is to add this line at the beginning of it:

import tweepy as name

Where name is the name you would like to use for using that module functions.


问:
order of expansion between variable expansion and command substitution
The bash man says that variable expansion occurs before command substitution. I was seeking of an example that shows it clearly. So i tried this:

```<code>root@antec:/# var=1
root@antec:/# echo $(var=2; echo $var)
2
root@antec:/#
</code>```

I was expecting bash to do:

1) replace $var by "1" in the substitution

2) execute echo $(var=2; echo 1)

Obviously this is not what bash is doing ..

Can someone please explain what is going one here ? And if someone has an example showing the precedence of variable expansion over command substitution it would be nice too

答:
I think your confusion here is that you think the variable expansion happens inside a command substitution, when it doesn't.

Actually, bash will only do a command substitution there, where the command is var=2; echo $var. That will then be run in a subshell, which will execute the command, doing all expansion passes yet again for each command run.

Body:
The bash man says that variable expansion occurs before command substitution. I was seeking of an example that shows it clearly. So i tried this:

root@antec:/# var=1
root@antec:/# echo $(var=2; echo $var)
2
root@antec:/#

I was expecting bash to do:

1) replace $var by "1" in the substitution

2) execute echo $(var=2; echo 1)

Obviously this is not what bash is doing ..

Can someone please explain what is going one here ? And if someone has an example showing the precedence of variable expansion over command substitution it would be nice too


问:
I am trying to extract the emailController and the passwordController but I keep getting an error

import 'package:flutter/material.dart';
import 'package:time_trackerpractice/common_widgets/form_submit_button.dart';
import 'package:time_trackerpractice/services/auth.dart';

enum EmailSignInFormType{signIn,register}

class EmailSignInForm extends StatefulWidget {
  EmailSignInForm({@required this.auth});
  final AuthBase auth;

  @override
  _EmailSignInFormState createState() => _EmailSignInFormState();
}

class _EmailSignInFormState extends State<EmailSignInForm> {

 final TextEditingController _emailController = TextEditingController();
 final TextEditingController _passwordController =TextEditingController();

 String get _email=>_emailController.text;
 String get _password=> _passwordController.text;

 EmailSignInFormType _formType = EmailSignInFormType.signIn;

 void _submit() async {
   try {
     if (_formType == EmailSignInFormType.signIn) {
       await widget.auth.signInWithEmailAndPassword(_email, _password);
     } else {
       await widget.auth.signInWithEmailAndPassword(_email, _password);
     }
   } catch (e) {
     print(e.toString());
   }
   Navigator.of(context).pop();
 }

  void _toggleFormType(){
   setState(() {
    _formType = _formType == EmailSignInFormType.signIn?
        EmailSignInFormType.register: EmailSignInFormType.signIn;
   });
  }

  List<Widget> _buildChildren() {
    final primaryText = _formType == EmailSignInFormType.signIn ? 'Sign in' : 'Create account';
    final secondaryText = _formType == EmailSignInFormType.signIn
        ? 'Need an account? Register'
        : 'Have an account? Sign in';
    return [
      TextField(
        controller: _emailController,
        decoration: InputDecoration(
          labelText: 'Email',
          hintText: 'test@test.com',
        ),
        autocorrect: false,
        keyboardType: TextInputType.emailAddress,
        textInputAction: TextInputAction.next,
      ),
      SizedBox(height: 8.0),
      TextField(
        controller: _passwordController,
        decoration: InputDecoration(
          labelText: 'Password',
        ),
        obscureText: true,
        textInputAction: TextInputAction.done,
      ),
      SizedBox(height: 8.0),
      FormSubmitButton(
        text: primaryText,
        onPressed: _submit,
      ),
      SizedBox(height: 8.0),
    FlatButton(
      child: Text(secondaryText),
      onPressed: _toggleFormType,
    ),
   ];

 }

  @override
  Widget build(BuildContext context) {
    return Padding(
      padding: const EdgeInsets.all(16.0),
      child: Column(
        crossAxisAlignment:CrossAxisAlignment.stretch,
        mainAxisSize: MainAxisSize.min,
        children: _buildChildren(),
      ),
    );
  }
}```

I'm working on customizing my text field for my  email and password.When I go to extract the method from emailController and  passwordController.I receive an error saying "the end of the selection contains characters that do not belong to the statement.I checked everything and the code seems correct to me but its still not working can you please help me out.I imported the all of the code into a code snippet so that you could see all of the code on the page.

答:
I don't know if it's that, but you do have some random + in the end of line 47

Secondly, I assume you wanted to return Column with TextFields and other widgets in it, but instead there's bunch of widgets separated with commas.

So possibly you've lost the top part of your code

Body:
import 'package:flutter/material.dart';
import 'package:time_trackerpractice/common_widgets/form_submit_button.dart';
import 'package:time_trackerpractice/services/auth.dart';

enum EmailSignInFormType{signIn,register}

class EmailSignInForm extends StatefulWidget {
  EmailSignInForm({@required this.auth});
  final AuthBase auth;

  @override
  _EmailSignInFormState createState() => _EmailSignInFormState();
}

class _EmailSignInFormState extends State<EmailSignInForm> {

 final TextEditingController _emailController = TextEditingController();
 final TextEditingController _passwordController =TextEditingController();

 String get _email=>_emailController.text;
 String get _password=> _passwordController.text;

 EmailSignInFormType _formType = EmailSignInFormType.signIn;

 void _submit() async {
   try {
     if (_formType == EmailSignInFormType.signIn) {
       await widget.auth.signInWithEmailAndPassword(_email, _password);
     } else {
       await widget.auth.signInWithEmailAndPassword(_email, _password);
     }
   } catch (e) {
     print(e.toString());
   }
   Navigator.of(context).pop();
 }

  void _toggleFormType(){
   setState(() {
    _formType = _formType == EmailSignInFormType.signIn?
        EmailSignInFormType.register: EmailSignInFormType.signIn;
   });
  }

  List<Widget> _buildChildren() {
    final primaryText = _formType == EmailSignInFormType.signIn ? 'Sign in' : 'Create account';
    final secondaryText = _formType == EmailSignInFormType.signIn
        ? 'Need an account? Register'
        : 'Have an account? Sign in';
    return [
      TextField(
        controller: _emailController,
        decoration: InputDecoration(
          labelText: 'Email',
          hintText: 'test@test.com',
        ),
        autocorrect: false,
        keyboardType: TextInputType.emailAddress,
        textInputAction: TextInputAction.next,
      ),
      SizedBox(height: 8.0),
      TextField(
        controller: _passwordController,
        decoration: InputDecoration(
          labelText: 'Password',
        ),
        obscureText: true,
        textInputAction: TextInputAction.done,
      ),
      SizedBox(height: 8.0),
      FormSubmitButton(
        text: primaryText,
        onPressed: _submit,
      ),
      SizedBox(height: 8.0),
    FlatButton(
      child: Text(secondaryText),
      onPressed: _toggleFormType,
    ),
   ];

 }

  @override
  Widget build(BuildContext context) {
    return Padding(
      padding: const EdgeInsets.all(16.0),
      child: Column(
        crossAxisAlignment:CrossAxisAlignment.stretch,
        mainAxisSize: MainAxisSize.min,
        children: _buildChildren(),
      ),
    );
  }
}

I'm working on customizing my text field for my  email and password.When I go to extract the method from emailController and  passwordController.I receive an error saying "the end of the selection contains characters that do not belong to the statement.I checked everything and the code seems correct to me but its still not working can you please help me out.I imported the all of the code into a code snippet so that you could see all of the code on the page.


问:
How to access state from a component in React - TypeScript?
How can I access my state from the component GamePieceSquares since GamePieceSquares is declared before the state is created?

Here is the code:

```<code>const GamePieceSquares = ({text, id} : {text:any, id:any}) => (
  <View style={styles.gamePieceSquares}>
    <Text style={styles.text} onPress={() => {console.log('You tapped the button!: ' + text);}}>{text}</Text>
  </View>
);

export default function TabTwoScreen() {

  const [pieceSelectedID, setPieceSelectedID] = useState(0);

  return (
        <Card containerStyle={styles.container}>
            <Card.Title>CARD WITH DIVIDER</Card.Title>
            <View style={styles.gamePiecesRow}>
              <GamePieceSquares text="B" /><Text>{"\n"}</Text>
              <GamePieceSquares text="D" /><Text>{"\n"}</Text>
              <GamePieceSquares text="F" /><Text>{"\n"}</Text>
              <GamePieceSquares text="G" /><Text>{"\n"}</Text>
              <GamePieceSquares text="I" /><Text>{"\n"}</Text>
              <GamePieceSquares text="O" /><Text>{"\n"}</Text>
              <GamePieceSquares text="P" /><Text>{"\n"}</Text>
              <GamePieceSquares text="L" /><Text>{"\n"}</Text>
            </View>
            <Card.Divider />
        </Card>
      <View style={styles.container}><Text >Keyboard</Text></View>
  </View>
  );
}
</code>```

Currently, when I click any of the GamePieceSquares, the text value of the component gets printed to the console.

My goal is this: when the GamePieceSquares get clicked, then set the pieceSelectedID to be the value of the id of the GamePieceSquares and then highlight the GamePieceSquare.

Long story short, I wanted to access the state so that I can correctly highlight the GamePieceSquare that was last clicked.

答:
You can pass it as a prop. It's like any function which accepts params. You can declare the function first, and then call it later with dynamic variables, which in your case is state.

 const [pieceSelectedID, setPieceSelectedID] = useState(0);

  return (
        <Card containerStyle={styles.container}>
            <Card.Title>CARD WITH DIVIDER</Card.Title>
            <View style={styles.gamePiecesRow}>
// here ---> <GamePieceSquares text="B" pieceSelectedID={pieceSelectedID} /><Text>{"\n"}</Text>
               ...
            <Card.Divider />
        </Card>
      <View style={styles.container}><Text >Keyboard</Text></View>
  </View>
  );
```

Body:
How can I access my state from the component GamePieceSquares since GamePieceSquares is declared before the state is created?

Here is the code:

const GamePieceSquares = ({text, id} : {text:any, id:any}) => (
  <View style={styles.gamePieceSquares}>
    <Text style={styles.text} onPress={() => {console.log('You tapped the button!: ' + text);}}>{text}</Text>
  </View>
);

export default function TabTwoScreen() {

  const [pieceSelectedID, setPieceSelectedID] = useState(0);

  return (
        <Card containerStyle={styles.container}>
            <Card.Title>CARD WITH DIVIDER</Card.Title>
            <View style={styles.gamePiecesRow}>
              <GamePieceSquares text="B" /><Text>{"\n"}</Text>
              <GamePieceSquares text="D" /><Text>{"\n"}</Text>
              <GamePieceSquares text="F" /><Text>{"\n"}</Text>
              <GamePieceSquares text="G" /><Text>{"\n"}</Text>
              <GamePieceSquares text="I" /><Text>{"\n"}</Text>
              <GamePieceSquares text="O" /><Text>{"\n"}</Text>
              <GamePieceSquares text="P" /><Text>{"\n"}</Text>
              <GamePieceSquares text="L" /><Text>{"\n"}</Text>
            </View>
            <Card.Divider />
        </Card>
      <View style={styles.container}><Text >Keyboard</Text></View>
  </View>
  );
}

Currently, when I click any of the GamePieceSquares, the text value of the component gets printed to the console.

My goal is this: when the GamePieceSquares get clicked, then set the pieceSelectedID to be the value of the id of the GamePieceSquares and then highlight the GamePieceSquare.

Long story short, I wanted to access the state so that I can correctly highlight the GamePieceSquare that was last clicked.


问:
How to generate a Django one-time download link with expire time
I am uploading files using the filefield model on media-root. Well, now I have a link like this : domain.com/media/file_name.file_extension.I'm asking about the best way to generate a one-time link with expire time from this main link for each user who clicks on file to download it.

```<code>class files(models.Model):

 title = models.CharField(max_length=50)
 picture = models.ImageField(upload_to='imges')
 desc = models.TextField()
 created_at = models.DateField(auto_now_add=True)
 updated_at = models.DateField(auto_now=True)
 download = models.FileField(upload_to='files')

 def __str__(self):
    return self.title
</code>```

this is my views:

```<code>def download(requset ,title):
    file = get_object_or_404 (files , title=title)
    try :
      file = files.objects.filter(title = title)
    except :
      raise Http404

    context ={
     'file' :file,
  }
return render( requset,'download.html',context)
</code>```

this is my template:

```<code><div class="fix download_button"><a href="{{f.download.url}}"></a></div>
</code>```

this is my url:

```<code>    path('download/<str:title>/' , views.download , name='download'),
</code>```

答: Take a look at django-request-token.</p>

Body:
I am uploading files using the filefield model on media-root. Well, now I have a link like this : domain.com/media/file_name.file_extension.I'm asking about the best way to generate a one-time link with expire time from this main link for each user who clicks on file to download it.

class files(models.Model):

 title = models.CharField(max_length=50)
 picture = models.ImageField(upload_to='imges')
 desc = models.TextField()
 created_at = models.DateField(auto_now_add=True)
 updated_at = models.DateField(auto_now=True)
 download = models.FileField(upload_to='files')

 def __str__(self):
    return self.title

this is my views:

def download(requset ,title):
    file = get_object_or_404 (files , title=title)
    try :
      file = files.objects.filter(title = title)
    except :
      raise Http404

    context ={
     'file' :file,
  }
return render( requset,'download.html',context)

this is my template:

this is my url:

    path('download/<str:title>/' , views.download , name='download'),

Body: Take a look at django-request-token.


问:
PhpMyAdmin, how to set 1st day for calendar
Since version 5.1.3, there's no function PMA_addDatepicker in js/functions.js, so that I can set the 1st day for the calendar to Monday instead of Sunday.

I used to change this manually everytime I upgrade PMA.
How could I achieve this from now on?

答:
Just discovered that this is now a parameter in config, also remember that it was a feature request from me about 3 years ago, cool!!

$cfg['FirstDayOfCalendar'] = 1; // 0 for sunday, 1 for monday


问:
Recursive search JSON/DICT in Python 3
I am realizing in Python 3 some APIs that allow me to receive information about a school based on the class code. But I would like to know how I get the information through the class code.
Example:
I enter the code GF528S and I want the program to tell me the class (3C INF), the address (Address 1, Milan), and if possible also the name of the school (Test School 1) and the previous keys. Thanks in advance! Of course I use a JSON structure:

```<code>{
    "schools": {
         "Lombardia": {
            "Milano": {
                "Milano": {
                    "Test School 1": {
                        "sedi": {
                            "0": {
                                "indirizzo": "Address 1, Milan",
                                "classi": {
                                    "INFORMATICA E TELECOMUNICAZIONI": {
                                        "3C INF": "GF528S"
                                    }
                                }
                            },
                            "1": {
                                "indirizzo": "Address 2, Milan",
                                "classi": {
                                    "INFORMATICA E TELECOMUNICAZIONI": {
                                        "1A IT": "HKPV5P",
                                        "2A IT": "QL3J3K",
                                        "3A INF": "X4E35C",
                                        "3A TEL": "ZAA7LC"
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }
    }
}
</code>```

When I get the values from my database they are converted to a python dictionary if it helps!
After a series of tests thanks to your answers, I found that the for in .items() is blocked when it shows the indirizzo field:
In particular, it cannot search in these dictionaries:

```<code>{'classi': {'INFORMATICA E TELECOMUNICAZIONI': {'3C INF': 'GF528S'}}, 'indirizzo': 'Address 1, Milan'}
{'classi': {'INFORMATICA E TELECOMUNICAZIONI': {'1A IT': 'HKPV5P', '2A IT': 'QL3J3K', '3A INF': 'X4E35C', '3A TEL': 'ZAA7LC'}}, 'indirizzo': 'Address 2, Milan'}
</code>```

I think the problem is precisely the indirizzo field. If you want to do the for first, it can be saved in a variable and deleted from the json:

```<code>del val ["address"]
</code>```

The problem is that then I can't associate the address with the class.
Code:

```<code>def dictionary_check(input):
    indirizzo = ""
    for key,value in input.items():
        if isinstance(value, dict):
            dictionary_check(value)
        else:
            for i in value:
                indirizzo += i["indirizzo"]
                del i['indirizzo']
                for x, y in i.items():
                    for z, j in y.items():
                        for a in j.items():
                            if a[1] == "HKPV5P":
                                print(indirizzo)
                                print("Classe: " + a[0])
</code>```

答:
You should use recursive function to find key or value.

```<code>def search_key(data, key, path=""):
    if type(data) is  dict:
        for k, v in data.items():
            path="{0} -> {1}".format(path, k)
            if k == key or v == key:
                return (k, v, path)
            res = search_key(data[k], key, path)
            if res is not None:
                return res

result = search_key(your_dictionary, key="GF528S")
if result is not None:
    print("key:", result[0])
    print("value:", result[1])
    print("path:", result[2])
else:
    print("key or value not found!")
</code>```

If you want to search entire of dictionary and get all duplicate keys or values using given pattern key, this below function is useful.

```<code>def entire_search_key(data, key, founds=[], path=""):
    if type(data) is  dict:
        for k, v in data.items():
            path="{0} -> {1}".format(path, k)
            if k == key or v == key:
                founds.append((k, v, path))
            entire_search_key(data[k], key, founds, path)
    return founds

result = entire_search_key(your_dictionary, key="ddd")
if result == []:
    print("key or value not found!")
else:
    for i in result:
        print(i)
</code>```

Title: Recursive search JSON/DICT in Python 3

Body:
I am realizing in Python 3 some APIs that allow me to receive information about a school based on the class code. But I would like to know how I get the information through the class code.
Example:
I enter the code GF528S and I want the program to tell me the class (3C INF), the address (Address 1, Milan), and if possible also the name of the school (Test School 1) and the previous keys. Thanks in advance! Of course I use a JSON structure:

{
    "schools": {
         "Lombardia": {
            "Milano": {
                "Milano": {
                    "Test School 1": {
                        "sedi": {
                            "0": {
                                "indirizzo": "Address 1, Milan",
                                "classi": {
                                    "INFORMATICA E TELECOMUNICAZIONI": {
                                        "3C INF": "GF528S"
                                    }
                                }
                            },
                            "1": {
                                "indirizzo": "Address 2, Milan",
                                "classi": {
                                    "INFORMATICA E TELECOMUNICAZIONI": {
                                        "1A IT": "HKPV5P",
                                        "2A IT": "QL3J3K",
                                        "3A INF": "X4E35C",
                                        "3A TEL": "ZAA7LC"
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }
    }
}

When I get the values from my database they are converted to a python dictionary if it helps!
After a series of tests thanks to your answers, I found that the for in .items() is blocked when it shows the indirizzo field:
In particular, it cannot search in these dictionaries:

{'classi': {'INFORMATICA E TELECOMUNICAZIONI': {'3C INF': 'GF528S'}}, 'indirizzo': 'Address 1, Milan'}
{'classi': {'INFORMATICA E TELECOMUNICAZIONI': {'1A IT': 'HKPV5P', '2A IT': 'QL3J3K', '3A INF': 'X4E35C', '3A TEL': 'ZAA7LC'}}, 'indirizzo': 'Address 2, Milan'}

I think the problem is precisely the indirizzo field. If you want to do the for first, it can be saved in a variable and deleted from the json:

del val ["address"]

The problem is that then I can't associate the address with the class.
Code:

def dictionary_check(input):
    indirizzo = ""
    for key,value in input.items():
        if isinstance(value, dict):
            dictionary_check(value)
        else:
            for i in value:
                indirizzo += i["indirizzo"]
                del i['indirizzo']
                for x, y in i.items():
                    for z, j in y.items():
                        for a in j.items():
                            if a[1] == "HKPV5P":
                                print(indirizzo)
                                print("Classe: " + a[0])

Body:
You should use recursive function to find key or value.

def search_key(data, key, path=""):
    if type(data) is  dict:
        for k, v in data.items():
            path="{0} -> {1}".format(path, k)
            if k == key or v == key:
                return (k, v, path)
            res = search_key(data[k], key, path)
            if res is not None:
                return res

result = search_key(your_dictionary, key="GF528S")
if result is not None:
    print("key:", result[0])
    print("value:", result[1])
    print("path:", result[2])
else:
    print("key or value not found!")

If you want to search entire of dictionary and get all duplicate keys or values using given pattern key, this below function is useful.

def entire_search_key(data, key, founds=[], path=""):
    if type(data) is  dict:
        for k, v in data.items():
            path="{0} -> {1}".format(path, k)
            if k == key or v == key:
                founds.append((k, v, path))
            entire_search_key(data[k], key, founds, path)
    return founds

result = entire_search_key(your_dictionary, key="ddd")
if result == []:
    print("key or value not found!")
else:
    for i in result:
        print(i)


问:
Selenium: Website always opens with selenium but then the site goes completely white immediately and keeps loading forever
I try to open the following site using selenium:
https://www.honestdoor.com/

Normally this works fine with every site with the following code:
(I am currently using google-chrome version 98.0.4758 - using ChromeDriverManager for downloading the version - see below in the code)

```<code>from selenium import webdriver
from selenium.webdriver.chrome.options import Options
from selenium.webdriver.chrome.service import Service
from selenium.webdriver.support.ui import WebDriverWait
from webdriver_manager.chrome import ChromeDriverManager
from fake_useragent import UserAgent
import time

    if __name__ == '__main__':
      ua = UserAgent()
      userAgent = ua.random
      options = Options()
      # options.add_argument('--headless')
      options.add_experimental_option ('excludeSwitches', ['enable-logging'])
      options.add_argument("start-maximized")
      options.add_argument('window-size=1920x1080')
      options.add_argument('--no-sandbox')
      options.add_argument('--disable-gpu')
      options.add_argument(f'user-agent={userAgent}')
      srv=Service(ChromeDriverManager().install())
      driver = webdriver.Chrome (service=srv, options=options)
      waitWebDriver = WebDriverWait (driver, 10)

      link = "https://www.honestdoor.com/"
      # link = "https://www.bcassessment.ca/"
      # driver.minimize_window()        # optional
      driver.get (link)
      time.sleep(1000)
</code>```

The site opens with selenium as allways but then the site goes immediately complete white and is still loading forever with the cicle going around in the top left corner (I can only kill the chrome-task in the task manager).

When I open the site in normal chrome or incognito chrome everything works fine - it seem to only crash when I open it with selenium. With other sites (like https://www.bcassessment.ca/ I have no problems at all and the open with selenium as allways)

Why is this not working for this particular website?

答:
Not that super clear about the exact issue you are facing while loading the website. However I was able to load the website using the following code block:

Code Block:

```<code>from selenium import webdriver
from selenium.webdriver.chrome.options import Options
from selenium.webdriver.chrome.service import Service

options = Options()
options.add_argument("start-maximized")
options.add_experimental_option("excludeSwitches", ["enable-automation"])
options.add_experimental_option('excludeSwitches', ['enable-logging'])
options.add_experimental_option('useAutomationExtension', False)
options.add_argument('--disable-blink-features=AutomationControlled')
s = Service('C:\\BrowserDrivers\\chromedriver.exe')
driver = webdriver.Chrome(service=s, options=options)
driver.get("https://www.honestdoor.com/")
</code>```

Browser Snapshot:

Body:
I try to open the following site using selenium:
https://www.honestdoor.com/

Normally this works fine with every site with the following code:
(I am currently using google-chrome version 98.0.4758 - using ChromeDriverManager for downloading the version - see below in the code)

from selenium import webdriver
from selenium.webdriver.chrome.options import Options
from selenium.webdriver.chrome.service import Service
from selenium.webdriver.support.ui import WebDriverWait
from webdriver_manager.chrome import ChromeDriverManager
from fake_useragent import UserAgent
import time

    if __name__ == '__main__':
      ua = UserAgent()
      userAgent = ua.random
      options = Options()
      # options.add_argument('--headless')
      options.add_experimental_option ('excludeSwitches', ['enable-logging'])
      options.add_argument("start-maximized")
      options.add_argument('window-size=1920x1080')
      options.add_argument('--no-sandbox')
      options.add_argument('--disable-gpu')
      options.add_argument(f'user-agent={userAgent}')
      srv=Service(ChromeDriverManager().install())
      driver = webdriver.Chrome (service=srv, options=options)
      waitWebDriver = WebDriverWait (driver, 10)

      link = "https://www.honestdoor.com/"
      # link = "https://www.bcassessment.ca/"
      # driver.minimize_window()        # optional
      driver.get (link)
      time.sleep(1000)

The site opens with selenium as allways but then the site goes immediately complete white and is still loading forever with the cicle going around in the top left corner (I can only kill the chrome-task in the task manager).

When I open the site in normal chrome or incognito chrome everything works fine - it seem to only crash when I open it with selenium. With other sites (like https://www.bcassessment.ca/ I have no problems at all and the open with selenium as allways)

Why is this not working for this particular website?

Body:
Not that super clear about the exact issue you are facing while loading the website. However I was able to load the website using the following code block:

Code Block:

from selenium import webdriver
from selenium.webdriver.chrome.options import Options
from selenium.webdriver.chrome.service import Service

options = Options()
options.add_argument("start-maximized")
options.add_experimental_option("excludeSwitches", ["enable-automation"])
options.add_experimental_option('excludeSwitches', ['enable-logging'])
options.add_experimental_option('useAutomationExtension', False)
options.add_argument('--disable-blink-features=AutomationControlled')
s = Service('C:\\BrowserDrivers\\chromedriver.exe')
driver = webdriver.Chrome(service=s, options=options)
driver.get("https://www.honestdoor.com/")

Browser Snapshot:


问:
./src/main.js in multi (webpack)-dev-server/client but I do not have main.js. I want to use typescript
I am making a demo Vue.js 3 app with tailwind and typescript. Whenever I run the app I get an error reading:

```<code>This relative module was not found:

* ./src/main.js in multi (webpack)-dev-server/client?https://192.168.2.102:8090&sockPath=/sockjs-node (webpack)/hot/dev-server.js ./src/main.js
</code>```

main.ts

```<code>import { createApp } from 'vue';
import App from './App.vue'
import router from './router'
import './styles/app.css';

createApp(App)
    .use(router)
    .mount('#app');
</code>```

App.vue

```<code><template>
    <div class="justify-center flex bg-yellow-300 items-center h-screen">
        <div class="text-4xl">
            {{ hello }}
        </div>
    </div>
</template>

<script lang="ts">
import {Vue} from "vue-property-decorator";

export default class App extends Vue {

    hello = 'Hello world'

}
</script>
</code>```

vue.config.js

```<code>module.exports = {
    devServer: {
        proxy: {
            '^/api': {
                target: 'http://localhost:8081'
            }
        }
    }
}
</code>```

package.json

```<code>{
  "name": "demo",
  "version": "0.1.0",
  "private": true,
  "scripts": {
    "serve": "vue-cli-service serve --port 8090 --https true",
    "build": "vue-cli-service build",
    "lint": "vue-cli-service lint"
  },
  "dependencies": {
    "core-js": "^3.6.5",
    "vue": "^3.0.0",
    "vue-property-decorator": "^9.1.2",
    "vue-router": "^4.0.12"
  },
</code>```

has anyone else had this issue too?

答:
Behind the scenes, @vue/cli uses webpack. Webpacks' config is accessible through vue.config.js and, technically, you could manually update the app's entry point. Docs here.

However, the recommended way to add typescript to an existing @vue/cli project is to add the dedicated plugin by running

```<code>vue add typescript
</code>```

in the root of your project.

You're supposed to do this without manually changing your files from .js to .ts, the script will do it for you. Most importantly, it will make the necessary webpack config changes, one of them being changing the entry point from src/main.js to src/main.ts.

Body:
I am making a demo Vue.js 3 app with tailwind and typescript. Whenever I run the app I get an error reading:

This relative module was not found:

* ./src/main.js in multi (webpack)-dev-server/client?https://192.168.2.102:8090&sockPath=/sockjs-node (webpack)/hot/dev-server.js ./src/main.js

main.ts

import { createApp } from 'vue';
import App from './App.vue'
import router from './router'
import './styles/app.css';

createApp(App)
    .use(router)
    .mount('#app');

App.vue

<template>

            {{ hello }}

</template>

vue.config.js

module.exports = {
    devServer: {
        proxy: {
            '^/api': {
                target: 'http://localhost:8081'
            }
        }
    }
}

package.json

{
  "name": "demo",
  "version": "0.1.0",
  "private": true,
  "scripts": {
    "serve": "vue-cli-service serve --port 8090 --https true",
    "build": "vue-cli-service build",
    "lint": "vue-cli-service lint"
  },
  "dependencies": {
    "core-js": "^3.6.5",
    "vue": "^3.0.0",
    "vue-property-decorator": "^9.1.2",
    "vue-router": "^4.0.12"
  },

has anyone else had this issue too?

Body:
Behind the scenes, @vue/cli uses webpack. Webpacks' config is accessible through vue.config.js and, technically, you could manually update the app's entry point. Docs here.

However, the recommended way to add typescript to an existing @vue/cli project is to add the dedicated plugin by running

vue add typescript

in the root of your project.

You're supposed to do this without manually changing your files from .js to .ts, the script will do it for you. Most importantly, it will make the necessary webpack config changes, one of them being changing the entry point from src/main.js to src/main.ts.


答:
You need to set the file path manually to import the modules from another directory. You can assign a directory path to the PYTHONPATH variable and still get your program working.

In Linux, you can use the following command in the terminal to set the path:

```<code>export PYTHONPATH='E:\myprojects\projectA\tweepy'
</code>```

In Windows system :

```<code>SET PYTHONPATH='E:\myprojects\projectA\tweepy'
</code>```

To see if PYTHONPATH variable holds the path of the new folder, you can use the following command:

```<code>echo $PYTHONPATH
</code>```

Then you can do your imports:

```<code>import tweepy
#import tweepy as tw
#from tweepy import sth
</code>```

Title: How can I Import a module from the working directory?

Body:
I have downloaded a module and moved it to my working directory, how can I import this module and all of its contents to use on my code?

a view of my working directory:
E:\myprojects\projectA

location of the downloaded module:
E:\myprojects\projectA\tweepy

NOTE:
I tried installing it using a CMD and I was unable to that's why I want to do it this way instead.

Body:
You need to set the file path manually to import the modules from another directory. You can assign a directory path to the PYTHONPATH variable and still get your program working.

In Linux, you can use the following command in the terminal to set the path:

export PYTHONPATH='E:\myprojects\projectA\tweepy'

In Windows system :

SET PYTHONPATH='E:\myprojects\projectA\tweepy'

To see if PYTHONPATH variable holds the path of the new folder, you can use the following command:

echo $PYTHONPATH

Then you can do your imports:

import tweepy
#import tweepy as tw
#from tweepy import sth


问:
Exit from gridview.builder iteration in flutter or remove empty space
I am trying to implement a vision board. I'm using gridview.builder for adding up to 12 images. Almost everything works as I expect: adding up to 12 images, but when the limit is reached, somehow I want to stop the iteration, because I am not able to return null, and any widget I return, it will create additional space I don't want.

```<code> GridView.builder(
                clipBehavior: Clip.none,
                physics: ScrollPhysics(),
                shrinkWrap: true,
                gridDelegate: SliverGridDelegateWithMaxCrossAxisExtent(
                    maxCrossAxisExtent: SizeConfig.screenWidth!/3,
                    crossAxisSpacing: 0,
                    mainAxisSpacing: 0),
                itemCount: visions.length+1,
                itemBuilder: (BuildContext ctx, index) {
                  print("__________");
                  print("AM INTRAT IN ITEM BUILDER");
                  print("INDEX $index");
                  print(visions.length);
                  if (index < visions.length) {
                    print("PHOTO ALREADY ADDED CONTAINER");
                    return Stack(
                      alignment: Alignment.center,
                      children: [
                        Container(
                          width: double.infinity,
                          height: double.infinity,
                        ),
                        Container(
                          width: SizeConfig.screenWidth!/4,
                          height: SizeConfig.screenWidth!/4,
                          decoration: BoxDecoration(
                            image: DecorationImage(
                                image: FileImage(File(visions[index])),
                                fit: BoxFit.cover),
                            borderRadius: const BorderRadius.all(
                                Radius.circular(
                                    5.0) //                 <--- border radius here
                            ),
                          ),
                        ),
                        Positioned(
                          top:0,
                          right:0,
                          child: Container(
                            child: ClipOval(
                              child: InkWell(
                                onTap: () {
                                  _removeVisions(index);
                                },
                                child: Container(
                                  padding: const EdgeInsets.all(5),
                                  color: Colors.white,
                                  child:
                                    const Icon(
                                        Icons.delete,
                                        size: 16,
                                        color: Color(0xff221F1E)),
                                ),
                              ),
                            ),
                          ),
                        ),
                      ],
                      clipBehavior: Clip.none,
                    );
                  }
                  else if(index<12){
                    print("ADAUGA POZA");
                    print("INDEX $index");
                    print(visions.length);
                    return InkWell(
                      onTap: () {
                        _openGallery(context);
                      },
                      child:
                      Stack(
                        alignment: Alignment.center,
                        children:[
                          Container(
                          width: SizeConfig.screenWidth!/4,
                            height: SizeConfig.screenWidth!/4,
                            decoration:
                            BoxDecoration(
                              border: Border.all(color: const Color(0xff221F1E)),
                              borderRadius: const BorderRadius.all(Radius.circular(5.0)),
                            ),
                            child:
                              const Icon(
                                Icons.add,
                                size: 22,
                                color: Color(0xff221F1E),
                              )
                        ),
                        ],
                      ),
                    );
                  }
                  else {
                    return  Container(color: Colors.red);
                  }
                }
            ),
</code>```

I want to remove that red container.
I have also tried to hardcode something with Positioned widget, but nothing worked, so I am trying somehow to exit when index is equal to 12 or any other solution...

答:
Yes, you can't return a null value but you can simply empty the widget. So, what I mean, SizedBox widget. Added an example for you, just check it

GridView.builder(
                clipBehavior: Clip.none,
                physics: ScrollPhysics(),
                shrinkWrap: true,
                gridDelegate: SliverGridDelegateWithMaxCrossAxisExtent(
                    maxCrossAxisExtent: SizeConfig.screenWidth!/3,
                    crossAxisSpacing: 0,
                    mainAxisSpacing: 0),
                itemCount: visions.length+1,
                itemBuilder: (BuildContext ctx, index) {
                  print("__________");
                  print("AM INTRAT IN ITEM BUILDER");
                  print("INDEX $index");
                  print(visions.length);
                  if (index < visions.length) {
                    print("PHOTO ALREADY ADDED CONTAINER");
                    return Stack(
                      alignment: Alignment.center,
                      children: [
                        Container(
                          width: double.infinity,
                          height: double.infinity,
                        ),
                        Container(
                          width: SizeConfig.screenWidth!/4,
                          height: SizeConfig.screenWidth!/4,
                          decoration: BoxDecoration(
                            image: DecorationImage(
                                image: FileImage(File(visions[index])),
                                fit: BoxFit.cover),
                            borderRadius: const BorderRadius.all(
                                Radius.circular(
                                    5.0) //                 <--- border radius here
                            ),
                          ),
                        ),
                        Positioned(
                          top:0,
                          right:0,
                          child: Container(
                            child: ClipOval(
                              child: InkWell(
                                onTap: () {
                                  _removeVisions(index);
                                },
                                child: Container(
                                  padding: const EdgeInsets.all(5),
                                  color: Colors.white,
                                  child:
                                    const Icon(
                                        Icons.delete,
                                        size: 16,
                                        color: Color(0xff221F1E)),
                                ),
                              ),
                            ),
                          ),
                        ),
                      ],
                      clipBehavior: Clip.none,
                    );
                  }
                  else if(index<12){
                    print("ADAUGA POZA");
                    print("INDEX $index");
                    print(visions.length);
                    return InkWell(
                      onTap: () {
                        _openGallery(context);
                      },
                      child:
                      Stack(
                        alignment: Alignment.center,
                        children:[
                          Container(
                          width: SizeConfig.screenWidth!/4,
                            height: SizeConfig.screenWidth!/4,
                            decoration:
                            BoxDecoration(
                              border: Border.all(color: const Color(0xff221F1E)),
                              borderRadius: const BorderRadius.all(Radius.circular(5.0)),
                            ),
                            child:
                              const Icon(
                                Icons.add,
                                size: 22,
                                color: Color(0xff221F1E),
                              )
                        ),
                        ],
                      ),
                    );
                  }
                  else {
                    return  const SizedBox.shrink();
                  }
                }
            ),
```

Body:
I am trying to implement a vision board. I'm using gridview.builder for adding up to 12 images. Almost everything works as I expect: adding up to 12 images, but when the limit is reached, somehow I want to stop the iteration, because I am not able to return null, and any widget I return, it will create additional space I don't want.

 GridView.builder(
                clipBehavior: Clip.none,
                physics: ScrollPhysics(),
                shrinkWrap: true,
                gridDelegate: SliverGridDelegateWithMaxCrossAxisExtent(
                    maxCrossAxisExtent: SizeConfig.screenWidth!/3,
                    crossAxisSpacing: 0,
                    mainAxisSpacing: 0),
                itemCount: visions.length+1,
                itemBuilder: (BuildContext ctx, index) {
                  print("__________");
                  print("AM INTRAT IN ITEM BUILDER");
                  print("INDEX $index");
                  print(visions.length);
                  if (index < visions.length) {
                    print("PHOTO ALREADY ADDED CONTAINER");
                    return Stack(
                      alignment: Alignment.center,
                      children: [
                        Container(
                          width: double.infinity,
                          height: double.infinity,
                        ),
                        Container(
                          width: SizeConfig.screenWidth!/4,
                          height: SizeConfig.screenWidth!/4,
                          decoration: BoxDecoration(
                            image: DecorationImage(
                                image: FileImage(File(visions[index])),
                                fit: BoxFit.cover),
                            borderRadius: const BorderRadius.all(
                                Radius.circular(
                                    5.0) //                 <--- border radius here
                            ),
                          ),
                        ),
                        Positioned(
                          top:0,
                          right:0,
                          child: Container(
                            child: ClipOval(
                              child: InkWell(
                                onTap: () {
                                  _removeVisions(index);
                                },
                                child: Container(
                                  padding: const EdgeInsets.all(5),
                                  color: Colors.white,
                                  child:
                                    const Icon(
                                        Icons.delete,
                                        size: 16,
                                        color: Color(0xff221F1E)),
                                ),
                              ),
                            ),
                          ),
                        ),
                      ],
                      clipBehavior: Clip.none,
                    );
                  }
                  else if(index<12){
                    print("ADAUGA POZA");
                    print("INDEX $index");
                    print(visions.length);
                    return InkWell(
                      onTap: () {
                        _openGallery(context);
                      },
                      child:
                      Stack(
                        alignment: Alignment.center,
                        children:[
                          Container(
                          width: SizeConfig.screenWidth!/4,
                            height: SizeConfig.screenWidth!/4,
                            decoration:
                            BoxDecoration(
                              border: Border.all(color: const Color(0xff221F1E)),
                              borderRadius: const BorderRadius.all(Radius.circular(5.0)),
                            ),
                            child:
                              const Icon(
                                Icons.add,
                                size: 22,
                                color: Color(0xff221F1E),
                              )
                        ),
                        ],
                      ),
                    );
                  }
                  else {
                    return  Container(color: Colors.red);
                  }
                }
            ),

I want to remove that red container.
I have also tried to hardcode something with Positioned widget, but nothing worked, so I am trying somehow to exit when index is equal to 12 or any other solution...


问:
Recreation of grid with flex box text alignment
I am pretty new to flexbox and I am trying to get proficient with it. I am trying to recreate this grid with flexbox - it's pretty close but I am having trouble with the text alignment, How can I align the flexbox text the way the grid text is aligned?'

Edit: I don't know what's unclear about this. I am trying to make the flex box aligned left-center the same way the bottom grid is. The flex box is centered but not left justified.

<link href="https://cdnjs.cloudflare.com/ajax/libs/tailwindcss/2.2.17/tailwind.min.css" rel="stylesheet"/>

This is Flex:

Box 1.1

Box 1.1 Flexbox

Box 1.2

Box 1.2 Flexbox

Box 1.3

Box 1.3 Flexbox

    This is Grid:

Box 2.1

Box 2.1 Flexbox

Box 2.2

Box 2.2 Flexbox

Box 2.3

Box 2.3 Flexbox

```

答:
This is how I solved it:

<link href="https://cdnjs.cloudflare.com/ajax/libs/tailwindcss/2.2.17/tailwind.min.css" rel="stylesheet"/>

Box 1

Box 1 Flexbox

Box 2

Box 2 Flexbox

Box 3

Box 4 Flexbox

```

If anyone has a better way let me know.

Body:
This is how I solved it:

<link href="https://cdnjs.cloudflare.com/ajax/libs/tailwindcss/2.2.17/tailwind.min.css" rel="stylesheet"/>

        <section class="flex flex-wrap w-full justify-center items-center content-center mt-20 lg:mt-0 min-h-85 fade fadeout">

            <div class="flex flex-col w-full md:w-1/3 max-w-md items-center bg-red-100">
                <div class="py-12 w-52 bg-red-200">
                    <h4 class="font-semibold tracking-widest text-xs">Box 1</h4>
                    <p>Box 1 Flexbox</p>
                </div>
            </div>

            <div class="flex flex-col w-full md:w-1/3 max-w-md items-center bg-blue-100">
                <div class="py-12 w-52 bg-blue-200">
                    <h4 class="font-semibold tracking-widest text-xs">Box 2</h4>
                    <p>Box 2 Flexbox</p>
                </div>
            </div>

            <div class="flex flex-col w-full md:w-1/3 max-w-md items-center bg-green-100">
                <div class="py-12 w-52 bg-green-200">
                    <h4 class="font-semibold tracking-widest text-xs">Box 3</h4>
                        <p>Box 4 Flexbox</p>
                </div>
            </div>

        </section>

If anyone has a better way let me know.


问:
how to set the input text in react by taking it from from the url?
I am trying to input a location as text input
I want qr code to show the blow and location is the dynamic input we put in the input field
https://google.com?location={location} ?

How can i set the url as above and put the location as input? showup in qr code

so input will be the location from the url which can be any location and the qr code should show <url/
currently i am using the below code but i can only get the input field showup in the qr code .

```<code>import React, { useState } from 'react';
import QRCode from 'qrcode.react';

function App() {

  const [inputText, setInputText] = useState('');
  const [qrCodeText, setQRCodeText] = useState('');

  // generate QR code
  const generateQRCode = () => {
    setQRCodeText(inputText);
  }

  return (
    <div className="App">
      <h3>Generate and download a QR code image in React Omneo</h3>
      <div className="qr-input">
        <input
          type="text"
          placeholder="Enter input"
          value={inputText}
          onChange={e => setInputText(e.target.value)}
        />
        <input
          type="button"
          value="Generate"
          onClick={generateQRCode}
        />
      </div>
      <QRCode
        id="qrCodeEl"
        size={150}
        value={qrCodeText}
      />

    </div>
  );
}

export default App;
</code>```

答:
```<code>//add to the top
import { useEffect } from 'react'

//add above return
useEffect(() => {
    setInputText(window.location.href);
  })
</code>```

Body:
I am trying to input a location as text input
I want qr code to show the blow and location is the dynamic input we put in the input field
https://google.com?location={location} ?

How can i set the url as above and put the location as input? showup in qr code

so input will be the location from the url which can be any location and the qr code should show <url/
currently i am using the below code but i can only get the input field showup in the qr code .

import React, { useState } from 'react';
import QRCode from 'qrcode.react';

function App() {

  const [inputText, setInputText] = useState('');
  const [qrCodeText, setQRCodeText] = useState('');

  // generate QR code
  const generateQRCode = () => {
    setQRCodeText(inputText);
  }

  return (

Generate and download a QR code image in React Omneo

        <input
          type="text"
          placeholder="Enter input"
          value={inputText}
          onChange={e => setInputText(e.target.value)}
        />
        <input
          type="button"
          value="Generate"
          onClick={generateQRCode}
        />

      <QRCode
        id="qrCodeEl"
        size={150}
        value={qrCodeText}
      />

  );
}

export default App;


问:
Apply format arguments to struct members in Display implementation
I want to apply format arguments (for example to limit the amount of digits) to the members of my struct. My current implementation looks roughly like this:

use std::fmt;

#[derive(Debug)]
pub struct Vec2 { x: f32, y: f32 }
impl fmt::Display for Vec2 {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "[{}, {}]", self.x, self.y)
    }
}
```

If I use the automatically derived debug printing using e.g. {:.2?}, the arguments are applied and only 2 places after the decimal are printed. This doesn't seem to work with my Display implementation though using {:.2}. I tried to look at the Debug implementation using cargo expand but there are many functions specifically for Debug.

答:
The easiest way will be to forward the formatting:

impl fmt::Display for Vec2 {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str("[")?;
        fmt::Display::fmt(&self.x, f)?;
        f.write_str(", ")?;
        fmt::Display::fmt(&self.y, f)?;
        f.write_str("]")
    }
}
```
<p>Note that if you want to have all formatting specifiers, you have to implement additional traits. For floats, it's only <code>std::fmt::LowerExp</code> and <code>std::fmt::UpperExp</code>. You can make a little helper function to not duplicate code:</p>
<pre class="lang-rust prettyprint-override"><code>impl Vec2 {
    fn fmt(
        &self,
        f: &mut fmt::Formatter<'_>,
        fmt_fn: fn(&f32, f: &mut fmt::Formatter<'_>) -> fmt::Result,
    ) -> fmt::Result {
        f.write_str("[")?;
        fmt_fn(&self.x, f)?;
        f.write_str(", ")?;
        fmt_fn(&self.y, f)?;
        f.write_str("]")
    }
}
impl fmt::Display for Vec2 {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        self.fmt(f, fmt::Display::fmt)
    }
}
impl fmt::LowerExp for Vec2 {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        self.fmt(f, fmt::LowerExp::fmt)
    }
}
impl fmt::UpperExp for Vec2 {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        self.fmt(f, fmt::UpperExp::fmt)
    }
}
</code>```

Body:
I want to apply format arguments (for example to limit the amount of digits) to the members of my struct. My current implementation looks roughly like this:

use std::fmt;

#[derive(Debug)]
pub struct Vec2 { x: f32, y: f32 }
impl fmt::Display for Vec2 {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "[{}, {}]", self.x, self.y)
    }
}

If I use the automatically derived debug printing using e.g. {:.2?}, the arguments are applied and only 2 places after the decimal are printed. This doesn't seem to work with my Display implementation though using {:.2}. I tried to look at the Debug implementation using cargo expand but there are many functions specifically for Debug.

Body:
The easiest way will be to forward the formatting:

impl fmt::Display for Vec2 {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str("[")?;
        fmt::Display::fmt(&self.x, f)?;
        f.write_str(", ")?;
        fmt::Display::fmt(&self.y, f)?;
        f.write_str("]")
    }
}

Note that if you want to have all formatting specifiers, you have to implement additional traits. For floats, it's only std::fmt::LowerExp and std::fmt::UpperExp. You can make a little helper function to not duplicate code:

impl Vec2 {
    fn fmt(
        &self,
        f: &mut fmt::Formatter<'_>,
        fmt_fn: fn(&f32, f: &mut fmt::Formatter<'_>) -> fmt::Result,
    ) -> fmt::Result {
        f.write_str("[")?;
        fmt_fn(&self.x, f)?;
        f.write_str(", ")?;
        fmt_fn(&self.y, f)?;
        f.write_str("]")
    }
}
impl fmt::Display for Vec2 {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        self.fmt(f, fmt::Display::fmt)
    }
}
impl fmt::LowerExp for Vec2 {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        self.fmt(f, fmt::LowerExp::fmt)
    }
}
impl fmt::UpperExp for Vec2 {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        self.fmt(f, fmt::UpperExp::fmt)
    }
}


问:
Assertion testing a void function
I am writing a code with multiple void methods within a class, I am tasked with testing all of my methods using the assert from the c++ header <cassert>.  Here is one of my methods, that goes through the array in the class and trims the leading and trailing blank spaces. How would I write a function to test this method using assert? I am confused because there is no return value.

```<code>void trim_all() {
    // Iterate through all strings
    for (int i = 0; i < strSize; i++) {
        // Initialize variables
        int begin = 0;
        int end = arr[i].size() - 1;
        // While loops to check how many spaces in front and back
        while (begin < arr[i].size() && arr[i][begin] == ' ') {
            begin++;
        }
        while (end >= 0 && arr[i][end] == ' ') {
            end--;
        }
        // Update string to trimmed version
        arr[i] = arr[i].substr(begin, end - begin + 1);
    }
}
</code>```

答:
Some of the comments and answers explain that the use of assert is not a good choice for writing test code - which is true.  However, since you write

I am tasked with testing all of my methods using the assert from the c++ header .

it sounds a bit as if this was an exercise for some kind of programming or testing course.  In that case, I take it that either at some later point in your course you will be introduced to some better suited testing framework, or that testing is not meant to be covered thoroughly during your course and for that reason the introduction of a testing framework is considered too time consuming.

Whatever the reason, you can actually start writing tests with the help of assert, using assert as a poor man's testing framework, as @long-kl has shown in his answer (but without giving more explanation).

assert(<condition>); will evaluate the condition, and, if the condition evaluates to some true value, the execution of your program will simply continue with the next statement.  Otherwise, the program will terminate.

Thus, you can use assert for the verification of a test result, namely by writing the condition to check if the actual result of some computation matches the expected result, as the following example test cases (by far not exhaustive) show:

```<code>// Test case: Array claimed to be empty is not touched
arr = { " a " };
strSize = 0;
trim_all();
assert(arr[0] == " a ");  // expected value is " a ", actual is arr[0]
// Only if the test passes, we reach the following line:
cout << "Passed: Array claimed to be empty is not touched\n";

// Test case: Empty string remains untouched
arr = { "" };
strSize = 1;
trim_all();
assert(arr[0] == "");
cout << "Passed: Empty string remains untouched\n";

// Test case: Blank-only string becomes empty string
arr = { "   " };
strSize = 1;
trim_all();
assert(arr[0] == "");
cout << "Passed: Blank-only string becomes empty string\n";

// Test case: Front blanks get trimmed
arr = { "   abc" };
strSize = 1;
trim_all();
assert(arr[0] == "abc");
cout << "Passed: Front blanks get trimmed\n";

// further test cases...
</code>```

In case of a passing test, the program will continue with the next test.  In contrast, if a test fails, that is, the condition evaluates to some false value, the program will terminate at that point with some error message.  Consequently, after a failing test no further tests will be executed.

Thus, the reason that assert has no return value is that a true condition means to continue executing, and a false condition means terminating.

Title: Assertion testing a void function

Body:
I am writing a code with multiple void methods within a class, I am tasked with testing all of my methods using the assert from the c++ header <cassert>.  Here is one of my methods, that goes through the array in the class and trims the leading and trailing blank spaces. How would I write a function to test this method using assert? I am confused because there is no return value.

void trim_all() {
    // Iterate through all strings
    for (int i = 0; i < strSize; i++) {
        // Initialize variables
        int begin = 0;
        int end = arr[i].size() - 1;
        // While loops to check how many spaces in front and back
        while (begin < arr[i].size() && arr[i][begin] == ' ') {
            begin++;
        }
        while (end >= 0 && arr[i][end] == ' ') {
            end--;
        }
        // Update string to trimmed version
        arr[i] = arr[i].substr(begin, end - begin + 1);
    }
}

Body:
Some of the comments and answers explain that the use of assert is not a good choice for writing test code - which is true.  However, since you write

I am tasked with testing all of my methods using the assert from the c++ header .

it sounds a bit as if this was an exercise for some kind of programming or testing course.  In that case, I take it that either at some later point in your course you will be introduced to some better suited testing framework, or that testing is not meant to be covered thoroughly during your course and for that reason the introduction of a testing framework is considered too time consuming.

Whatever the reason, you can actually start writing tests with the help of assert, using assert as a poor man's testing framework, as @long-kl has shown in his answer (but without giving more explanation).

assert(<condition>); will evaluate the condition, and, if the condition evaluates to some true value, the execution of your program will simply continue with the next statement.  Otherwise, the program will terminate.

Thus, you can use assert for the verification of a test result, namely by writing the condition to check if the actual result of some computation matches the expected result, as the following example test cases (by far not exhaustive) show:

// Test case: Array claimed to be empty is not touched
arr = { " a " };
strSize = 0;
trim_all();
assert(arr[0] == " a ");  // expected value is " a ", actual is arr[0]
// Only if the test passes, we reach the following line:
cout << "Passed: Array claimed to be empty is not touched\n";

// Test case: Empty string remains untouched
arr = { "" };
strSize = 1;
trim_all();
assert(arr[0] == "");
cout << "Passed: Empty string remains untouched\n";

// Test case: Blank-only string becomes empty string
arr = { "   " };
strSize = 1;
trim_all();
assert(arr[0] == "");
cout << "Passed: Blank-only string becomes empty string\n";

// Test case: Front blanks get trimmed
arr = { "   abc" };
strSize = 1;
trim_all();
assert(arr[0] == "abc");
cout << "Passed: Front blanks get trimmed\n";

// further test cases...

In case of a passing test, the program will continue with the next test.  In contrast, if a test fails, that is, the condition evaluates to some false value, the program will terminate at that point with some error message.  Consequently, after a failing test no further tests will be executed.

Thus, the reason that assert has no return value is that a true condition means to continue executing, and a false condition means terminating.


问:
Error in PreAuthorize annotation with hasRole('ROLE_ADMIN')
The controller in my application is mentioned below and I get the error when I try to start the Application:

```<code>@RestController
@CrossOrigin
@RequestMapping("/api/admin")
@PreAuthorize("hasRole('ROLE_ADMIN')")
class AdminController (private val userRepository: UserRepository, private val roleRepository: RoleRepository) {

    @GetMapping("/getUsers")
    fun getUsers(): List<UserResponseAdmin> {
        return userRepository.findAll().stream().map { user: User ->
            UserResponseAdmin(user)
        }.collect(Collectors.toList())
    }
}
</code>```
```<code>org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'adminController' defined in file [E:\_dev\appspring\target\classes\de\totwart\appspring\controller\AdminController.class]: Initialization of bean failed; nested exception is org.springframework.aop.framework.AopConfigException: Could not generate CGLIB subclass of class de.totwart.appspring.controller.AdminController: Common causes of this problem include using a final class or a non-visible class; nested exception is java.lang.IllegalArgumentException: Cannot subclass final class de.totwart.appspring.controller.AdminController
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:628)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:542)
    at ...
Caused by: org.springframework.aop.framework.AopConfigException: Could not generate CGLIB subclass of class de.totwart.apppongspring.controller.AdminController: Common causes of this problem include using a final class or a non-visible class; nested exception is java.lang.IllegalArgumentException: Cannot subclass final class de.totwart.apppongspring.controller.AdminController
    at org.springframework.aop.framework.CglibAopProxy.getProxy(CglibAopProxy.java:209)
    at org.springframework.aop.framework.ProxyFactory.getProxy(ProxyFactory.java:110)
    at org.springframework.aop.framework.autoproxy.AbstractAutoProxyCreator.createProxy(AbstractAutoProxyCreator.java:478)
    at org.springframework.aop.framework.autoproxy.AbstractAutoProxyCreator.wrapIfNecessary(AbstractAutoProxyCreator.java:342)
    at org.springframework.aop.framework.autoproxy.AbstractAutoProxyCreator.postProcessAfterInitialization(AbstractAutoProxyCreator.java:291)
    at
</code>```

When I remove the annotation, everything is working fine. I don't understand the issue. Why its saying that I am using a final class, when I don't.

Any Ideas, what I can try?

PS: found the solution.
@PreAuthorize maybe extends the AdminController, so AdminController must be "open"

open class AdminController

答:
Unlike Java, all classes in Kotlin are by default closed or final.

Why does this matter when you add the @PreAuthorize ? - well, what Spring does is inject some behaviour around the method to enforce the check.  That is implemented by subclassing your original class, hence the need for your class to be open.  Many other parts of the Spring framework use this same subclassing technique, so it is a very common requirement to need to open all your Controller and similar classes.

As you found yourself, adding the open keyword fixes this but you can make a project-wide change if you simply include a special dependency called Kotlin-Allopen.  Find out more here: https://www.baeldung.com/kotlin/allopen-spring

Body:
The controller in my application is mentioned below and I get the error when I try to start the Application:

@RestController
@CrossOrigin
@RequestMapping("/api/admin")
@PreAuthorize("hasRole('ROLE_ADMIN')")
class AdminController (private val userRepository: UserRepository, private val roleRepository: RoleRepository) {

    @GetMapping("/getUsers")
    fun getUsers(): List<UserResponseAdmin> {
        return userRepository.findAll().stream().map { user: User ->
            UserResponseAdmin(user)
        }.collect(Collectors.toList())
    }
}

org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'adminController' defined in file [E:\_dev\appspring\target\classes\de\totwart\appspring\controller\AdminController.class]: Initialization of bean failed; nested exception is org.springframework.aop.framework.AopConfigException: Could not generate CGLIB subclass of class de.totwart.appspring.controller.AdminController: Common causes of this problem include using a final class or a non-visible class; nested exception is java.lang.IllegalArgumentException: Cannot subclass final class de.totwart.appspring.controller.AdminController
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:628)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:542)
    at ...
Caused by: org.springframework.aop.framework.AopConfigException: Could not generate CGLIB subclass of class de.totwart.apppongspring.controller.AdminController: Common causes of this problem include using a final class or a non-visible class; nested exception is java.lang.IllegalArgumentException: Cannot subclass final class de.totwart.apppongspring.controller.AdminController
    at org.springframework.aop.framework.CglibAopProxy.getProxy(CglibAopProxy.java:209)
    at org.springframework.aop.framework.ProxyFactory.getProxy(ProxyFactory.java:110)
    at org.springframework.aop.framework.autoproxy.AbstractAutoProxyCreator.createProxy(AbstractAutoProxyCreator.java:478)
    at org.springframework.aop.framework.autoproxy.AbstractAutoProxyCreator.wrapIfNecessary(AbstractAutoProxyCreator.java:342)
    at org.springframework.aop.framework.autoproxy.AbstractAutoProxyCreator.postProcessAfterInitialization(AbstractAutoProxyCreator.java:291)
    at

When I remove the annotation, everything is working fine. I don't understand the issue. Why its saying that I am using a final class, when I don't.

Any Ideas, what I can try?

PS: found the solution.
@PreAuthorize maybe extends the AdminController, so AdminController must be "open"

open class AdminController


问:
How to avoid primary key clashes when merging two identical tables with a view
I have a central database and a unique database for a project I am working on.  The central database allows me to provide users with default options and data.

The unique database matches the central database structure to allow users own customized data.  I have views that union each identical table pair.

The "primary key" field in each view is set as a primary key in the dbml I am using (Linq-to-sql).  I then add associations to other tables in the dbml.

This means that I cannot set both tables to auto-increment with a base of 0, because the primary keys are used as "foreign keys" in unique db tables (I know they're not strictly foreign keys in this instance).

Therefore in the view, I need all records from each table pair to have a unique primary key.

I have thought about setting the unique database pk base number at 1000000 or something, but this eventually may backfire on me when the global database (0 base) caught up.

I also though about prefixing each with a number in the view, e.g.

Global: 11, 12, 13, 14, 15, 16, 17, 18, 19, 110 ,111
Unique: 21, 22, 23, 24, 25, 26, 27, 28, 29, 210, 211

I am worried how this may affect performance when querying,  this has to be as efficient as possible.

Not sure of the best method?

答:
One issue with your solution is that it is brittle and would fail if you ever needed more than two sources to be merged.  This may or may not be a realistic risk depending on your business scenario.

People sometimes get around this issue by using a GUID for a candidate key.  In this way, your source DBs have the IDENTITY columns as PK and also a GUID which is unique but not primary in the source databases.  However, in the merged view the PK is the GUID and the originial source keys (IDENTITY) are brought along for the ride but don't actually get used in PK/FK relationships.

In this type of model, the merged view typically also includes some kind of source code column which tells you where the row came from.  If you do this, then source code + identity key is also a candidate key in the merged view.