问:
Identifying the class type for arguments required in gerDeclaredMethod in java
I am using Java Reflection to invoke a method xyz with these 4 parameter types:

```<code>Set<LineItems>
String
Document
Profiler
</code>```

While using getDeclaredMethod I am required to give the method argument type. If String's argument type is String.class, what should be done for Set<LineItems>? Should it be Set.class? (Keeping in mind that Set is an interface)

The function xyz is a default function in interface abc. This interface is being implemented in multiple other classes, so method should be reflected here only. Here is my code:

```<code>Class c = abc.getClass();

Class args[] = new Class[4];
args[0] = Set.class;
args[1] = String.class;
args[2] = Document.class;
args[3] = Profiler.class;

Method m = c.getMethod("xyz",args) ;
</code>```

I'm getting the NoSuchMethodFoundException
I know there could be multiple flaws in this. Any help?

答:
what should be done for Set<LineItems>?

What you have there Set.class should do. Remember that Java generics come with type erasure, therefore, at runtime, the signature of that method will say Set.class, too!

And yes, when the signature of the method you intend to call says Set, then using the Set (interface) class is exactly what you have to do. If for example, the method signature said HashSet then Set.class would not do!

Body:
I am using Java Reflection to invoke a method xyz with these 4 parameter types:

Set<LineItems>
String
Document
Profiler

While using getDeclaredMethod I am required to give the method argument type. If String's argument type is String.class, what should be done for Set<LineItems>? Should it be Set.class? (Keeping in mind that Set is an interface)

The function xyz is a default function in interface abc. This interface is being implemented in multiple other classes, so method should be reflected here only. Here is my code:

Class c = abc.getClass();

Class args[] = new Class[4];
args[0] = Set.class;
args[1] = String.class;
args[2] = Document.class;
args[3] = Profiler.class;

Method m = c.getMethod("xyz",args) ;

I'm getting the NoSuchMethodFoundException
I know there could be multiple flaws in this. Any help?


来源: stackexchange

问:
What does isLocal() actually do in Laravel?
I've been looking into Laravel Telescope and it mentioned the ability of being able to run only in one's local environment as opposed to production by including the following code snippet in AppServiceProvider.

```<code>public function register()
{
    if ($this->app->isLocal()) {
        $this->app->register(TelescopeServiceProvider::class);
    }
}
</code>```

This works fine but I am trying to figure out what exactly the isLocal() method does. So far, I have not been able to find much information.

Thanks,

答:
In your .env file you would have a APP_ENV set to local on your development environment and it will be different on other servers. So isLocal just checks if that is set to local or not.

Here is the answer from the repository.

To check for a different env other than local or production use this helper function:

```<code>config('app.env') // get the env
</code>```

for production there is a isProduction() helper function on the app instance.

ContentLicense: CC BY-SA 4.0

Body:
I've been looking into Laravel Telescope and it mentioned the ability of being able to run only in one's local environment as opposed to production by including the following code snippet in AppServiceProvider.

public function register()
{
    if ($this->app->isLocal()) {
        $this->app->register(TelescopeServiceProvider::class);
    }
}

This works fine but I am trying to figure out what exactly the isLocal() method does. So far, I have not been able to find much information.

Thanks,

Body:
In your .env file you would have a APP_ENV set to local on your development environment and it will be different on other servers. So isLocal just checks if that is set to local or not.

Here is the answer from the repository.

To check for a different env other than local or production use this helper function:

config('app.env') // get the env

for production there is a isProduction() helper function on the app instance.


问:
How to make a Python program automatically prints what matched after iterating through lists
I have this Python code:

```<code>with open('save.data') as fp:
    save_data = dict([line.split(' = ') for line in fp.read().splitlines()])

with open('brute.txt') as fp:
    brute = fp.read().splitlines()

for username, password in save_data.items():
    if username in brute:
        break
else:
    print("didn't find the username")
</code>```

Here is a quick explanation; the save.data is a file that contains variables of Batch-file game (such as username, hp etc...) and brute.txt is a file that contains "random" strings (like what seen in wordlists used for brute-force).

save.data:

```<code>username1 = PlayerName
password1 = PlayerPass
hp = 100
</code>```

As i said before, it's a Batch-file game so, no need to quote strings

brute.txt:

```<code>username
usrnm
username1
password
password1
health
hp
</code>```

So, let's assume that the Python file is a "game hacker" that "brute" a Batch-file's game save file in hope of finding matches and when it does find, it retrieves them and display them to the user.

```<code>## We did all the previous code
...
>>> print(save_data["username1"])
PlayerName

</code>```

Success! we retrieved the variables! But I want to make the program capable of displaying the variables it self (because I knew that "username1" was the match, that's why I chose to print it). What I mean is, I want to make the program print the variables that matched. E.g: If instead of "username1" in save.data there was "usrnm", it will surely get recognized after the "bruting" process because it's already in brute.txt. So, how to make the program print what matched? because I don't know if it's "username" or "username1" etc... The program does :p (of course without opening save.data) And of course that doesn't mean the program will search only for the username, it's a game and there should be other variables like gold/coins, hp etc... If you didn't understand something, kindly comment it and I will clear it up, and thanks for your time!

答:
Use a dict such as this:

```<code>with open('brute.txt', 'r') as f:
    # First get all the brute file stuff
    lookup_dic = {word.strip(): None for word in f.readlines()}
with open('save.data', 'r') as f:
    # Update that dict with the stuff from the save.data
    lines = (line.strip().split(' = ') for line in f.readlines())
    for lookup, val in lines:
        if lookup in lookup_dic:
            print(f"{lookup} matched and its value is {val}")
            lookup_dic[lookup] = val
# Now you have a complete lookup table.
print(lookup_dic)
print(lookup_dic['hp'])
</code>```

Output:

```<code>username1 matched and its value is PlayerName
password1 matched and its value is PlayerPass
hp matched and its value is 100
{'username': None, 'usrnm': None, 'username1': 'PlayerName', 'password': None, 'password1': 'PlayerPass','health': None, 'hp': '100'}
100
</code>```

Body:
I have this Python code:

with open('save.data') as fp:
    save_data = dict([line.split(' = ') for line in fp.read().splitlines()])

with open('brute.txt') as fp:
    brute = fp.read().splitlines()

for username, password in save_data.items():
    if username in brute:
        break
else:
    print("didn't find the username")

Here is a quick explanation; the save.data is a file that contains variables of Batch-file game (such as username, hp etc...) and brute.txt is a file that contains "random" strings (like what seen in wordlists used for brute-force).

save.data:

username1 = PlayerName
password1 = PlayerPass
hp = 100

As i said before, it's a Batch-file game so, no need to quote strings

brute.txt:

username
usrnm
username1
password
password1
health
hp

So, let's assume that the Python file is a "game hacker" that "brute" a Batch-file's game save file in hope of finding matches and when it does find, it retrieves them and display them to the user.

## We did all the previous code
...
>>> print(save_data["username1"])
PlayerName

Success! we retrieved the variables! But I want to make the program capable of displaying the variables it self (because I knew that "username1" was the match, that's why I chose to print it). What I mean is, I want to make the program print the variables that matched. E.g: If instead of "username1" in save.data there was "usrnm", it will surely get recognized after the "bruting" process because it's already in brute.txt. So, how to make the program print what matched? because I don't know if it's "username" or "username1" etc... The program does :p (of course without opening save.data) And of course that doesn't mean the program will search only for the username, it's a game and there should be other variables like gold/coins, hp etc... If you didn't understand something, kindly comment it and I will clear it up, and thanks for your time!

Body:
Use a dict such as this:

with open('brute.txt', 'r') as f:
    # First get all the brute file stuff
    lookup_dic = {word.strip(): None for word in f.readlines()}
with open('save.data', 'r') as f:
    # Update that dict with the stuff from the save.data
    lines = (line.strip().split(' = ') for line in f.readlines())
    for lookup, val in lines:
        if lookup in lookup_dic:
            print(f"{lookup} matched and its value is {val}")
            lookup_dic[lookup] = val
# Now you have a complete lookup table.
print(lookup_dic)
print(lookup_dic['hp'])

Output:

username1 matched and its value is PlayerName
password1 matched and its value is PlayerPass
hp matched and its value is 100
{'username': None, 'usrnm': None, 'username1': 'PlayerName', 'password': None, 'password1': 'PlayerPass','health': None, 'hp': '100'}
100


问:
How to get original image using PHImageManager
I am using below code to get original image from PHAsset:

```<code>PHImageRequestOptions *requestOptions = [[PHImageRequestOptions alloc] init];
requestOptions.resizeMode   = PHImageRequestOptionsResizeModeNone;
requestOptions.deliveryMode = PHImageRequestOptionsDeliveryModeHighQualityFormat;

[[PHImageManager defaultManager] requestImageForAsset:phasset
                                                                   targetSize:PHImageManagerMaximumSize
                                                                  contentMode:PHImageContentModeDefault
                                                                      options:requestOptions
                                                                resultHandler:^void(UIImage *image, NSDictionary *info) {
                                                                    if (image) {
                                                                                }
}];
</code>```

But found that, image size is greater than the original size. I picked 54 MB file but found its size 123.5MB in response.
Using below code to calculate image size:

```<code>NSData *imgData = UIImageJPEGRepresentation(image, 1.0);
NSLog(@"img size: %@", [[NSByteCountFormatter new] stringFromByteCount:imgData.length]);
</code>```

Any idea how to get an original image using  [[PHImageManager defaultManager] requestImageForAsset: API.

答:
Use following code to get original image. I have code in Swift, you should convert it to Objective-C

```<code>PHImageManager.default().requestImage(for: phAssets.firstObject!, targetSize: PHImageManagerMaximumSize, contentMode: PHImageContentMode.default, options: requestOption) { (image, dictResult) in

    // Get file path url of original image.
    if let url = dictResult!["PHImageFileURLKey"] as? URL {
        self.getImageFromFileUrl(url)
    }
}

func getImageFromFileUrl(_ fileUrl: URL) {

    // Get dat from url, here I have not using catch block, you must use it for swift.
    let imageData = try? Data(contentsOf: fileUrl)

    // Get image from data
    let image = UIImage(data: imageData!)

    // Size count, which is same as original image
    let size = ByteCountFormatter()
    print("image size = \(size.string(fromByteCount: Int64(imageData!.count)))")
}
</code>```

For details, I have added comment above the line of code.

I hope this will help you.

Body:
I am using below code to get original image from PHAsset:

PHImageRequestOptions *requestOptions = [[PHImageRequestOptions alloc] init];
requestOptions.resizeMode   = PHImageRequestOptionsResizeModeNone;
requestOptions.deliveryMode = PHImageRequestOptionsDeliveryModeHighQualityFormat;

[[PHImageManager defaultManager] requestImageForAsset:phasset
                                                                   targetSize:PHImageManagerMaximumSize
                                                                  contentMode:PHImageContentModeDefault
                                                                      options:requestOptions
                                                                resultHandler:^void(UIImage *image, NSDictionary *info) {
                                                                    if (image) {
                                                                                }
}];

But found that, image size is greater than the original size. I picked 54 MB file but found its size 123.5MB in response.
Using below code to calculate image size:

NSData *imgData = UIImageJPEGRepresentation(image, 1.0);
NSLog(@"img size: %@", [[NSByteCountFormatter new] stringFromByteCount:imgData.length]);

Any idea how to get an original image using  [[PHImageManager defaultManager] requestImageForAsset: API.

Body:
Use following code to get original image. I have code in Swift, you should convert it to Objective-C

PHImageManager.default().requestImage(for: phAssets.firstObject!, targetSize: PHImageManagerMaximumSize, contentMode: PHImageContentMode.default, options: requestOption) { (image, dictResult) in

    // Get file path url of original image.
    if let url = dictResult!["PHImageFileURLKey"] as? URL {
        self.getImageFromFileUrl(url)
    }
}

func getImageFromFileUrl(_ fileUrl: URL) {

    // Get dat from url, here I have not using catch block, you must use it for swift.
    let imageData = try? Data(contentsOf: fileUrl)

    // Get image from data
    let image = UIImage(data: imageData!)

    // Size count, which is same as original image
    let size = ByteCountFormatter()
    print("image size = \(size.string(fromByteCount: Int64(imageData!.count)))")
}

For details, I have added comment above the line of code.

I hope this will help you.


问:
How can nomad' job from local docker images
nomad docker image will be fetched from Docker Hub.But I have want use some local images.How can I use theme.(I dont want to use private repo)

Example I want to use local image test

> docker images
REPOSITORY                         TAG                 IMAGE ID            CREATED             SIZE
test                        latest              da795ca8a32f        36 minutes ago      567MB
```

```job "test" {
  datacenters = ["dc1"]

  group "example" {
    task "test" {
      driver = "docker"

      config {
        image = "test"
      }

      resources {
        cpu = 500
        memory = 256
      }
    }
  }
}

```

It's wrong !

答:
Looking at Nomad's source code here and here, it seems that using machine local images is not supported. That would make sense, as in a cluster environment with several nodes, the scheduler needs to be able to get the image irrespective of which machine the job is allocated to.

(One possible workaround would be to run a registry service within the Nomad cluster, and use whichever storage backend is most convenient for you)

Body:
nomad docker image will be fetched from Docker Hub.But I have want use some local images.How can I use theme.(I dont want to use private repo)

Example I want to use local image test

> docker images
REPOSITORY                         TAG                 IMAGE ID            CREATED             SIZE
test                        latest              da795ca8a32f        36 minutes ago      567MB

job "test" {
  datacenters = ["dc1"]

  group "example" {
    task "test" {
      driver = "docker"

      config {
        image = "test"
      }

      resources {
        cpu = 500
        memory = 256
      }
    }
  }
}

It's wrong !


问:
Why can't I locate ProgressiveMediaSource?
Looking at the ExoPlayer documentation, the "Hello World" example suggests that to play a standard video you should use a ProgressiveMediaSource (compared to many online tutorials I've seen suggesting you use an ExtractorMediaSource)

Looking at the source code for ExoPlayer, it claims that ExtractorMediaSource is deprecated, and ProgressiveMediaSource has replaced it:

```<code>/** @deprecated Use {@link ProgressiveMediaSource} instead. */
</code>```

In my own project I'm using ExoPlayer v2.9.5 -- which is the latest version on jcenter, released February 2019

Yet when I try to instantiate a ProgressiveMediaSource, I get the error:

```<code>Cannot resolve symbol 'ProgressiveMediaSource'
</code>```

Why can I not locate this class? What am I doing wrong?

答:
I found that by clicking on this tab, newer versions of ExoPlayer were listed.

ProgressiveMediaSource was added in version 2.10.0

However version 2.10.0 also made the switch from the Android Support Library to AndroidX, so you will have to upgrade your whole project to AndroidX if you wish to use it.

Body:
Looking at the ExoPlayer documentation, the "Hello World" example suggests that to play a standard video you should use a ProgressiveMediaSource (compared to many online tutorials I've seen suggesting you use an ExtractorMediaSource)

Looking at the source code for ExoPlayer, it claims that ExtractorMediaSource is deprecated, and ProgressiveMediaSource has replaced it:

/** @deprecated Use {@link ProgressiveMediaSource} instead. */

In my own project I'm using ExoPlayer v2.9.5 -- which is the latest version on jcenter, released February 2019

Yet when I try to instantiate a ProgressiveMediaSource, I get the error:

Cannot resolve symbol 'ProgressiveMediaSource'

Why can I not locate this class? What am I doing wrong?


问:
When I run this code I get error admin is not defined
How to retrieve user list from fire base authentication? I want to retrieve all register user list. When I'm using listAllUsers()-function, I get a message that "admin is not defined".

I'm using this function:

```<code>function listAllUsers(nextPageToken) {
  admin.auth().listUsers(1000, nextPageToken)
    .then(function(listUsersResult) {
        listUsersResult.users.forEach(function(userRecord) {
            console.log('user', userRecord.toJSON());
        });
        if (listUsersResult.pageToken) {
            listAllUsers(listUsersResult.pageToken);
        }
    })
    .catch(function(error) {
          console.log('Error listing users:', error);
    });
}
</code>```

答:
There is no API to get a list of all users from Firebase Authentication for use in a web page. If you want to show a list of users in your web page, you will either have to store that list in a database you can access from the web page (like the Firebase Realtime Database or Cloud Firestore), or use the Firebase Admin SDK in a trusted environment (such as a server you control, or Cloud Functions), and to build your own API, and then call that API from your web page.

See these previous questions for more on this:

How to programmatically get the list of registered users in Firebase

How do I return a list of users if I use the Firebase simple username & password authentication

Retrieving a list of users who have registered using Firebase Auth

Body:
How to retrieve user list from fire base authentication? I want to retrieve all register user list. When I'm using listAllUsers()-function, I get a message that "admin is not defined".

I'm using this function:

function listAllUsers(nextPageToken) {
  admin.auth().listUsers(1000, nextPageToken)
    .then(function(listUsersResult) {
        listUsersResult.users.forEach(function(userRecord) {
            console.log('user', userRecord.toJSON());
        });
        if (listUsersResult.pageToken) {
            listAllUsers(listUsersResult.pageToken);
        }
    })
    .catch(function(error) {
          console.log('Error listing users:', error);
    });
}


问:
Swift scrollview adding from XIB not scrollable at all
I'm trying to import from Xib full screen ScrollView into my ViewController.

Following that guide i've made many working examples of it, but when importing it from Xib, ScrollView not responding on scroll (not even bouncing)

My Xib View class:

```<code>class TestScroll: UIView {

override init(frame: CGRect) {
    super.init(frame: frame)
}

required init?(coder aDecoder: NSCoder) {
    super.init(coder: aDecoder)
}

override func awakeFromNib() {
    super.awakeFromNib()

    self.translatesAutoresizingMaskIntoConstraints = false
}

public static func getViewFromNib() -> TestScroll {
    return UINib(nibName: "TestScroll", bundle: .main).instantiate(withOwner: nil, options: nil).first as! TestScroll
    }
}
</code>```

And this is how i adding it in ViewController:

```<code>override func viewDidLoad() {
    super.viewDidLoad()

    let testScroll = TestScroll.getViewFromNib()
    self.view.addSubview(testScroll)
}
</code>```

Please help, i've checked many guides already, but not found working example with Xib.

答:
You need to set a frame / constraints

```<code>let testScroll = TestScroll.getViewFromNib()
testScroll.frame = self.view.bounds
self.view.addSubview(testScroll)
</code>```

leave this

```<code>self.translatesAutoresizingMaskIntoConstraints = false
</code>```

only if you'll set constraints

Body:
I'm trying to import from Xib full screen ScrollView into my ViewController.

Following that guide i've made many working examples of it, but when importing it from Xib, ScrollView not responding on scroll (not even bouncing)

My Xib View class:

class TestScroll: UIView {

override init(frame: CGRect) {
    super.init(frame: frame)
}

required init?(coder aDecoder: NSCoder) {
    super.init(coder: aDecoder)
}

override func awakeFromNib() {
    super.awakeFromNib()

    self.translatesAutoresizingMaskIntoConstraints = false
}

public static func getViewFromNib() -> TestScroll {
    return UINib(nibName: "TestScroll", bundle: .main).instantiate(withOwner: nil, options: nil).first as! TestScroll
    }
}

And this is how i adding it in ViewController:

override func viewDidLoad() {
    super.viewDidLoad()

    let testScroll = TestScroll.getViewFromNib()
    self.view.addSubview(testScroll)
}

Please help, i've checked many guides already, but not found working example with Xib.

Body:
You need to set a frame / constraints

let testScroll = TestScroll.getViewFromNib()
testScroll.frame = self.view.bounds
self.view.addSubview(testScroll)

leave this

self.translatesAutoresizingMaskIntoConstraints = false

only if you'll set constraints


问:
$match in $lookup result
I have next mongo code:

```<code>db.users.aggregate([
    {
        $match: {
            $and: [
                { UserName: { $eq: 'administrator' } },
                { 'Company.CompanyName': { $eq: 'test' } }
            ]
        }
    },
    {
        $lookup: {
            from: "companies",
            localField: "CompanyID",
            foreignField: "CompanyID",
            as: "Company"
        }
    },
])
</code>```

The $lookup part of the code working great. I got next result:

But if I add $match to the code, it brings nothing.

I found that the problem is in the second match:  { 'Company.CompanyName': { $eq: 'test' } }, but I can not realize what is wrong with it.
Any ideas?

UPDATE:

I had also tried $unwind on the $lookup result, but no luck:

```<code>db.users.aggregate([
    {
        $match: {
            $and: [
                { UserName: { $eq: 'administrator' } },
                { 'Company.CompanyName': { $eq: 'edt5' } }
            ]
        }
    },
    {   unwind: '$Company' },
    {
        $lookup: {
            from: 'companies',
            localField: 'CompanyID',
            foreignField: 'CompanyID',
            as: 'Company'
        }
    },
])
</code>```

答:
Below answer is for mongoDB 3.6 or later.

Given that:

You have a collection users with a field CompanyID and a collection of companies with a field CompanyID

you want to lookup Companies on Users by matching CompanyID, where additionally:

each User must match condition: User.UserName equals administrator

each Company on User must match condition: CompanyName equals edt5

The following query will work for you:

```<code>  db.users.aggregate([
    { $match: { UserName: 'administrator' } },
    {
      $lookup: {
        from: 'companies',
        as: 'Company',
        let: { CompanyID: '$CompanyID' },
        pipeline: [
          {
            $match: {
              $expr: {
                $and: [
                  { $eq: ['$CompanyID', '$$CompanyID'] },
                  { $eq: ['$CompanyName', 'edt5'] },
                ]
              }
            }
          }
        ]
      }
    },
  ])
</code>```

Explanation:
This is the way to perform left join queries with conditions more complex than simple foreign / local field equality match.

Instead of using localField and foreignField, you use:

let option where you can map local fields to variables,

pipeline option where you can specify aggregation Array.

In pipeline you can use $match filter, with $expr, where you can reuse variables defined earlier in let.

More info on $lookup

Nice tutorial

ContentLicense: CC BY-SA 3.0

Title: $match in $lookup result

Body:
I have next mongo code:

db.users.aggregate([
    {
        $match: {
            $and: [
                { UserName: { $eq: 'administrator' } },
                { 'Company.CompanyName': { $eq: 'test' } }
            ]
        }
    },
    {
        $lookup: {
            from: "companies",
            localField: "CompanyID",
            foreignField: "CompanyID",
            as: "Company"
        }
    },
])

The $lookup part of the code working great. I got next result:

But if I add $match to the code, it brings nothing.

I found that the problem is in the second match:  { 'Company.CompanyName': { $eq: 'test' } }, but I can not realize what is wrong with it.
Any ideas?

UPDATE:

I had also tried $unwind on the $lookup result, but no luck:

db.users.aggregate([
    {
        $match: {
            $and: [
                { UserName: { $eq: 'administrator' } },
                { 'Company.CompanyName': { $eq: 'edt5' } }
            ]
        }
    },
    {   unwind: '$Company' },
    {
        $lookup: {
            from: 'companies',
            localField: 'CompanyID',
            foreignField: 'CompanyID',
            as: 'Company'
        }
    },
])

Body:
Below answer is for mongoDB 3.6 or later.

Given that:

You have a collection users with a field CompanyID and a collection of companies with a field CompanyID

you want to lookup Companies on Users by matching CompanyID, where additionally:

each User must match condition: User.UserName equals administrator

each Company on User must match condition: CompanyName equals edt5

The following query will work for you:

  db.users.aggregate([
    { $match: { UserName: 'administrator' } },
    {
      $lookup: {
        from: 'companies',
        as: 'Company',
        let: { CompanyID: '$CompanyID' },
        pipeline: [
          {
            $match: {
              $expr: {
                $and: [
                  { $eq: ['$CompanyID', '$$CompanyID'] },
                  { $eq: ['$CompanyName', 'edt5'] },
                ]
              }
            }
          }
        ]
      }
    },
  ])

Explanation:
This is the way to perform left join queries with conditions more complex than simple foreign / local field equality match.

Instead of using localField and foreignField, you use:

let option where you can map local fields to variables,

pipeline option where you can specify aggregation Array.

In pipeline you can use $match filter, with $expr, where you can reuse variables defined earlier in let.

More info on $lookup

Nice tutorial


问:
Scala.Byte vs java.lang.Byte -Which one is recomended to use?
I was wondering which of the two possibilities is preferred. In my opinion they do more or less the same.
What are the reasons why there are two implementation?
Are there differences in the performance or functionality?</p>

答:
In my opinion they do more or less the same.

It's quite the same. Scala compiler compiles to Java bytecode, just like the Java compiler also compiles to JVM bytecode. A scala.Byte will therefore result in the same bytecode as the usage of java.lang.Byte.

What are the reasons why there are two implementation?

"Scala runs on the JVM, so Java and Scala stacks can be freely mixed for totally seamless integration." This is how Scala is described on https://www.scala-lang.org/. So there are not really two implementations within Scala. You are just provided with the ability to use things from Java if you like / have to.

Are there differences in the performance or functionality

As mentioned above, you can consider them on byte code level as equal. However, they are at least diffrent in usage. If you write your Scala code like you would in Java, you can expect the same performance.

Which one is recomended to use?

If you can, use the Scala implementation. Simply because you'll not leave the "Scala world" and therefore benefit from potential improvements made by the language.


问:
R data.table values depending on previous row
I am trying to solve the problem proposed here. Basically what I need is, for each row of the data.table, take the values of each variable in the previous row and use them to define the variable values in the following row.

I have tried using data.table, but the result is quite bulky and I believe extremely inefficient (especially for a big number of rows). I also tried using the shift() function, but could not fit it in my temporary solution.

Here is a toy example:

library(data.table)
DT = data.table(a = numeric(10L), b = numeric(10L), c = numeric(10L), iter = 1:10)

for(i in DT[,.I]){

  DT[i, c('a','b','c') := {
    if(iter == 1) {
      a = 1
      b = 2
      c = 3
    } else { # if it is not the first iteration
      a = DT[i-1, a + b] # read the values from the previous row to compute the new values
      b = DT[i-1, b] - a
      c = a / b + DT[i-1, c]
    }

    .(a, b, c)
  }]

}
```

<p>and here's the output:</p>

```     a  b          c iter
 1:  1  2  3.0000000    1
 2:  3 -1  0.0000000    2
 3:  2 -3 -0.6666667    3
 4: -1 -2 -0.1666667    4
 5: -3  1 -3.1666667    5
 6: -2  3 -3.8333333    6
 7:  1  2 -3.3333333    7
 8:  3 -1 -6.3333333    8
 9:  2 -3 -7.0000000    9
10: -1 -2 -6.5000000   10
```

Can someone help me improve the code?

答:
You can use Reduce with acumulate = T

```<code>fun <- function(x, junk){
 x[1] <- sum(x[1:2])
 x[2] <- diff(x[1:2])
 x[3] <- x[1]/x[2] + x[3]
 x
}

dt <-
  as.data.table(do.call(rbind, Reduce(fun, numeric(9L), accumulate = T, init = 1:3)))

setnames(dt, c('a', 'b', 'c'))

dt
#      a  b          c
#  1:  1  2  3.0000000
#  2:  3 -1  0.0000000
#  3:  2 -3 -0.6666667
#  4: -1 -2 -0.1666667
#  5: -3  1 -3.1666667
#  6: -2  3 -3.8333333
#  7:  1  2 -3.3333333
#  8:  3 -1 -6.3333333
#  9:  2 -3 -7.0000000
# 10: -1 -2 -6.5000000
</code>```

You can use transpose instead of do.call(rbind, as below, but if you have tidyverse or purrr loaded, make sure transpose is data.table::transpose

```<code>dt <-
  as.data.table(transpose(Reduce(fun, numeric(9L), accumulate = T, init = 1:3)))
</code>```

Explanation for junk:

Each iteration, Reduce passes the previous output (or init) as well as the i-th element of its x argument, to f. So even if you're not going to use the x argument of Reduce in your function f you still need to have an argument for it. If you don't add this extra "junk" argument, you get an "unused argument" error when it runs because it tries to add the extra argument to f, but f only has one argument.

Body:
I am trying to solve the problem proposed here. Basically what I need is, for each row of the data.table, take the values of each variable in the previous row and use them to define the variable values in the following row.

I have tried using data.table, but the result is quite bulky and I believe extremely inefficient (especially for a big number of rows). I also tried using the shift() function, but could not fit it in my temporary solution.

Here is a toy example:

library(data.table)
DT = data.table(a = numeric(10L), b = numeric(10L), c = numeric(10L), iter = 1:10)

for(i in DT[,.I]){

  DT[i, c('a','b','c') := {
    if(iter == 1) {
      a = 1
      b = 2
      c = 3
    } else { # if it is not the first iteration
      a = DT[i-1, a + b] # read the values from the previous row to compute the new values
      b = DT[i-1, b] - a
      c = a / b + DT[i-1, c]
    }

    .(a, b, c)
  }]

}

and here's the output:

     a  b          c iter
 1:  1  2  3.0000000    1
 2:  3 -1  0.0000000    2
 3:  2 -3 -0.6666667    3
 4: -1 -2 -0.1666667    4
 5: -3  1 -3.1666667    5
 6: -2  3 -3.8333333    6
 7:  1  2 -3.3333333    7
 8:  3 -1 -6.3333333    8
 9:  2 -3 -7.0000000    9
10: -1 -2 -6.5000000   10

Can someone help me improve the code?

Body:
You can use Reduce with acumulate = T

fun <- function(x, junk){
 x[1] <- sum(x[1:2])
 x[2] <- diff(x[1:2])
 x[3] <- x[1]/x[2] + x[3]
 x
}

dt <-
  as.data.table(do.call(rbind, Reduce(fun, numeric(9L), accumulate = T, init = 1:3)))

setnames(dt, c('a', 'b', 'c'))

dt
#      a  b          c
#  1:  1  2  3.0000000
#  2:  3 -1  0.0000000
#  3:  2 -3 -0.6666667
#  4: -1 -2 -0.1666667
#  5: -3  1 -3.1666667
#  6: -2  3 -3.8333333
#  7:  1  2 -3.3333333
#  8:  3 -1 -6.3333333
#  9:  2 -3 -7.0000000
# 10: -1 -2 -6.5000000

You can use transpose instead of do.call(rbind, as below, but if you have tidyverse or purrr loaded, make sure transpose is data.table::transpose

dt <-
  as.data.table(transpose(Reduce(fun, numeric(9L), accumulate = T, init = 1:3)))

Explanation for junk:

Each iteration, Reduce passes the previous output (or init) as well as the i-th element of its x argument, to f. So even if you're not going to use the x argument of Reduce in your function f you still need to have an argument for it. If you don't add this extra "junk" argument, you get an "unused argument" error when it runs because it tries to add the extra argument to f, but f only has one argument.


问:
how to eliminate 3 letter words or 4 letter words from a column of a dataframe
I have a dataframe  as below:

```<code>import pandas as pd
import dask.dataframe as dd
a = {'b':['category','categorical','cater pillar','coming and going','bat','No Data','calling','cal'],
     'c':['strd1','strd2','strd3', 'strd4','strd5','strd6','strd7', 'strd8']
    }
df11 = pd.DataFrame(a,index=['x1','x2','x3','x4','x5','x6','x7','x8'])
</code>```

I wanted to remove words whose length of each value is three.
I expect results to be like:

```<code>   b                         c
category                   strd1
categorical                strd2
cater pillar               strd3
coming and going           strd4
NaN                        strd5
No Data                    strd6
calling                    strd7
NaN                        strd8
</code>```

答:
Maybe check mask

```<code>df11.b.mask(df11.b.str.len()<=3,inplace=True)
df11
Out[16]:
                   b      c
x1          category  strd1
x2       categorical  strd2
x3      cater pillar  strd3
x4  coming and going  strd4
x5               NaN  strd5
x6           No Data  strd6
x7           calling  strd7
x8               NaN  strd8
</code>```

Body:
I have a dataframe  as below:

import pandas as pd
import dask.dataframe as dd
a = {'b':['category','categorical','cater pillar','coming and going','bat','No Data','calling','cal'],
     'c':['strd1','strd2','strd3', 'strd4','strd5','strd6','strd7', 'strd8']
    }
df11 = pd.DataFrame(a,index=['x1','x2','x3','x4','x5','x6','x7','x8'])

I wanted to remove words whose length of each value is three.
I expect results to be like:

   b                         c
category                   strd1
categorical                strd2
cater pillar               strd3
coming and going           strd4
NaN                        strd5
No Data                    strd6
calling                    strd7
NaN                        strd8

Body:
Maybe check mask

df11.b.mask(df11.b.str.len()<=3,inplace=True)
df11
Out[16]:
                   b      c
x1          category  strd1
x2       categorical  strd2
x3      cater pillar  strd3
x4  coming and going  strd4
x5               NaN  strd5
x6           No Data  strd6
x7           calling  strd7
x8               NaN  strd8


问:
Calculate rate by group with sapply
I have a data like this:

This is just a fake data I create:

```<code># dt
Col1      Col2   Col3   Col4
2014/1/1  A        10   1
2014/4/1  A        15   1.5
2015/1/1  A        15   3
2015/4/1  A        30   4
2014/1/1  B        20   2
2014/4/1  B        30   6
2015/1/1  B        40   10
2015/4/1  B        80   16
</code>```

What I want:

```<code>Col1      Col2   Col3   Col4   Col3.R   Col4.R
2014/1/1  A        10   1      1        1
2014/4/1  A        15   1.5    1.5      1.5
2015/1/1  A        15   3      1.5      3
2015/4/1  A        30   4      3        4
2014/1/1  B        20   2      1        1
2014/4/1  B        30   6      3/2      3
2015/1/1  B        40   10     2        5
2015/4/1  B        80   16     4        8
</code>```

The new column Col3.R is calculated by the value of col3 under each group Col2 divide the first value in each group. Same as col4.R.

I try the code below:

```<code>dt[, sapply(.SD, function(x) R = x / x[1]), .SDcols = 3:4, by = .(Col2)]
</code>```

How to keep the original columns? Do I need to use argument on for data.table?

Data:

```<code>dt <- fread("    Col1      Col2   Col3   Col4
2014/1/1  A        10   1
2014/4/1  A        15   1.5
2015/1/1  A        15   3
2015/4/1  A        30   4
2014/1/1  B        20   2
2014/4/1  B        30   6
2015/1/1  B        40   10
2015/4/1  B        80   16", header = T)
dt$Col3 <- as.numeric(dt$Col3)
</code>```

Title: Calculate rate by group with sapply

Body:
I have a data like this:

This is just a fake data I create:

# dt
Col1      Col2   Col3   Col4
2014/1/1  A        10   1
2014/4/1  A        15   1.5
2015/1/1  A        15   3
2015/4/1  A        30   4
2014/1/1  B        20   2
2014/4/1  B        30   6
2015/1/1  B        40   10
2015/4/1  B        80   16

What I want:

Col1      Col2   Col3   Col4   Col3.R   Col4.R
2014/1/1  A        10   1      1        1
2014/4/1  A        15   1.5    1.5      1.5
2015/1/1  A        15   3      1.5      3
2015/4/1  A        30   4      3        4
2014/1/1  B        20   2      1        1
2014/4/1  B        30   6      3/2      3
2015/1/1  B        40   10     2        5
2015/4/1  B        80   16     4        8

The new column Col3.R is calculated by the value of col3 under each group Col2 divide the first value in each group. Same as col4.R.

I try the code below:

dt[, sapply(.SD, function(x) R = x / x[1]), .SDcols = 3:4, by = .(Col2)]

How to keep the original columns? Do I need to use argument on for data.table?

Data:

dt <- fread("    Col1      Col2   Col3   Col4
2014/1/1  A        10   1
2014/4/1  A        15   1.5
2015/1/1  A        15   3
2015/4/1  A        30   4
2014/1/1  B        20   2
2014/4/1  B        30   6
2015/1/1  B        40   10
2015/4/1  B        80   16", header = T)
dt$Col3 <- as.numeric(dt$Col3)

Body:
We can group by 'Col2', specify the columns of interest in .SDcols, loop through the Subset of Data.table and divide by the first element of x

dt[, paste0(names(dt)[3:4],  ".R") :=
    lapply(.SD, function(x) x/first(x)), .SDcols = 3:4, by = .(Col2)]
dt
#       Col1 Col2 Col3 Col4 Col3.R Col4.R
#1: 2014/1/1    A   10  1.0    1.0    1.0
#2: 2014/4/1    A   15  1.5    1.5    1.5
#3: 2015/1/1    A   15  3.0    1.5    3.0
#4: 2015/4/1    A   30  4.0    3.0    4.0
#5: 2014/1/1    B   20  2.0    1.0    1.0
#6: 2014/4/1    B   30  6.0    1.5    3.0
#7: 2015/1/1    B   40 10.0    2.0    5.0
#8: 2015/4/1    B   80 16.0    4.0    8.0

Or using tidyverse

library(tidyverse)
dt %>%
    group_by(Col2) %>%
    mutate_at(3:4, list(R = ~ ./first(.)))
# A tibble: 8 x 6
# Groups:   Col2 [2]
#  Col1     Col2   Col3  Col4 Col3_R Col4_R
#  <chr>    <chr> <dbl> <dbl>  <dbl>  <dbl>
#1 2014/1/1 A        10   1      1      1
#2 2014/4/1 A        15   1.5    1.5    1.5
#3 2015/1/1 A        15   3      1.5    3
#4 2015/4/1 A        30   4      3      4
#5 2014/1/1 B        20   2      1      1
#6 2014/4/1 B        30   6      1.5    3
#7 2015/1/1 B        40  10      2      5
#8 2015/4/1 B        80  16      4      8


问:
How can i add class for div inside of javascript function
guys I need to add a class for div inside of a javascript function. I wanna put a box every agency_name, ADRESS_TEXT and  phone  How can I do this

```<code>  function jsFilt(value) {
                   document.getElementById("myDiv").innerHTML = "";
                    value.AGENCY.forEach(agency => {
                        $("#myDiv").append(
                       //HERE     "<div class ="xxx" style='border-style:ridge' ><strong>Agency Name :</strong>  " + agency.agency_name + "<br>" +
                            "<strong>Adress : </strong> " + agency.ADRESS_TEXT + "<br> "+
                            "<strong>Phone :</strong>  " + agency.phone + "<br></div>"
                        );
                    });
                }
</code>```

CSS

```<code>.xxx{
    width: 220px;
    padding: 10px;
    border: 5px solid gray;
    margin: 0px;
}
</code>```

答:
You can addClass to the div after the append like:</p>

```<code>    function jsFilt(value) {
                   document.getElementById("myDiv").innerHTML = "";
                    value.AGENCY.forEach(agency => {
                        $("#myDiv").append(
                            "<strong>Adress : </strong> " + agency.ADRESS_TEXT + "<br> "+
                            "<strong>Phone :</strong>  " + agency.phone + "<br></div>"
                        ).addClass("CLASSNAME1 CLASSNAME2");
                    });
                }
</code>```

Body:
guys I need to add a class for div inside of a javascript function. I wanna put a box every agency_name, ADRESS_TEXT and  phone  How can I do this

  function jsFilt(value) {
                   document.getElementById("myDiv").innerHTML = "";
                    value.AGENCY.forEach(agency => {
                        $("#myDiv").append(
                       //HERE     "
Agency Name :  " + agency.agency_name + "
" +
                            "Adress :  " + agency.ADRESS_TEXT + "
 "+
                            "Phone :  " + agency.phone + "

"
                        );
                    });
                }

CSS

.xxx{
    width: 220px;
    padding: 10px;
    border: 5px solid gray;
    margin: 0px;
}

Body:
You can addClass to the div after the append like:

    function jsFilt(value) {
                   document.getElementById("myDiv").innerHTML = "";
                    value.AGENCY.forEach(agency => {
                        $("#myDiv").append(
                            "<strong>Adress : </strong> " + agency.ADRESS_TEXT + "<br> "+
                            "<strong>Phone :</strong>  " + agency.phone + "<br></div>"
                        ).addClass("CLASSNAME1 CLASSNAME2");
                    });
                }


问:
Run Spring Batch (JSR-352) application on Spring Boot
I have a simple Spring Batch application complying with JSR-352.

I need to deploy this as a managed Task on Spring Cloud Data Flow server. As far as I know - to be able to deploy this as a Task I need to convert this application as a Spring Boot app.

I have tried to add Spring Boot dependencies and Main class however it is not running the Batch job when I start the app.

Main Class

```<code>@SpringBootConfiguration
@EnableAutoConfiguration
@EnableBatchProcessing
public class Application {

    public static void main(String[] args) {
        SpringApplication.run(Application.class, args);
    }

}
</code>```

Batch File created at

```<code>META-INF/batch-jobs/myjob.xml
</code>```

It works when I use JobOperator in the main class to start the job (without Spring Boot).

What am I missing to run this as a Spring Boot app?

答:
You're missing @EnableTask annotation. With that, your batch-job will be run as a short-lived application. In other words, the application will run as long as the business logic in your XML needs to run, and it will gracefully shut down and free-up resources.

Please clone and try out the Spring Cloud Task samples [see: BatchJobApplication]. All of them should work as-is in SCDF as well.

Body:
I have a simple Spring Batch application complying with JSR-352.

I need to deploy this as a managed Task on Spring Cloud Data Flow server. As far as I know - to be able to deploy this as a Task I need to convert this application as a Spring Boot app.

I have tried to add Spring Boot dependencies and Main class however it is not running the Batch job when I start the app.

Main Class

@SpringBootConfiguration
@EnableAutoConfiguration
@EnableBatchProcessing
public class Application {

    public static void main(String[] args) {
        SpringApplication.run(Application.class, args);
    }

}

Batch File created at

META-INF/batch-jobs/myjob.xml

It works when I use JobOperator in the main class to start the job (without Spring Boot).

What am I missing to run this as a Spring Boot app?


问:
How to add external fonts to android application
I was looking for some stylish fonts for my android application. but the problem is how can i make my android application supportable for external fonts.

Thank you.

答:
The easiest way to accomplish this is to package the desired font(s)
  with your application. To do this, simply create an assets/ folder in
  the project root, and put your fonts (in TrueType, or TTF, form) in
  the assets. You might, for example, create assets/fonts/ and put your
  TTF files in there.

Then, you need to tell your widgets to use that font. Unfortunately,
  you can no longer use layout XML for this, since the XML does not know
  about any fonts you may have tucked away as an application asset.
  Instead, you need to make the change in Java code, by calling
  Typeface.createFromAsset(getAssets(), “fonts/HandmadeTypewriter.ttf”),
  then taking the created Typeface object and passing it to your
  TextView via setTypeface().

For more reference here is the tutorial where I got this:

http://www.androidguys.com/2008/08/18/fun-with-fonts/


答:
Something like:</p>

```<code>for i, ele in enumerate(df11['b']):
    if len(ele) == 3:
        df11['b'][i] = np.nan
</code>```

Title: how to eliminate 3 letter words or 4 letter words from a column of a dataframe

Body:
Something like:

for i, ele in enumerate(df11['b']):
    if len(ele) == 3:
        df11['b'][i] = np.nan


问:
Photo Library and Camera are accessible after permission got denied
I'm currently working on an app where I need to access either the photo library or the camera (or even both, it's up to the user).

If I close the app and deny the access to both camera and library for the app.

After restarting my App, it's still possible to access both, I can open and use the camera or even pick a photo from the library.
How is this possible, I thought Apple would restrict the access.

答:
I dont think so. Apple always restrict use of camera or photo library if access is denied. Please use following code to check current status and verify it.</p>

```<code>    import Photos

    if type == .CAMERA{

        if AVCaptureDevice.authorizationStatus(forMediaType: AVMediaTypeVideo) ==  AVAuthorizationStatus.authorized {
            completionHander(true) //Allowed
        } else {
            //Dont Know
            AVCaptureDevice.requestAccess(forMediaType: AVMediaTypeVideo, completionHandler: { (granted: Bool) -> Void in
                completionHander(granted)
            })
        }
    }else{
        let status = PHPhotoLibrary.authorizationStatus()
        switch status {
        case .authorized:
            completionHander(true)//Allowed
            break
        case .denied, .restricted :
            completionHander(false)//Not Allowed
            break
        case .notDetermined:
            //Dont Know
            PHPhotoLibrary.requestAuthorization { status in
                switch status {
                case .authorized:
                    completionHander(true)
                    break
                case .denied, .restricted:
                    completionHander(false)
                    break
                case .notDetermined:
                    completionHander(false)
                    break
                }
            }
        }
    }
</code>```

Body:
I dont think so. Apple always restrict use of camera or photo library if access is denied. Please use following code to check current status and verify it.

    import Photos

    if type == .CAMERA{

        if AVCaptureDevice.authorizationStatus(forMediaType: AVMediaTypeVideo) ==  AVAuthorizationStatus.authorized {
            completionHander(true) //Allowed
        } else {
            //Dont Know
            AVCaptureDevice.requestAccess(forMediaType: AVMediaTypeVideo, completionHandler: { (granted: Bool) -> Void in
                completionHander(granted)
            })
        }
    }else{
        let status = PHPhotoLibrary.authorizationStatus()
        switch status {
        case .authorized:
            completionHander(true)//Allowed
            break
        case .denied, .restricted :
            completionHander(false)//Not Allowed
            break
        case .notDetermined:
            //Dont Know
            PHPhotoLibrary.requestAuthorization { status in
                switch status {
                case .authorized:
                    completionHander(true)
                    break
                case .denied, .restricted:
                    completionHander(false)
                    break
                case .notDetermined:
                    completionHander(false)
                    break
                }
            }
        }
    }


问:
React Native: TouchableOpacity onPress not triggering on when absolutely positioned with zIndex
I'm working on a React Native project and I'm struggling to get a TouchableOpacity to trigger it's press function when the element has the following CSS:

```<code>position: absolute;
z-index: 2;
</code>```

Below is the code:

```<code>import React from 'react';
import PropTypes from 'prop-types';
import styled from 'styled-components';
import { View } from 'react-native';

const StyledImage = styled.Image`
  height: 24px;
  width: 32px;
`;

const MenuContainer = styled.View`
  display: flex;
  position: absolute;
  background-color: #2d2d2d;
  height: ${Dimensions.get('screen').height};
  width: ${Dimensions.get('screen').width * 0.75};
  z-index: 2;
  margin-left: -8px;
  margin-top: -16px;
`;

const ProfileSectionContainer = styled.View`
  display: flex;
  flex-direction: row;
  justify-content: space-around;
  margin-bottom: 24px;
`;

const HeadingContainer = styled.View`
  display: flex;
  flex-direction: row;
  justify-content: space-between;
  padding: 20px;
`;

const CloseButton = styled(Body1)`
  font-size: 18px;
`;

const MenuItemsContainer = styled.View`
  padding: 0 20px;
`;

const SignOutContainer = styled.View`
  position: absolute;
  bottom: 100;
  flex: 1;
  left: 40%;
`;

const handleLogout = navigate => async () => {
  await logout()
  redirectToLogin(navigate)();
};

const toggleIsOpen = (isOpen, setIsOpen) => () => setIsOpen(!isOpen);

const Menu = ({ isOpen, setIsOpen, navigate }) => (
  <MenuContainer>
    <HeadingContainer>
      <View>
        <Body1 color="#fff">New App</Body1>
      </View>
      <View>
        <TouchableOpacity onPress={toggleIsOpen(isOpen, setIsOpen)}>
          <CloseButton color="#fff">X</CloseButton>
        </TouchableOpacity>
      </View>
    </HeadingContainer>
    <ProfileSectionContainer>
      <ProfileSection />
    </ProfileSectionContainer>
    <MenuItemsContainer>
      <MenuItems menuItems={[{ text: 'Link 1' }, { text: 'Link 2' }]} />
    </MenuItemsContainer>
    <SignOutContainer>
      <TouchableOpacity onPress={handleLogout(navigate)}>
        <Body1 color="#fff">Sign Out</Body1>
      </TouchableOpacity>
    </SignOutContainer>
  </MenuContainer>
);
</code>```

I've looked at all the StackOverflow links and none of the solutions seem to work.

I'm currently on React Native 0.59.8 which is the latest at the time of writing this question.

EDIT:
The TouchableOpacity that currently isn't working is the Sign Out button which is located at the bottom of the MenuContainer. I do have another TouchableOpacity which contains the X to close the menu and that seems to work well.

答:
Try this bind option:</p>

```<code>constructor(props) {
    super(props);
    this.toggleIsOpen = this.toggleIsOpen.bind(this);
    this.handleLogout = this.handleLogout.bind(this);
}
</code>```

Body:
I'm working on a React Native project and I'm struggling to get a TouchableOpacity to trigger it's press function when the element has the following CSS:

position: absolute;
z-index: 2;

Below is the code:

import React from 'react';
import PropTypes from 'prop-types';
import styled from 'styled-components';
import { View } from 'react-native';

const StyledImage = styled.Image`
  height: 24px;
  width: 32px;
`;

const MenuContainer = styled.View`
  display: flex;
  position: absolute;
  background-color: #2d2d2d;
  height: ${Dimensions.get('screen').height};
  width: ${Dimensions.get('screen').width * 0.75};
  z-index: 2;
  margin-left: -8px;
  margin-top: -16px;
`;

const ProfileSectionContainer = styled.View`
  display: flex;
  flex-direction: row;
  justify-content: space-around;
  margin-bottom: 24px;
`;

const HeadingContainer = styled.View`
  display: flex;
  flex-direction: row;
  justify-content: space-between;
  padding: 20px;
`;

const CloseButton = styled(Body1)`
  font-size: 18px;
`;

const MenuItemsContainer = styled.View`
  padding: 0 20px;
`;

const SignOutContainer = styled.View`
  position: absolute;
  bottom: 100;
  flex: 1;
  left: 40%;
`;

const handleLogout = navigate => async () => {
  await logout()
  redirectToLogin(navigate)();
};

const toggleIsOpen = (isOpen, setIsOpen) => () => setIsOpen(!isOpen);

const Menu = ({ isOpen, setIsOpen, navigate }) => (
  <MenuContainer>
    <HeadingContainer>
      <View>
        <Body1 color="#fff">New App</Body1>
      </View>
      <View>
        <TouchableOpacity onPress={toggleIsOpen(isOpen, setIsOpen)}>
          <CloseButton color="#fff">X</CloseButton>
        </TouchableOpacity>
      </View>
    </HeadingContainer>
    <ProfileSectionContainer>
      <ProfileSection />
    </ProfileSectionContainer>
    <MenuItemsContainer>
      <MenuItems menuItems={[{ text: 'Link 1' }, { text: 'Link 2' }]} />
    </MenuItemsContainer>
    <SignOutContainer>
      <TouchableOpacity onPress={handleLogout(navigate)}>
        <Body1 color="#fff">Sign Out</Body1>
      </TouchableOpacity>
    </SignOutContainer>
  </MenuContainer>
);

I've looked at all the StackOverflow links and none of the solutions seem to work.

I'm currently on React Native 0.59.8 which is the latest at the time of writing this question.

EDIT:
The TouchableOpacity that currently isn't working is the Sign Out button which is located at the bottom of the MenuContainer. I do have another TouchableOpacity which contains the X to close the menu and that seems to work well.

Body:
Try this bind option:

constructor(props) {
    super(props);
    this.toggleIsOpen = this.toggleIsOpen.bind(this);
    this.handleLogout = this.handleLogout.bind(this);
}


问:
Magento 2 not showing text swatches values
I'm trying to upgrade my store from V2.3 to V2.3.1. I'm working on my local development version and have got almost everything working. I use text swatches which work fine in V2.3 but in V2.3.1 all I see in the swatch is "null". I know the correct text is being sent to the page as I see it when I hover over the swatch (see the image below where you can see the second colour swatch has the value Grey). I suspect something isn't working with the javascript but I've no idea where to start looking. There are no errors in the console log btw.

Anyone able to suggest where the problem might be?

答:
I've tracked the problem down to something in swatch-renderer.js. The V2.3 version has the following line at 517:

```<code>value = optionConfig[id].hasOwnProperty('value') ? optionConfig[id].value : '';
</code>```

The version V2.3.1 has changed this to the following:

```<code>value = optionConfig[id].hasOwnProperty('value') ? $('<i></i>').text(optionConfig[id].value).html() : '';
</code>```

and the value is then used in the following statement to put the text into the html:

```<code>html += '<div class="' + optionClass + ' text" ' + attr + '>' + (value ? value : label) + '</div>';
</code>```

I used alert() to see the content of value before and after each variant of this statement as well as its type. Before it's undefined, after it's null for both variants yet changing this back to the old version resolves the problem! That's probably because before in V2.3 it's of type object whereas in V2.3.1 it's of type string (and presumably has the value "null"!).

I'll be honest, my knowledge of javascript is fairly limited. Does this look like an error? If so, what would be the best way to fix it (I presume test for the sting "null")?

Body:
I've tracked the problem down to something in swatch-renderer.js. The V2.3 version has the following line at 517:

value = optionConfig[id].hasOwnProperty('value') ? optionConfig[id].value : '';

The version V2.3.1 has changed this to the following:

value = optionConfig[id].hasOwnProperty('value') ? $('<i></i>').text(optionConfig[id].value).html() : '';

and the value is then used in the following statement to put the text into the html:

html += '<div class="' + optionClass + ' text" ' + attr + '>' + (value ? value : label) + '</div>';

I used alert() to see the content of value before and after each variant of this statement as well as its type. Before it's undefined, after it's null for both variants yet changing this back to the old version resolves the problem! That's probably because before in V2.3 it's of type object whereas in V2.3.1 it's of type string (and presumably has the value "null"!).

I'll be honest, my knowledge of javascript is fairly limited. Does this look like an error? If so, what would be the best way to fix it (I presume test for the sting "null")?


问:
Array with `n` elements in Kotlin doesn't work
I thought it was really simple...

```<code>fun main(args: Array<String>) {
    val a = Array<Boolean>(5) { false };
}
</code>```

But apparently, that doesn't work (it gives a NullPointerException): Try It Online!

This is the right way to do it according to another SO post that the OP commented was correct, so is it the runtime environment's fault or is Kotlin behaving weirdly?

答:
For me it results in [false, false, false, false, false]:

```<code>val a = Array(5) { false }
println(a.contentToString())
</code>```

Seems to be an issue related to the environment you were using.

Body:
I thought it was really simple...

fun main(args: Array<String>) {
    val a = Array<Boolean>(5) { false };
}

But apparently, that doesn't work (it gives a NullPointerException): Try It Online!

This is the right way to do it according to another SO post that the OP commented was correct, so is it the runtime environment's fault or is Kotlin behaving weirdly?

Body:
For me it results in [false, false, false, false, false]:

val a = Array(5) { false }
println(a.contentToString())

Seems to be an issue related to the environment you were using.


问:
how to remove a query parameter from a query string
I am using UriBuilder to remove a parameter from a URI:

```<code>public static URI removeParameterFromURI(URI uri, String param) {
    UriBuilder uriBuilder = UriBuilder.fromUri(uri);
    return uriBuilder.replaceQueryParam(param, "").build();
}

public static String removeParameterFromURIString(String uriString, String param) {
    try {
        URI uri = removeParameterFromURI(new URI(uriString), param);
        return uri.toString();
    } catch (URISyntaxException e) {
        throw new RuntimeException(e);
    }
}
</code>```

The above sort of works and modifies:

http://a.b.c/d/e/f?foo=1&bar=2&zar=3

… into:

http://a.b.c/d/e/f?bar=&foo=1&zar=3

But it has the following issues:

It messes up the order of the parameters. I know that the order is not relevant but it still bothers me.

it doesn't fully remove the parameter, it just sets its value to the empty string. I would prefer is the parameter is completely removed from the query string.

Is there some standard or commonly used library that can achieve the above neatly without having to parse and hack the query string myself?

答:
If you are on Android and want to remove all query parameters, you can use

Uri uriWithoutQuery = Uri.parse(urlWithQuery).buildUpon().clearQuery().build();

Body:
I am using UriBuilder to remove a parameter from a URI:

public static URI removeParameterFromURI(URI uri, String param) {
    UriBuilder uriBuilder = UriBuilder.fromUri(uri);
    return uriBuilder.replaceQueryParam(param, "").build();
}

public static String removeParameterFromURIString(String uriString, String param) {
    try {
        URI uri = removeParameterFromURI(new URI(uriString), param);
        return uri.toString();
    } catch (URISyntaxException e) {
        throw new RuntimeException(e);
    }
}

The above sort of works and modifies:

http://a.b.c/d/e/f?foo=1&bar=2&zar=3

… into:

http://a.b.c/d/e/f?bar=&foo=1&zar=3

But it has the following issues:

It messes up the order of the parameters. I know that the order is not relevant but it still bothers me.

it doesn't fully remove the parameter, it just sets its value to the empty string. I would prefer is the parameter is completely removed from the query string.

Is there some standard or commonly used library that can achieve the above neatly without having to parse and hack the query string myself?


问:
Which widget can be used as a root widget (supports Text) in a new route without covering the entire screen in Flutter?
I am creating a new page route PopupRoute and using a Stack as the root of the new popup page. It works fine until I add Text to its children. Text will have two yellow lines underneath. I tried Material(child:Stack()) and Scaffold(child:Stack()). It can fix the yellow line issue, but it covers the entire screen and make the barrierDismissible not work.

Are there any other widgets can solve the Text yellow issues in my case?

答:
There might be a cleaner solution, but the first thing I thought of is wrapping Material inside of Align widget.

e.g.

showDialog(context: context, barrierDismissible: true, builder: (context) {
  return Stack(alignment: Alignment.center, fit: StackFit.loose, children: <Widget>[

    Container(width: 100, height: 100, color: Colors.blue),
    Align(
      child: Material(
        type: MaterialType.transparency,
        child: Text("TEXT"),
      )
    ),

  ]);
});
```


问:
Formatting csv row made from dictionary
I am writing appending new dictionary entries to a csv as they are made. This works completely fine, however the formatting is funky. I am recording the trades my automated strategy makes. It records the timestamp, the trade, and the price.

Here is my function that records a new dictionary entry and appends to my csv:

```<code>def record_example(x):
    now = datetime.now()
    unix = int(mktime(now.timetuple()))
    price = 8110

    log.example[unix] = [unix, x, price]

    with open('example.csv', 'a') as e:
        writer = csv.DictWriter(e, fieldnames=log.example)
        writer.writerow(log.example)

        e.close()
</code>```

I call the function w/:

```<code>record('buy')
</code>```

this creates the dictionary as it should:

```<code>{1559052353: [1559052353, 'buy', 8110]}
</code>```

however the entry into the csv now looks like with it only filling A1:

```<code>"[1559052353, 'buy', 8110]"
</code>```

when I am trying to get it to look like: (so that I can import the csv into another .py file and plot trade performance)

```<code>1559052353, buy, 8110
</code>```

so that 1559052353 will be in A1, buy in A2, and 8110 in A3 for example

I have tried ''.join(split(',') for each row in csv yet get error message.. thanks so much if you can help!

答:
Check out the dialects option in csv.dictwriter this allows you to set different conventions for your csv, my guess is you want QUOTE_MINIMAL.

Also, you're writing out a key, and a list to your dictwriter. Normally, the dictwriter will take a dictionary per row, with each field being lodged in the dictionary as a "fieldname":fieldvalue pair.

Try converting your output routine so it passes individual row-dictionaries like:

```<code>log.example[unix] = {"unix":unix, "x":x, "price":price}

{"unix" : 1559052353, "x" : 'buy', "price" : 8110}
</code>```

The dictwriter will output a row with the 3 fields, "unix", "x", "price" according to your preferred csv dialect.

As it stands, you're giving it a key'ed list, so it's outputting that list "raw", which means it applies those unwanted extra decorations "[", "]"

Title: Formatting csv row made from dictionary

Body:
I am writing appending new dictionary entries to a csv as they are made. This works completely fine, however the formatting is funky. I am recording the trades my automated strategy makes. It records the timestamp, the trade, and the price.

Here is my function that records a new dictionary entry and appends to my csv:

def record_example(x):
    now = datetime.now()
    unix = int(mktime(now.timetuple()))
    price = 8110

    log.example[unix] = [unix, x, price]

    with open('example.csv', 'a') as e:
        writer = csv.DictWriter(e, fieldnames=log.example)
        writer.writerow(log.example)

        e.close()

I call the function w/:

record('buy')

this creates the dictionary as it should:

{1559052353: [1559052353, 'buy', 8110]}

however the entry into the csv now looks like with it only filling A1:

"[1559052353, 'buy', 8110]"

when I am trying to get it to look like: (so that I can import the csv into another .py file and plot trade performance)

1559052353, buy, 8110

so that 1559052353 will be in A1, buy in A2, and 8110 in A3 for example

I have tried ''.join(split(',') for each row in csv yet get error message.. thanks so much if you can help!

Body:
Check out the dialects option in csv.dictwriter this allows you to set different conventions for your csv, my guess is you want QUOTE_MINIMAL.

Also, you're writing out a key, and a list to your dictwriter. Normally, the dictwriter will take a dictionary per row, with each field being lodged in the dictionary as a "fieldname":fieldvalue pair.

Try converting your output routine so it passes individual row-dictionaries like:

log.example[unix] = {"unix":unix, "x":x, "price":price}

{"unix" : 1559052353, "x" : 'buy', "price" : 8110}

The dictwriter will output a row with the 3 fields, "unix", "x", "price" according to your preferred csv dialect.

As it stands, you're giving it a key'ed list, so it's outputting that list "raw", which means it applies those unwanted extra decorations "[", "]"


问:
Comparison of sublist and take operator(#) in q kdb
While fetching a subset of data from a table when I use sublist or take operator(#), most of the times take operator is slow compared to sublist function.

5 observations posted in comment after querying
table t in hdb which consists of 231131 rows and 71 cols.

```<code>\t 10000 10 sublist select from t where date=.z.d-5 /Time taken - 62j 92j 68j  63j 65j
\t 10000 10#select from t where date=.z.d-5 / Time taken - 544j 546j 567j 569j 585j
</code>```

With this small sample, it seems like sublist is faster as compared to take operator.

But when I see the code of sublist, it internally uses take operator, wondering how does sublist manage to be more efficient?

答:
The syntax you have used for timing the operations means that you are timing two different operations.

```<code>\t 10000 10 sublist select from t where date=.z.d-5 /Time taken - 62j 92j 68j  63j 65j
</code>```

This sublist operation shows a slice of length 10 starting at the 10000th entry.

```<code>\t 10000 10#select from t where date=.z.d-5 / Time taken - 544j 546j 567j 569j 585j
</code>```

This # operation would return 10000 rows, each consisting of 10 rows from the result of the select function.

What you probably meant to do is:

```<code>\t:10000 10 sublist select from t where date=.z.d-5 /Time taken - 62j 92j 68j  63j 65j
\t:10000 10#select from t where date=.z.d-5 / Time taken - 544j 546j 567j 569j 585j
</code>```

Which would time each of the functions 10000 times. From my own testing, sublist and # give similar timings.

Body:
While fetching a subset of data from a table when I use sublist or take operator(#), most of the times take operator is slow compared to sublist function.

5 observations posted in comment after querying
table t in hdb which consists of 231131 rows and 71 cols.

\t 10000 10 sublist select from t where date=.z.d-5 /Time taken - 62j 92j 68j  63j 65j
\t 10000 10#select from t where date=.z.d-5 / Time taken - 544j 546j 567j 569j 585j

With this small sample, it seems like sublist is faster as compared to take operator.

But when I see the code of sublist, it internally uses take operator, wondering how does sublist manage to be more efficient?

Body:
The syntax you have used for timing the operations means that you are timing two different operations.

\t 10000 10 sublist select from t where date=.z.d-5 /Time taken - 62j 92j 68j  63j 65j

This sublist operation shows a slice of length 10 starting at the 10000th entry.

\t 10000 10#select from t where date=.z.d-5 / Time taken - 544j 546j 567j 569j 585j

This # operation would return 10000 rows, each consisting of 10 rows from the result of the select function.

What you probably meant to do is:

\t:10000 10 sublist select from t where date=.z.d-5 /Time taken - 62j 92j 68j  63j 65j
\t:10000 10#select from t where date=.z.d-5 / Time taken - 544j 546j 567j 569j 585j

Which would time each of the functions 10000 times. From my own testing, sublist and # give similar timings.


问:
Remove user and all its posts
I need to use WordPress Rest API to delete a user and all its own (maybe custom) posts.

I tried to call <url_base>/wp/v2/users/<id> and I have to provide a further parameter ?reassign=USER_ID to reassign its posts to another user.

A silly solution should be adding a "garbage" user to the system and assign him all deleted posts. Then I can create a job to delete all posts. It seems a very stupid way to me.. :(

I just want to delete them. I can do it from WP admin panel... why I can't via Rest Api?

Thanks

EDIT
Passing "reassign" as an empty params (null is not accepted...) the API informs me that I'm not able to delete my own profile. I'm testing it as a subscriber (end user), but I need to be able to manage and delete my own data... Am I wrong?!

答:
This is my solution... maybe not the best one, but it seems to work.

I added delete_users and remove_users capabilities to the Subscriber role (for my convenience).

My /DeleteUsers rest endpoint check for the user ID encrypted inside the JWT token that is sent in header and compare it with the user_id params. If they match, I can delete the user.

Now I just have to avoid that a user can access the WP Admin panel and make some mess!

This is the code:

```<code>function myDeleteProfile($data) {
  require_once(ABSPATH.'wp-admin/includes/user.php');

  $headers = getallheaders();
  if(!isset($headers['Authorization']) || !$headers['Authorization']) {
    return array('esito'=>'ko', 'descrizione'=>'Fail message!');
  }

  $jwt_parts = preg_split('/\./', $headers['Authorization']);
  $jwt_decoded = json_decode(base64_decode($jwt_parts[1]));
  $jwt_user = $jwt_decoded->data->user->id;

  if( intval($data['user_id']) != intval($jwt_user) ) {
    return array('esito'=>'ko', 'descrizione'=>'User cannot delete.');
  }
  else {
    if( wp_delete_user($jwt_user,null) ){
        return array('esito'=>'ok', 'descrizione'=>'Deleting...');
    }
    else {
        return array('esito'=>'ko', 'descrizione'=>'Error.');
    }
  }
}
</code>```

Title: Remove user and all its posts

Body:
This is my solution... maybe not the best one, but it seems to work.

I added delete_users and remove_users capabilities to the Subscriber role (for my convenience).

My /DeleteUsers rest endpoint check for the user ID encrypted inside the JWT token that is sent in header and compare it with the user_id params. If they match, I can delete the user.

Now I just have to avoid that a user can access the WP Admin panel and make some mess!

This is the code:

function myDeleteProfile($data) {
  require_once(ABSPATH.'wp-admin/includes/user.php');

  $headers = getallheaders();
  if(!isset($headers['Authorization']) || !$headers['Authorization']) {
    return array('esito'=>'ko', 'descrizione'=>'Fail message!');
  }

  $jwt_parts = preg_split('/\./', $headers['Authorization']);
  $jwt_decoded = json_decode(base64_decode($jwt_parts[1]));
  $jwt_user = $jwt_decoded->data->user->id;

  if( intval($data['user_id']) != intval($jwt_user) ) {
    return array('esito'=>'ko', 'descrizione'=>'User cannot delete.');
  }
  else {
    if( wp_delete_user($jwt_user,null) ){
        return array('esito'=>'ok', 'descrizione'=>'Deleting...');
    }
    else {
        return array('esito'=>'ko', 'descrizione'=>'Error.');
    }
  }
}


答:
You could use a where conditional:        </p>

```<code>    df11['b'] = df11['b'].where(df11.b.map(len) != 3, np.nan)
</code>```

Body:
I have a dataframe  as below:

import pandas as pd
import dask.dataframe as dd
a = {'b':['category','categorical','cater pillar','coming and going','bat','No Data','calling','cal'],
     'c':['strd1','strd2','strd3', 'strd4','strd5','strd6','strd7', 'strd8']
    }
df11 = pd.DataFrame(a,index=['x1','x2','x3','x4','x5','x6','x7','x8'])

I wanted to remove words whose length of each value is three.
I expect results to be like:

   b                         c
category                   strd1
categorical                strd2
cater pillar               strd3
coming and going           strd4
NaN                        strd5
No Data                    strd6
calling                    strd7
NaN                        strd8

Body:
You could use a where conditional:

    df11['b'] = df11['b'].where(df11.b.map(len) != 3, np.nan)


答: you probably wanted to write: writer.writerow(log.example[unix]). this will do the thing you want. you also don't need to use e.close(), as the with block closes the file automatically for you.

Title: Formatting csv row made from dictionary


答:
You just need to wrap your Text widget inside a DefaultTextStyle widget. A DefaultTextStyle widget gets added implicitly by the Scaffold or Material widget.

```<code>DefaultTextStyle(
  style: TextStyle(),
  child: Text("This is a test"),
),
</code>```

Title: Which widget can be used as a root widget (supports Text) in a new route without covering the entire screen in Flutter?

Body:
I am creating a new page route PopupRoute and using a Stack as the root of the new popup page. It works fine until I add Text to its children. Text will have two yellow lines underneath. I tried Material(child:Stack()) and Scaffold(child:Stack()). It can fix the yellow line issue, but it covers the entire screen and make the barrierDismissible not work.

Are there any other widgets can solve the Text yellow issues in my case?

Body:
You just need to wrap your Text widget inside a DefaultTextStyle widget. A DefaultTextStyle widget gets added implicitly by the Scaffold or Material widget.

DefaultTextStyle(
  style: TextStyle(),
  child: Text("This is a test"),
),


问:
How do I create a query statement for the Laravel Search Filter feature?
How do I create a query statement for the Laravel Search Filter feature?
I'd like to combine the Laravel search query into one.
Now there is a problem with this code. It is not a multi-conditions superposition. I want to unify this query into one and get results that satisfy all conditions. What should I do?</p>

```<code>//펜팔 메인 페이지
public function index (Request $request){
    //base Object
    $penpals =  $this->penpalModel->getUsers();

    //name search
    if (!empty($request->name)) {
        $users = $this->userModel->where('name', 'like', '%' . $request->name . '%')->get();
        if (!empty($users)) {

            $penpals->whereIn('user_id', $users);
        }
    }

    //gender search
    if (!empty($request->gender) && $request->gender !== 'all') {
        $penpals->leftJoin('users', 'penpals.user_id', '=', 'users.id')
        ->select('penpals.*', 'users.gender')
        ->where('users.gender', $request->gender);
    }

    //country search
    if (!empty($request->country) && $request->country !== 'all') {
        $penpals->leftJoin('users', 'penpals.user_id', '=', 'users.id')
        ->select('penpals.*', 'users.country')
        ->where(['users.country', $request->country]);
    }

     // goal name search
     if (!empty($request->goal) && $request->goal !== 'all') {

        $penpals = $this->penpalModel->where('goal_id',$request->goal)->latest();
     }

    //age search
    if($request->ageMin || $request->ageMax){

        $ageMin = floor($request->ageMin);
        $ageMax = floor($request->ageMax);

        $penpals = $this->penpalModel->leftJoin('users', 'penpals.user_id', '=', 'users.id')
        ->select('penpals.*', 'users.age')
        ->whereBetween('users.age', [$ageMin, $ageMax]);
    }

    $penpalsData = $penpals->orderBy('penpals.created_at','desc')->paginate(12);

    $penpalsCount = count($penpalsData);

    return view('penpal.index')->with([
        'penpals'       => $penpalsData,
        'penpalsCount'  => $penpalsCount
        ]);

}
</code>```

答:
You should add relation user to penpal model.

```<code>class Penpal extends Model {
    ...

    public function user()
    {
        return $this->belongsTo(User::class);
    }

    ...
}
</code>```

Then you can use whereHas eloquent method:

```<code>public function index (Request $request){
    //query builder
    $query =  $this->penpalModel->query();

    //user fields
    if(
        $request->name ||
        $request->ageMin ||
        $request->ageMax ||
        ($request->gender && $request->gender !== 'all') ||
        ($request->country && $request->country !== 'all')
    ){
        $query->whereHas('user', function($query) use ($request){
            if($request->name){
                $query->where('name', 'like', '%' . $request->name . '%');
            }

            if($request->gender && $request->gender !== 'all'){
                $query->where('gender', $request->gender);
            }

            if($request->country && $request->country !== 'all'){
                $query->where('country', $request->country);
            }

            if($request->ageMin){
                $query->where('age', '>', floor($request->ageMin));
            }

            if($request->ageMax){
                $query->where('age', '<', floor($request->ageMax));
            }
        })
    }

    //goal
    if ($request->goal && $request->goal !== 'all') {
        $query->where('goal_id', $request->goal);
    }

    $penpals = $query
        ->with('user')
        ->latest()
        ->paginate(12);

    return view('penpal.index')->with([
        'penpals'       => $penpals,
        'penpalsCount'  => $penpals->count() //use $query->count() to get count of all results in db, not only in paginator collection
    ]);
}
</code>```

Unfortunately, this solution is not 100% copy of your code/idea because it lose selects, but filtering will work right and you could access user of each penpal like this:

```<code>$penpal->user->name //in php

penpal.user.name //in js
</code>```

Body:
How do I create a query statement for the Laravel Search Filter feature?
I'd like to combine the Laravel search query into one.
Now there is a problem with this code. It is not a multi-conditions superposition. I want to unify this query into one and get results that satisfy all conditions. What should I do?

//펜팔 메인 페이지
public function index (Request $request){
    //base Object
    $penpals =  $this->penpalModel->getUsers();

    //name search
    if (!empty($request->name)) {
        $users = $this->userModel->where('name', 'like', '%' . $request->name . '%')->get();
        if (!empty($users)) {

            $penpals->whereIn('user_id', $users);
        }
    }

    //gender search
    if (!empty($request->gender) && $request->gender !== 'all') {
        $penpals->leftJoin('users', 'penpals.user_id', '=', 'users.id')
        ->select('penpals.*', 'users.gender')
        ->where('users.gender', $request->gender);
    }

    //country search
    if (!empty($request->country) && $request->country !== 'all') {
        $penpals->leftJoin('users', 'penpals.user_id', '=', 'users.id')
        ->select('penpals.*', 'users.country')
        ->where(['users.country', $request->country]);
    }

     // goal name search
     if (!empty($request->goal) && $request->goal !== 'all') {

        $penpals = $this->penpalModel->where('goal_id',$request->goal)->latest();
     }

    //age search
    if($request->ageMin || $request->ageMax){

        $ageMin = floor($request->ageMin);
        $ageMax = floor($request->ageMax);

        $penpals = $this->penpalModel->leftJoin('users', 'penpals.user_id', '=', 'users.id')
        ->select('penpals.*', 'users.age')
        ->whereBetween('users.age', [$ageMin, $ageMax]);
    }

    $penpalsData = $penpals->orderBy('penpals.created_at','desc')->paginate(12);

    $penpalsCount = count($penpalsData);

    return view('penpal.index')->with([
        'penpals'       => $penpalsData,
        'penpalsCount'  => $penpalsCount
        ]);

}

Body:
You should add relation user to penpal model.

class Penpal extends Model {
    ...

    public function user()
    {
        return $this->belongsTo(User::class);
    }

    ...
}

Then you can use whereHas eloquent method:

public function index (Request $request){
    //query builder
    $query =  $this->penpalModel->query();

    //user fields
    if(
        $request->name ||
        $request->ageMin ||
        $request->ageMax ||
        ($request->gender && $request->gender !== 'all') ||
        ($request->country && $request->country !== 'all')
    ){
        $query->whereHas('user', function($query) use ($request){
            if($request->name){
                $query->where('name', 'like', '%' . $request->name . '%');
            }

            if($request->gender && $request->gender !== 'all'){
                $query->where('gender', $request->gender);
            }

            if($request->country && $request->country !== 'all'){
                $query->where('country', $request->country);
            }

            if($request->ageMin){
                $query->where('age', '>', floor($request->ageMin));
            }

            if($request->ageMax){
                $query->where('age', '<', floor($request->ageMax));
            }
        })
    }

    //goal
    if ($request->goal && $request->goal !== 'all') {
        $query->where('goal_id', $request->goal);
    }

    $penpals = $query
        ->with('user')
        ->latest()
        ->paginate(12);

    return view('penpal.index')->with([
        'penpals'       => $penpals,
        'penpalsCount'  => $penpals->count() //use $query->count() to get count of all results in db, not only in paginator collection
    ]);
}

Unfortunately, this solution is not 100% copy of your code/idea because it lose selects, but filtering will work right and you could access user of each penpal like this:

$penpal->user->name //in php

penpal.user.name //in js


问:
Javascript array issue with vue-infinite-loading
I am trying to implement Infinite Loading using vue-InfiniteLoading component.
I am getting an array everytime I scroll and I try to push the contents from the array to another array when I get the data.  When I used push, I see new elements on screen but no images and infomation..

I tried push, concat and foreach, none of them worked for me. response.data.data.data is the array containin new elements and dorms is the main array shown on UI.

I also tried push (...response.data.data.data)

```<code>    .get(`/site/cities/dorms/istanbul?page=${self.page}`)
    .then(response => {
      if (response.data.data.data) {
        this.page += 1;
        // var myArray = self.dorms;
        // self.dorms = myArray .concat(response.data.data.data);
        // self.dorms.push(response.data.data.data[1]);
        /*             response.data.data.data.forEach(item => {
          self.dorms.push(item);
        }); */
        self.dorms.push(...response.data.data.data);

        //self.dorms = response.data.data.data;
        self.popupDorms = response.data.data.popups;
        $state.loaded();
      } else {
        $state.complete();
      }
    });
</code>```

I expect all informatin within array pushed but it doesnt work.

答:
We can write a small function that checks scroll position and fires an ajax call to get more data or just get the next slot of data from your JSON object and bind it to HTML. something as below:

```<code>$(window).scroll(function() {
    if($(window).scrollTop() == $(document).height() - $(window).height()) {
           // ajax call or some other logic to show data here
    }
});
</code>```

Or you can use one of the plugins that are available, I am myself using "Waypoint" for one of the same things.

Body:
I am trying to implement Infinite Loading using vue-InfiniteLoading component.
I am getting an array everytime I scroll and I try to push the contents from the array to another array when I get the data.  When I used push, I see new elements on screen but no images and infomation..

I tried push, concat and foreach, none of them worked for me. response.data.data.data is the array containin new elements and dorms is the main array shown on UI.

I also tried push (...response.data.data.data)

    .get(`/site/cities/dorms/istanbul?page=${self.page}`)
    .then(response => {
      if (response.data.data.data) {
        this.page += 1;
        // var myArray = self.dorms;
        // self.dorms = myArray .concat(response.data.data.data);
        // self.dorms.push(response.data.data.data[1]);
        /*             response.data.data.data.forEach(item => {
          self.dorms.push(item);
        }); */
        self.dorms.push(...response.data.data.data);

        //self.dorms = response.data.data.data;
        self.popupDorms = response.data.data.popups;
        $state.loaded();
      } else {
        $state.complete();
      }
    });

I expect all informatin within array pushed but it doesnt work.

Body:
We can write a small function that checks scroll position and fires an ajax call to get more data or just get the next slot of data from your JSON object and bind it to HTML. something as below:

$(window).scroll(function() {
    if($(window).scrollTop() == $(document).height() - $(window).height()) {
           // ajax call or some other logic to show data here
    }
});

Or you can use one of the plugins that are available, I am myself using "Waypoint" for one of the same things.


问:
Python : Flatten xml to csv with parent tag repeated in child
My xml looks like below.

```<code><RootTag xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<Branch>
<BranchID>100</BranchID>
   <Child>
        <policy1>hello</policy1>
        <policy2>how are you</policy2>
   </Child>
   <Child>
        <policy1>hello1</policy1>
        <policy2>how are you1</policy2>
   </Child>
</Branch>
<Branch>
<BranchID>200</BranchID>
<Child>
        <policy1>I am good</policy1>
        <policy2>how about you</policy2>
</Child>
<Child>
        <policy1>I am good1</policy1>
        <policy2>how about you1</policy2>
</Child>
</Branch>
</RootTag>
</code>```

I tried using getiterator(beacuse I'm in python 2.6) to get all the elements. I am able to flatten them but the parent tag(BranchID) values should be present in all the rows of its child.

Output expected:

```<code>BranchID,policy1,policy2
100,hello,how are you
100,hello1,how are you1
200,I am good,how about you
200,I am good1,how about you1
</code>```

答:
please try this code (remember to replace YOUR FILE HERE with an actual file path):

import xml.etree.ElementTree as ET

root = ET.parse('YOUR FILE HERE')  # replace file name

print("BranchID,policy1,policy2")
branches = root.findall('.//Branch')
for branch in branches:
    branch_id = branch.find("BranchID").text
    for child in branch.findall('.//Child'):
        policy1 = child.find('policy1').text
        policy2 = child.find('policy2').text
        print("{},{},{}".format(branch_id,policy1,policy2))

```

Body:
My xml looks like below.

<RootTag xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<Branch>
<BranchID>100</BranchID>
   <Child>
        <policy1>hello</policy1>
        <policy2>how are you</policy2>
   </Child>
   <Child>
        <policy1>hello1</policy1>
        <policy2>how are you1</policy2>
   </Child>
</Branch>
<Branch>
<BranchID>200</BranchID>
<Child>
        <policy1>I am good</policy1>
        <policy2>how about you</policy2>
</Child>
<Child>
        <policy1>I am good1</policy1>
        <policy2>how about you1</policy2>
</Child>
</Branch>
</RootTag>

I tried using getiterator(beacuse I'm in python 2.6) to get all the elements. I am able to flatten them but the parent tag(BranchID) values should be present in all the rows of its child.

Output expected:

BranchID,policy1,policy2
100,hello,how are you
100,hello1,how are you1
200,I am good,how about you
200,I am good1,how about you1


问:
How to pretty print a hierarchical list?
I am very new to Python, and in the University, our teacher gave us the following problem:

He gave us the following list:

[ '1,2,3,4', '2,5,6', '3,7,8', '4,9' ]

It is supposed to go like this: 1 is the supervisor of 2, 3, 4 and 2 is the supervisor of 5, 6 etc
So, our teacher wants us to write a program that pretty-prints the graph like this:

```<code>1

....2

........5

........6

....3

........7

........8

....4

........9
</code>```

Problem is, I cannot understand how to do this...
Any help or ideas please?

答:
I propose this solution. At least it works with the example you gave. Please ask questions if you need any explanations of the code below: the comments should guide you.</p>

```<code>lst_string = ['1,2,3,4', '2,5,6', '3,7,8', '4,9']
# first, transform your list into a nested list

# create an empty list
lst_nested = list()

for seq_string in lst_string:
    to_list = list(seq_string)  # the first list looks like ["1", ",", "2", ",", "3", ",", "4']
    to_list = to_list[0::2]  # this removes the "," inputs
    to_list = list(map(int, to_list))  # this transforms ["1", "2", "3"] into [1,2,3]
    lst_nested.append(to_list)

# define the list of first elements
first_elements = list()
for lst in lst_nested:
    first_elements.append(lst[0])

# prepare the output
tab = "...."

def fill_in(seq, idx_tab):
    # always displays the first element
    output = ""
    output += tab * idx_tab
    output += str(seq[0])
    output += "\n"

    for intgr in seq[1:]:
        if intgr in first_elements:
            # call recursively function fill_in with the corresponding seq
            output += fill_in(lst_nested[first_elements.index(intgr)], idx_tab + 1)

        else:
            output += tab * (idx_tab + 1)
            output += str(intgr)
            output += "\n"

    return output

print(fill_in(lst_nested[0], 0))
</code>```

Body:
I am very new to Python, and in the University, our teacher gave us the following problem:

He gave us the following list:

[ '1,2,3,4', '2,5,6', '3,7,8', '4,9' ]

It is supposed to go like this: 1 is the supervisor of 2, 3, 4 and 2 is the supervisor of 5, 6 etc
So, our teacher wants us to write a program that pretty-prints the graph like this:

1

....2

........5

........6

....3

........7

........8

....4

........9

Problem is, I cannot understand how to do this...
Any help or ideas please?

Body:
I propose this solution. At least it works with the example you gave. Please ask questions if you need any explanations of the code below: the comments should guide you.

lst_string = ['1,2,3,4', '2,5,6', '3,7,8', '4,9']
# first, transform your list into a nested list

# create an empty list
lst_nested = list()

for seq_string in lst_string:
    to_list = list(seq_string)  # the first list looks like ["1", ",", "2", ",", "3", ",", "4']
    to_list = to_list[0::2]  # this removes the "," inputs
    to_list = list(map(int, to_list))  # this transforms ["1", "2", "3"] into [1,2,3]
    lst_nested.append(to_list)

# define the list of first elements
first_elements = list()
for lst in lst_nested:
    first_elements.append(lst[0])

# prepare the output
tab = "...."

def fill_in(seq, idx_tab):
    # always displays the first element
    output = ""
    output += tab * idx_tab
    output += str(seq[0])
    output += "\n"

    for intgr in seq[1:]:
        if intgr in first_elements:
            # call recursively function fill_in with the corresponding seq
            output += fill_in(lst_nested[first_elements.index(intgr)], idx_tab + 1)

        else:
            output += tab * (idx_tab + 1)
            output += str(intgr)
            output += "\n"

    return output

print(fill_in(lst_nested[0], 0))


答:
You could do:

self.dorms = [...self.dorms, ...response.data.data.data]

or

self.dorms = [].concat(self.dorms, response.data.data.data)

or

self.dorms.push(...response.data.data.data)

all result in the same result. Your error should be somewhere else.

Title: Javascript array issue with vue-infinite-loading


问:
Spring data rest shows id as path variable in swagger for POST method in mongo repository?
I am just using MongoRepository. Below is my entity class:

```<code>import com.fasterxml.jackson.annotation.JsonInclude;
import lombok.Data;
import lombok.EqualsAndHashCode;
import lombok.ToString;
import org.springframework.data.annotation.Id;
import org.springframework.data.mongodb.core.index.Indexed;
import org.springframework.data.mongodb.core.mapping.Document;

@Document(collection = "product")
@Data
@ToString
@EqualsAndHashCode
@JsonInclude(JsonInclude.Include.NON_EMPTY)
public class Product {

  @Id private String id;

  @Indexed(unique = true)
  private String name;

  private boolean displayAds;
}
</code>```

When I view the resource in Swagger the POST method appears as follows:

This is my repository:

```<code>import org.springframework.data.mongodb.repository.MongoRepository;

public interface ProductRepository extends MongoRepository<Product, String> {
}
</code>```

Why does this happen? Is there a fix? I'm using springfox-swagger2 and springfox-swagger-ui.

Anyway it can post via Postman without adding such path variable.

答:
Updating to 2.8.0 should resolve the issue.

This seems to have been a bug in Springfox version 2.7.0. Should be fixed in 2.8.0 as highlighted here.

Body:
I am just using MongoRepository. Below is my entity class:

import com.fasterxml.jackson.annotation.JsonInclude;
import lombok.Data;
import lombok.EqualsAndHashCode;
import lombok.ToString;
import org.springframework.data.annotation.Id;
import org.springframework.data.mongodb.core.index.Indexed;
import org.springframework.data.mongodb.core.mapping.Document;

@Document(collection = "product")
@Data
@ToString
@EqualsAndHashCode
@JsonInclude(JsonInclude.Include.NON_EMPTY)
public class Product {

  @Id private String id;

  @Indexed(unique = true)
  private String name;

  private boolean displayAds;
}

When I view the resource in Swagger the POST method appears as follows:

This is my repository:

import org.springframework.data.mongodb.repository.MongoRepository;

public interface ProductRepository extends MongoRepository<Product, String> {
}

Why does this happen? Is there a fix? I'm using springfox-swagger2 and springfox-swagger-ui.

Anyway it can post via Postman without adding such path variable.


问:
Which is the difference between Long.valueOf(0) and 0L in Java?
I would like to know the difference between using Long.valueOf(0); or 0L. Are they the same?

I understand that both are Long types so they have a memory consumption of 64-bits long in Java 8.

So how it is better to initialize a variable, considering memory consumption and time complexity?

Long a = Long.valueOf(0);

or

Long b = 0L;

答:
As others have pointed out, Long l = Long.valueOf(0) and Long l = 0L will compile to the same bytecode, the only difference is style and readability.

Additionally..

It's a bit silly to worry about time complexity for something like this: both expressions are constant time. You usually only talk about time complexity when acting on collections of data not just a single piece of data.

As for memory consumption, they do not use 64 bits as you say; It's the primitive long type that typically uses 64 bits but Long (the wrapper type) uses more memory than the primitive type because it needs that memory for object-related stuff.