问:
Laravel 6 send mail
I have an issue with authentication while sending mail with Laravel smtp driver.

.env file:

```<code>MAIL_DRIVER=smtp
MAIL_HOST=smtp.gmail.com
MAIL_PORT=587
MAIL_USERNAME=account@gmail.com
MAIL_FROM_ADDRESS=account@gmail.com
MAIL_PASSWORD=app_password
MAIL_ENCRYPTION=tls
</code>```

It gives the following error:

"530-5.7.0 Authentication Required. "

2-Factor auth is enabled and app password is used;

Also tried with SSL on 465, same error;

Config is flushed every time .env is changed;

Everything in config/mail corresponds to .env;

SO all typical solutions are not working. What else may cause this problem?

I have also tried using smtp.vivaldi.net with vivaldi account, it authenticates, but gives an error:

"no valid recipients"

while recipient email is surely valid, which is also strange for me.

答:
I've stumbled across this multiple times already, hence I do not remember the exact error-message which I received but here is my assumption.

Google has an option called "less secure apps" which you need to enable in order to send directly mails through their SMTP interface. Can you check if this flag is disabled and try to enable it?

https://support.google.com/a/answer/6260879

In addition to that google is slowly deprecating this feature. Starting from Mid 2020 you'll be not able to enable this flag anymore and they will completely remove this in 2021.

Reference: https://gsuiteupdates.googleblog.com/2019/12/less-secure-apps-oauth-google-username-password-incorrect.html

Title: Laravel 6 send mail

Body:
I have an issue with authentication while sending mail with Laravel smtp driver.

.env file:

MAIL_DRIVER=smtp
MAIL_HOST=smtp.gmail.com
MAIL_PORT=587
MAIL_USERNAME=account@gmail.com
MAIL_FROM_ADDRESS=account@gmail.com
MAIL_PASSWORD=app_password
MAIL_ENCRYPTION=tls

It gives the following error:

"530-5.7.0 Authentication Required. "

2-Factor auth is enabled and app password is used;

Also tried with SSL on 465, same error;

Config is flushed every time .env is changed;

Everything in config/mail corresponds to .env;

SO all typical solutions are not working. What else may cause this problem?

I have also tried using smtp.vivaldi.net with vivaldi account, it authenticates, but gives an error:

"no valid recipients"

while recipient email is surely valid, which is also strange for me.


来源: stackexchange

问:
Does Firestore database count more document reads when applying multiple conditions?
Consider this example

```<code>citiesRef.where("state", "==", "CO").where("name", "==", "Denver").get().then( res => ... );
</code>```

Assume there are 10 documents satisfying the first condition, 20 documents satisfying the second condition and only 5 documents satisfying the both conditions.

How many document reads does Firestore count ?

答:
How many document reads does Firestore count?

You'll be charged with a number of document reads that is equal with the number of documents that are returned by your query. So if your combined query will return 5 elements, you'll only be charged with 5 reads.

ContentLicense: CC BY-SA 4.0

Body:
Consider this example

citiesRef.where("state", "==", "CO").where("name", "==", "Denver").get().then( res => ... );

Assume there are 10 documents satisfying the first condition, 20 documents satisfying the second condition and only 5 documents satisfying the both conditions.

How many document reads does Firestore count ?


问:
is it possible to make equalizer android
Doing a little search i realized that to make an equalizer. I need to use C or C++ That would also mean that i have to use the NDK to integrate that with my Java code. The question is, how can i make the C and Java code interact with each other. I don't even know C but i really want that equalizer in my music player. Do you guys know of any good C book which is the best for beginners?

Thanks.

答:
Here is a link to a list of great books. Do a search through there and see what people suggest.

SO list of books

ContentLicense: CC BY-SA 3.0


问:
Could not find matching close tag for "<%"
I am trying to access variables passed from the server to the client with ejs

My server file:

```<code>router.get('/', function (req, res, next) {
    res.render('chat', {user: req.user, message: null});
});

</code>```

My client file:

```<code><!DOCTYPE html>
<html>
<head>
    <meta http-equiv="Content-Type" const="text/html;charset=UTF-8"/>
    <link href="http://fonts.googleapis.com/css?family=Comfortaa" rel="stylesheet" type="text/css">
    <link rel="stylesheet" type="text/css" href="style.css">
    <script src="https://cdnjs.cloudflare.com/ajax/libs/socket.io/2.0.4/socket.io.js"></script>
    <title>Simple Chat App</title>
</head>

<body>
<header>
    <h1>Super Chat</h1>
</header>

<section>
    <div id="change_username">
        <input id="username" type="text"/>
        <button id="send_username" type="button">Change username</button>
    </div>
</section>

<section id="chatroom">
    <section id="feedback"></section>
</section>

<section id="input_zone">
    <input id="message" class="vertical-align" type="text"/>
    <button id="send_message" class="vertical-align" type="button">Send</button>
</section>

<script src="http://code.jquery.com/jquery-latest.min.js"></script>

<script type="text/javascript">
    <% var user = <% user %> %>
    console.log(user);
</script>
<script src="chat.js"></script>
</body>
</html>

</code>```

I get an error:

```<code>Could not find matching close tag for "<%".

</code>```

How do I fix this?

答:
The problem is here, you just have to replace the value of the user in the template.

```<code> var user = "<%=user%>" // Please change this line
</code>```

Updated Code

<!DOCTYPE html>

    <meta http-equiv="Content-Type" const="text/html;charset=UTF-8"/>
    <link href="http://fonts.googleapis.com/css?family=Comfortaa" rel="stylesheet" type="text/css">
    <link rel="stylesheet" type="text/css" href="style.css">

    <title>Simple Chat App</title>

Super Chat

        <input id="username" type="text"/>
        <button id="send_username" type="button">Change username</button>

    <input id="message" class="vertical-align" type="text"/>
    <button id="send_message" class="vertical-align" type="button">Send</button>

```

I Hope this helps you.

Body:
I am trying to access variables passed from the server to the client with ejs

My server file:

router.get('/', function (req, res, next) {
    res.render('chat', {user: req.user, message: null});
});

My client file:

<!DOCTYPE html>

    <meta http-equiv="Content-Type" const="text/html;charset=UTF-8"/>
    <link href="http://fonts.googleapis.com/css?family=Comfortaa" rel="stylesheet" type="text/css">
    <link rel="stylesheet" type="text/css" href="style.css">

    <title>Simple Chat App</title>

Super Chat

        <input id="username" type="text"/>
        <button id="send_username" type="button">Change username</button>

    <input id="message" class="vertical-align" type="text"/>
    <button id="send_message" class="vertical-align" type="button">Send</button>

I get an error:

Could not find matching close tag for "<%".

How do I fix this?

Body:
The problem is here, you just have to replace the value of the user in the template.

 var user = "<%=user%>" // Please change this line

Updated Code

<!DOCTYPE html>
<html>
<head>
    <meta http-equiv="Content-Type" const="text/html;charset=UTF-8"/>
    <link href="http://fonts.googleapis.com/css?family=Comfortaa" rel="stylesheet" type="text/css">
    <link rel="stylesheet" type="text/css" href="style.css">
    <script src="https://cdnjs.cloudflare.com/ajax/libs/socket.io/2.0.4/socket.io.js"></script>
    <title>Simple Chat App</title>
</head>

<body>
<header>
    <h1>Super Chat</h1>
</header>

<section>
    <div id="change_username">
        <input id="username" type="text"/>
        <button id="send_username" type="button">Change username</button>
    </div>
</section>

<section id="chatroom">
    <section id="feedback"></section>
</section>

<section id="input_zone">
    <input id="message" class="vertical-align" type="text"/>
    <button id="send_message" class="vertical-align" type="button">Send</button>
</section>

<script src="http://code.jquery.com/jquery-latest.min.js"></script>

<script type="text/javascript">
    var user = "<%= user %>" // problem is here
    console.log(user);
</script>
<script src="chat.js"></script>
</body>
</html>

I Hope this helps you.


问:
HTML5Up Overflow how to put links on the picture
I downloaded this html5 template for a project https://html5up.net/overflow and I dont know how to put a link for github on the pictures displayed in the gallery (those 8 ) I want that when I click the pic and expand , the next click should sent me to a link and not to scroll over the next or previous picture.I tried to check the code but i found it to complicated for my actual level to figure it out . I am hoping that i can get some help here :) thank you

EDIT: I actualy need help in this part of code

```<code>            <div class="inner gallery">
                <div class="row gtr-0">
                    <div class="col-3 col-12-mobile"><a href="images/fulls/Pairs.png" class="image fit"><img src="images/thumbs/Pairs.png" alt="" title="A little game in"/></a></div>
                    <div class="col-3 col-12-mobile"><a href="images/fulls/Chrome.png" class="image fit"><img src="images/thumbs/Chrome.png" alt="" title="Dressed in Clarity" /></a></div>
                    <div class="col-3 col-12-mobile"><a href="images/fulls/MP3.png" class="image fit"><img src="images/thumbs/MP3.png" alt="" title="Raven" /></a></div>
                    <div class="col-3 col-12-mobile"><a href="images/fulls/Studenti.png" class="image fit"><img src="images/thumbs/Studenti.png" alt="" title="I'll have a cup of Disneyland, please" /></a></div>
                </div>
            </div>
</code>```

When I click them twice I would like to send me to other links on other sites

答:
if im understanding correctly what do you want do this

Change in your code..

```<code><a href="#banner" class="button style2 scrolly-middle">Proceed as anticipated</a>
</code>```

for

```<code><a href="https://www...(URL)">Proceed as anticipated</a>
</code>```

dont forget to remove remove class="..."

Body:
I downloaded this html5 template for a project https://html5up.net/overflow and I dont know how to put a link for github on the pictures displayed in the gallery (those 8 ) I want that when I click the pic and expand , the next click should sent me to a link and not to scroll over the next or previous picture.I tried to check the code but i found it to complicated for my actual level to figure it out . I am hoping that i can get some help here :) thank you

EDIT: I actualy need help in this part of code

When I click them twice I would like to send me to other links on other sites

Body:
if im understanding correctly what do you want do this

Change in your code..

<a href="#banner" class="button style2 scrolly-middle">Proceed as anticipated</a>

for

<a href="https://www...(URL)">Proceed as anticipated</a>

dont forget to remove remove class="..."


问:
Datepicker not displays when input hide according to selected category
I'm currently working on a project in Laravel & VueJs. I have the following dropdown list.

```<code><select class="form-control" v-model="form.type" @change="typeChange()">
    <option value="1">Repair</option>
    <option value="2">PM</option>
    <option value="3">Upgrade/NFC</option>
</select>
</code>```

According to the selected option, some fields appear like if I select PM following input field appears

```<code><input name="latest_pm_date" v-model="form.latest_pm_date" class="form-control boost-date" id="latest_pm_date" required="" placeholder="">
</code>```

But the Datepicker is not appearing when I click on the above input field. I use following code when the page loads:

```<code>mounted(){
    jQuery(".boost-date").datetimepicker({
        format: 'YYYY-MM-DD ',
    }).on('dp.change',  function(e) {
        let event = new Event('input');
        this.dispatchEvent(event);
    });
}
</code>```

However, I also used the above datepicker also in typeChange() function.

```<code>typeChange(){
    this.form.reminder_id = "";

    jQuery(".boost-date").datetimepicker({
        format: 'YYYY-MM-DD ',
    }).on('dp.change',  function(e) {
        let event = new Event('input');
        this.dispatchEvent(event);
    });
}
</code>```

Still, datepicker is not appearing. I think the reason for this is this input field is hidden when the page loads. And after I select PM from dropdown only this input field appears.

Can someone point me out what's the mistake here? Your help will be very much appreciated. Thank You!

答:
If it is "hidden" by v-if it is not in the DOM, so jQuery can't find it via jQuery(".boost-date")

You can try to solve it by using v-show which hid via CSS but the elements are not added or removed from the DOM.

Body:
I'm currently working on a project in Laravel & VueJs. I have the following dropdown list.

<select class="form-control" v-model="form.type" @change="typeChange()">
    <option value="1">Repair</option>
    <option value="2">PM</option>
    <option value="3">Upgrade/NFC</option>
</select>

According to the selected option, some fields appear like if I select PM following input field appears

<input name="latest_pm_date" v-model="form.latest_pm_date" class="form-control boost-date" id="latest_pm_date" required="" placeholder="">

But the Datepicker is not appearing when I click on the above input field. I use following code when the page loads:

mounted(){
    jQuery(".boost-date").datetimepicker({
        format: 'YYYY-MM-DD ',
    }).on('dp.change',  function(e) {
        let event = new Event('input');
        this.dispatchEvent(event);
    });
}

However, I also used the above datepicker also in typeChange() function.

typeChange(){
    this.form.reminder_id = "";

    jQuery(".boost-date").datetimepicker({
        format: 'YYYY-MM-DD ',
    }).on('dp.change',  function(e) {
        let event = new Event('input');
        this.dispatchEvent(event);
    });
}

Still, datepicker is not appearing. I think the reason for this is this input field is hidden when the page loads. And after I select PM from dropdown only this input field appears.

Can someone point me out what's the mistake here? Your help will be very much appreciated. Thank You!


问:
How to read a list of all users and their permissions of a certain team drive?
I would like to create in spreadsheet a list of all users how have access to a certain team drive (by name) including their permission.

And would like to change, revoke or limit by date the permission.

答:
In Apps Script you need to enable the Advanced Drive Service which allows you to use methods of the Drive API

In specific, you need the method Drive.Permissions.list(fileId, optionalArgs)

For this method, you need to specify the ID, no the name of the drive

If you don't know the ID, you can Logger.log the results of Drive.Teamdrives.list() which lists all your drive including name and ID

For optional properties you need to specify "supportsTeamDrives" : true

For changing the permission, you need the method Drive.Permissions.update(resource, fileId, permissionId, optionalArgs), specifying the parameters as indicated here


问:
How do I Rewrite URL from some-sub-domain.some-domain.com to some-domain.com/some-sub-domain
I want to rewrite my URL, so that I can reach the folder which is seen by the clients as sub-domain. Client will put the following in the URL Bar:

```<code>abc.def.com
</code>```

and by URL rewrite it will be gone to

```<code>def.com/abc
</code>```

silently. Please tell me how can I do that ?

答:
If you already know the subdomain, you can:

```<code>RewriteCond %{REMOTE_HOST} ^(?:www\.)?subdomain\.your_domain\.com [NC]
RewriteRule ^(.*) /subdomain/$1 [L]
</code>```

And if you wish to support ANY possible subdomain, use:

```<code>RewriteCond %{REMOTE_HOST} ^(?:www\.)?([^\.]+)\.your_domain\.com [NC]
RewriteRule ^(.*) /%1/$1 [L]
</code>```

Body:
I want to rewrite my URL, so that I can reach the folder which is seen by the clients as sub-domain. Client will put the following in the URL Bar:

abc.def.com

and by URL rewrite it will be gone to

def.com/abc

silently. Please tell me how can I do that ?

Body:
If you already know the subdomain, you can:

RewriteCond %{REMOTE_HOST} ^(?:www\.)?subdomain\.your_domain\.com [NC]
RewriteRule ^(.*) /subdomain/$1 [L]

And if you wish to support ANY possible subdomain, use:

RewriteCond %{REMOTE_HOST} ^(?:www\.)?([^\.]+)\.your_domain\.com [NC]
RewriteRule ^(.*) /%1/$1 [L]


问:
SwiftUI: Button in NavigationBar won't fire after modal dismissal
I'm running into some weird behavior, trying to get a simple modal to pop after it has been dismissed.

I have an Add button in the NavigationBar that pops a modal. The modal has a button that will dismiss it, which works. However, I cannot interact with the Add button in the NavigationBar again until I interact with something else on the screen, such as scrolling the List below.

I have also placed another Add button, just for kicks, in the List itself, which always works.

Here's the code for the main view:

```<code>import SwiftUI

struct ContentView: View {
  @State var displayModal: Bool = false

  var body: some View {
    NavigationView {
      List {
        Text("Hello again.")
          Button(action: { self.displayModal = true }) {
            Text("Add")
          }
      }
      .sheet(isPresented: $displayModal) {
        Modal(isPresented: self.$displayModal)
      }
      .navigationBarTitle("The Title")
      .navigationBarItems(trailing: Button(action: { self.displayModal = true }) {
        Text("Add")
      })
    }
  }
}
</code>```

And the modal, for completeness:

```<code>import SwiftUI

struct Modal: View {
  @Binding var isPresented: Bool

  var body: some View {
    VStack {
      HStack {
        Button(action: {
          self.isPresented = false
        }) {
          Text("Cancel")
        }
        .padding()
        Spacer()
      }
      Text("I am the modal")
      Spacer()
    }
  }
}
</code>```

The only thing I can think of is that something invisible is preventing me from working with the NavigationBar button. So I fired up the UI Debugger, and here's what the ContentView looks like. Note the NavigationBar button.

Now, after I tap the button and display the modal, and then use the UI Debugger to see the ContentView again, all the same elements are in place, but the Button parent views are offset a bit, like this:

Once I drag the List up and down, the UI Debugger shows a view hierarchy identical to the first image.

Does anyone have any idea what's going on here?

I'm using Xcode 11.2.1 and iOS 13 on an iPhone 11 Pro simulator, but have also observed this on my iPhone.

答:
I ran into the same issue, and for me the workaround was to use an inline-style navigation bar title on the presenter.

```<code>.navigationBarTitle(Text("The Title"), displayMode: .inline)
</code>```

HOWEVER, if you use a custom accent color on your ContentView (like .accentColor(Color.green)), this workaround no longer works.

Edit: the bug seems fixed in 13.4, and no workarounds are needed anymore.

Body:
I'm running into some weird behavior, trying to get a simple modal to pop after it has been dismissed.

I have an Add button in the NavigationBar that pops a modal. The modal has a button that will dismiss it, which works. However, I cannot interact with the Add button in the NavigationBar again until I interact with something else on the screen, such as scrolling the List below.

I have also placed another Add button, just for kicks, in the List itself, which always works.

Here's the code for the main view:

import SwiftUI

struct ContentView: View {
  @State var displayModal: Bool = false

  var body: some View {
    NavigationView {
      List {
        Text("Hello again.")
          Button(action: { self.displayModal = true }) {
            Text("Add")
          }
      }
      .sheet(isPresented: $displayModal) {
        Modal(isPresented: self.$displayModal)
      }
      .navigationBarTitle("The Title")
      .navigationBarItems(trailing: Button(action: { self.displayModal = true }) {
        Text("Add")
      })
    }
  }
}

And the modal, for completeness:

import SwiftUI

struct Modal: View {
  @Binding var isPresented: Bool

  var body: some View {
    VStack {
      HStack {
        Button(action: {
          self.isPresented = false
        }) {
          Text("Cancel")
        }
        .padding()
        Spacer()
      }
      Text("I am the modal")
      Spacer()
    }
  }
}

The only thing I can think of is that something invisible is preventing me from working with the NavigationBar button. So I fired up the UI Debugger, and here's what the ContentView looks like. Note the NavigationBar button.

Now, after I tap the button and display the modal, and then use the UI Debugger to see the ContentView again, all the same elements are in place, but the Button parent views are offset a bit, like this:

Once I drag the List up and down, the UI Debugger shows a view hierarchy identical to the first image.

Does anyone have any idea what's going on here?

I'm using Xcode 11.2.1 and iOS 13 on an iPhone 11 Pro simulator, but have also observed this on my iPhone.

Body:
I ran into the same issue, and for me the workaround was to use an inline-style navigation bar title on the presenter.

.navigationBarTitle(Text("The Title"), displayMode: .inline)

HOWEVER, if you use a custom accent color on your ContentView (like .accentColor(Color.green)), this workaround no longer works.

Edit: the bug seems fixed in 13.4, and no workarounds are needed anymore.


问:
Get IMEI from Android using browser like iOS
In iOS is possible to obtain IMEI using Safari after install a profile in device.E.g:

https://get.udid.io

Is it possible to get UDID from iPhone safari browser?

get iphone ID in web app

From Android 10 its't possible obtain IMEI programmatically.I want to know if it is possible to obtain it from Android in a method similar to iOS.

Do you have any ideas? Thanks a lot!

答:
No, it's not possible.

Also, Google Clearly says "Third-party apps installed from the Google Play Store cannot declare privileged permissions."

For more details regarding the privacy, you can check the below link.
https://developer.android.com/about/versions/10/privacy/changes#data-ids


问:
Should I pack parameters of my rest controller into class or as seperate strings spring boot
I have a controller with multiple endpoints. Those endpoints serve the same domain. But the input parameters differ a bit from each other.

For example:

```<code>endpointA:
 - username
 - firstname
 - address

endpointB:
 - username
 - phoneNumber
 - addresss

endpointC:
 - username
 - email
 - workAddress
</code>```

At the moment every parameter is a String which I pass it to the service responsible for handling the endpoint...
I am also performing validation. Each parameter has its own requirements for validating. So I implemented a custom validation (just a class with static methods for each param I need to validate) for each of them and validate those string before passing them to the service.

I found a really nice way of doing validation:
http://dolszewski.com/spring/custom-validation-annotation-in-spring/
Here he creates a model and on input param it validates it with @Valid validation logic is implemented with custom validator and can be specified for every attribute.

I havent found a way to do this for String and doing it for every param. So I thought I would create a wrapper object for each endpoint's params. Annotate attributes with custom validators and that's it. The problem is that with multiple endpoints I'd have lots of classes and duplicate code...

Is it sensible to create a UserRequest object. Implement validation on every attribute and have that object as input parameter on each endpoint.

End result would look like:

```<code>UserRequestModel
  @usernameValidation
  username
  @firsstnameValidation
  firstname
  @addressValidation
  addresss
  @phonenumberValidation
  phoneNumber
  @emailValidation
  email
  @workaddressValidation
  workaddress

endpointA:
 - UserRequestModel

endpointB:
 - UserRequestModel

endpointC:
 - UserRequestModel
</code>```

Attributes not needed in all endpoints would be marked as optional.

I also use swagger for API docs that auto-generates endpoints for testing API. Would be possible to tell swagger which attributes are needed for each endpoint?

I am looking for tips and best patterns to handle situations like this. Thanks in advance!

答:
I don't see any problem in having three different classes, one for each of your endpoints, and each of them would define their fields (even if duplicate). You have the validation logic in one place only. For example, the logic for @usernameValidation is defined only once, in the validator implementation.

So, I would go for:

```<code>UserRequestModelA
  @usernameValidation
  username
  @firsstnameValidation
  firstname
  @addressValidation
  address

UserRequestModelB
  @usernameValidation
  username
  @phonenumberValidation
  phoneNumber
  @addressValidation
  address

UserRequestModelC
  @usernameValidation
  username
  @emailValidation
  email
  @workaddressValidation
  workaddress

endpointA:
 - UserRequestModelA

endpointB:
 - UserRequestModelB

endpointC:
 - UserRequestModelC
</code>```

Alternatively, if you'd really want some sort of fields re-usage, you could opt for class extension. You should have a base class that has only the common fields, and your other classes specific per endpoint would extend that base class, as below:

```<code>UserRequestModel
  @usernameValidation
  username

UserRequestModelA extends UserRequestModel
  @firsstnameValidation
  firstname
  @addressValidation
  address

UserRequestModelB extends UserRequestModel
  @phonenumberValidation
  phoneNumber
  @addressValidation
  address

UserRequestModelC extends UserRequestModel
  @emailValidation
  email
  @workaddressValidation
  workaddress

endpointA:
 - UserRequestModelA

endpointB:
 - UserRequestModelB

endpointC:
 - UserRequestModelC

</code>```

Body:
I have a controller with multiple endpoints. Those endpoints serve the same domain. But the input parameters differ a bit from each other.

For example:

endpointA:
 - username
 - firstname
 - address

endpointB:
 - username
 - phoneNumber
 - addresss

endpointC:
 - username
 - email
 - workAddress

At the moment every parameter is a String which I pass it to the service responsible for handling the endpoint...
I am also performing validation. Each parameter has its own requirements for validating. So I implemented a custom validation (just a class with static methods for each param I need to validate) for each of them and validate those string before passing them to the service.

I found a really nice way of doing validation:
http://dolszewski.com/spring/custom-validation-annotation-in-spring/
Here he creates a model and on input param it validates it with @Valid validation logic is implemented with custom validator and can be specified for every attribute.

I havent found a way to do this for String and doing it for every param. So I thought I would create a wrapper object for each endpoint's params. Annotate attributes with custom validators and that's it. The problem is that with multiple endpoints I'd have lots of classes and duplicate code...

Is it sensible to create a UserRequest object. Implement validation on every attribute and have that object as input parameter on each endpoint.

End result would look like:

UserRequestModel
  @usernameValidation
  username
  @firsstnameValidation
  firstname
  @addressValidation
  addresss
  @phonenumberValidation
  phoneNumber
  @emailValidation
  email
  @workaddressValidation
  workaddress

endpointA:
 - UserRequestModel

endpointB:
 - UserRequestModel

endpointC:
 - UserRequestModel

Attributes not needed in all endpoints would be marked as optional.

I also use swagger for API docs that auto-generates endpoints for testing API. Would be possible to tell swagger which attributes are needed for each endpoint?

I am looking for tips and best patterns to handle situations like this. Thanks in advance!

Body:
I don't see any problem in having three different classes, one for each of your endpoints, and each of them would define their fields (even if duplicate). You have the validation logic in one place only. For example, the logic for @usernameValidation is defined only once, in the validator implementation.

So, I would go for:

UserRequestModelA
  @usernameValidation
  username
  @firsstnameValidation
  firstname
  @addressValidation
  address

UserRequestModelB
  @usernameValidation
  username
  @phonenumberValidation
  phoneNumber
  @addressValidation
  address

UserRequestModelC
  @usernameValidation
  username
  @emailValidation
  email
  @workaddressValidation
  workaddress

endpointA:
 - UserRequestModelA

endpointB:
 - UserRequestModelB

endpointC:
 - UserRequestModelC

Alternatively, if you'd really want some sort of fields re-usage, you could opt for class extension. You should have a base class that has only the common fields, and your other classes specific per endpoint would extend that base class, as below:

UserRequestModel
  @usernameValidation
  username

UserRequestModelA extends UserRequestModel
  @firsstnameValidation
  firstname
  @addressValidation
  address

UserRequestModelB extends UserRequestModel
  @phonenumberValidation
  phoneNumber
  @addressValidation
  address

UserRequestModelC extends UserRequestModel
  @emailValidation
  email
  @workaddressValidation
  workaddress

endpointA:
 - UserRequestModelA

endpointB:
 - UserRequestModelB

endpointC:
 - UserRequestModelC


问:
Select Top n Values from Excel Row
I'm struggling tremendously with this problem. I have a row (B14:CW15) of integers that count how many times each unique string occurs within the original string. It is structured like so.

```<code>Biagrams:        +h hb bl I) )m mj jk km mm mk k^ mm +h
Unique Biagrams: +h hb bl I) )m mj jk km mm mk k^
Biagram Count:   2  1  1  1  1  1  1  1  2  1  1
</code>```

I can't for the life of my figure out how I can extract the top n biagrams from this without excel selecting duplicate biagrams. The Large() function has not worked as it will return the same biagram for each number, not unique biagrams for the same number.

答:
If Range of Cells is B1:B10, and you want to calculate Sum of Top 5 values. Apply Following

```<code>=Sum(LARGE(B1:B10, {1,2,3,4,5}))
</code>```

It works. Check it

Title: Select Top n Values from Excel Row

Body:
I'm struggling tremendously with this problem. I have a row (B14:CW15) of integers that count how many times each unique string occurs within the original string. It is structured like so.

Biagrams:        +h hb bl I) )m mj jk km mm mk k^ mm +h
Unique Biagrams: +h hb bl I) )m mj jk km mm mk k^
Biagram Count:   2  1  1  1  1  1  1  1  2  1  1

I can't for the life of my figure out how I can extract the top n biagrams from this without excel selecting duplicate biagrams. The Large() function has not worked as it will return the same biagram for each number, not unique biagrams for the same number.

Body:
If Range of Cells is B1:B10, and you want to calculate Sum of Top 5 values. Apply Following

=Sum(LARGE(B1:B10, {1,2,3,4,5}))

It works. Check it


问:
Compute pairs from two lists that when multiplied make a perfect square
You are given two lists and you have to find out the pairs which make a perfect square.

For example in:

```<code>a = [2, 6, 10, 13, 17, 18]

b = [3, 7, 8, 9, 11, 15]
</code>```

There are two pairs (2,8) and (8,18).

Is there any method efficient than the brute-force?
Here is my code which has a time complexity of O(n*m)
(where n is the length of a and m is the length of b).

```<code>pl = []
a = [ 2, 6, 10, 13, 17,18]
b = [ 3, 7, 8, 9, 11, 15 ]
i = 0
while(i < len(a)):
    j = 0
    while(j < len(b)):
        p = a[i]*b[j]
        n = p**0.5
        u = int(n)
        if n == u:
            pl.append((a[i],b[j]))

        j = j+1

    i = i+1

print(pl)
</code>```

This question has been asked before using C# here, but I don't get what they mean by "All we would need to store for each number is which of its prime factors have an odd count", so I can't implement this in my Python code.

Can someone explain to me how we might implement an efficient solution in Python?

答:
The logic described in the linked question is as follows. A perfect square's prime factors will always be in pairs. For example, 36 = 2*2*3*3. We have two 3s and two 2s. Therefore, if we take any two numbers that multiply to form a perfect square, if we take the combined counts of each of their prime factors, we will also get even counts.

For example, 8 = 2*2*2, and 18 = 2*3*3. Combined, we get four 2s and two 3s.

Below is some Python code that implements this algorithm, using collections.Counter and sets to remove duplicates. First, we precompute all prime factorizations for each unique element in a and b to avoid redundancy, and store this in a dictionary. Then, we loop over pairs of elements from a and b, using itertools.product, and combine the prime factor counts. If every count is even, we add the sorted pair to a set.

Code:

```<code>from collections import Counter
import itertools

def prime_factors(n):
    """
    https://stackoverflow.com/a/22808285/12366110
    """
    i = 2
    factors = []
    while i * i <= n:
        if n % i:
            i += 1
        else:
            n //= i
            factors.append(i)
    if n > 1:
        factors.append(n)
    return Counter(factors)

a = [2, 6, 10, 13, 17,18]

b = [3, 7, 8, 9, 11, 15]

prime_factors = {i: prime_factors(i) for i in set(a) | set(b)}

rv = set()

for a, b in itertools.product(a, b):
    combined_counts = prime_factors[a] + prime_factors[b]
    if all(v%2 == 0 for v in combined_counts.values()):
        rv.add(tuple(sorted([a, b])))
</code>```

Output:

```<code>>>> rv
{(2, 8), (8, 18)}
</code>```

Body:
You are given two lists and you have to find out the pairs which make a perfect square.

For example in:

a = [2, 6, 10, 13, 17, 18]

b = [3, 7, 8, 9, 11, 15]

There are two pairs (2,8) and (8,18).

Is there any method efficient than the brute-force?
Here is my code which has a time complexity of O(n*m)
(where n is the length of a and m is the length of b).

pl = []
a = [ 2, 6, 10, 13, 17,18]
b = [ 3, 7, 8, 9, 11, 15 ]
i = 0
while(i < len(a)):
    j = 0
    while(j < len(b)):
        p = a[i]*b[j]
        n = p**0.5
        u = int(n)
        if n == u:
            pl.append((a[i],b[j]))

        j = j+1

    i = i+1

print(pl)

This question has been asked before using C# here, but I don't get what they mean by "All we would need to store for each number is which of its prime factors have an odd count", so I can't implement this in my Python code.

Can someone explain to me how we might implement an efficient solution in Python?

Body:
The logic described in the linked question is as follows. A perfect square's prime factors will always be in pairs. For example, 36 = 2*2*3*3. We have two 3s and two 2s. Therefore, if we take any two numbers that multiply to form a perfect square, if we take the combined counts of each of their prime factors, we will also get even counts.

For example, 8 = 2*2*2, and 18 = 2*3*3. Combined, we get four 2s and two 3s.

Below is some Python code that implements this algorithm, using collections.Counter and sets to remove duplicates. First, we precompute all prime factorizations for each unique element in a and b to avoid redundancy, and store this in a dictionary. Then, we loop over pairs of elements from a and b, using itertools.product, and combine the prime factor counts. If every count is even, we add the sorted pair to a set.

Code:

from collections import Counter
import itertools

def prime_factors(n):
    """
    https://stackoverflow.com/a/22808285/12366110
    """
    i = 2
    factors = []
    while i * i <= n:
        if n % i:
            i += 1
        else:
            n //= i
            factors.append(i)
    if n > 1:
        factors.append(n)
    return Counter(factors)

a = [2, 6, 10, 13, 17,18]

b = [3, 7, 8, 9, 11, 15]

prime_factors = {i: prime_factors(i) for i in set(a) | set(b)}

rv = set()

for a, b in itertools.product(a, b):
    combined_counts = prime_factors[a] + prime_factors[b]
    if all(v%2 == 0 for v in combined_counts.values()):
        rv.add(tuple(sorted([a, b])))

Output:

>>> rv
{(2, 8), (8, 18)}


问:
Android Studio: create another activity (package name is not set to a valid package name)
My android application has a package spectorsky placed directly in java1 catalog. Incide this package, there is launched activity MainActivity, and I need to create additional activity in the same package.

However when I call New activity dialog and type spectorky as a package name, error package name is not set to a valid package name appears.

Dialog suggests com.tmp.spectorsky.calendar as a package name (calendar is a name of the app), but this creates some directories and places new activity in a new created package.

So, the question: how to create new activity in the same package?

Thanks for any idea

答:
Your activity package name should start with your project package name. your activity package must present in your project package.

1st change your view from project to android
if you want to create your own package then right-click on the 1st package name then choose to create the package. After that right-click on your package name then create activity.


问:
Unbalanced data and weighted cross entropy
I'm trying to train a network with an unbalanced data. I have A (198 samples), B (436 samples), C (710 samples), D (272 samples) and I have read about the "weighted_cross_entropy_with_logits" but all the examples I found are for binary classification so I'm not very confident in how to set those weights.

Total samples: 1616

A_weight: 198/1616 = 0.12?

The idea behind, if I understood, is to penalize the errors of the majority class and value more positively the hits in the minority one, right?

My piece of code:

```<code>weights = tf.constant([0.12, 0.26, 0.43, 0.17])
cost = tf.reduce_mean(tf.nn.weighted_cross_entropy_with_logits(logits=pred, targets=y, pos_weight=weights))
</code>```

I have read this one and others examples with binary classification but still not very clear.

答:
Tensorflow 2.0 Compatible Answer: Migrating the Code specified in P-Gn's Answer to 2.0, for the benefit of the community.

```<code># your class weights
class_weights = tf.compat.v2.constant([[1.0, 2.0, 3.0]])
# deduce weights for batch samples based on their true label
weights = tf.compat.v2.reduce_sum(class_weights * onehot_labels, axis=1)
# compute your (unweighted) softmax cross entropy loss
unweighted_losses = tf.compat.v2.nn.softmax_cross_entropy_with_logits(onehot_labels, logits)
# apply the weights, relying on broadcasting of the multiplication
weighted_losses = unweighted_losses * weights
# reduce the result to get your final loss
loss = tf.reduce_mean(weighted_losses)
</code>```

For more information about migration of code from Tensorflow Version 1.x to 2.x, please refer this Migration Guide.

Body:
I'm trying to train a network with an unbalanced data. I have A (198 samples), B (436 samples), C (710 samples), D (272 samples) and I have read about the "weighted_cross_entropy_with_logits" but all the examples I found are for binary classification so I'm not very confident in how to set those weights.

Total samples: 1616

A_weight: 198/1616 = 0.12?

The idea behind, if I understood, is to penalize the errors of the majority class and value more positively the hits in the minority one, right?

My piece of code:

weights = tf.constant([0.12, 0.26, 0.43, 0.17])
cost = tf.reduce_mean(tf.nn.weighted_cross_entropy_with_logits(logits=pred, targets=y, pos_weight=weights))

I have read this one and others examples with binary classification but still not very clear.

Body:
Tensorflow 2.0 Compatible Answer: Migrating the Code specified in P-Gn's Answer to 2.0, for the benefit of the community.

# your class weights
class_weights = tf.compat.v2.constant([[1.0, 2.0, 3.0]])
# deduce weights for batch samples based on their true label
weights = tf.compat.v2.reduce_sum(class_weights * onehot_labels, axis=1)
# compute your (unweighted) softmax cross entropy loss
unweighted_losses = tf.compat.v2.nn.softmax_cross_entropy_with_logits(onehot_labels, logits)
# apply the weights, relying on broadcasting of the multiplication
weighted_losses = unweighted_losses * weights
# reduce the result to get your final loss
loss = tf.reduce_mean(weighted_losses)

For more information about migration of code from Tensorflow Version 1.x to 2.x, please refer this Migration Guide.


问:
How do I make a TextInput editable and focus on it in the same go?
I have the following code:

```<code>    const handleClick = () => {
        setToggleEditable(true);
        textInput.current.focus();
    }
</code>```

A button triggers this when pressed, setting the TextInput with the ref "textInput" to be editable, and then tries to focus on it. However, it never focuses on it the first time the button is pressed. I think that is because the TextInput hasn't finished being set as editalbe, so it can't focus on it. Is there any way I can change this?

答:
I had a similar problem, I fixed it by waiting a little (100-150 ms) after button was pressed and then focusing on textinput</p>

```<code>  focusOn = (ref: TextInput) => {
    setTimeout(() => ref.focus(), 100)
  }
</code>```

Body:
I have the following code:

    const handleClick = () => {
        setToggleEditable(true);
        textInput.current.focus();
    }

A button triggers this when pressed, setting the TextInput with the ref "textInput" to be editable, and then tries to focus on it. However, it never focuses on it the first time the button is pressed. I think that is because the TextInput hasn't finished being set as editalbe, so it can't focus on it. Is there any way I can change this?

Body:
I had a similar problem, I fixed it by waiting a little (100-150 ms) after button was pressed and then focusing on textinput

  focusOn = (ref: TextInput) => {
    setTimeout(() => ref.focus(), 100)
  }


问:
soft keyboard not appearing
I have a following dialog:

```<code>import android.app.AlertDialog;

public class IpDiscoveryDialog extends AlertDialog implements View.OnClickListener {

    private View view;
    private Context context;
    private Activity activity;

    private EditText ipEditText;

    protected IpDiscoveryDialog(Context context) {
        super(context);
        this.context = context;
    }

    public IpDiscoveryDialog(Context context, Activity activity) {
        this(context);
        this.activity = activity;
    }

    @Override
    public void setContentView(int layoutResID) {
        View view = getLayoutInflater().inflate(layoutResID, null);
        this.view = view;
        this.setContentView(view);
    }

    @Override
    public void setContentView(@NonNull View view) {
        super.setContentView(view);
        this.buildView(view);
        this.setCancelable(false);
    }

    private void buildView(View view) {
        view.findViewById(R.id.ipConfirmButton).setOnClickListener(this);
        this.ipEditText = view.findViewById(R.id.ipEditText);
    }
}
</code>```

I open it from a different activity like this:

```<code>IpDiscoveryDialog ipDiscoveryDialog = new IpDiscoveryDialog(ScanDevicesActivity.this, ScanDevicesActivity.this);
ipDiscoveryDialog.create();
ipDiscoveryDialog.setContentView(R.layout.ip_discovery_dialog);
ipDiscoveryDialog.show();
</code>```

And the layout of the dialog is the following:

```<code><?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:padding="10dp">

    <TextView
        android:id="@+id/textView8"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="@string/set_ip_address"
        android:textAlignment="center"
        android:textColor="@android:color/black"
        android:textSize="24sp" />

    <EditText
        android:id="@+id/ipEditText"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:ems="10"
        android:hint="@string/ip_address"
        android:importantForAutofill="no"
        android:inputType="text" >

        <requestFocus />
    </EditText>

    <Button
        android:id="@+id/ipConfirmButton"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="@string/confirm" />
</LinearLayout>
</code>```

The problem I have is that no matter what I do, I cannot open soft keyboard to edit that EditText. I tried open it manually in code, I tried different settings, nothing works.

Code like this does not work:

```<code>InputMethodManager mImm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
mImm.showSoftInput(SearchEdit, InputMethodManager.SHOW_IMPLICIT);
</code>```

What else can I try? What is the issue here?

答:
Try this class</p>

```<code>public class IpDiscoveryDialog extends AlertDialog implements View.OnClickListener {

private View view;
private Context context;
private Activity activity;

private EditText ipEditText;

protected IpDiscoveryDialog(Context context) {
    super(context);
    this.context = context;
}

public IpDiscoveryDialog(Context context, Activity activity) {
    this(context);
    this.activity = activity;
}

@Override
protected void onCreate(Bundle savedInstanceState) {
    setContentView(R.layout.ip_discovery_dialog);
    getWindow().clearFlags(WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE | WindowManager.LayoutParams.FLAG_ALT_FOCUSABLE_IM);
    getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_VISIBLE);
    buildView();
    this.setCancelable(false);
}

private void buildView() {
    findViewById(R.id.ipConfirmButton).setOnClickListener(this);
    this.ipEditText = findViewById(R.id.ipEditText);
}

@Override
public void onClick(View v) {

}
}
</code>```

Title: soft keyboard not appearing

Body:
I have a following dialog:

import android.app.AlertDialog;

public class IpDiscoveryDialog extends AlertDialog implements View.OnClickListener {

    private View view;
    private Context context;
    private Activity activity;

    private EditText ipEditText;

    protected IpDiscoveryDialog(Context context) {
        super(context);
        this.context = context;
    }

    public IpDiscoveryDialog(Context context, Activity activity) {
        this(context);
        this.activity = activity;
    }

    @Override
    public void setContentView(int layoutResID) {
        View view = getLayoutInflater().inflate(layoutResID, null);
        this.view = view;
        this.setContentView(view);
    }

    @Override
    public void setContentView(@NonNull View view) {
        super.setContentView(view);
        this.buildView(view);
        this.setCancelable(false);
    }

    private void buildView(View view) {
        view.findViewById(R.id.ipConfirmButton).setOnClickListener(this);
        this.ipEditText = view.findViewById(R.id.ipEditText);
    }
}

I open it from a different activity like this:

IpDiscoveryDialog ipDiscoveryDialog = new IpDiscoveryDialog(ScanDevicesActivity.this, ScanDevicesActivity.this);
ipDiscoveryDialog.create();
ipDiscoveryDialog.setContentView(R.layout.ip_discovery_dialog);
ipDiscoveryDialog.show();

And the layout of the dialog is the following:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:padding="10dp">

    <TextView
        android:id="@+id/textView8"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="@string/set_ip_address"
        android:textAlignment="center"
        android:textColor="@android:color/black"
        android:textSize="24sp" />

    <EditText
        android:id="@+id/ipEditText"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:ems="10"
        android:hint="@string/ip_address"
        android:importantForAutofill="no"
        android:inputType="text" >

        <requestFocus />
    </EditText>

    <Button
        android:id="@+id/ipConfirmButton"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="@string/confirm" />
</LinearLayout>

The problem I have is that no matter what I do, I cannot open soft keyboard to edit that EditText. I tried open it manually in code, I tried different settings, nothing works.

Code like this does not work:

InputMethodManager mImm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
mImm.showSoftInput(SearchEdit, InputMethodManager.SHOW_IMPLICIT);

What else can I try? What is the issue here?

Body:
Try this class

public class IpDiscoveryDialog extends AlertDialog implements View.OnClickListener {

private View view;
private Context context;
private Activity activity;

private EditText ipEditText;

protected IpDiscoveryDialog(Context context) {
    super(context);
    this.context = context;
}

public IpDiscoveryDialog(Context context, Activity activity) {
    this(context);
    this.activity = activity;
}

@Override
protected void onCreate(Bundle savedInstanceState) {
    setContentView(R.layout.ip_discovery_dialog);
    getWindow().clearFlags(WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE | WindowManager.LayoutParams.FLAG_ALT_FOCUSABLE_IM);
    getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_VISIBLE);
    buildView();
    this.setCancelable(false);
}

private void buildView() {
    findViewById(R.id.ipConfirmButton).setOnClickListener(this);
    this.ipEditText = findViewById(R.id.ipEditText);
}

@Override
public void onClick(View v) {

}
}


问:
Python - Pandas - Replace a string from a column based on the value from other column - Dealing with substrings
Based on the following post:
Python - Pandas - Replace a string from a column based on the value from other column

I was doing some similar on my side and I have faced new challenges. I use the same example as the previous post.

The new challenge that consists with the substrings.

Imagine that I have the following dataframe:

What I am trying is to replace on col2 the values that exists on col0 with the values from col2.

If I use the code (it is the same from the previous post):

```<code>df['col3'] = df['col1'].replace(df['col0'].values, df['col2'].values, regex = True)
</code>```

I will return the following dataframe:

And what I am trying is the following one:

Can I add some more precision on .values to achieve this?

Thanks!

答:
Use re.sub with replace by rows in DataFrame.apply:

```<code>import re

df['col3'] = df.apply(lambda x: re.sub(x['col0'],x['col2'],x['col1']), axis=1)
</code>```

Or in list comprehension:

```<code>df['col3'] = [re.sub(a,c,b) for a,b,c in df[['col0','col1','col2']].to_numpy()]
</code>```

```<code>print (df)
        col0                  col1     col2                col3
0    Table 1    Tablename: Table 1  Table A  Tablename: Table A
1    Table 2    Tablename: Table 2  Table B  Tablename: Table B
2  Table 2_1  Tablename: Table 2_1  Table C  Tablename: Table C
</code>```

Body:
Based on the following post:
Python - Pandas - Replace a string from a column based on the value from other column

I was doing some similar on my side and I have faced new challenges. I use the same example as the previous post.

The new challenge that consists with the substrings.

Imagine that I have the following dataframe:

What I am trying is to replace on col2 the values that exists on col0 with the values from col2.

If I use the code (it is the same from the previous post):

df['col3'] = df['col1'].replace(df['col0'].values, df['col2'].values, regex = True)

I will return the following dataframe:

And what I am trying is the following one:

Can I add some more precision on .values to achieve this?

Thanks!

Body:
Use re.sub with replace by rows in DataFrame.apply:

import re

df['col3'] = df.apply(lambda x: re.sub(x['col0'],x['col2'],x['col1']), axis=1)

Or in list comprehension:

df['col3'] = [re.sub(a,c,b) for a,b,c in df[['col0','col1','col2']].to_numpy()]

print (df)
        col0                  col1     col2                col3
0    Table 1    Tablename: Table 1  Table A  Tablename: Table A
1    Table 2    Tablename: Table 2  Table B  Tablename: Table B
2  Table 2_1  Tablename: Table 2_1  Table C  Tablename: Table C


问:
Adding dictonary with static keys inside another dictonary in python 3
I wanna make a dictonary with another dictonary that have fixed keys e.g

```<code>dic1 = {'filename':'file1','namelen':'5'}
dic2 = {
"file1":dic1,
"file2":dic2,
...
...
}
</code>```

The issue with my code is adding a new dictonary overwrites all the exisitng inner dictonary.

```<code>dic1 ={}
dic2 ={}
file_list = ["file1","file2", "file3"]
for file in file_list:
 dic1["filename"] = file
 dic1["namelen"] = len(file)
 dic2[file] = dic1
print(dic2)
</code>```

My dictonary looks like this

```<code>    dic2 =
{
'file1': {'namelen': 5, 'filename': 'file3'},
'file3': {'namelen': 5, 'filename': 'file3'},
'file2': {'namelen': 5, 'filename': 'file3'}
}
</code>```

How to prevent the overwrite, without switching to list ?

答:
You can use a single line of python code in for to achieve your result.

dic ={}
file_list = ["file1","file2", "file3"]
for file in file_list:
    dic[file] = { "filename": file, "namelen": len(file) }
print(dic)
```

<h3>Output</h3>

```{
   'file1': {'filename': 'file1', 'namelen': 5},
   'file2': {'filename': 'file2', 'namelen': 5},
   'file3': {'filename': 'file3', 'namelen': 5}
}
```

Body:
I wanna make a dictonary with another dictonary that have fixed keys e.g

dic1 = {'filename':'file1','namelen':'5'}
dic2 = {
"file1":dic1,
"file2":dic2,
...
...
}

The issue with my code is adding a new dictonary overwrites all the exisitng inner dictonary.

dic1 ={}
dic2 ={}
file_list = ["file1","file2", "file3"]
for file in file_list:
 dic1["filename"] = file
 dic1["namelen"] = len(file)
 dic2[file] = dic1
print(dic2)

My dictonary looks like this

    dic2 =
{
'file1': {'namelen': 5, 'filename': 'file3'},
'file3': {'namelen': 5, 'filename': 'file3'},
'file2': {'namelen': 5, 'filename': 'file3'}
}

How to prevent the overwrite, without switching to list ?

Body:
You can use a single line of python code in for to achieve your result.

dic ={}
file_list = ["file1","file2", "file3"]
for file in file_list:
    dic[file] = { "filename": file, "namelen": len(file) }
print(dic)

Output

{
   'file1': {'filename': 'file1', 'namelen': 5},
   'file2': {'filename': 'file2', 'namelen': 5},
   'file3': {'filename': 'file3', 'namelen': 5}
}


问:
How to add value to a list in class that have a string array?
I am creating a tournument app that will have group stage and knockouts. I'm using a class with a list to create different groups so i can save them to an xml file later.

this is how my list and class looks like (xmlHandlerScript).

```<code>public void AddGroup(int group,string[] team)
{

    groupDB.list.Add(new Groups { groupIndex = group, team = team });
}

public GroupDatabse groupDB;

[System.Serializable]
public class Groups
{
    public int groupIndex;
    public string[] team;
}

[System.Serializable]
public class GroupDatabse
{
    public List<Groups> list = new List<Groups>();
}
</code>```

this is how i add value to list variables.

```<code> groups = new string[totalTeamsPerGroup];
 int  j = 0;

  for(int i = 0; i < totalGroups; i++)
  {
        for (int x = 0; x < totalTeamsPerGroup; x++)
        {

            groups[x] = teams[j];
            j++;
        }
            xmlHandlerScript.AddGroup(i, groups);

   }
</code>```

My problem is when i have more then 1 "totalGroups" and add the array "groups" to the List, the string[] team gets replaced with the last teams[] in both my arrays

like this:

Teams in Tournument
Groups after i added them to list

答:
Try this - you need to re-initialize the groups list for each team iteration. I've used a List instead of an array since Lists in c# are much simpler to manage.</p>

```<code> int  j = 0;

  for(int i = 0; i < totalGroups; i++)
  {
       var groups = new List<string>();
        for (int x = 0; x < totalTeamsPerGroup; x++)
        {

            groups.Add(teams[j]);
            j++;
        }
            xmlHandlerScript.AddGroup(i, groups);

   }
</code>```

Body:
I am creating a tournument app that will have group stage and knockouts. I'm using a class with a list to create different groups so i can save them to an xml file later.

this is how my list and class looks like (xmlHandlerScript).

public void AddGroup(int group,string[] team)
{

    groupDB.list.Add(new Groups { groupIndex = group, team = team });
}

public GroupDatabse groupDB;

[System.Serializable]
public class Groups
{
    public int groupIndex;
    public string[] team;
}

[System.Serializable]
public class GroupDatabse
{
    public List<Groups> list = new List<Groups>();
}

this is how i add value to list variables.

 groups = new string[totalTeamsPerGroup];
 int  j = 0;

  for(int i = 0; i < totalGroups; i++)
  {
        for (int x = 0; x < totalTeamsPerGroup; x++)
        {

            groups[x] = teams[j];
            j++;
        }
            xmlHandlerScript.AddGroup(i, groups);

   }

My problem is when i have more then 1 "totalGroups" and add the array "groups" to the List, the string[] team gets replaced with the last teams[] in both my arrays

like this:

Teams in Tournument
Groups after i added them to list

Body:
Try this - you need to re-initialize the groups list for each team iteration. I've used a List instead of an array since Lists in c# are much simpler to manage.

 int  j = 0;

  for(int i = 0; i < totalGroups; i++)
  {
       var groups = new List<string>();
        for (int x = 0; x < totalTeamsPerGroup; x++)
        {

            groups.Add(teams[j]);
            j++;
        }
            xmlHandlerScript.AddGroup(i, groups);

   }


问:
Rpy2 on windows
I want to install rpy2 on my windows machine and it gives me the following famous error

```<code>      self.convert_pycparser_error(e, csource)
      File "c:\users\96171\appdata\local\temp\pip-install-lxsxk7q4\rpy2\.eggs\cffi-1.14.0-py3.6-win-amd64.egg\cffi\cparser.py", line 336, in convert_pycparser_error
        raise CDefError(msg)
    cffi.CDefError: cannot parse "void __cffi_extern_python_start; void _capsule_finalizer(SEXP); void __cffi_extern_python_stop;"
    <cdef source string>:495:96: Illegal character '\r'

    ----------------------------------------
Command "python setup.py egg_info" failed with error code 1 in C:\Users\96171\AppData\Local\Temp\pip-install-lxsxk7q4\rpy2\

</code>```

I have done the following:

upgraded set up tools

upgraded pip to the latest version

I have followed the link here for installing rpy2 on windows and they're saying we have to download a precompiled binary in order for this to work.

I have downloaded from the followinf link this wheel:
rpy2‑2.9.5‑cp37‑cp37m‑win_amd64.whl however I am still facing trouble; I did as follows:

After I downloaded rpy2‑2.9.5‑cp37‑cp37m‑win_amd64.whl

I opened cmd as Administrator in the directory where the wheel is downloaded

I set %R_USER% in the system variables to my username as such: R_USER C:\Users\my_username
However I am getting the following error:

ERROR: rpy2-2.9.5-cp37-cp37m-win_amd64.whl is not a supported wheel on this platform.

in the website for the binaries they say that:

Rpy2 (discontinued, unstable): provide access to the R software environment for statistical computing and graphics. Requires R 3.3, and I have R 3.6.2 on  my system. Is this causing the error?

答:
OLD ANSWER

The issue was that I downloaded the wrong wheel. cp37 means CPython 3.7 and I have python 3.6 on my system. I downloaded rpy2-2.9.5-cp36-cp36m-win_amd64.whl istead of rpy2-2.9.5-cp37-cp37m-win_amd64.whl and it worked.

Also as I faced problems with R_USERand R_HOME I did the following in my python script:

```<code>import os
# see the following 2 lines
os.environ['R_HOME'] = 'C:/Program Files/R/R-3.6.2'
os.environ['R_USER'] = 'C:/Users/96171/AppData/Local/Programs/Python/Python36/Lib/site-packages/rpy2' #path depends on where you installed Python. Mine is the site packages of the regular python installation, it could have been Anaconda

# importing rpy2
import rpy2.robjects as robjects
r = robjects.r
r['source']('sample_r.r')
</code>```

References: this

UPDATED

To avoid os calls I was able to achieve the desired behavior by including R_USER and R_HOME to the SYSTEM VARIABLE in  ENVIRONMENT VARIABLES

R_USER:
C:\Users\96171\AppData\Local\Programs\Python\Python36\Lib\site-packages\rpy2

R_HOME: C:\Program Files\R\R-3.6.2

Title: Rpy2 on windows

Body:
I want to install rpy2 on my windows machine and it gives me the following famous error

      self.convert_pycparser_error(e, csource)
      File "c:\users\96171\appdata\local\temp\pip-install-lxsxk7q4\rpy2\.eggs\cffi-1.14.0-py3.6-win-amd64.egg\cffi\cparser.py", line 336, in convert_pycparser_error
        raise CDefError(msg)
    cffi.CDefError: cannot parse "void __cffi_extern_python_start; void _capsule_finalizer(SEXP); void __cffi_extern_python_stop;"
    <cdef source string>:495:96: Illegal character '\r'

    ----------------------------------------
Command "python setup.py egg_info" failed with error code 1 in C:\Users\96171\AppData\Local\Temp\pip-install-lxsxk7q4\rpy2\

I have done the following:

upgraded set up tools

upgraded pip to the latest version

I have followed the link here for installing rpy2 on windows and they're saying we have to download a precompiled binary in order for this to work.

I have downloaded from the followinf link this wheel:
rpy2‑2.9.5‑cp37‑cp37m‑win_amd64.whl however I am still facing trouble; I did as follows:

After I downloaded rpy2‑2.9.5‑cp37‑cp37m‑win_amd64.whl

I opened cmd as Administrator in the directory where the wheel is downloaded

I set %R_USER% in the system variables to my username as such: R_USER C:\Users\my_username
However I am getting the following error:

ERROR: rpy2-2.9.5-cp37-cp37m-win_amd64.whl is not a supported wheel on this platform.

in the website for the binaries they say that:

Rpy2 (discontinued, unstable): provide access to the R software environment for statistical computing and graphics. Requires R 3.3, and I have R 3.6.2 on  my system. Is this causing the error?

Body:
OLD ANSWER

The issue was that I downloaded the wrong wheel. cp37 means CPython 3.7 and I have python 3.6 on my system. I downloaded rpy2-2.9.5-cp36-cp36m-win_amd64.whl istead of rpy2-2.9.5-cp37-cp37m-win_amd64.whl and it worked.

Also as I faced problems with R_USERand R_HOME I did the following in my python script:

import os
# see the following 2 lines
os.environ['R_HOME'] = 'C:/Program Files/R/R-3.6.2'
os.environ['R_USER'] = 'C:/Users/96171/AppData/Local/Programs/Python/Python36/Lib/site-packages/rpy2' #path depends on where you installed Python. Mine is the site packages of the regular python installation, it could have been Anaconda

# importing rpy2
import rpy2.robjects as robjects
r = robjects.r
r['source']('sample_r.r')

References: this

UPDATED

To avoid os calls I was able to achieve the desired behavior by including R_USER and R_HOME to the SYSTEM VARIABLE in  ENVIRONMENT VARIABLES

R_USER:
C:\Users\96171\AppData\Local\Programs\Python\Python36\Lib\site-packages\rpy2

R_HOME: C:\Program Files\R\R-3.6.2


问:
Set Global variable from Controller function
i am working on CI project where i am stuck somewhere. I try to set a global variable value from function and access this value from other function. Here is my code..

```<code>class Example extends CI_Controller {

    public $gData = "";

    public function userinfo() {
        //Here i fetch user infomration from database table
        $userName = "userName";
        $this->gData = $userName;
    }

    public function getuserinfo() {
        echo $this->gData;
    }

}
</code>```

userinfo is my actual page which opens in browser, and fetch data of user from user table. On my view i have button on click of button i am calling ajax which call the getuserinfo method of controller, it suppose to return the username which i set in userinfo method but unfortunetly it not working. Any will plz guide me where i am making mistake. (I am not allowed to use session)

答:
You can define the variable in the constructor as Amitesh stated or you could change your userinfo() method to just return data so the getuserinfo() method can use it. For example:

```<code>class Example extends CI_Controller {

    public function userinfo() {
        //Here i fetch user infomration from database table
        $userName = "userName";
        return $userName;
    }

    public function getuserinfo() {
        // get the data
        $username = $this->userinfo();
        echo $username;
    }

}
</code>```

By calling $this->userinfo() you'll be running that method and the return value will be available to any function (within the same controller) who makes the call

Body:
i am working on CI project where i am stuck somewhere. I try to set a global variable value from function and access this value from other function. Here is my code..

class Example extends CI_Controller {

    public $gData = "";

    public function userinfo() {
        //Here i fetch user infomration from database table
        $userName = "userName";
        $this->gData = $userName;
    }

    public function getuserinfo() {
        echo $this->gData;
    }

}

userinfo is my actual page which opens in browser, and fetch data of user from user table. On my view i have button on click of button i am calling ajax which call the getuserinfo method of controller, it suppose to return the username which i set in userinfo method but unfortunetly it not working. Any will plz guide me where i am making mistake. (I am not allowed to use session)

Body:
You can define the variable in the constructor as Amitesh stated or you could change your userinfo() method to just return data so the getuserinfo() method can use it. For example:

class Example extends CI_Controller {

    public function userinfo() {
        //Here i fetch user infomration from database table
        $userName = "userName";
        return $userName;
    }

    public function getuserinfo() {
        // get the data
        $username = $this->userinfo();
        echo $username;
    }

}

By calling $this->userinfo() you'll be running that method and the return value will be available to any function (within the same controller) who makes the call


问:
Subsetting an object in R by character sequence
I would like to subset an object in R according to the suffixes of the barcodes it contains. These end in '-n' where n is a number from 1 to 6. e.g. AAACCGTGCCCTCA-1, GAACCGTGCCCTCA-2, CATGCGTGCCCTCA-5, etc. I would like all the corresponding information about each barcode to be split accordingly as well. Here is some example code of an object, cds.

```<code>grp = sub("[A-Z]*[-]","",cds$barcodes)
group1 = cds[,grp==1]
</code>```

However, when I view group1, I get

```<code>> group1$barcode
factor(0)
7047 Levels: AAACATACCAGTTG-3 AAACATACTATGCG-4 AAACATTGAAGCCT-5 AAACATTGGCGAAG-4 AAACATTGTGAAGA-4     ... TTTGCATGGCCAAT-5
</code>```

and all the barcodes are still there. I also don't want to substitute the barcodes for the number at the end - I just want a way of telling R to locate a specific barcode by the number it ends in, so I can group them, but to keep the barcodes as they are.

For example, I would like group1$barcodes to look something like this:

```<code>group1$barcode
1   AAACCGTGCCCTCA-1
2   AAACGCACACGCAT-1
3   AAACGGCTTCCGAA-1
4   AAAGACGAACCCAA-1
5   AAAGACGACTGTTT-1
6   AAAGAGACAAAGCA-1
7   AAAGATCTGGTAAA-1
8   AAAGCAGAGCAAGG-1
9   AAAGCAGATTATCC-1
10  AAAGCCTGATGACC-1
</code>```

Many thanks!

Abigail

答:
Edit:

Use 'suffix' not 'prefix'!

I'd suggest using dplyr:

```<code>library(dplyr)
cds %>%
mutate(grp = gsub("([A-Z]*)-([0-9]+)", "\\2", barcodes))
</code>```

And then to filter single groups:

```<code>cds %>%
  mutate(grp = gsub("([A-Z]*)-([0-9]+)", "\\2", barcodes)) %>%
  filter(grp == 3)
</code>```

Body:
I would like to subset an object in R according to the suffixes of the barcodes it contains. These end in '-n' where n is a number from 1 to 6. e.g. AAACCGTGCCCTCA-1, GAACCGTGCCCTCA-2, CATGCGTGCCCTCA-5, etc. I would like all the corresponding information about each barcode to be split accordingly as well. Here is some example code of an object, cds.

grp = sub("[A-Z]*[-]","",cds$barcodes)
group1 = cds[,grp==1]

However, when I view group1, I get

> group1$barcode
factor(0)
7047 Levels: AAACATACCAGTTG-3 AAACATACTATGCG-4 AAACATTGAAGCCT-5 AAACATTGGCGAAG-4 AAACATTGTGAAGA-4     ... TTTGCATGGCCAAT-5

and all the barcodes are still there. I also don't want to substitute the barcodes for the number at the end - I just want a way of telling R to locate a specific barcode by the number it ends in, so I can group them, but to keep the barcodes as they are.

For example, I would like group1$barcodes to look something like this:

group1$barcode
1   AAACCGTGCCCTCA-1
2   AAACGCACACGCAT-1
3   AAACGGCTTCCGAA-1
4   AAAGACGAACCCAA-1
5   AAAGACGACTGTTT-1
6   AAAGAGACAAAGCA-1
7   AAAGATCTGGTAAA-1
8   AAAGCAGAGCAAGG-1
9   AAAGCAGATTATCC-1
10  AAAGCCTGATGACC-1

Many thanks!

Abigail

Body:
Edit:

Use 'suffix' not 'prefix'!

I'd suggest using dplyr:

library(dplyr)
cds %>%
mutate(grp = gsub("([A-Z]*)-([0-9]+)", "\\2", barcodes))

And then to filter single groups:

cds %>%
  mutate(grp = gsub("([A-Z]*)-([0-9]+)", "\\2", barcodes)) %>%
  filter(grp == 3)


问:
ReactJs project
After I initialized the project with the command: "npx create-react-app my-app", then I "cd into my-app" and ran the "npm start" command, what is the screen about cmd? So guys, can you give me instructions on how to handle this error, I thank you very much!
enter image description here</p>

答:
ctrl+alt+supr
Open administrator tools
Find and NodeJS instance kill all
Then get in the folder where your project is
Once inside run npm install then npm start

Title: ReactJs project


问:
I want to understand the concept of list comprehension in python

Given code

```<code>x=[(a,b) for a in range(3) for b in range(a)]
print(x)
</code>```

Output

```<code>[(1, 0), (2, 0), (2, 1)]
</code>```

I know the comprehension can be broken down as follows:

```<code>for a in range(3):
    for b in range(a):
        print(a,b)
</code>```

Can someone explain me how the output came as such provided above....

答:
The list comprehension is not translated to:

```<code>for a in range(3):
    for b in range(a):
        print(a,b)
</code>```

but rather to:

```<code>x = []
for a in range(3):
    for b in range(a):
        x.append((a, b))
</code>```

Body:
Given code

x=[(a,b) for a in range(3) for b in range(a)]
print(x)

Output

[(1, 0), (2, 0), (2, 1)]

I know the comprehension can be broken down as follows:

for a in range(3):
    for b in range(a):
        print(a,b)

Can someone explain me how the output came as such provided above....

Body:
The list comprehension is not translated to:

for a in range(3):
    for b in range(a):
        print(a,b)

but rather to:

x = []
for a in range(3):
    for b in range(a):
        x.append((a, b))


问:
How to allocate and copy 2D arrays between host and device in CUDA correctly
Is it possible to copy a 2D host array allocated like that

```<code>h_A=(int**)malloc(N*sizeof(int*));

for(i=0;i<N;i++)
{
   h_A[i]=(int*)malloc(3*sizeof(int));
}
</code>```

to 2D device array allocated like that

```<code>cudaMallocPitch((void**)&d_A, &pitch, 3*sizeof(int), N);
</code>```

I've tried to copy from host to device and back to host to check if the process worked and the result was that only the 2 first rows copied correctly

https://drive.google.com/file/d/1gXpChyYd2Div0pDjTRxZhwYd7GHRfjXN/view?usp=sharing

Copy from host array h_A to device array d_A

```<code>cudaMemcpy2D(d_A, pitch, h_A, 3*sizeof(int), 3*sizeof(int), N, cudaMemcpyHostToDevice);
</code>```

Copy from device array d_A to host array d_B

```<code>cudaMemcpy2D(h_B, pitch, d_A, 3*sizeof(int), 3*sizeof(int), N, cudaMemcpyDeviceToHost);
</code>```

答:
If you allocate an array of pointers to store rows, like this:

```<code>h_A=(int**)malloc(N*sizeof(int*));

for(i=0;i<N;i++)
{
   h_A[i]=(int*)malloc(3*sizeof(int));
}
</code>```

then to allocate and move that to a comparable device side structure using conventional device memory requires this:

```<code>dh_A=(int**)malloc(N*sizeof(int*));

for(i=0;i<N;i++)
{
   int* p;
   cudaMalloc(&p, 3*sizeof(int))
   cudaMemcpy(p, h_A[i], 3*sizeof(int), cudaMemcpyHostToDevice);
   dh_A[i]=p;
}

int** d_A = cudaMalloc(&d_A, sizeof(int*) * N);
cudaMemcpy(d_A, dh_A, N*sizeof(int*), cudaMemcpyHostToDevice);
</code>```

[Note: all code written in browser, not guaranteed to compile or work correctly]

I will leave it as an exercise to the reader how to perform the device to host copy. At this point you might conclude that it is simpler to just use linear memory on both the host and device. It will be simpler and faster.

Body:
Is it possible to copy a 2D host array allocated like that

h_A=(int**)malloc(N*sizeof(int*));

for(i=0;i<N;i++)
{
   h_A[i]=(int*)malloc(3*sizeof(int));
}

to 2D device array allocated like that

cudaMallocPitch((void**)&d_A, &pitch, 3*sizeof(int), N);

I've tried to copy from host to device and back to host to check if the process worked and the result was that only the 2 first rows copied correctly

https://drive.google.com/file/d/1gXpChyYd2Div0pDjTRxZhwYd7GHRfjXN/view?usp=sharing

Copy from host array h_A to device array d_A

cudaMemcpy2D(d_A, pitch, h_A, 3*sizeof(int), 3*sizeof(int), N, cudaMemcpyHostToDevice);

Copy from device array d_A to host array d_B

cudaMemcpy2D(h_B, pitch, d_A, 3*sizeof(int), 3*sizeof(int), N, cudaMemcpyDeviceToHost);

Body:
If you allocate an array of pointers to store rows, like this:

h_A=(int**)malloc(N*sizeof(int*));

for(i=0;i<N;i++)
{
   h_A[i]=(int*)malloc(3*sizeof(int));
}

then to allocate and move that to a comparable device side structure using conventional device memory requires this:

dh_A=(int**)malloc(N*sizeof(int*));

for(i=0;i<N;i++)
{
   int* p;
   cudaMalloc(&p, 3*sizeof(int))
   cudaMemcpy(p, h_A[i], 3*sizeof(int), cudaMemcpyHostToDevice);
   dh_A[i]=p;
}

int** d_A = cudaMalloc(&d_A, sizeof(int*) * N);
cudaMemcpy(d_A, dh_A, N*sizeof(int*), cudaMemcpyHostToDevice);

[Note: all code written in browser, not guaranteed to compile or work correctly]

I will leave it as an exercise to the reader how to perform the device to host copy. At this point you might conclude that it is simpler to just use linear memory on both the host and device. It will be simpler and faster.


答:
what the list comprehension does is this:

```<code>ret = []
for a in range(3):
    for b in range(a):
        ret.append((a,b))

print(ret)  # [(1, 0), (2, 0), (2, 1)]
</code>```

which returns the list you are getting...

Title: I want to understand the concept of list comprehension in python

Body:
what the list comprehension does is this:

ret = []
for a in range(3):
    for b in range(a):
        ret.append((a,b))

print(ret)  # [(1, 0), (2, 0), (2, 1)]

which returns the list you are getting...


问:
.htaccess redirect issues with sub-folders for HTTPS
I have an issue with a website HTTPS .htaccess redirect.

The website originally has two divisions: the main site (http://example.com/) and a blog site (http://example.com/blog/). I created an .htaccess to enforce HTTPS after the website has been in operation for over 20 years under port 80 (HTTP). So there are many links on multiple websites linking back to this site.

The first issue I had was when I click on a link http://example.com/blog/test it gets redirected to https://example.com/test (note, HTTPS but dropping "blog"). This results in 404 error pages. So I wrote the follwing code:

```<code># Forced HTTPS
RewriteCond %{HTTPS} off
RewriteRule ^ https://example.com%{REQUEST_URI} [NE,L,R]
# rewrite root requests to subfolder
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^ /blog%{REQUEST_URI} [L]
</code>```

Now the above code did resolve the 404 error issue on http://example.com/blog/[page_here], but when it gets redirected, it loses the "blog" part. Basically a visitor who clicks on a link http://example.com/blog/test will see https://example.com/test on the address bar. I noticed it did find the correct page and no 404 errors but dropped the "blog" from the address. (I can access blog php pages without "blog" in the URL so it looks like two web addresses for the exact same page).

The other problem is the main site's 404 pages are now directed to the blog site's 404 page and now visitors can access the exact same blog page with or without "blog" in the URL.

Is there anyway to resolve this? The main site is on php while the blog site is on WordPress. The .htaccess file I edited is in the main site's root www folder.

答:
Have tried with permalink changes?

wp-admin / Settings->Permalinks and set to post name

Working sample code, change required things, but first try with plugin https://wordpress.org/plugins/really-simple-ssl/

```<code>RewriteEngine On
RewriteCond %{SERVER_PORT} 80
RewriteRule ^(.*)$ https://www.example.com/$1 [R=301,L,NE]

# BEGIN WordPress
# The directives (lines) between `BEGIN WordPress` and `END WordPress` are
# dynamically generated, and should only be modified via WordPress filters.
# Any changes to the directives between these markers will be overwritten.
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /
RewriteRule ^index\.php$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /index.php [L]
</IfModule>
# END WordPress
</code>```

Body:
I have an issue with a website HTTPS .htaccess redirect.

The website originally has two divisions: the main site (http://example.com/) and a blog site (http://example.com/blog/). I created an .htaccess to enforce HTTPS after the website has been in operation for over 20 years under port 80 (HTTP). So there are many links on multiple websites linking back to this site.

The first issue I had was when I click on a link http://example.com/blog/test it gets redirected to https://example.com/test (note, HTTPS but dropping "blog"). This results in 404 error pages. So I wrote the follwing code:

# Forced HTTPS
RewriteCond %{HTTPS} off
RewriteRule ^ https://example.com%{REQUEST_URI} [NE,L,R]
# rewrite root requests to subfolder
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^ /blog%{REQUEST_URI} [L]

Now the above code did resolve the 404 error issue on http://example.com/blog/[page_here], but when it gets redirected, it loses the "blog" part. Basically a visitor who clicks on a link http://example.com/blog/test will see https://example.com/test on the address bar. I noticed it did find the correct page and no 404 errors but dropped the "blog" from the address. (I can access blog php pages without "blog" in the URL so it looks like two web addresses for the exact same page).

The other problem is the main site's 404 pages are now directed to the blog site's 404 page and now visitors can access the exact same blog page with or without "blog" in the URL.

Is there anyway to resolve this? The main site is on php while the blog site is on WordPress. The .htaccess file I edited is in the main site's root www folder.

Body:
Have tried with permalink changes?

wp-admin / Settings->Permalinks and set to post name

Working sample code, change required things, but first try with plugin https://wordpress.org/plugins/really-simple-ssl/

RewriteEngine On
RewriteCond %{SERVER_PORT} 80
RewriteRule ^(.*)$ https://www.example.com/$1 [R=301,L,NE]

# BEGIN WordPress
# The directives (lines) between `BEGIN WordPress` and `END WordPress` are
# dynamically generated, and should only be modified via WordPress filters.
# Any changes to the directives between these markers will be overwritten.
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /
RewriteRule ^index\.php$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /index.php [L]
</IfModule>
# END WordPress


问:
FrameLayout with layout_weight is considered useless
Consider the following layout:

```<code><?xml version="1.0" encoding="utf-8" ?>
<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@color/black"
>
    <FrameLayout
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:layout_weight="2"
    />
    <TextView
        android:id="@+id/primary_text"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        android:textColor="@color/white"
        android:textSize="24sp"
        tools:text="Primary!"
    />
    <FrameLayout
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:layout_weight="1"
    />
    <TextView
        android:id="@+id/secondary_text"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        android:textColor="@color/white"
        android:textSize="24sp"
        tools:text="Secondary!"
    />
    <FrameLayout
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:layout_weight="3"
    />
</LinearLayout>
</code>```

See the screenshot below for the result. The layout works fine, but Android Studio warns me that the FrameLayouts are considered useless and should be removed. However, they're not useless. I use layout_weight here. The idea is that the space between and around the two TextViews are relative with weights 2:1:3.

How can I rewrite my layout that results in the same weighted positioning of the views without having to use empty FrameLayouts?

答: You can get rid of the first two FrameLayout by setting the height of your TextView to 0dp and their weight to the values you set for your FrameLayout.

Body:
Consider the following layout:

<?xml version="1.0" encoding="utf-8" ?>
<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@color/black"
>
    <FrameLayout
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:layout_weight="2"
    />
    <TextView
        android:id="@+id/primary_text"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        android:textColor="@color/white"
        android:textSize="24sp"
        tools:text="Primary!"
    />
    <FrameLayout
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:layout_weight="1"
    />
    <TextView
        android:id="@+id/secondary_text"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        android:textColor="@color/white"
        android:textSize="24sp"
        tools:text="Secondary!"
    />
    <FrameLayout
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:layout_weight="3"
    />
</LinearLayout>

See the screenshot below for the result. The layout works fine, but Android Studio warns me that the FrameLayouts are considered useless and should be removed. However, they're not useless. I use layout_weight here. The idea is that the space between and around the two TextViews are relative with weights 2:1:3.

How can I rewrite my layout that results in the same weighted positioning of the views without having to use empty FrameLayouts?


问:
Use value of an Input in a function
I'm a bit ashamed to write this topic because even if I got a HTML formation (4 years ago) I can't resolve my problem :

I can't use the value of an input type text in a function, this is my code:

import React from 'react'
//import db from '../../constants/FirebaseConfig'

class Account extends React.Component {

    state = {
        name: '',
        content: ''
    }

    _formSubmit(e) {
        e.preventDefault()
        var name = document.getElementsByName('name')
        console.log(name)

    }

    render(){
        return(

Account

                <form id="form">

                    Titre
                    <input type="text" name="name" placeholder="Ici le nom de l'Article"/>

                    Contenue
                    <input type="text" name="content" placeholder="Ici le contenue de l'article"/>

                    <input type="button" value="suivant" onClick={(e) =>this._formSubmit(e)}/>

                </form>

        )
    }
}

export default Account```

After attempting to debug a few times I think the problem is with the var name object which is a  NodeList<input> type.
My goal is to stock the 'name' and 'content' value in a firebase db.

Thank You

答:
On HandleChange function, it will automatically check the name where you have changed, and it will update the value

```<code>import React, { Component } from "react";

export default class App extends Component {
  state = {
    name: "",
    content: "",
    datas: []
  };
  handleChange = e => {
    this.setState({
      [e.target.name]: e.target.value
    });
  };

  handleSubmit = e => {
    e.preventDefault();
    const data = {
      name: this.state.name,
      content: this.state.name
    };
    this.setState({
      datas: [...this.state.datas, data],
      name: "",
      content: ""
    });
  };
  render() {
    return (
      <div>
        <form onSubmit={this.handleSubmit}>
          <input
            type="text"
            name="name"
            value={this.state.name}
            onChange={this.handleChange}
            placeholder="Ici le nom de l'Article"
          />
          <input
            type="text"
            name="content"
            value={this.state.content}
            onChange={this.handleChange}
            placeholder="Ici le nom de l'Article"
          />
          <button>Submit</button>
        </form>
        <div>
          {this.state.datas.map(item => {
            return (
              <div key={Math.random()}>
                <h6>{Math.random()}</h6>
                <h4>Name:{item.name}</h4>
                <h4>Content:{item.content}</h4>
              </div>
            );
          })}
        </div>
      </div>
    );
  }
}
</code>```

Title: Use value of an Input in a function

Body:
I'm a bit ashamed to write this topic because even if I got a HTML formation (4 years ago) I can't resolve my problem :

I can't use the value of an input type text in a function, this is my code:

import React from 'react'
//import db from '../../constants/FirebaseConfig'

class Account extends React.Component {

    state = {
        name: '',
        content: ''
    }

    _formSubmit(e) {
        e.preventDefault()
        var name = document.getElementsByName('name')
        console.log(name)

    }

    render(){
        return(

Account

                <form id="form">

                    Titre
                    <input type="text" name="name" placeholder="Ici le nom de l'Article"/>

                    Contenue
                    <input type="text" name="content" placeholder="Ici le contenue de l'article"/>

                    <input type="button" value="suivant" onClick={(e) =>this._formSubmit(e)}/>

                </form>

        )
    }
}

export default Account

After attempting to debug a few times I think the problem is with the var name object which is a  NodeList<input> type.
My goal is to stock the 'name' and 'content' value in a firebase db.

Thank You

Body:
On HandleChange function, it will automatically check the name where you have changed, and it will update the value

import React, { Component } from "react";

export default class App extends Component {
  state = {
    name: "",
    content: "",
    datas: []
  };
  handleChange = e => {
    this.setState({
      [e.target.name]: e.target.value
    });
  };

  handleSubmit = e => {
    e.preventDefault();
    const data = {
      name: this.state.name,
      content: this.state.name
    };
    this.setState({
      datas: [...this.state.datas, data],
      name: "",
      content: ""
    });
  };
  render() {
    return (
      <div>
        <form onSubmit={this.handleSubmit}>
          <input
            type="text"
            name="name"
            value={this.state.name}
            onChange={this.handleChange}
            placeholder="Ici le nom de l'Article"
          />
          <input
            type="text"
            name="content"
            value={this.state.content}
            onChange={this.handleChange}
            placeholder="Ici le nom de l'Article"
          />
          <button>Submit</button>
        </form>
        <div>
          {this.state.datas.map(item => {
            return (
              <div key={Math.random()}>
                <h6>{Math.random()}</h6>
                <h4>Name:{item.name}</h4>
                <h4>Content:{item.content}</h4>
              </div>
            );
          })}
        </div>
      </div>
    );
  }
}


问:
Regex to match URL route
I'm writing a regex to match a route with the pattern /events/awesome-schema/value2/1.

The values could be described as:

```<code>/events >> static part
awesome-schema >> could be any char, number, _ or -
value2 >> could be any char, number, _ or -
1 >> one or more digit
</code>```

For now, I have wrote the following syntax ^/events/([a-z]+[0-9_-]*)/?([a-z]+[0-9_-]*)?/?(\d+)?$ but it's failing.

Any idea why is it wrong?

答:
This part ([a-z]+[0-9_-]*)/?([a-z]+[0-9_-]*)? matches until the slash before /value2.

The following (\d+)? would not match the v from value, which is possible as it is optional, but the $ anchor that follows makes the pattern not match the whole string as value2/1 is not matched.

You might use

```<code>^/events/[a-z0-9_]+(?:-[a-z0-9_]+)*/[a-z0-9+_]+/[0-9]+$
</code>```

Explanation

^ Start of string

/events/ Match literally

[a-z0-9_]+ Match 1+ times any of [a-z0-9_]

(?: Non capture group

-[a-z0-9_]+ Match - and 1+ times any of [a-z0-9_]

)* Close group and repeat 0+ times

/[a-z0-9+_]+ Match / and 1+ times any of [a-z0-9_]

/[0-9]+ match / and 1+ digits

$ End of string

regex demo

If the parts should start with a lowercase as in your original pattern and a match like awesome-schema-- is also possible , you can start the match with [a-z] and use [a-z0-9_-]* for the character class.

```<code>^/events/[a-z][a-z0-9_-]*/[a-z][a-z0-9+_]*/[0-9]+$
</code>```

Regex demo

Title: Regex to match URL route

Body:
I'm writing a regex to match a route with the pattern /events/awesome-schema/value2/1.

The values could be described as:

/events >> static part
awesome-schema >> could be any char, number, _ or -
value2 >> could be any char, number, _ or -
1 >> one or more digit

For now, I have wrote the following syntax ^/events/([a-z]+[0-9_-]*)/?([a-z]+[0-9_-]*)?/?(\d+)?$ but it's failing.

Any idea why is it wrong?

Body:
This part ([a-z]+[0-9_-]*)/?([a-z]+[0-9_-]*)? matches until the slash before /value2.

The following (\d+)? would not match the v from value, which is possible as it is optional, but the $ anchor that follows makes the pattern not match the whole string as value2/1 is not matched.

You might use

^/events/[a-z0-9_]+(?:-[a-z0-9_]+)*/[a-z0-9+_]+/[0-9]+$

Explanation

^ Start of string

/events/ Match literally

[a-z0-9_]+ Match 1+ times any of [a-z0-9_]

(?: Non capture group

-[a-z0-9_]+ Match - and 1+ times any of [a-z0-9_]

)* Close group and repeat 0+ times

/[a-z0-9+_]+ Match / and 1+ times any of [a-z0-9_]

/[0-9]+ match / and 1+ digits

$ End of string

regex demo

If the parts should start with a lowercase as in your original pattern and a match like awesome-schema-- is also possible , you can start the match with [a-z] and use [a-z0-9_-]* for the character class.

^/events/[a-z][a-z0-9_-]*/[a-z][a-z0-9+_]*/[0-9]+$

Regex demo


问:
Symfony 3.4. overwrite class Symfony\Component\Form
i need to overwrite the function "public function submit($submittedData, $clearMissing = true)" in Symfony\Component\Form.

I can overwrite the "RequestHandlerInterface" but not the form component.

Background: There is a problem with choiceTypes if you submit with Patch-Method (github.com/symfony/symfony/issues/17799). So i want to insert this line into the submit function:

```<code>$clearMissing = $this->getConfig()->getOption('expanded', false) ?: $clearMissing;
</code>```

答:
You can patch the Form class directly as suggested here:
https://github.com/symfony/symfony/issues/17799#issuecomment-184473725

The only problem is: How to make this change permanent for you project?

I ended up creating a patch for the form class. On Linux and supposing you are using git it works something like this:

Open a terminal in your project root directory

Add the form class to your git repository

```<code>git add vendor/symfony/symfony/src/Symfony/Component/Form/Form.php
</code>```

Patch the form class as described above

Create a patch

```<code>git diff > form.patch
</code>```

Remove the form class from you git repository

```<code>git rm --cached vendor/symfony/symfony/src/Symfony/Component/Form/Form.php
</code>```

Somehow incorporate the patch in your project update process. For my project I wrote a small script that runs after every composer install or composer update.

```<code>#!/bin/sh

# apply form component patch to fix HTTP PATCH issue with ChoiceType
# run after composer install/update
patch -p1 -N -r /dev/null < form.patch
</code>```

The options for the patch command are chosen such that there will be no interaction or other side effects in case the patch was already applied.

form.patch itself looks something like this:

```<code>diff --git a/vendor/symfony/symfony/src/Symfony/Component/Form/Form.php b/vendor/symfony/symfony/src/Symfony/Component/Form/Form.php
index 67fd234f..27ed9e81 100644
--- a/www/vendor/symfony/symfony/src/Symfony/Component/Form/Form.php
+++ b/www/vendor/symfony/symfony/src/Symfony/Component/Form/Form.php
@@ -553,6 +553,10 @@ class Form implements \IteratorAggregate, FormInterface
                 $submittedData = $event->getData();
             }

+            // HTTP PATCH fix for ChoiceType
+            // https://github.com/symfony/symfony/issues/17799#issuecomment-184473725
+            $clearMissing = $this->getConfig()->getOption('expanded', false) ?: $clearMissing;
+
             // Check whether the form is compound.
             // This check is preferable over checking the number of children,
             // since forms without children may also be compound.
</code>```

Body:
i need to overwrite the function "public function submit($submittedData, $clearMissing = true)" in Symfony\Component\Form.

I can overwrite the "RequestHandlerInterface" but not the form component.

Background: There is a problem with choiceTypes if you submit with Patch-Method (github.com/symfony/symfony/issues/17799). So i want to insert this line into the submit function:

$clearMissing = $this->getConfig()->getOption('expanded', false) ?: $clearMissing;

Body:
You can patch the Form class directly as suggested here:
https://github.com/symfony/symfony/issues/17799#issuecomment-184473725

The only problem is: How to make this change permanent for you project?

I ended up creating a patch for the form class. On Linux and supposing you are using git it works something like this:

Open a terminal in your project root directory

Add the form class to your git repository

git add vendor/symfony/symfony/src/Symfony/Component/Form/Form.php

Patch the form class as described above

Create a patch

git diff > form.patch

Remove the form class from you git repository

git rm --cached vendor/symfony/symfony/src/Symfony/Component/Form/Form.php

Somehow incorporate the patch in your project update process. For my project I wrote a small script that runs after every composer install or composer update.

#!/bin/sh

# apply form component patch to fix HTTP PATCH issue with ChoiceType
# run after composer install/update
patch -p1 -N -r /dev/null < form.patch

The options for the patch command are chosen such that there will be no interaction or other side effects in case the patch was already applied.

form.patch itself looks something like this:

diff --git a/vendor/symfony/symfony/src/Symfony/Component/Form/Form.php b/vendor/symfony/symfony/src/Symfony/Component/Form/Form.php
index 67fd234f..27ed9e81 100644
--- a/www/vendor/symfony/symfony/src/Symfony/Component/Form/Form.php
+++ b/www/vendor/symfony/symfony/src/Symfony/Component/Form/Form.php
@@ -553,6 +553,10 @@ class Form implements \IteratorAggregate, FormInterface
                 $submittedData = $event->getData();
             }

+            // HTTP PATCH fix for ChoiceType
+            // https://github.com/symfony/symfony/issues/17799#issuecomment-184473725
+            $clearMissing = $this->getConfig()->getOption('expanded', false) ?: $clearMissing;
+
             // Check whether the form is compound.
             // This check is preferable over checking the number of children,
             // since forms without children may also be compound.


问:
Capture windows messages generated by an MFC app in plain C++ dll
First of all: Is this even possible?

I have a third party dll that interfaces some hardware. It's written in MFC. I received (from the dll vendors) a sample Visual Studio 2010 solution which has only one project: An MFC application (.exe) which calls the third party dll in question. It works fine.

When I try to use the third party dll from my dll (which is plain C++, no MFC, no .NET), I can call its functions fine, but there's a catch: the sample MFC app seems to "override" MessageProc in order to capture certain messages that the third party dll generates. And though the dll has a function called "RegisterFuncCallback" and I use it, my callback never gets called.

So here's the problem: How can I capture those messages without creating an MFC app? (Is it even possible?)

答: If the DLL works with Win32 messages you won't get around them. But you do not neccessarily need MFC for that, a simple WinAPI solution would suffice. MFC just wraps the Win32 API. If those messages aren't Win32 messages, you do not need a Win32 application.</p>