问:
What is the best practice to save a quiz answers with different data types in MYSQL?
UPDATE: part 1- start:

We want to get our customers data, but which kind of data? they are not specified! actually we want to have a dynamic application that the admin can define new questions (he can set the answer's data type, length, and other rules) and he also can deactivate old questions!

(I don't want to use EAV schema design, but I can't find the alternative way)

UPDATE: part 1 - end:

so I decided to create a quiz application, admin can define questions which their answers data type can be different!

Example:

question ID 1 : what is you name?  answer: John (varchar)

question ID 2 : how old are you? answer: 25 (integer)

question ID 3 : how much is your salary per hour? answer: 30.65 (decimal)

question ID 4 : describe yourself? answer: I'm so kind ... (text)

UPDATE: part 2 - start:

to save the answers it comes to my mind 3 choices:

UPDATE: part 2 - end:

create a table like this (EAV schema design):

```<code>    Table profile_answers
    id int [pk, increment]
    question_id int
    profile_id int
    answer text
</code>```

as you see I've save all answers as text!
I know that it works, but is it the best way? actually this app is going to have millions of answers and we want to analyze the answers by machine (for example: getting customers average age, getting married customers, customers with salary > 30.52 and etc) so I want to implement the way with the best performance!

create a table like this (EAV schema design):

```<code>Table answers
id int [pk, increment]
question_id int
profile_id int
integer_value int
decimal_value decimal
varchar_value varchar
boolean_value boolean
longtext_value longtext
</code>```

now I can save data in the proper field and put NULL in the other fields (the answer's data type will be determined while defining it's question)

For example:

```<code>question ID 1 : what is you name? answer: John (varchar)

id 1
profile_question_id 1
profile_id 1
integer_value NULL
decimal_value NULL
varchar_value John
boolean_value NULL
longtext_value NULL

 ----------------
question ID 2 : how old are you? answer: 25 (integer)

id 2
profile_question_id 2
profile_id 1
integer_value 25
decimal_value NULL
varchar_value NULL
boolean_value NULL
longtext_value NULL

 ----------------
question ID 3 : how much is your salary per hour? answer: 30.65 (decimal)

id 3
profile_question_id 3
profile_id 1
integer_value NULL
decimal_value 30.65
varchar_value NULL
boolean_value NULL
longtext_value NULL

</code>```

UPDATE: part 3 - start:

when admin adds a new question, I can add a column to answers table (change table's schema) like this

UPDATE: part 3 - end:

It's all about performance! what's the best way?
If none of them is not the best one and I should redesign the database what is the correct database design?

答:
Having NULL values is never a good practice. In point 2. you have 8 columns and 4 of them are NULL. Adding the column for each answers's data type is bad practice.

Having a column with a string data type is a workaround to solve adding nullable columns for each answer's data type.

You will get better performance with 2. approach.
If you need even better performance, you can go with a separate table for each answer data type.

I had experience with quizzes and forms. We need to have rules for conditional showing page, question ... We discussed a lot and I had trouble to convince team that we should switch to JSON or something like that (NOSQL). Relation database is not intended to solve this kind of problems.

Right way would be to separate quiz questions and answers from statistics.
You should move questions, answers, rules and that kind of stuff to NOSQL. Answer and question statistics should be in the relational database.

Body:
UPDATE: part 1- start:

We want to get our customers data, but which kind of data? they are not specified! actually we want to have a dynamic application that the admin can define new questions (he can set the answer's data type, length, and other rules) and he also can deactivate old questions!

(I don't want to use EAV schema design, but I can't find the alternative way)

UPDATE: part 1 - end:

so I decided to create a quiz application, admin can define questions which their answers data type can be different!

Example:

question ID 1 : what is you name?  answer: John (varchar)

question ID 2 : how old are you? answer: 25 (integer)

question ID 3 : how much is your salary per hour? answer: 30.65 (decimal)

question ID 4 : describe yourself? answer: I'm so kind ... (text)

UPDATE: part 2 - start:

to save the answers it comes to my mind 3 choices:

UPDATE: part 2 - end:

create a table like this (EAV schema design):

    Table profile_answers
    id int [pk, increment]
    question_id int
    profile_id int
    answer text

as you see I've save all answers as text!
I know that it works, but is it the best way? actually this app is going to have millions of answers and we want to analyze the answers by machine (for example: getting customers average age, getting married customers, customers with salary > 30.52 and etc) so I want to implement the way with the best performance!

create a table like this (EAV schema design):

Table answers
id int [pk, increment]
question_id int
profile_id int
integer_value int
decimal_value decimal
varchar_value varchar
boolean_value boolean
longtext_value longtext

now I can save data in the proper field and put NULL in the other fields (the answer's data type will be determined while defining it's question)

For example:

question ID 1 : what is you name? answer: John (varchar)

id 1
profile_question_id 1
profile_id 1
integer_value NULL
decimal_value NULL
varchar_value John
boolean_value NULL
longtext_value NULL

 ----------------
question ID 2 : how old are you? answer: 25 (integer)

id 2
profile_question_id 2
profile_id 1
integer_value 25
decimal_value NULL
varchar_value NULL
boolean_value NULL
longtext_value NULL

 ----------------
question ID 3 : how much is your salary per hour? answer: 30.65 (decimal)

id 3
profile_question_id 3
profile_id 1
integer_value NULL
decimal_value 30.65
varchar_value NULL
boolean_value NULL
longtext_value NULL

UPDATE: part 3 - start:

when admin adds a new question, I can add a column to answers table (change table's schema) like this

UPDATE: part 3 - end:

It's all about performance! what's the best way?
If none of them is not the best one and I should redesign the database what is the correct database design?


来源: stackexchange

问:
How to add additional paths to baseurl using Javascript
I have a base URL

```<code>url= 'www.baseUrl.com'
</code>```

I have an array of my paths Paths = [path1,path2,path3]

how do i create something like perhaps i need to do a loop?

```<code>www.baseUrl.com/path1
www.baseUrl.com/path2
www.baseUrl.com/path3
</code>```

答:
Go through your Paths-list and manipulate the items like this: </p>

```<code>url= 'www.baseUrl.com/'
newPath=url + path
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I have a base URL

url= 'www.baseUrl.com'

I have an array of my paths Paths = [path1,path2,path3]

how do i create something like perhaps i need to do a loop?

www.baseUrl.com/path1
www.baseUrl.com/path2
www.baseUrl.com/path3

Body:
Go through your Paths-list and manipulate the items like this:

url= 'www.baseUrl.com/'
newPath=url + path


问:
How to overcome CSS calc() function invalid property value, but when typed in inspector same code does work?
I have the following code in an .scss file:

```<code>.device_content_div {
    width: calc(100% – 169px);
    margin-left: 204px;
  }
</code>```

It gets processed by Gulp. When I open the relevant page in the Chrome inspector it gets an Invalid Property alert.

However, when I type the exact same code, manually in the inspector, there is no alert and the code works as it should.

The same thing goes for Firefox and Safari. I have tried adding it as a  insert in the html page itself, and as an 'unprocessed' plain .css file, but the same thing occurs. I have made sure there are spaces between the operator and the numbers, but to no avail. I'm really stuck here.

How can this happen, and how can I fix this?

答:
The first one doesn't look like the minus - symbol. It's a bit wider. It's actually an en dash symbol not a minus symbol. Check here -> https://www.babelstone.co.uk/Unicode/whatisit.html and copy/paste the symbol you use and then write the minus  - symbol.

They have different unicodes.
This –  ( the one you use ) is an EN DASH ( you can make it with ALT + 0150 ) and this - is a HYPHEN-MINUS {hyphen or minus sign}.

I guess you copy/pasted the code from somewhere and you accidentally inserted an en dash instead of the minus.

should be calc(100% - 169px) iso calc(100% – 169px) you can see there's a slight difference in the width of the symbol

See example below

div {
  height:50px;
  background: red;
  margin: 10px 0;
}
div.first {
  /* EN DASH */
  width : calc(100% – 169px);
}

div.second {
  /* minus */
  width : calc(100% - 169px);
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="first">
  Not working ( EN DASH )
</div>
<div class="second">
  Working ( minus )
</div></code>```

Body:
I have the following code in an .scss file:

.device_content_div {
    width: calc(100% – 169px);
    margin-left: 204px;
  }

It gets processed by Gulp. When I open the relevant page in the Chrome inspector it gets an Invalid Property alert.

However, when I type the exact same code, manually in the inspector, there is no alert and the code works as it should.

The same thing goes for Firefox and Safari. I have tried adding it as a  insert in the html page itself, and as an 'unprocessed' plain .css file, but the same thing occurs. I have made sure there are spaces between the operator and the numbers, but to no avail. I'm really stuck here.

How can this happen, and how can I fix this?

Body:
The first one doesn't look like the minus - symbol. It's a bit wider. It's actually an en dash symbol not a minus symbol. Check here -> https://www.babelstone.co.uk/Unicode/whatisit.html and copy/paste the symbol you use and then write the minus  - symbol.

They have different unicodes.
This –  ( the one you use ) is an EN DASH ( you can make it with ALT + 0150 ) and this - is a HYPHEN-MINUS {hyphen or minus sign}.

I guess you copy/pasted the code from somewhere and you accidentally inserted an en dash instead of the minus.

should be calc(100% - 169px) iso calc(100% – 169px) you can see there's a slight difference in the width of the symbol

See example below

div {
  height:50px;
  background: red;
  margin: 10px 0;
}
div.first {
  /* EN DASH */
  width : calc(100% – 169px);
}

div.second {
  /* minus */
  width : calc(100% - 169px);
}

<div class="first">
  Not working ( EN DASH )
</div>
<div class="second">
  Working ( minus )
</div>


问:
How to get the max number and key
I have has like this

var hash = {};
hash['a'] = ["a", "b", "c", "d", "e"];
hash['b'] = ["a", "b", "c"];
hash['k'] = ["q", "b"];

Math.max(Object.keys(hash)
    .map(function(key) {
      return hash[key].length;
    })
  )```

It returns 5 but, I want to get the hash key 'a' at the same time.

Is it possible??

答:
i have used this approach for your problem:</p>

```<code>var hash = {};
hash['a'] = ["a", "b", "c", "d", "e"];
hash['b'] = ["a", "b", "c"];
hash['k'] = ["q", "b"];

var largestInfo = {
  key:'',
  length:0
}

 Object.keys(hash).map(function(key) {
    if(hash[key].length > largestInfo.length){
        largestInfo.key = key;
        largestInfo.length = hash[key].length;
    }
    return hash[key].length;
});
console.log(largestInfo);
</code>```

Title: How to get the max number and key

Body:
I have has like this

var hash = {};
hash['a'] = ["a", "b", "c", "d", "e"];
hash['b'] = ["a", "b", "c"];
hash['k'] = ["q", "b"];

Math.max(Object.keys(hash)
    .map(function(key) {
      return hash[key].length;
    })
  )

It returns 5 but, I want to get the hash key 'a' at the same time.

Is it possible??

Body:
i have used this approach for your problem:

var hash = {};
hash['a'] = ["a", "b", "c", "d", "e"];
hash['b'] = ["a", "b", "c"];
hash['k'] = ["q", "b"];

var largestInfo = {
  key:'',
  length:0
}

 Object.keys(hash).map(function(key) {
    if(hash[key].length > largestInfo.length){
        largestInfo.key = key;
        largestInfo.length = hash[key].length;
    }
    return hash[key].length;
});
console.log(largestInfo);


问:
If possible how can one embed PostgreSQL?
If it's possible, I'm interested in being able to embed a PostgreSQL database, similar to sqllite.  I've read that it's not possible.  I'm no database expert though, so I want to hear from you.

Essentially I want PostgreSQL without all the configuration and installation.  If it's possible, tell me how.

答: PostgreSQL is intended to run as a stand-alone server; it's probably possible to embed it if you hack at it hard and long enough, but it would be much easier to just run it as intended in a separate process.</p>

ContentLicense: CC BY-SA 3.0

OwnerDisplayName: John Millikin

ContentLicense: CC BY-SA 2.5


问:
Is there a way to see all Google Sheets that link/depend on another one?
I know what I'm doing is not good, and we're working on changing it for the better, but in the meantime I need to make do with what I have...

I have a rather large Google Sheet that more or less is acting as a DB. It's fed data from GForms and then that data is used on a number of other sheets for various purposes (e.g. reporting, selective info sharing to certain groups, etc.) mostly through querys and importranges.

The editing of the main sheet is restricted to only a handful of people, including myself. One of the others has made some changes (deleting some columns) that are going to break any queries or imports because the importrange won't catch the column changes and auto-update the range.

The changes made are actually good and worth keeping, so I don't want to revert them.

Is there a way for me to easily find out all of the sheets that use the main one so that I can update the affected formulas? In updating, I'll also need to find a way to avoid this happening again (I think I can do this by setting the range references using address? But that's future me's problem...)

Thanks in advance!

答:
Find (Ctrl-H) gives the option to "Also search within formulae"

You can use this to search for references to a particular sheet eg searching "sheet1!" will find all cells that reference sheet1

Note this may not work if named ranges are defined, you may need to search for the named range as well.


问:
can't show image in my gridView by adding glide
I am trying to create a gridview with some cardview containing imageview, and I am setting the default image in the adapter getView method but it is not working.

This is my gridView Adapter:

```<code>class ImageAdapter constructor(private val mContext: Context, private val images: Array<Int>) :  BaseAdapter() {
    override fun getView(position: Int, convertView: View?, parent: ViewGroup?): View {
        var convertView = convertView

        if(convertView == null) {
            val layoutInflater = LayoutInflater.from(mContext)
            convertView = layoutInflater.inflate(R.layout.card_view, null)
        }
        val image = convertView!!.findViewById<ImageView>(R.id.added_picture)

        Glide.with(mContext).load(images[position]).into(image)

        return convertView
    }

    override fun getItem(position: Int): Any? {
        return images[position]
    }

    override fun getItemId(position: Int): Long {
        return position.toLong()
    }

    override fun getCount(): Int {
        return images.size
    }

}
</code>```

The layout I'm adding in the adapter :

```<code><?xml version="1.0" encoding="utf-8"?>
<androidx.cardview.widget.CardView
  xmlns:android="http://schemas.android.com/apk/res/android"
  xmlns:app="http://schemas.android.com/apk/res-auto"
  android:layout_width="110dp"
  android:layout_height="110dp"
  android:layout_margin="3dp"
  app:layout_columnSpan="1"
  app:cardCornerRadius="8dp"
  app:layout_rowSpan="1"
  app:layout_column="2"
  app:layout_row="0" >
  <ImageView
    android:layout_height="match_parent"
    android:layout_width="match_parent"
    android:id="@+id/added_picture"
    />
</androidx.cardview.widget.CardView>
</code>```

The
MainActivity.kt onCreate method:

```<code>    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        gridView.adapter = ImageAdapter(this, arrayOf(R.drawable.filled_rectangle, R.drawable.filled_rectangle))
}
</code>```

My gridView is showing only empty space, if I do not use

答:
Ensure that your glider loading the correct link to the imageview.

simply toast the loading links to ensure it is correct.

Body:
I am trying to create a gridview with some cardview containing imageview, and I am setting the default image in the adapter getView method but it is not working.

This is my gridView Adapter:

class ImageAdapter constructor(private val mContext: Context, private val images: Array<Int>) :  BaseAdapter() {
    override fun getView(position: Int, convertView: View?, parent: ViewGroup?): View {
        var convertView = convertView

        if(convertView == null) {
            val layoutInflater = LayoutInflater.from(mContext)
            convertView = layoutInflater.inflate(R.layout.card_view, null)
        }
        val image = convertView!!.findViewById<ImageView>(R.id.added_picture)

        Glide.with(mContext).load(images[position]).into(image)

        return convertView
    }

    override fun getItem(position: Int): Any? {
        return images[position]
    }

    override fun getItemId(position: Int): Long {
        return position.toLong()
    }

    override fun getCount(): Int {
        return images.size
    }

}

The layout I'm adding in the adapter :

<?xml version="1.0" encoding="utf-8"?>
<androidx.cardview.widget.CardView
  xmlns:android="http://schemas.android.com/apk/res/android"
  xmlns:app="http://schemas.android.com/apk/res-auto"
  android:layout_width="110dp"
  android:layout_height="110dp"
  android:layout_margin="3dp"
  app:layout_columnSpan="1"
  app:cardCornerRadius="8dp"
  app:layout_rowSpan="1"
  app:layout_column="2"
  app:layout_row="0" >
  <ImageView
    android:layout_height="match_parent"
    android:layout_width="match_parent"
    android:id="@+id/added_picture"
    />
</androidx.cardview.widget.CardView>

The
MainActivity.kt onCreate method:

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        gridView.adapter = ImageAdapter(this, arrayOf(R.drawable.filled_rectangle, R.drawable.filled_rectangle))
}

My gridView is showing only empty space, if I do not use


问:
How to limite scroll move of Recyclerview?
In my vertical recyclerview, I have multiple horizontal recyclerviews and I have a problem: when I want to scroll left or right, if I'm scrolling a bit up or down at the same time, the horizontal scrolling doesn't work.

So my idea was to redefine what is up, down, left and right for the recycler view. So I stumbled upon this thread : How to detect swipe direction between left/right and up/down

First I though it was what I need but then I understood, it was just redefining directions at the end of a swipe (not during), so I tried to do all the angle computation during the swipe. I ended with this :

```<code>var initialX: Float
var initialY: Float

    ui_recyclerView?.setOnTouchListener(object: View.OnTouchListener{

            override fun onTouch(v: View?, event: MotionEvent?): Boolean {
                val action = event?.actionMasked

                if (action == MotionEvent.ACTION_DOWN) {
                    initialX = event.x
                    initialY = event.y

                }
                else if(action == MotionEvent.ACTION_MOVE) {
                    val swipeDirection = GestureUtils.getSwipeDirection(initialX, initialY, event.x, event.y)

                    if (swipeDirection == GestureUtils.Direction.UP || swipeDirection == GestureUtils.Direction.DOWN) {
                        return false
                    }

                }

                return true
            }

        })
</code>```

It worked but then I didn't have the smooth scrolling any more (it was very robotic), and neither the click.

Is there a built-in function with recycler view to limit MoveEvent to a certain angle ? If not, how can I put back the smooth scrolling effect of a normal recycler view ?

That would help me a lot !

答:
You can try to limit your scroll vertical movements on your recycler with a ScrollListener, so it only triggers when you make a large scroll on the screen, like this:

```<code>final int delimitationUp=25;
final int delimitationDown=-25;
yourVerticalRecycler.addOnScrollListener(new RecyclerView.OnScrollListener() {
        @Override
        public void onScrollStateChanged(@NonNull RecyclerView recyclerView, int newState) {
            super.onScrollStateChanged(recyclerView, newState);
        }

        @Override
        public void onScrolled(@NonNull RecyclerView recyclerView, int dx, int dy) {
            super.onScrolled(recyclerView, dx, dy);
            if(dy>delimitationUp){//move up}
            if (dy<delimitationDown){//move down}
</code>```

Test with the delimitations

Body:
In my vertical recyclerview, I have multiple horizontal recyclerviews and I have a problem: when I want to scroll left or right, if I'm scrolling a bit up or down at the same time, the horizontal scrolling doesn't work.

So my idea was to redefine what is up, down, left and right for the recycler view. So I stumbled upon this thread : How to detect swipe direction between left/right and up/down

First I though it was what I need but then I understood, it was just redefining directions at the end of a swipe (not during), so I tried to do all the angle computation during the swipe. I ended with this :

var initialX: Float
var initialY: Float

    ui_recyclerView?.setOnTouchListener(object: View.OnTouchListener{

            override fun onTouch(v: View?, event: MotionEvent?): Boolean {
                val action = event?.actionMasked

                if (action == MotionEvent.ACTION_DOWN) {
                    initialX = event.x
                    initialY = event.y

                }
                else if(action == MotionEvent.ACTION_MOVE) {
                    val swipeDirection = GestureUtils.getSwipeDirection(initialX, initialY, event.x, event.y)

                    if (swipeDirection == GestureUtils.Direction.UP || swipeDirection == GestureUtils.Direction.DOWN) {
                        return false
                    }

                }

                return true
            }

        })

It worked but then I didn't have the smooth scrolling any more (it was very robotic), and neither the click.

Is there a built-in function with recycler view to limit MoveEvent to a certain angle ? If not, how can I put back the smooth scrolling effect of a normal recycler view ?

That would help me a lot !

Body:
You can try to limit your scroll vertical movements on your recycler with a ScrollListener, so it only triggers when you make a large scroll on the screen, like this:

final int delimitationUp=25;
final int delimitationDown=-25;
yourVerticalRecycler.addOnScrollListener(new RecyclerView.OnScrollListener() {
        @Override
        public void onScrollStateChanged(@NonNull RecyclerView recyclerView, int newState) {
            super.onScrollStateChanged(recyclerView, newState);
        }

        @Override
        public void onScrolled(@NonNull RecyclerView recyclerView, int dx, int dy) {
            super.onScrolled(recyclerView, dx, dy);
            if(dy>delimitationUp){//move up}
            if (dy<delimitationDown){//move down}

Test with the delimitations


答:
You can use forEach

```<code>let url = 'www.baseUrl.com';
let paths = [ 'path1','path2','path3'];
let urlsWithPath = [];

paths.forEach(path => {
  let singleUrlWithpath = url + '/' + path;
  urlsWithPath.push(singleUrlWithpath);
});
</code>```

And then, urlsWithPath array will containt those 3 urls

Title: How to add additional paths to baseurl using Javascript

Body:
You can use forEach

let url = 'www.baseUrl.com';
let paths = [ 'path1','path2','path3'];
let urlsWithPath = [];

paths.forEach(path => {
  let singleUrlWithpath = url + '/' + path;
  urlsWithPath.push(singleUrlWithpath);
});

And then, urlsWithPath array will containt those 3 urls


问:
Website nav links not working on IE9
My website: http://botvps.com

The text on the button is not appearing.
I have already made an IE css for IE 8 or lower.

What do I need to do?

Regards,
LB

答:
You are using Cufon 1.09, an outdated version. Please use the new 1.09i version of Cufon, which adds support for Internet Explorer 9.

I tested your site with 1.09i, it renders fine then!

Download cufon-yui.js from the following website:
http://cufon.shoqolate.com/

Replace the following file on the server with the new javascript:
http://www.botvps.com/js/cufon-yui.js

Title: Website nav links not working on IE9


问:
Cannot convert value of type '(_) -> ()' to expected argument type 'CompletionHandler?' using KingFisher Swift
I am using a library called KingFisher to download image from internet.
For the reference:

https://github.com/onevcat/Kingfisher

https://cocoapods.org/pods/Kingfisher

imageView.kf.setImage(with: url)

This instruction works flawless but i wanted to track success so i added completion handler so the documentation suggestion this snippet.

```<code>imageView.kf.setImage(with: userInfo.getImageUrl()){ result in
            switch result {
            case .success(let value):
                print("success")
            case .failure(let error):
                print(error) // The error happens
            }
        }
</code>```

For the reference this is the cheat sheet i am using:

https://github.com/onevcat/Kingfisher/wiki/Cheat-Sheet

On adding this snippet i am getting this compilation error:

Cannot convert value of type '(_) -> ()' to expected argument type 'CompletionHandler?' (aka 'Optional<(Optional, Optional, CacheType, Optional) -> ()>')

答:
I had similar issue. I have been using Kingfisher 4.0.0 with Swift 4.

Changing to the following did the trick,

```<code>imageView.kf.setImage(with: url, placeholder: nil, options: nil, progressBlock: nil) { image, error, cacheType, imageURL in

}
</code>```

Body:
I am using a library called KingFisher to download image from internet.
For the reference:

https://github.com/onevcat/Kingfisher

https://cocoapods.org/pods/Kingfisher

imageView.kf.setImage(with: url)

This instruction works flawless but i wanted to track success so i added completion handler so the documentation suggestion this snippet.

imageView.kf.setImage(with: userInfo.getImageUrl()){ result in
            switch result {
            case .success(let value):
                print("success")
            case .failure(let error):
                print(error) // The error happens
            }
        }

For the reference this is the cheat sheet i am using:

https://github.com/onevcat/Kingfisher/wiki/Cheat-Sheet

On adding this snippet i am getting this compilation error:

Cannot convert value of type '(_) -> ()' to expected argument type 'CompletionHandler?' (aka 'Optional<(Optional, Optional, CacheType, Optional) -> ()>')

Body:
I had similar issue. I have been using Kingfisher 4.0.0 with Swift 4.

Changing to the following did the trick,

imageView.kf.setImage(with: url, placeholder: nil, options: nil, progressBlock: nil) { image, error, cacheType, imageURL in

}


问:
How to use passport-jwt strategy on express to protect post route
I am using passportJs to authenticate users on my app, I can create users, create them credentials, and they can login with no issues. For the protected routes, I'm using passport-jwt strategy, and all routes work just fine. However, I have been trying to use the same passport strategy for the route that creates those users, but no matter what I do I always get the unauthorized response 401. On the front end I use react and axios.
Here is my passport code:

```<code>const opts = {
        jwtFromRequest: ExtractJWT.fromAuthHeaderWithScheme("JWT"),
        secretOrKey: process.env.JWT_SECRET
    };

passport.use(
        "jwtToPostUser",
        new JWTstrategy(opts, (jwt_payload, done) => {
            try {
                User.findOne({
                    where: {
                        email: jwt_payload.email
                    }
                }).then(user => {
                    if (user) {
                        console.log("user found in db in passport");
                        done(null, user);
                    } else {
                        console.log("user not found in db");
                        done(null, false);
                    }
                });
            } catch (err) {
                done(err);
            }
        })
    );
</code>```

Here is the route to create users:

```<code>router.post(
    "/signup",
    passport.authenticate("jwtToPostUser", { session: false }),
    (req, res, next) => {
        console.log(req.body);

        const {
            businessname,
            username,
            firstName,
            lastName,
            phoneNumber,
            email,
            password,
            customerStatus,
            userType,
            Gooduntil
        } = req.body;

        if (password.length < 8) {
            throw "Password must be at least 8 characters";
        } else {
            User.findOne({
                where: {
                    email
                }
            }).then(user => {
                if (user) {
                    res.send("Email already exists!");
                } else {
                    const encryptedPassword = bcrypt.hashSync(password, salt);

                    let newUser = {
                        businessname,
                        username,
                        firstName,
                        lastName,
                        phoneNumber,
                        email,
                        password: encryptedPassword,
                        customerStatus,
                        userType,
                        Gooduntil
                    };
                    User.create(newUser)
                        .then(() => {
                            // newUser.isAdmin = true
                            delete newUser.password;
                            res.send(newUser);
                        })
                        .catch(function(err) {
                            console.log(err);
                            res.json(err);
                        });
                }
            });
        }
    }
);
</code>```

This JWTstrategy works for all the get routes, except for this one, that creates the user.

Here is my request from the front end:

```<code> addClient = async e => {

        let newUser = {
                businessname: businessname.toLowerCase(),
                firstName: firstName.toLowerCase(),
                lastName: lastName.toLowerCase(),
                email,
                username,
                password,
                phoneNumber,
                customerStatus: customerStatus.value,
                userType,
                Gooduntil
            };
            const accessString = localStorage.getItem("JWT");
            await Axios.post(
                "/auth/signup",
                {
                    headers: {
                        Authorization: `JWT ${accessString}`
                    }
                },
                newUser
            )
                .then(res => {
                    console.log(res);
                    this.setState({
                        loadingAxiosReq: false
                    });
                })
                .catch(err => console.log(err));
    }
</code>```

This it the error I'm getting: Error: Request failed with status code 401

Does anybody know why is this happening? The only way I can make it work is by removing the passport-JWT strategy from the signup route, but that's not secure. please help!

答: are you sure that you have attached your auth token on your POST request?</p>

Body:
I am using passportJs to authenticate users on my app, I can create users, create them credentials, and they can login with no issues. For the protected routes, I'm using passport-jwt strategy, and all routes work just fine. However, I have been trying to use the same passport strategy for the route that creates those users, but no matter what I do I always get the unauthorized response 401. On the front end I use react and axios.
Here is my passport code:

const opts = {
        jwtFromRequest: ExtractJWT.fromAuthHeaderWithScheme("JWT"),
        secretOrKey: process.env.JWT_SECRET
    };

passport.use(
        "jwtToPostUser",
        new JWTstrategy(opts, (jwt_payload, done) => {
            try {
                User.findOne({
                    where: {
                        email: jwt_payload.email
                    }
                }).then(user => {
                    if (user) {
                        console.log("user found in db in passport");
                        done(null, user);
                    } else {
                        console.log("user not found in db");
                        done(null, false);
                    }
                });
            } catch (err) {
                done(err);
            }
        })
    );

Here is the route to create users:

router.post(
    "/signup",
    passport.authenticate("jwtToPostUser", { session: false }),
    (req, res, next) => {
        console.log(req.body);

        const {
            businessname,
            username,
            firstName,
            lastName,
            phoneNumber,
            email,
            password,
            customerStatus,
            userType,
            Gooduntil
        } = req.body;

        if (password.length < 8) {
            throw "Password must be at least 8 characters";
        } else {
            User.findOne({
                where: {
                    email
                }
            }).then(user => {
                if (user) {
                    res.send("Email already exists!");
                } else {
                    const encryptedPassword = bcrypt.hashSync(password, salt);

                    let newUser = {
                        businessname,
                        username,
                        firstName,
                        lastName,
                        phoneNumber,
                        email,
                        password: encryptedPassword,
                        customerStatus,
                        userType,
                        Gooduntil
                    };
                    User.create(newUser)
                        .then(() => {
                            // newUser.isAdmin = true
                            delete newUser.password;
                            res.send(newUser);
                        })
                        .catch(function(err) {
                            console.log(err);
                            res.json(err);
                        });
                }
            });
        }
    }
);

This JWTstrategy works for all the get routes, except for this one, that creates the user.

Here is my request from the front end:

 addClient = async e => {

        let newUser = {
                businessname: businessname.toLowerCase(),
                firstName: firstName.toLowerCase(),
                lastName: lastName.toLowerCase(),
                email,
                username,
                password,
                phoneNumber,
                customerStatus: customerStatus.value,
                userType,
                Gooduntil
            };
            const accessString = localStorage.getItem("JWT");
            await Axios.post(
                "/auth/signup",
                {
                    headers: {
                        Authorization: `JWT ${accessString}`
                    }
                },
                newUser
            )
                .then(res => {
                    console.log(res);
                    this.setState({
                        loadingAxiosReq: false
                    });
                })
                .catch(err => console.log(err));
    }

This it the error I'm getting: Error: Request failed with status code 401

Does anybody know why is this happening? The only way I can make it work is by removing the passport-JWT strategy from the signup route, but that's not secure. please help!


问:
regex to remove any string before _, except for several strings
I am wondering of regular expression  (preferably in notepad++) to remove string1_ in the pattern string1_string2, except for several strings?

For instance, I want to get this (know and can are maintained)

```<code>PUNC PUNC know_X2.2+ Z5 can_A7+ can_Z5[i6.2.2 PUNC Z5
</code>```

from this

```<code><TYP 1>_PUNC [_PUNC know_X2.2+ outside_Z5 can_A7+ can_Z5[i6.2.2 <SEX ?>_PUNC am_Z5
</code>```

I've tried using this
(?<!(can_|know_))

but did not match.

Thank you very much

答:
You may use

```<code>(?:<[^<>]*>|[^_\s])*_(?<!can_)(?<!know_)
</code>```

See the regex demo

Details

(?:<[^<>]*>|[^_\s])* - 0 or more occurrences of

<[^<>]*> - a <, then any 0+ chars other than < and > and then >

| - or

[^_\s] - any char other than whitespace and _

_(?<!can_)(?<!know_) - a _ that is not preceded with can_ nor know_.

Notepad++ settings & demo:

Body:
I am wondering of regular expression  (preferably in notepad++) to remove string1_ in the pattern string1_string2, except for several strings?

For instance, I want to get this (know and can are maintained)

PUNC PUNC know_X2.2+ Z5 can_A7+ can_Z5[i6.2.2 PUNC Z5

from this

<TYP 1>_PUNC [_PUNC know_X2.2+ outside_Z5 can_A7+ can_Z5[i6.2.2 <SEX ?>_PUNC am_Z5

I've tried using this
(?<!(can_|know_))

but did not match.

Thank you very much

Body:
You may use

(?:<[^<>]*>|[^_\s])*_(?<!can_)(?<!know_)

See the regex demo

Details

(?:<[^<>]*>|[^_\s])* - 0 or more occurrences of

<[^<>]*> - a <, then any 0+ chars other than < and > and then >

| - or

[^_\s] - any char other than whitespace and _

_(?<!can_)(?<!know_) - a _ that is not preceded with can_ nor know_.

Notepad++ settings & demo:


问:
Compile Rust Code properly for bare-metal ARM as static lib and as binary for x86_64?
What I want to do:
I have a piece of Rustcode, that I want to build

as static lib for bare-metal ARM so it can be linked to an existing c program, AND

as executable for x86_64, so I can develop, unittest, etc.

I can do both, but unfortunately I have to change each time the Cargo.toml.

main.rs

use foobar::foo::Bar;

fn main() {
    let bar = Bar::new();
    let ret = bar.do_something();

    //  ...
}
```

<p>lib.rs</p>

<pre class="lang-rust prettyprint-override"><code>#![feature(core_intrinsics)]
#![cfg_attr(feature = "EMBEDDED", no_std)]

#[cfg(feature = "EMBEDDED")]
use core::intrinsics;

#[cfg(feature = "EMBEDDED")]
use core::panic::PanicInfo;

#[cfg(feature = "EMBEDDED")]
#[panic_handler]
fn panic(_info: &PanicInfo) -> ! {
    unsafe { intrinsics::abort() }
}

#[cfg(not(feature = "EMBEDDED"))]
pub mod foo;
</code>```

foo.rs

pub struct Bar;

impl Bar {
    pub fn new() -> Self {
        Bar{}
    }

    pub fn do_something(&self) -> u32 {
        42
    }
}

#[no_mangle]
pub extern "C" fn call_from_c_prog() -> u32 {
    let bar = Bar::new();

    bar.do_something()
}

#[cfg(test)]
mod test {
    use super::*;

    #[test]
    fn foo_test() {
        let bar = Bar::new();
        let ret = bar.do_something();

        assert_eq!(ret, 42);
    }
}
```

<p>Cargo.toml</p>

```[package]
name = "foobar"
version = "0.1.0"
authors = ["..."]
edition = "2018"

[dependencies]

#[[bin]]
#name = "foobar"
#path = "src/main.rs"
#test = true
#bench = false

[lib]
name = "foobar"
path = "src/lib.rs"
crate-type = ["staticlib"] # Creates static lib
#crate-type = ["cdylib"] # Creates synamic lib

[features]
default = []
EMBEDDED = []
```

<p>With this Cargo.toml, I can build the code as static lib by running cargo</p>

```cargo build --lib --release --features EMBEDDED --target thumbv7em-none-eabihf
```

<p>But when I try to build that code for x86_64 with</p>

```cargo test --target x86_64-unknown-linux-gnu
```

<p>I get this error:</p>

```error[E0433]: failed to resolve: use of undeclared type or module `foobar`
 --> src/main.rs:1:5
  |
1 | use foobar::foo::Bar;
  |     ^^^^^^ use of undeclared type or module `foobar`

error[E0433]: failed to resolve: use of undeclared type or module `Bar`
 --> src/main.rs:4:15
  |
4 |     let bar = Bar::new();
  |               ^^^ use of undeclared type or module `Bar`

error: aborting due to 2 previous errors
```

<p>I get the same error, when enable both sections ([[bin]] + [lib]).</p>

<p>So, when I change now the Cargo.toml to</p>

```[[bin]]
name = "foobar"
path = "src/main.rs"
test = true
bench = false

#[lib]
#name = "foobar"
#path = "src/lib.rs"
#crate-type = ["staticlib"] # Creates static lib
##crate-type = ["cdylib"] # Creates synamic lib
```

<p>I can build and run the code with</p>

```cargo test --target x86_64-unknown-linux-gnu
```

<p>But if run now </p>

```cargo build --lib --release --features EMBEDDED --target thumbv7em-none-eabihf
```

I get an .rlib which is obvious since the section is commented out.

So, my question is now:
How can I do both things, without changing the Cargo.toml every time? I couldn't find a proper way yet.

Regards

答:
From The cargo book:

--manifest-path PATH

Path to the Cargo.toml file. By default, Cargo searches for the Cargo.toml file in the current directory or any parent directory.

Just have two Cargo.toml files and use --manifest-path to specify the manifest file. Also use --target-dir different for both builds, to build both at the same time.

Body:
What I want to do:
I have a piece of Rustcode, that I want to build

as static lib for bare-metal ARM so it can be linked to an existing c program, AND

as executable for x86_64, so I can develop, unittest, etc.

I can do both, but unfortunately I have to change each time the Cargo.toml.

main.rs

use foobar::foo::Bar;

fn main() {
    let bar = Bar::new();
    let ret = bar.do_something();

    //  ...
}

lib.rs

#![feature(core_intrinsics)]
#![cfg_attr(feature = "EMBEDDED", no_std)]

#[cfg(feature = "EMBEDDED")]
use core::intrinsics;

#[cfg(feature = "EMBEDDED")]
use core::panic::PanicInfo;

#[cfg(feature = "EMBEDDED")]
#[panic_handler]
fn panic(_info: &PanicInfo) -> ! {
    unsafe { intrinsics::abort() }
}

#[cfg(not(feature = "EMBEDDED"))]
pub mod foo;

foo.rs

pub struct Bar;

impl Bar {
    pub fn new() -> Self {
        Bar{}
    }

    pub fn do_something(&self) -> u32 {
        42
    }
}

#[no_mangle]
pub extern "C" fn call_from_c_prog() -> u32 {
    let bar = Bar::new();

    bar.do_something()
}

#[cfg(test)]
mod test {
    use super::*;

    #[test]
    fn foo_test() {
        let bar = Bar::new();
        let ret = bar.do_something();

        assert_eq!(ret, 42);
    }
}

Cargo.toml

[package]
name = "foobar"
version = "0.1.0"
authors = ["..."]
edition = "2018"

[dependencies]

#[[bin]]
#name = "foobar"
#path = "src/main.rs"
#test = true
#bench = false

[lib]
name = "foobar"
path = "src/lib.rs"
crate-type = ["staticlib"] # Creates static lib
#crate-type = ["cdylib"] # Creates synamic lib

[features]
default = []
EMBEDDED = []

With this Cargo.toml, I can build the code as static lib by running cargo

cargo build --lib --release --features EMBEDDED --target thumbv7em-none-eabihf

But when I try to build that code for x86_64 with

cargo test --target x86_64-unknown-linux-gnu

I get this error:

error[E0433]: failed to resolve: use of undeclared type or module `foobar`
 --> src/main.rs:1:5
  |
1 | use foobar::foo::Bar;
  |     ^^^^^^ use of undeclared type or module `foobar`

error[E0433]: failed to resolve: use of undeclared type or module `Bar`
 --> src/main.rs:4:15
  |
4 |     let bar = Bar::new();
  |               ^^^ use of undeclared type or module `Bar`

error: aborting due to 2 previous errors

I get the same error, when enable both sections ([[bin]] + [lib]).

So, when I change now the Cargo.toml to

[[bin]]
name = "foobar"
path = "src/main.rs"
test = true
bench = false

#[lib]
#name = "foobar"
#path = "src/lib.rs"
#crate-type = ["staticlib"] # Creates static lib
##crate-type = ["cdylib"] # Creates synamic lib

I can build and run the code with

cargo test --target x86_64-unknown-linux-gnu

But if run now

cargo build --lib --release --features EMBEDDED --target thumbv7em-none-eabihf

I get an .rlib which is obvious since the section is commented out.

So, my question is now:
How can I do both things, without changing the Cargo.toml every time? I couldn't find a proper way yet.

Regards


问:
Remove ns2 as default namespace prefix
I have a file that is printed with a default namespace. The elements are printed with a prefix of ns2, I need this to be removed, how it is with my code:

```<code><ns2:foo xmlns:ns2="http://namespace" />
</code>```

how I want it to be:

```<code><foo xmlns="http://namespace" />
</code>```

this is how I have coded it, something which as I see it should be enough for the ns2 to go away:

```<code><?xml version="1.0" encoding="UTF-8"?>
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema"
    xmlns:bar="http://namespace" targetNamespace="http://namespace"
    elementFormDefault="qualified">
...
</code>```

the generated package-info turns out like this:

```<code>@javax.xml.bind.annotation.XmlSchema(namespace = "http://namespace",
    elementFormDefault = javax.xml.bind.annotation.XmlNsForm.QUALIFIED)
package com.foo.bar;
</code>```

I create the file like this:

```<code>JAXBContext jaxbContext = JAXBContext.newInstance(generatedClassesPackage);
Marshaller marshaller = jaxbContext.createMarshaller();
marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE);
marshaller.marshal(new JAXBElement<Foo>(new QName("http://namespace", "Foo"),
Foo.class, rootFoo), outputStream);
</code>```

generatedClassesPackage is the package where package-info.java and the elements are.

The Foo object is defined and has elements like this::

```<code>@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "", propOrder = {
    "group"
})
@XmlRootElement(name = "Foo")
public class Foo {

    @XmlElement(name = "Group", required = true)
    protected List<Group> group;
</code>```

Is it something I have missed? or have I misunderstood how this works?

答:
Change the attribute value of elementFormDefault="unqualified" in </p>

```<code><xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns:bar="http://namespace" targetNamespace="http://namespace" elementFormDefault="qualified">
</code>```

Title: Remove ns2 as default namespace prefix

Body:
I have a file that is printed with a default namespace. The elements are printed with a prefix of ns2, I need this to be removed, how it is with my code:

<ns2:foo xmlns:ns2="http://namespace" />

how I want it to be:

<foo xmlns="http://namespace" />

this is how I have coded it, something which as I see it should be enough for the ns2 to go away:

<?xml version="1.0" encoding="UTF-8"?>
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema"
    xmlns:bar="http://namespace" targetNamespace="http://namespace"
    elementFormDefault="qualified">
...

the generated package-info turns out like this:

@javax.xml.bind.annotation.XmlSchema(namespace = "http://namespace",
    elementFormDefault = javax.xml.bind.annotation.XmlNsForm.QUALIFIED)
package com.foo.bar;

I create the file like this:

JAXBContext jaxbContext = JAXBContext.newInstance(generatedClassesPackage);
Marshaller marshaller = jaxbContext.createMarshaller();
marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE);
marshaller.marshal(new JAXBElement<Foo>(new QName("http://namespace", "Foo"),
Foo.class, rootFoo), outputStream);

generatedClassesPackage is the package where package-info.java and the elements are.

The Foo object is defined and has elements like this::

@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "", propOrder = {
    "group"
})
@XmlRootElement(name = "Foo")
public class Foo {

    @XmlElement(name = "Group", required = true)
    protected List<Group> group;

Is it something I have missed? or have I misunderstood how this works?

Body:
Change the attribute value of elementFormDefault="unqualified" in

<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns:bar="http://namespace" targetNamespace="http://namespace" elementFormDefault="qualified">


问:
Getting return value from a Volley request
I have seen many response on the subject matter but none is enough for what I want.

I want to be able to return a response like a list from a volley response and pass that list to another class to be added to my database.

I have tried use an interface and a callback function but the response still hangs in another interface.

I want something like this

```<code>class Big:Interface{
  override fun A():List<Model> = getResponseFromVolley()
  fun getResponseFromVolley(){ setUp Volley request return List}

}

How can I do this

</code>```

Code

```<code>class RemoteDataSourceManager: ServiceCall {

    override suspend fun getMovies(context: Context): Result<List<MovieEntity>> {

        var results: Result<List<MovieEntity>>

      getRemoteMovies(context, object : VolleyCallBack{
          override fun onResponse(result: Result<List<MovieEntity>>): Result<List<MovieEntity>> {
              results = result
              return results
          }

      })

        return results //result mustbe initialized

    }

    private fun getRemoteMovies(context: Context, callBack: VolleyCallBack): Result<List<MovieEntity>> {
        val responseBool = MutableLiveData<Boolean>(false)
        var listResult: Result<List<MovieEntity>>
        val listOfMovies = ArrayList<MovieEntity>()

        val url =
            "https://api.themoviedb.org/3/movie/popular?api_key=f1e256985ebc2be710bf1f4ed754da11&language=en-US&page=1"
        val request: JsonObjectRequest =
            JsonObjectRequest(
                Request.Method.GET,
                url, null,
                Response.Listener { response ->

                    try {
                        val results = response.getJSONArray("results")
                        val size = results.length()
                        var title = ""
                        var movieImage = ""
                        var rating = 0
                        var overView = ""
                        var releaseDate = ""
                        var movieId = ""

                        for (movie in 0 until results.length()) {
                            val eachMovie = results.getJSONObject(movie)
                            movieImage = "https://image.tmdb.org/t/p/w500"
                            title = eachMovie.getString("title")
                            movieImage +=eachMovie.getString("poster_path")
                            rating  = eachMovie.getInt("vote_average")
                            overView = eachMovie.getString("overview")
                            releaseDate = eachMovie.getString("release_date")
                            movieId = eachMovie.getInt("id").toString()

                            val newMovie =  MovieEntity(
                                title,
                                movieImage,
                                rating,
                                overView,
                                releaseDate
                            )
                            newMovie.movieId = movieId
                            newMovie.id = movieId.toInt()
                            listOfMovies.add(newMovie)

                            responseBool.value = true

                        }

                        listResult = getResult(Result.Success(listOfMovies.toList()))

                        callBack.onResponse(listResult)
                        Log.i("insideList", "$listOfMovies")

                    } catch (e: Exception) {
                        Log.i("error", "Response $e")

//                        Toast.makeText(context!!.applicationContext, "No activity", Toast.LENGTH_SHORT).show()
                    }
                }, Response.ErrorListener { error ->

                    val errroMessage = VolleyErrorHandler.instance.erroHandler(error)
                    CoroutineScope(Dispatchers.Main).launch {
//                        Toast.makeText(context, errroMessage, Toast.LENGTH_LONG).show()
                    }

                })

        context.applicationContext.let {
            VolleySingleton.getInstance(it).addToRequestQueue(request)

        }

        Log.i("listOfMovies", "$listResult")
        return listResult
    }

    override suspend fun saveMovies(movieEntity: MovieEntity) {
        TODO("not implemented") //To change body of created functions use File | Settings | File Templates.
    }

    interface VolleyCallBack{
        fun onResponse(result:Result<List<MovieEntity>>): Result<List<MovieEntity>>

    }

    private fun getResult(result: Result<List<MovieEntity>>):Result<List<MovieEntity>>{
        return result
    }

}
</code>```

答:
Your interface should not have return value, that's useless.

```<code>interface VolleyCallBack{
        fun onResponse(result: Result<List<MovieEntity>>)

    }
</code>```

You're querying data from internet, so will need time to receive it. I recommend you only send data to other class. Like this:

In your original class:

```<code>fun getMovies() {
// start request data from internet. Should have something to notify user that i'm requesting data (loading dialog for example)
//loadingdialog.show()
RemoteDataSorceManager().getRemoteMovies(context, object : VolleyCallBack{
          override fun onResponse(result: Result<List<MovieEntity>>) {
// this is when you receive data
// loadingdialog.hide()
              sendDataToOtherClassAndSaveToDatabase(result)
              return@onResponse
          }

      })
}
</code>```

I'm not familiar with Volley. Just my opinion.

Body:
I have seen many response on the subject matter but none is enough for what I want.

I want to be able to return a response like a list from a volley response and pass that list to another class to be added to my database.

I have tried use an interface and a callback function but the response still hangs in another interface.

I want something like this

class Big:Interface{
  override fun A():List<Model> = getResponseFromVolley()
  fun getResponseFromVolley(){ setUp Volley request return List}

}

How can I do this

Code

class RemoteDataSourceManager: ServiceCall {

    override suspend fun getMovies(context: Context): Result<List<MovieEntity>> {

        var results: Result<List<MovieEntity>>

      getRemoteMovies(context, object : VolleyCallBack{
          override fun onResponse(result: Result<List<MovieEntity>>): Result<List<MovieEntity>> {
              results = result
              return results
          }

      })

        return results //result mustbe initialized

    }

    private fun getRemoteMovies(context: Context, callBack: VolleyCallBack): Result<List<MovieEntity>> {
        val responseBool = MutableLiveData<Boolean>(false)
        var listResult: Result<List<MovieEntity>>
        val listOfMovies = ArrayList<MovieEntity>()

        val url =
            "https://api.themoviedb.org/3/movie/popular?api_key=f1e256985ebc2be710bf1f4ed754da11&language=en-US&page=1"
        val request: JsonObjectRequest =
            JsonObjectRequest(
                Request.Method.GET,
                url, null,
                Response.Listener { response ->

                    try {
                        val results = response.getJSONArray("results")
                        val size = results.length()
                        var title = ""
                        var movieImage = ""
                        var rating = 0
                        var overView = ""
                        var releaseDate = ""
                        var movieId = ""

                        for (movie in 0 until results.length()) {
                            val eachMovie = results.getJSONObject(movie)
                            movieImage = "https://image.tmdb.org/t/p/w500"
                            title = eachMovie.getString("title")
                            movieImage +=eachMovie.getString("poster_path")
                            rating  = eachMovie.getInt("vote_average")
                            overView = eachMovie.getString("overview")
                            releaseDate = eachMovie.getString("release_date")
                            movieId = eachMovie.getInt("id").toString()

                            val newMovie =  MovieEntity(
                                title,
                                movieImage,
                                rating,
                                overView,
                                releaseDate
                            )
                            newMovie.movieId = movieId
                            newMovie.id = movieId.toInt()
                            listOfMovies.add(newMovie)

                            responseBool.value = true

                        }

                        listResult = getResult(Result.Success(listOfMovies.toList()))

                        callBack.onResponse(listResult)
                        Log.i("insideList", "$listOfMovies")

                    } catch (e: Exception) {
                        Log.i("error", "Response $e")

//                        Toast.makeText(context!!.applicationContext, "No activity", Toast.LENGTH_SHORT).show()
                    }
                }, Response.ErrorListener { error ->

                    val errroMessage = VolleyErrorHandler.instance.erroHandler(error)
                    CoroutineScope(Dispatchers.Main).launch {
//                        Toast.makeText(context, errroMessage, Toast.LENGTH_LONG).show()
                    }

                })

        context.applicationContext.let {
            VolleySingleton.getInstance(it).addToRequestQueue(request)

        }

        Log.i("listOfMovies", "$listResult")
        return listResult
    }

    override suspend fun saveMovies(movieEntity: MovieEntity) {
        TODO("not implemented") //To change body of created functions use File | Settings | File Templates.
    }

    interface VolleyCallBack{
        fun onResponse(result:Result<List<MovieEntity>>): Result<List<MovieEntity>>

    }

    private fun getResult(result: Result<List<MovieEntity>>):Result<List<MovieEntity>>{
        return result
    }

}

Body:
Your interface should not have return value, that's useless.

interface VolleyCallBack{
        fun onResponse(result: Result<List<MovieEntity>>)

    }

You're querying data from internet, so will need time to receive it. I recommend you only send data to other class. Like this:

In your original class:

fun getMovies() {
// start request data from internet. Should have something to notify user that i'm requesting data (loading dialog for example)
//loadingdialog.show()
RemoteDataSorceManager().getRemoteMovies(context, object : VolleyCallBack{
          override fun onResponse(result: Result<List<MovieEntity>>) {
// this is when you receive data
// loadingdialog.hide()
              sendDataToOtherClassAndSaveToDatabase(result)
              return@onResponse
          }

      })
}

I'm not familiar with Volley. Just my opinion.


问:
Using flexbox to change ordering in Bootstrap 4
I'm currently building a site that has a team section that should look like the following:

Here is my current scss file:

```<code>.team-member-card {
  &__text-content {
    background-color: red;
    padding: 16px;
    overflow-y: scroll;
  }

  &__name {
    font-family: CircularStd;
    font-size: 24px;
    font-weight: bold;
    font-stretch: normal;
    font-style: normal;
    line-height: normal;
    letter-spacing: normal;
    color: $white;
  }

  &__role {
    font-family: CircularStd;
    font-size: 18px;
    font-weight: 500;
    font-stretch: normal;
    font-style: normal;
    line-height: 1.44;
    letter-spacing: normal;
    color: $white;
  }

  &__biography {
    font-family: Balto;
    font-size: 16px;
    font-weight: normal;
    font-stretch: normal;
    font-style: normal;
    line-height: 1.5;
    letter-spacing: normal;
    color: $white;
  }

  &__image-container {
    position: relative;
  }

  &__image {
    height: auto;
    max-width: 100%;
    object-fit: contain;
    background-color: #ffffff;
  }

  &__social-link {
    position: absolute;
    width: 48px;
    height: 48px;
    object-fit: contain;
  }
}
</code>```

I have broken the component down into the obvious sections I can see but as you can see, every n+1 team member has their image on the other side, is there a way to inverse the column order?

答:
Please try to look for the css nth element selector. It has odd and even selector.

```<code>:nth-child(odd) {
  float: right;
}

//or with flex-direction
flex-direction: row-reverse;
</code>```

Please have a look here

Body:
I'm currently building a site that has a team section that should look like the following:

Here is my current scss file:

.team-member-card {
  &__text-content {
    background-color: red;
    padding: 16px;
    overflow-y: scroll;
  }

  &__name {
    font-family: CircularStd;
    font-size: 24px;
    font-weight: bold;
    font-stretch: normal;
    font-style: normal;
    line-height: normal;
    letter-spacing: normal;
    color: $white;
  }

  &__role {
    font-family: CircularStd;
    font-size: 18px;
    font-weight: 500;
    font-stretch: normal;
    font-style: normal;
    line-height: 1.44;
    letter-spacing: normal;
    color: $white;
  }

  &__biography {
    font-family: Balto;
    font-size: 16px;
    font-weight: normal;
    font-stretch: normal;
    font-style: normal;
    line-height: 1.5;
    letter-spacing: normal;
    color: $white;
  }

  &__image-container {
    position: relative;
  }

  &__image {
    height: auto;
    max-width: 100%;
    object-fit: contain;
    background-color: #ffffff;
  }

  &__social-link {
    position: absolute;
    width: 48px;
    height: 48px;
    object-fit: contain;
  }
}

I have broken the component down into the obvious sections I can see but as you can see, every n+1 team member has their image on the other side, is there a way to inverse the column order?

Body:
Please try to look for the css nth element selector. It has odd and even selector.

:nth-child(odd) {
  float: right;
}

//or with flex-direction
flex-direction: row-reverse;

Please have a look here


问:
Get top n counted rows in table within group [MySQL]
I'm trying to get just top 3 selling products grouped within categories (just top 3 products by occurrence in transactions (id) count(id) by each category). I was searching a lot for possible solution but with no result. It looks like it is a bit tricky in MySQL since one can't simply use top() function and so on. Sample data structure bellow:

```<code>+--------+------------+-----------+
|     id |category_id | product_id|
+--------+------------+-----------+
| 1      | 10         | 32        |
| 2      | 10         | 34        |
| 3      | 10         | 32        |
| 4      | 10         | 21        |
| 5      | 10         | 100       |
| 6      | 7          | 101       |
| 7      | 7          | 39        |
| 8      | 7          | 41        |
| 9      | 7          | 39        |
+--------+------------+-----------+
</code>```

答:
If you are running MySQL 8.0, you can use window function rank() for this:

```<code>select *
from (
    select
        category_id,
        product_id,
        count(*) cnt,
        rank() over(partition by category_id order by count(*) desc) rn
    from mytable
    group by category_id, product_id
) t
where rn <= 3
</code>```

In earlier versions, one option is to filter with a correlated subquery:

```<code>select
    category_id,
    product_id,
    count(*) cnt
from mytable t
group by category_id, product_id
having count(*) >= (
    select count(*)
    from mytable t1
    where t1.category_id = t.category_id and t1.product_id = t.product_id
    order by count(*) desc
    limit 3, 1
)
</code>```

Body:
I'm trying to get just top 3 selling products grouped within categories (just top 3 products by occurrence in transactions (id) count(id) by each category). I was searching a lot for possible solution but with no result. It looks like it is a bit tricky in MySQL since one can't simply use top() function and so on. Sample data structure bellow:

+--------+------------+-----------+
|     id |category_id | product_id|
+--------+------------+-----------+
| 1      | 10         | 32        |
| 2      | 10         | 34        |
| 3      | 10         | 32        |
| 4      | 10         | 21        |
| 5      | 10         | 100       |
| 6      | 7          | 101       |
| 7      | 7          | 39        |
| 8      | 7          | 41        |
| 9      | 7          | 39        |
+--------+------------+-----------+

Body:
If you are running MySQL 8.0, you can use window function rank() for this:

select *
from (
    select
        category_id,
        product_id,
        count(*) cnt,
        rank() over(partition by category_id order by count(*) desc) rn
    from mytable
    group by category_id, product_id
) t
where rn <= 3

In earlier versions, one option is to filter with a correlated subquery:

select
    category_id,
    product_id,
    count(*) cnt
from mytable t
group by category_id, product_id
having count(*) >= (
    select count(*)
    from mytable t1
    where t1.category_id = t.category_id and t1.product_id = t.product_id
    order by count(*) desc
    limit 3, 1
)


问:
Select the option whose text is contained with a string value
I have a select with several option elements. Each option has an id and a value. This select is loaded with an AJAX request via jQuery.

There is also a string variable that contains text with which you would have to compare all the option values. If any of them are within this text, set the option as selected.

In this example you would have to select the <option id="27">Mini 4</option> which is the one inside the string var mytexto.

How do I get these two values, the id and the value?

var mytexto = 'Ipad Mini 4 16GB/1GB Azul';
```

<pre class="lang-html prettyprint-override"><code><select id="nombre_modelo" class="form-control">
 <option value="" disabled="disabled" selected="selected">Select one model name</option>
 <option id="25">Ipad 3</option>
 <option id="26">Ipad 4</option>
 <option id="27">Mini 4</option>
 <option id="28">Mini Wifi A1403</option>
 <option id="29">Mini Wifi A1432</option>
</select>
</code>```

答:
$(document).ready(function() {
  var mytext = 'Ipad Mini 4 16GB/1GB Azul';

  var options = $("#nombre_modelo")[0].options
  for (i = 0; i < options.length; i++) {

    if (mytext.includes(options[i].innerText)) {
      console.log(options[i].innerText)
      console.log(options[i].id)
    }

  }

});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<select id="nombre_modelo" class="form-control">
  <option value="" disabled="disabled" selected="selected">Select one model name</option>
  <option id="25">Ipad 3</option>
  <option id="26">Ipad 4</option>
  <option id="27">Mini 4</option>
  <option id="28">Mini Wifi A1403</option>
  <option id="29">Mini Wifi A1432</option>
</select></code>```

Body:
I have a select with several option elements. Each option has an id and a value. This select is loaded with an AJAX request via jQuery.

There is also a string variable that contains text with which you would have to compare all the option values. If any of them are within this text, set the option as selected.

In this example you would have to select the <option id="27">Mini 4</option> which is the one inside the string var mytexto.

How do I get these two values, the id and the value?

var mytexto = 'Ipad Mini 4 16GB/1GB Azul';

<select id="nombre_modelo" class="form-control">
 <option value="" disabled="disabled" selected="selected">Select one model name</option>
 <option id="25">Ipad 3</option>
 <option id="26">Ipad 4</option>
 <option id="27">Mini 4</option>
 <option id="28">Mini Wifi A1403</option>
 <option id="29">Mini Wifi A1432</option>
</select>

Body:
$(document).ready(function() {
  var mytext = 'Ipad Mini 4 16GB/1GB Azul';

  var options = $("#nombre_modelo")[0].options
  for (i = 0; i < options.length; i++) {

    if (mytext.includes(options[i].innerText)) {
      console.log(options[i].innerText)
      console.log(options[i].id)
    }

  }

});

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<select id="nombre_modelo" class="form-control">
  <option value="" disabled="disabled" selected="selected">Select one model name</option>
  <option id="25">Ipad 3</option>
  <option id="26">Ipad 4</option>
  <option id="27">Mini 4</option>
  <option id="28">Mini Wifi A1403</option>
  <option id="29">Mini Wifi A1432</option>
</select>


问:
Spring Cloud Config Server - Connect to Github account with 2FA
I'm trying to create a Spring Cloud Config Server to retrieve configuration files from a private GitHub repository. My GitHub account has 2 Factor Authentication activated so I wasn't expecting the below configuration to work, which it didn't but I can't find any documentation to suggest what I need to do in order to make it work.

What configuration do I need to set that will allow the connection to work?

```<code>spring.cloud.config.server.git.uri=https://github.com/DanBonehill/photo-app-config
spring.cloud.config.server.git.username=USERNAME
spring.cloud.config.server.git.password=PASSWORD
</code>```

Error

org.eclipse.jgit.api.errors.TransportException: https://github.com/DanBonehill/photo-app-config: not authorized

答:
What you could try and do (have not tested this), is create a personal access token from the Github console. </p>

<p>Then configure </p>

```<code>spring.cloud.config.server.git.username=<yourusername>
spring.cloud.config.server.git.password=<yourtoken>
</code>```

Body:
I'm trying to create a Spring Cloud Config Server to retrieve configuration files from a private GitHub repository. My GitHub account has 2 Factor Authentication activated so I wasn't expecting the below configuration to work, which it didn't but I can't find any documentation to suggest what I need to do in order to make it work.

What configuration do I need to set that will allow the connection to work?

spring.cloud.config.server.git.uri=https://github.com/DanBonehill/photo-app-config
spring.cloud.config.server.git.username=USERNAME
spring.cloud.config.server.git.password=PASSWORD

Error

org.eclipse.jgit.api.errors.TransportException: https://github.com/DanBonehill/photo-app-config: not authorized

Body:
What you could try and do (have not tested this), is create a personal access token from the Github console.

Then configure

spring.cloud.config.server.git.username=<yourusername>
spring.cloud.config.server.git.password=<yourtoken>


问:
Define and plot constant function in python
I am trying to plot a constant function in python (this is not what I am actually trying to do but if I solve this it might be a first step).

```<code>import matplotlib.pyplot as plt
import numpy as np

def constant_function(x):
    return 2

t1 = np.arange(0.0,1.0,0.1)
plt.plot(t1,constant_function(t1))
</code>```

However I get the error

```<code>ValueError: x and y must have same first dimension, but have shapes (10,) and (1,)
</code>```

答:
In my opinion vectorize is overkill to plot a simple "function" which just yields a constant value, especially if basic python syntax is the source of the problem. (And imho decorators are quite more advanced than using simple numpy methods.)

Instead I'd recommend just setting the return value of the function to an array of the same shape:

```<code>import matplotlib.pyplot as plt
import numpy as np

def constant_function(x):
    return 2

t1 = np.arange(0.0,1.0,0.1)
plt.plot(t1, np.full(t1.shape, constant_function(t1)))
</code>```

Since constant_function currently takes an argument which is not used, another improvement could be to construct the array inside constant_function, using the information from the argument x:

```<code>def constant_function(x):
    return np.full(x.shape, 2)

t1 = np.arange(0.0,1.0,0.1)
plt.plot(t1, constant_function(t1))
</code>```

Body:
I am trying to plot a constant function in python (this is not what I am actually trying to do but if I solve this it might be a first step).

import matplotlib.pyplot as plt
import numpy as np

def constant_function(x):
    return 2

t1 = np.arange(0.0,1.0,0.1)
plt.plot(t1,constant_function(t1))

However I get the error

ValueError: x and y must have same first dimension, but have shapes (10,) and (1,)

Body:
In my opinion vectorize is overkill to plot a simple "function" which just yields a constant value, especially if basic python syntax is the source of the problem. (And imho decorators are quite more advanced than using simple numpy methods.)

Instead I'd recommend just setting the return value of the function to an array of the same shape:

import matplotlib.pyplot as plt
import numpy as np

def constant_function(x):
    return 2

t1 = np.arange(0.0,1.0,0.1)
plt.plot(t1, np.full(t1.shape, constant_function(t1)))

Since constant_function currently takes an argument which is not used, another improvement could be to construct the array inside constant_function, using the information from the argument x:

def constant_function(x):
    return np.full(x.shape, 2)

t1 = np.arange(0.0,1.0,0.1)
plt.plot(t1, constant_function(t1))


问:
Creating and pushing elements in an new array depends on conditions
My Data Array

```<code>data:[
0:{
   id:1 ,.....
   competetion:[
          0:{
              id: 1....,
              match:[
                      0:{id: 1 ......},
                      1:{same}
                      .
                      .
                    ]
          1:{same}]},
          2:{same}
          .
          .
        ]
  },
1:{same},
2:{same}
.
.
.
]

</code>```

For data[] i able to create a new array(sportarr[]) with pushing elements but i want to create for the same as competetion[] and match[] in the same array sportarr[]
If there any other way to do it please Help me...

My Code: Here i am looping it:

```<code>this.sportsSidebar = response.data;   // My data Array (this.sportsSidebar)
const arrlength = response.data.length;
for (let i = 0; i < arrlength; i++) {
    this.sportarr.push({       // I declared a new array where i want to push the element
      id: i,
      value: false
    });
}
</code>```

答:
if you want your own content based on the mapping what I will suggest is that first iterate through the array then map each match and competetion and write your own logic inside the map</p>

```<code> const arrlength = data.length;
      for (let i = 0; i < arrlength; i++) {
        let competition = [];
        competition = data[i].competetion.map( (val, index) => {
          #write your own logic to produce the required outcome
          return {
              id: index,
              value: false
          };
        });
        this.sportarr.push({
          id: i,
          value: false,
          competetion: competition
        });
        console.log('myarrr...', this.sportarr);
</code>```

Body:
My Data Array

data:[
0:{
   id:1 ,.....
   competetion:[
          0:{
              id: 1....,
              match:[
                      0:{id: 1 ......},
                      1:{same}
                      .
                      .
                    ]
          1:{same}]},
          2:{same}
          .
          .
        ]
  },
1:{same},
2:{same}
.
.
.
]

For data[] i able to create a new array(sportarr[]) with pushing elements but i want to create for the same as competetion[] and match[] in the same array sportarr[]
If there any other way to do it please Help me...

My Code: Here i am looping it:

this.sportsSidebar = response.data;   // My data Array (this.sportsSidebar)
const arrlength = response.data.length;
for (let i = 0; i < arrlength; i++) {
    this.sportarr.push({       // I declared a new array where i want to push the element
      id: i,
      value: false
    });
}

Body:
if you want your own content based on the mapping what I will suggest is that first iterate through the array then map each match and competetion and write your own logic inside the map

 const arrlength = data.length;
      for (let i = 0; i < arrlength; i++) {
        let competition = [];
        competition = data[i].competetion.map( (val, index) => {
          #write your own logic to produce the required outcome
          return {
              id: index,
              value: false
          };
        });
        this.sportarr.push({
          id: i,
          value: false,
          competetion: competition
        });
        console.log('myarrr...', this.sportarr);


问:
How to create a random logical vector with specific numbers of TRUE / FALSE entries
I would like to create a logical vector that has 10 rows, with each row randomly assigned either TRUE or FALSE.  However, I want there to only be 3 FALSE and 7 TRUE.

Example of desired outcome (logical vector with three randomly assigned FALSE entries and 7 randomly assigned TRUE entries):

```<code>> vector
 [1] "TRUE"  "TRUE"  "FALSE" "TRUE"  "FALSE" "FALSE" "TRUE" "TRUE" "TRUE"
[10] "TRUE"
</code>```

I can create a logical vector of size 10 that has TRUE or FALSE, but I don't know how to specify I want three FALSE entries and 7 TRUE entries.

```<code>vector <- sample(x = c("TRUE","FALSE"), size = 10, replace = TRUE)
</code>```

This produces:

```<code>> train
 [1] "TRUE"  "TRUE"  "FALSE" "TRUE"  "FALSE" "FALSE" "FALSE" "FALSE" "FALSE"
[10] "TRUE"
</code>```

Which has the incorrect number of TRUE and FALSE entries (4 TRUE and 6 FALSE).

答:
If you just want to shuffle the positions of TRUE and FALSE, you can try the code below

```<code>res <- (v <- c(rep(TRUE, 7), rep(FALSE, 3)))[sample(seq(v))]
</code>```

where sample(seq(v)) generates random positions from 1 to length(v)

Body:
I would like to create a logical vector that has 10 rows, with each row randomly assigned either TRUE or FALSE.  However, I want there to only be 3 FALSE and 7 TRUE.

Example of desired outcome (logical vector with three randomly assigned FALSE entries and 7 randomly assigned TRUE entries):

> vector
 [1] "TRUE"  "TRUE"  "FALSE" "TRUE"  "FALSE" "FALSE" "TRUE" "TRUE" "TRUE"
[10] "TRUE"

I can create a logical vector of size 10 that has TRUE or FALSE, but I don't know how to specify I want three FALSE entries and 7 TRUE entries.

vector <- sample(x = c("TRUE","FALSE"), size = 10, replace = TRUE)

This produces:

> train
 [1] "TRUE"  "TRUE"  "FALSE" "TRUE"  "FALSE" "FALSE" "FALSE" "FALSE" "FALSE"
[10] "TRUE"

Which has the incorrect number of TRUE and FALSE entries (4 TRUE and 6 FALSE).

Body:
If you just want to shuffle the positions of TRUE and FALSE, you can try the code below

res <- (v <- c(rep(TRUE, 7), rep(FALSE, 3)))[sample(seq(v))]

where sample(seq(v)) generates random positions from 1 to length(v)


问:
Illegal reflective access by org.springframework.cglib.core.ReflectUtils$1
My JDK 9+181 Spring Boot 2.0.0.BUILD-SNAPSHOT CLI application displays this warning on startup:

```<code>WARNING: An illegal reflective access operation has occurred
WARNING: Illegal reflective access by org.springframework.cglib.core.ReflectUtils$1 (jar:file:/home/jan/src/fm-cli/target/fm-cli-0.1.0-SNAPSHOT.jar!/BOOT-INF/lib/spring-core-5.0.0.RELEASE.jar!/) to method java.lang.ClassLoader.defineClass(java.lang.String,byte[],int,int,java.security.ProtectionDomain)
WARNING: Please consider reporting this to the maintainers of org.springframework.cglib.core.ReflectUtils$1
</code>```

This is a console application, so I need to disable this warning -- how can I do that?

Note: This question asks the specific question of how to disable this warning triggered by Spring; it is not a duplicate of JDK9: An illegal reflective access operation has occurred. org.python.core.PySystemState which deals with a similar symptom in a different library.

答:
This also happened to me on JDK 11 and Spring Boot 2.2.1 (Spring Core 5.2.1).

What helped was removing the dependency to org.springframework.boot:spring-boot-devtools, as suggested in some comments to Spring Framework issue #22814.

Body:
My JDK 9+181 Spring Boot 2.0.0.BUILD-SNAPSHOT CLI application displays this warning on startup:

WARNING: An illegal reflective access operation has occurred
WARNING: Illegal reflective access by org.springframework.cglib.core.ReflectUtils$1 (jar:file:/home/jan/src/fm-cli/target/fm-cli-0.1.0-SNAPSHOT.jar!/BOOT-INF/lib/spring-core-5.0.0.RELEASE.jar!/) to method java.lang.ClassLoader.defineClass(java.lang.String,byte[],int,int,java.security.ProtectionDomain)
WARNING: Please consider reporting this to the maintainers of org.springframework.cglib.core.ReflectUtils$1

This is a console application, so I need to disable this warning -- how can I do that?

Note: This question asks the specific question of how to disable this warning triggered by Spring; it is not a duplicate of JDK9: An illegal reflective access operation has occurred. org.python.core.PySystemState which deals with a similar symptom in a different library.


问:
How to update the state of a Toggle Button after process completion?
I want to execute a task when a Toggle Button is clicked(on) and toggle it off after the task is completed, I execute the task in a new process because I don't want it to block the UI, event.GetEventObject().SetValue(False) seems to update correctly the value of the Toggle but it doesn't reflect on the UI.

from  multiprocessing import Process
import time
import wx

class MyFrame(wx.Frame):
    def __init__(self, *args, **kwds):
        kwds["style"] = kwds.get("style", 0) | wx.DEFAULT_FRAME_STYLE
        wx.Frame.__init__(self, *args, **kwds)
        self.toggle_button = wx.ToggleButton(self, wx.ID_ANY, "OK")
        control = Control()
        self.Bind(wx.EVT_TOGGLEBUTTON, control.action, self.toggle_button)
        self.SetTitle("Update UI with a process")
        sizer = wx.BoxSizer(wx.VERTICAL)
        sizer.Add(self.toggle_button, 0, 0, 0)
        self.SetSizer(sizer)
        self.Layout()

class Control():
    def update_toggle(self, duration, event):
        time.sleep(duration)
        event.GetEventObject().SetValue(False)
        print("Toggled")

    def action(self, event):
        if event.GetEventObject().GetValue():
            self.update_toggle_process = Process(target = self.update_toggle,
                                                args=(5, event,))
            self.update_toggle_process.start()
        else:
            print("UnToggled")

class MyApp(wx.App):
    def OnInit(self):
        self.frame = MyFrame(None, wx.ID_ANY, "")
        self.SetTopWindow(self.frame)
        self.frame.Show()
        return True

if __name__ == "__main__":
    app = MyApp(0)
    app.MainLoop()
```

A call to event.GetEventObject().Update() or event.GetEventObject().Refresh() after changing the value of the Toggle doesn't seem to change anything.

EDIT:

If I use a Thread instead of Process, it works correctly, but I chose Process over Thread because I want the ability to kill it cleanly whenever I need to.

Python version: 3.7

WxPython version: 4.0.1

答:
You must remember, that the your update_toggle runs in a new process. Simply put, it has got a copy of data, so if you call event.GetEventObject().SetValue(False) it happens in the new process, and the original one with the Window and Button won't know.

You must somehow pass a message from the new process to the original. I would suggest that the first thing you try is:

```<code>        self.update_toggle_process.start()
        self.update_toggle_process.join()
        print("the process has finished")
</code>```

This will block, but at least you will see if the "update_toggle_process" has finished and if this approach works. After that, there are a few possibilities:

Set up a times and periodically call self.update_toggle_process.is_alive()

Create a new thread, call the update_toggle_process.start() from it, and also join(). When finished, tell the main thread to toggle the button (remember that you may only manipulate the UI from the main thread in wx)

Maybe you do not need a new process, a thread will be enough

Look at the multiprocessing IPC

Body:
I want to execute a task when a Toggle Button is clicked(on) and toggle it off after the task is completed, I execute the task in a new process because I don't want it to block the UI, event.GetEventObject().SetValue(False) seems to update correctly the value of the Toggle but it doesn't reflect on the UI.

from  multiprocessing import Process
import time
import wx

class MyFrame(wx.Frame):
    def __init__(self, *args, **kwds):
        kwds["style"] = kwds.get("style", 0) | wx.DEFAULT_FRAME_STYLE
        wx.Frame.__init__(self, *args, **kwds)
        self.toggle_button = wx.ToggleButton(self, wx.ID_ANY, "OK")
        control = Control()
        self.Bind(wx.EVT_TOGGLEBUTTON, control.action, self.toggle_button)
        self.SetTitle("Update UI with a process")
        sizer = wx.BoxSizer(wx.VERTICAL)
        sizer.Add(self.toggle_button, 0, 0, 0)
        self.SetSizer(sizer)
        self.Layout()

class Control():
    def update_toggle(self, duration, event):
        time.sleep(duration)
        event.GetEventObject().SetValue(False)
        print("Toggled")

    def action(self, event):
        if event.GetEventObject().GetValue():
            self.update_toggle_process = Process(target = self.update_toggle,
                                                args=(5, event,))
            self.update_toggle_process.start()
        else:
            print("UnToggled")

class MyApp(wx.App):
    def OnInit(self):
        self.frame = MyFrame(None, wx.ID_ANY, "")
        self.SetTopWindow(self.frame)
        self.frame.Show()
        return True

if __name__ == "__main__":
    app = MyApp(0)
    app.MainLoop()

A call to event.GetEventObject().Update() or event.GetEventObject().Refresh() after changing the value of the Toggle doesn't seem to change anything.

EDIT:

If I use a Thread instead of Process, it works correctly, but I chose Process over Thread because I want the ability to kill it cleanly whenever I need to.

Python version: 3.7

WxPython version: 4.0.1

Body:
You must remember, that the your update_toggle runs in a new process. Simply put, it has got a copy of data, so if you call event.GetEventObject().SetValue(False) it happens in the new process, and the original one with the Window and Button won't know.

You must somehow pass a message from the new process to the original. I would suggest that the first thing you try is:

        self.update_toggle_process.start()
        self.update_toggle_process.join()
        print("the process has finished")

This will block, but at least you will see if the "update_toggle_process" has finished and if this approach works. After that, there are a few possibilities:

Set up a times and periodically call self.update_toggle_process.is_alive()

Create a new thread, call the update_toggle_process.start() from it, and also join(). When finished, tell the main thread to toggle the button (remember that you may only manipulate the UI from the main thread in wx)

Maybe you do not need a new process, a thread will be enough

Look at the multiprocessing IPC


问:
How can I create an observable like the one returned by defer using Observable.create?
I'm trying to create an observable with behavior similar to what is returned by defer, but using create method. So I try:

```<code>const obs = Observable.create(function(observer) {
   from(fetch('https://jsonplaceholder.typicode.com/todos/1').then(console.log('fetch done'))).subscribe(observer)
})

setTimeout(()=>obs.subscribe((resp)=>console.log(resp.statusText)), 5000)
</code>```

But when I run it in node It just prints "fetch done" (on subscription, after 5 seconds as expected) but waits forever there.

When I wrap the from(..) in setImmediate() or setTimeout(,0), then sometimes it prints both messages ("Fetch done", "OK") and exits and sometimes it only prints "fetch done" and waits forever.

code:

```<code>const obs = Observable.create(function(observer) {
    setTimeout(()=>from(fetch('https://jsonplaceholder.typicode.com/todos/1').then(console.log('fetch done'))).subscribe(observer), 0)
})

setTimeout(()=>obs.subscribe((resp)=>console.log(resp.statusText)), 5000)
</code>```

Why this happens? What am I doing wrong?

答: Promise.then takes a callback function, and you need to return the argument to chain it, so it becomes then(result => { console.log('fetch done', result); return result; })

Body:
I'm trying to create an observable with behavior similar to what is returned by defer, but using create method. So I try:

const obs = Observable.create(function(observer) {
   from(fetch('https://jsonplaceholder.typicode.com/todos/1').then(console.log('fetch done'))).subscribe(observer)
})

setTimeout(()=>obs.subscribe((resp)=>console.log(resp.statusText)), 5000)

But when I run it in node It just prints "fetch done" (on subscription, after 5 seconds as expected) but waits forever there.

When I wrap the from(..) in setImmediate() or setTimeout(,0), then sometimes it prints both messages ("Fetch done", "OK") and exits and sometimes it only prints "fetch done" and waits forever.

code:

const obs = Observable.create(function(observer) {
    setTimeout(()=>from(fetch('https://jsonplaceholder.typicode.com/todos/1').then(console.log('fetch done'))).subscribe(observer), 0)
})

setTimeout(()=>obs.subscribe((resp)=>console.log(resp.statusText)), 5000)

Why this happens? What am I doing wrong?


问:
Issue with image orientation when capturing using camera2 api in android version 10
I have been updated my camera feature from Camera to camera2 api.

When i capture the image with front camera and display it in imageview. the orientation of the image is changed. Then i used this code to change the orientation of the image.

```<code>int jpegOrientation =
                (ORIENTATIONS.get(rotation) + characteristics.get(CameraCharacteristics.SENSOR_ORIENTATION) + 270) % 360;
capturebuilder.set(CaptureRequest.JPEG_ORIENTATION, jpegOrientation);
</code>```

Above code is working for android version(i.e version 5,9) which i have tested. When i run the same code in Android version 10 it does not work. Below is the image

please,any one can help me out for this issue

答:
Did you try the solution below :
https://medium.com/@kenodoggy/solving-image-rotation-on-android-using-camera2-api-7b3ed3518ab6</p>

Body:
I have been updated my camera feature from Camera to camera2 api.

When i capture the image with front camera and display it in imageview. the orientation of the image is changed. Then i used this code to change the orientation of the image.

int jpegOrientation =
                (ORIENTATIONS.get(rotation) + characteristics.get(CameraCharacteristics.SENSOR_ORIENTATION) + 270) % 360;
capturebuilder.set(CaptureRequest.JPEG_ORIENTATION, jpegOrientation);

Above code is working for android version(i.e version 5,9) which i have tested. When i run the same code in Android version 10 it does not work. Below is the image

please,any one can help me out for this issue


问:
Generate 8 digit OTP in java
Generate 8 digit OTP in java with first digit as zero.
I have tried with Math() function in Java but it gives random numbers first digit without zero.
Suggest me an easiest way to achieve the same

答:
You should be using SecureRandom. Refer https://stackoverflow.com/a/11052736/1776132

```<code>String.format("%08d", new SecureRandom().nextInt(10_000_000))
</code>```

Title: Generate 8 digit OTP in java

Body:
You should be using SecureRandom. Refer https://stackoverflow.com/a/11052736/1776132

String.format("%08d", new SecureRandom().nextInt(10_000_000))


答:
Not perfect but close:</p>

```<code>newcol<-sapply(rownames(t), function(rn){z[match(rn, rownames(z)), 5]})
cbind(data.frame(t), newcol)
</code>```

Title: Merge or combine by rownames

Body:
In the example below I have two datasets (Z and A). I want to merge or combine these sets by the ILMN numbers. If there is no match, fill in NA.

z <- matrix(c(0,0,1,1,0,0,1,1,0,0,0,0,1,0,1,1,0,1,1,1,1,0,0,0,"RND1","WDR", "PLAC8","TYBSA","GRA","TAF"), nrow=6,
    dimnames=list(c("ILMN_1651838","ILMN_1652371","ILMN_1652464","ILMN_1652952","ILMN_1653026","ILMN_1653103"),c("A","B","C","D","symbol")))

t<-matrix(c("GO:0002009", 8, 342, 1, 0.07, 0.679, 0, 0, 1, 0,
        "GO:0030334", 6, 343, 1, 0.07, 0.065, 0, 0, 1, 0,
        "GO:0015674", 7, 350, 1, 0.07, 0.065, 1, 0, 0, 0), nrow=10, dimnames= list(c("GO.ID","LEVEL","Annotated","Significant","Expected","resultFisher","ILMN_1652464","ILMN_1651838","ILMN_1711311","ILMN_1653026")))

The result will be like this:

             [,1]         [,2]         [,3]         [,4]
GO.ID        "GO:0002009" "GO:0030334" "GO:0015674"  NA
LEVEL        "8"          "6"          "7"           NA
Annotated    "342"        "343"        "350"         NA
Significant  "1"          "1"          "1"           NA
Expected     "0.07"       "0.07"       "0.07"        NA
resultFisher "0.679"      "0.065"      "0.065"       NA
ILMN_1652464 "0"          "0"          "1"           PLAC8
ILMN_1651838 "0"          "0"          "0"           RND1
ILMN_1711311 "1"          "1"          "0"           NA
ILMN_1653026 "0"          "0"          "0"           GRA

Body:
Not perfect but close:

newcol<-sapply(rownames(t), function(rn){z[match(rn, rownames(z)), 5]})
cbind(data.frame(t), newcol)


问:
Symfony Doctrine query builder LIKE not working in PostgreSQL
So I have a UserRepository that contains the following code

```<code>namespace AppBundle\Repository;
use \Doctrine\ORM\EntityRepository;
class UserRepository extends EntityRepository
{
    public function findByRole($role)
    {
        $qb = $this->_em->createQueryBuilder();
        $qb->select('u')
            ->from($this->_entityName, 'u')
            ->where('u.roles LIKE :roles')
            ->setParameter('roles', '%"'.$role.'"%');

        return $qb->getQuery()->getResult();
    }
}
</code>```

This seems to be working perfectly fine if my database is MySQL but if i change the database to PostgreSQL this query throws the following error

An exception occurred while executing 'SELECT p0_.id AS id_0,
  p0_.username AS username_1, p0_.password AS password_2, p0_.is_active
  AS is_active_3, p0_.roles AS roles_4, p0_.name AS name_5, p0_.street
  AS street_6, p0_.city AS city_7, p0_.state AS state_8, p0_.zip_code AS
  zip_code_9, p0_.phone_number AS phone_number_10, p0_.dob AS dob_11,
  p0_.company_name AS company_name_12, p0_.company_slug AS
  company_slug_13, p0_.company_logo AS company_logo_14,
  p0_.company_details AS company_details_15, p0_.stripe_customer_id AS
  stripe_customer_id_16, p0_.created_at AS created_at_17, p0_.updated_at
  AS updated_at_18 FROM px_user p0_ WHERE p0_.roles LIKE ?' with params
  ["%\"ROLE_EMPLOYER\"%"]:

SQLSTATE[42883]: Undefined function: 7 ERROR: operator does not exist:
  json ~~ unknown LINE 1: ...at AS updated_at_18 FROM px_user p0_ WHERE
  p0_.roles LIKE $1 ^ HINT: No operator matches the given name and
  argument type(s). You might need to add explicit type casts.

This is the first time I am working with PostgreSQL so I am not getting what the problem is. After playing around with it for a while if I change the generated query to by adding the following piece

```<code>WHERE
  p0_.roles::text LIKE '%ROLE_EMPLOYER%'
</code>```

Everything works fine. Note the ::text.

So now how can i add that to the query builder so it works with PostgreSQL as well.

答:
I solved the problem with the module boldtrn/jsonb-bundle but it created an error depending on the version of Postgres used.

I also solved the issue without the module by a native query like this :

```<code>public function findEmailsByRole($role)
{
    return $this->_em->getConnection()->executeQuery(
        "SELECT email FROM public.utilisateur WHERE roles::text LIKE :role",
        ['role'=>'%"' . $role . '"%']
    )->fetchAll();
}
</code>```

Body:
So I have a UserRepository that contains the following code

namespace AppBundle\Repository;
use \Doctrine\ORM\EntityRepository;
class UserRepository extends EntityRepository
{
    public function findByRole($role)
    {
        $qb = $this->_em->createQueryBuilder();
        $qb->select('u')
            ->from($this->_entityName, 'u')
            ->where('u.roles LIKE :roles')
            ->setParameter('roles', '%"'.$role.'"%');

        return $qb->getQuery()->getResult();
    }
}

This seems to be working perfectly fine if my database is MySQL but if i change the database to PostgreSQL this query throws the following error

An exception occurred while executing 'SELECT p0_.id AS id_0,
  p0_.username AS username_1, p0_.password AS password_2, p0_.is_active
  AS is_active_3, p0_.roles AS roles_4, p0_.name AS name_5, p0_.street
  AS street_6, p0_.city AS city_7, p0_.state AS state_8, p0_.zip_code AS
  zip_code_9, p0_.phone_number AS phone_number_10, p0_.dob AS dob_11,
  p0_.company_name AS company_name_12, p0_.company_slug AS
  company_slug_13, p0_.company_logo AS company_logo_14,
  p0_.company_details AS company_details_15, p0_.stripe_customer_id AS
  stripe_customer_id_16, p0_.created_at AS created_at_17, p0_.updated_at
  AS updated_at_18 FROM px_user p0_ WHERE p0_.roles LIKE ?' with params
  ["%\"ROLE_EMPLOYER\"%"]:

SQLSTATE[42883]: Undefined function: 7 ERROR: operator does not exist:
  json ~~ unknown LINE 1: ...at AS updated_at_18 FROM px_user p0_ WHERE
  p0_.roles LIKE $1 ^ HINT: No operator matches the given name and
  argument type(s). You might need to add explicit type casts.

This is the first time I am working with PostgreSQL so I am not getting what the problem is. After playing around with it for a while if I change the generated query to by adding the following piece

WHERE
  p0_.roles::text LIKE '%ROLE_EMPLOYER%'

Everything works fine. Note the ::text.

So now how can i add that to the query builder so it works with PostgreSQL as well.

Body:
I solved the problem with the module boldtrn/jsonb-bundle but it created an error depending on the version of Postgres used.

I also solved the issue without the module by a native query like this :

public function findEmailsByRole($role)
{
    return $this->_em->getConnection()->executeQuery(
        "SELECT email FROM public.utilisateur WHERE roles::text LIKE :role",
        ['role'=>'%"' . $role . '"%']
    )->fetchAll();
}