问:
sessions not being set in all pages on php5
I am using session_start(); at the top of my login page. After a user logs in, a message is displayed on screen which shows that the session is being set. But, I cannot carry sessions from page to page or can I echo out SID. It is a blank value. I would be grateful if someone could show me where I am going wrong. Thanks</p>

```<code><?php

  $userpost = mysql_real_escape_string($_POST['user']);

  if (!isset($_SESSION['user'])) {
   session_start();
   $_SESSION['user'] = $userpost;
}

   echo $_SESSION['user'] .' '. 'Just logged in' .  SID;
   // Or maybe pass along the session id, if needed

?>
</code>```

答:
It's because you're always looking in $_POST for your user data.

Bring the session_start() out of that condition:

```<code><?php
  session_start();
  $userpost = mysql_real_escape_string($_POST['user']);

  if (!isset($_SESSION['user'])) {
   $_SESSION['user'] = $userpost;
  }
</code>```

Body:
I am using session_start(); at the top of my login page. After a user logs in, a message is displayed on screen which shows that the session is being set. But, I cannot carry sessions from page to page or can I echo out SID. It is a blank value. I would be grateful if someone could show me where I am going wrong. Thanks

<?php

  $userpost = mysql_real_escape_string($_POST['user']);

  if (!isset($_SESSION['user'])) {
   session_start();
   $_SESSION['user'] = $userpost;
}

   echo $_SESSION['user'] .' '. 'Just logged in' .  SID;
   // Or maybe pass along the session id, if needed

?>

Body:
It's because you're always looking in $_POST for your user data.

Bring the session_start() out of that condition:

<?php
  session_start();
  $userpost = mysql_real_escape_string($_POST['user']);

  if (!isset($_SESSION['user'])) {
   $_SESSION['user'] = $userpost;
  }


来源: stackexchange

问:
how to fixed position gridview flutter
It also gives me an error when I have taken GridView as an expended  child

error:

RenderFlex children have non-zero flex but incoming height constraints are unbounded.

import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';

class MyHomePage extends StatefulWidget {
  const MyHomePage({Key? key}) : super(key: key);

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

class _MyHomePageState extends State<MyHomePage> {

  Widget topItem(){
    return Padding(
      padding: const EdgeInsets.all(15.0),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          const Text('Your Best Products',
            style: TextStyle(fontSize: 20,fontWeight: FontWeight.bold
            ),
          ),
      Padding(
        padding: const EdgeInsets.only(top: 20),
        child: SizedBox(
          height: 45,
          width: 300,
          child: TextField(

                decoration: InputDecoration(

                hintText:'Search here' ,
                suffixIcon:Icon(Icons.search) ,
                fillColor: Colors.grey,
                filled: true,
                border: OutlineInputBorder(
                    borderSide: BorderSide.none,
                    borderRadius: BorderRadius.circular(20.0)
                )
            ),

          ),
        ),
      ),
          const SizedBox(height: 12,),
          Container(
            height: 50,

            child: ListView.separated(
              shrinkWrap: true,
              scrollDirection: Axis.horizontal,
                itemBuilder: (context,index){
                  return Card(
                    child: MaterialButton(
                      onPressed: (){},
                      color: Colors.blue,
                      shape: StadiumBorder(),
                      child: Text('Sandle'),
                    ),
                  );
                },
                separatorBuilder: (context ,index){
                  return SizedBox(width: 12,);
                },
                itemCount: 10),
          ),
          Expanded(

            child: GridView.builder(
              scrollDirection: Axis.vertical,
                gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
                  crossAxisCount: 2,
                   crossAxisSpacing: 5,
                  mainAxisExtent: 5
                ),
                itemBuilder: (context,index){
                  return Container(
                    height: 50,
                    width: 50,
                    color: Colors.red,
                  );
                }),
          )
        ],

      ),
    );
  }}
```

答: Remove mainAxisExtent: 5 from GridView.builder. And where did you use topItem()?

ContentLicense: CC BY-SA 4.0

Title: how to fixed position gridview flutter


问:
Exclude field from Django validation in admin form
I am working on project with a lot of legacy code base (Django 2.2). I have a custom model field for price that goes like this

class PriceField(PositiveIntegerField):

    def get_prep_value(self, value: float) -> Optional[int]:
        return int(value * 100) if value else self.default

    def from_db_value(self, value: int, expression, connection) -> Optional[float]:
        return value / 100 if value else value

class Expertise(models.Model):
    price = PriceField(blank=True, default=0, help_text='Price per min.')
    ...

```

Prices are stored in db multiplied by 100, e.g. 9.90 is stored as 990, and values are obtained from db in human readable way (990 as 9.90).

Now I am facing a problem with default PositiveIntegerField Django admin form validation for that field. Because this value represented as float every time I click "Save" I get a PositiveIntegerField's ValidationError.
Is there any way to exclude this field from admin form validation or to send this field value multiplied by 100?

答:
If you setup a custom form you can manipulate the data entry of the form before actually save it to the DB, as well as determine the data type for the input.

Edit: to do what i said you may as well end up removing the custom input and just doing the *100 thing on the custom form, anyway i think if you wanna ignore validations the anwser may be in a custom form.

I used to have custom form like this:

```<code>class ArticleModelForm(forms.ModelForm):
    project = forms.ModelChoiceField(
        queryset=Project.objects.order_by('title'),
        label="Proyecto",
        empty_label="Seleccionar proyecto",
        widget=forms.Select(
            attrs={
                "class": "basic-single form-control w-100",
                "id": "id-select-project-article"
            }))
    //lot more inputs

    def __init__(self, *args, **kwargs):
        super(ArticleModelForm, self).__init__(*args, **kwargs)
        self.fields['image'].widget.attrs['class'] = 'form-control-file'
        self.fields['image'].widget.attrs['accept'] = 'image/*'
        self.fields['file'].widget.attrs['class'] = 'form-control-file'
        self.fields['file'].widget.attrs['accept'] = 'application/pdf'
        for field in self.fields.values():
            field.error_messages = {
                'required':
                'El campo {fieldname} es requerido'.format(
                    fieldname=field.label)
            }

    def clean_file(self):
        file = self.cleaned_data.get("file")
        if not (file.name.endswith(".pdf")):
            raise forms.ValidationError(
                "Favor de ingresar un archivo en formato pdf")
        return file

    def clean_project(self):
        project = self.cleaned_data.get("project")
        user = self.cleaned_data.get("user")
        if project:
            projectObj = Project.objects.get(id=project.id)
            if not user in projectObj.participants.all():
                raise forms.ValidationError(
                    "Usted no es participante en este proyecto.")
        return project

    class Meta:
        model = Article
        fields = [
            'user', 'project', 'journal', 'authors', 'title', 'indexed',
            'indexInfo', 'arbitration', 'publicationYear', 'pages', 'file',
            'image', 'programTribute', 'academyTribute', 'eventPublication',
            'tags'
        ]
</code>```

You can do your logic to *100 your number on the clean method for the field and return that value to be saved.

I don't remember excatly how to setup custom forms on admin but i know for sure you can do it.

I know i did this to setup custom usermodel and had to import my custom user forms on the admin.py of my users app:

```<code>from django.contrib import admin
from django.contrib.auth import get_user_model
from django.contrib.auth.admin import UserAdmin

from .forms import UserSapCreationForm, UserSapChangeForm //my custom forms
from .models import UserSap

class UserSapAdmin(UserAdmin):
    add_form = UserSapCreationForm
    form = UserSapChangeForm
    model = UserSap
    verbose_name = 'Usuario Sap'
    list_display = (
        'email',
        'account',
        'rol',
        'is_staff',
        'is_active',
    )
    list_filter = (
        'rol',
        'is_staff',
        'is_active',
    )

    fieldsets = (
        ('Usuario Sap', {
            'fields': (
                'email',
                'password',
                'rol',
            )
        }),
        ('Informacion personal', {
            'fields': ('account', )
        }),
        ('Grupos', {
            'classes': ('wide', ),
            'fields': ('groups', )
        }),
        ('Permisos', {
            'classes': ('wide', ),
            'fields': ('user_permissions', )
        }),
        ('Login', {
            'fields': ('is_active', )
        }),
        ('Staff', {
            'fields': ('is_staff', )
        }),
    )
    """
    add_fieldsets = (
        ('add', {
            'classes': ('wide',),
            'fields': ('email', 'account', 'rol', 'password1', 'password2', 'is_staff', 'is_active')}
         ),
    )
"""
    ordering = ('email', )

    search_fields = ('email', )

    filter_horizontal = ()

admin.site.register(UserSap, UserSapAdmin)
</code>```

sorry i can't develop a full answer for you case but hopefully this examples will help you start searching for solutions.

Body:
I am working on project with a lot of legacy code base (Django 2.2). I have a custom model field for price that goes like this

class PriceField(PositiveIntegerField):

    def get_prep_value(self, value: float) -> Optional[int]:
        return int(value * 100) if value else self.default

    def from_db_value(self, value: int, expression, connection) -> Optional[float]:
        return value / 100 if value else value

class Expertise(models.Model):
    price = PriceField(blank=True, default=0, help_text='Price per min.')
    ...

Prices are stored in db multiplied by 100, e.g. 9.90 is stored as 990, and values are obtained from db in human readable way (990 as 9.90).

Now I am facing a problem with default PositiveIntegerField Django admin form validation for that field. Because this value represented as float every time I click "Save" I get a PositiveIntegerField's ValidationError.
Is there any way to exclude this field from admin form validation or to send this field value multiplied by 100?

Body:
If you setup a custom form you can manipulate the data entry of the form before actually save it to the DB, as well as determine the data type for the input.

Edit: to do what i said you may as well end up removing the custom input and just doing the *100 thing on the custom form, anyway i think if you wanna ignore validations the anwser may be in a custom form.

I used to have custom form like this:

class ArticleModelForm(forms.ModelForm):
    project = forms.ModelChoiceField(
        queryset=Project.objects.order_by('title'),
        label="Proyecto",
        empty_label="Seleccionar proyecto",
        widget=forms.Select(
            attrs={
                "class": "basic-single form-control w-100",
                "id": "id-select-project-article"
            }))
    //lot more inputs

    def __init__(self, *args, **kwargs):
        super(ArticleModelForm, self).__init__(*args, **kwargs)
        self.fields['image'].widget.attrs['class'] = 'form-control-file'
        self.fields['image'].widget.attrs['accept'] = 'image/*'
        self.fields['file'].widget.attrs['class'] = 'form-control-file'
        self.fields['file'].widget.attrs['accept'] = 'application/pdf'
        for field in self.fields.values():
            field.error_messages = {
                'required':
                'El campo {fieldname} es requerido'.format(
                    fieldname=field.label)
            }

    def clean_file(self):
        file = self.cleaned_data.get("file")
        if not (file.name.endswith(".pdf")):
            raise forms.ValidationError(
                "Favor de ingresar un archivo en formato pdf")
        return file

    def clean_project(self):
        project = self.cleaned_data.get("project")
        user = self.cleaned_data.get("user")
        if project:
            projectObj = Project.objects.get(id=project.id)
            if not user in projectObj.participants.all():
                raise forms.ValidationError(
                    "Usted no es participante en este proyecto.")
        return project

    class Meta:
        model = Article
        fields = [
            'user', 'project', 'journal', 'authors', 'title', 'indexed',
            'indexInfo', 'arbitration', 'publicationYear', 'pages', 'file',
            'image', 'programTribute', 'academyTribute', 'eventPublication',
            'tags'
        ]

You can do your logic to *100 your number on the clean method for the field and return that value to be saved.

I don't remember excatly how to setup custom forms on admin but i know for sure you can do it.

I know i did this to setup custom usermodel and had to import my custom user forms on the admin.py of my users app:

from django.contrib import admin
from django.contrib.auth import get_user_model
from django.contrib.auth.admin import UserAdmin

from .forms import UserSapCreationForm, UserSapChangeForm //my custom forms
from .models import UserSap

class UserSapAdmin(UserAdmin):
    add_form = UserSapCreationForm
    form = UserSapChangeForm
    model = UserSap
    verbose_name = 'Usuario Sap'
    list_display = (
        'email',
        'account',
        'rol',
        'is_staff',
        'is_active',
    )
    list_filter = (
        'rol',
        'is_staff',
        'is_active',
    )

    fieldsets = (
        ('Usuario Sap', {
            'fields': (
                'email',
                'password',
                'rol',
            )
        }),
        ('Informacion personal', {
            'fields': ('account', )
        }),
        ('Grupos', {
            'classes': ('wide', ),
            'fields': ('groups', )
        }),
        ('Permisos', {
            'classes': ('wide', ),
            'fields': ('user_permissions', )
        }),
        ('Login', {
            'fields': ('is_active', )
        }),
        ('Staff', {
            'fields': ('is_staff', )
        }),
    )
    """
    add_fieldsets = (
        ('add', {
            'classes': ('wide',),
            'fields': ('email', 'account', 'rol', 'password1', 'password2', 'is_staff', 'is_active')}
         ),
    )
"""
    ordering = ('email', )

    search_fields = ('email', )

    filter_horizontal = ()

admin.site.register(UserSap, UserSapAdmin)

sorry i can't develop a full answer for you case but hopefully this examples will help you start searching for solutions.


问:
JS redirect based on browser language
I'm using this test code:

```<code><script type="type/javascript">

$( document ).ready(function(){
    var userLang = navigator.language || navigator.userLanguage;
    if (userLang == "fr") {
        window.location.href = "www.facebook.com"
    }
    else if(userLang == "de"){
       window.location.href = "www.facebook.com"
    }
    else {
        window.location.href = "www.google.com"
    }
});
</script>
</code>```

But nothing happens. I must be dumb?

You can see it here:
URL removed

答:
You were missing a protocol. Also, here's a suggestion for a cleaner approach replacing the series of if's.

var userLang = navigator.language || navigator.userLanguage;
var urls = {
    'fr': 'http://www.facebook.com',
    'de': 'http://www.facebook.com',
};
var defaultUrl = 'http://www.google.com';

var url = urls[userLang] ?? defaultUrl;
console.log(url);

//window.location.href = url;```

Title: JS redirect based on browser language

Body:
I'm using this test code:

But nothing happens. I must be dumb?

You can see it here:
URL removed


问:
Can polarplot take more than one array?
I need to show several radial vectors in one polar graph, but polarplot takes one array only. Is it possible to have a polar graph with multiple radial vectors?
I have already tried to create another array which contains both Z and Z1, but it doesn't work: in the graph Z and Z1 are linked creating some kind of polygon.</p>
```<code>Z = [ 0, 2+3i];
Z1 = [0, 2 -1i];
p = polarplot(Z, '-');
%can't plot Z and Z1 in the same graph
</code>```

答:
From the MATLAB page for polarplot:

```<code>polarplot(theta,rho)
polarplot(theta,rho,LineSpec)
polarplot(theta1,rho1,...,thetaN,rhoN)
polarplot(theta1,rho1,LineSpec1,...,thetaN,rhoN,LineSpecN)
</code>```

polarplot(theta1,rho1,...,thetaN,rhoN) plots multiple rho,theta
pairs.

polarplot(theta1,rho1,LineSpec1,...,thetaN,rhoN,LineSpecN) specifies
the line style, marker symbol, and color for each line.

However, given that it looks like you're trying to plot complex numbers, that's not what polar plot it for.  Polar plot is expecting a vector of angles and a corresponding vector of distances from the origin.

Do you have an example of what you are trying to achieve?  If you are trying to plot a number in the complex plane you can try something like:

```<code>plot(real(z), imag(Z), '-', real(Z1), imag(Z1), '--')
</code>```

Title: Can polarplot take more than one array?

Body:
I need to show several radial vectors in one polar graph, but polarplot takes one array only. Is it possible to have a polar graph with multiple radial vectors?
I have already tried to create another array which contains both Z and Z1, but it doesn't work: in the graph Z and Z1 are linked creating some kind of polygon.

Z = [ 0, 2+3i];
Z1 = [0, 2 -1i];
p = polarplot(Z, '-');
%can't plot Z and Z1 in the same graph

Body:
From the MATLAB page for polarplot:

polarplot(theta,rho)
polarplot(theta,rho,LineSpec)
polarplot(theta1,rho1,...,thetaN,rhoN)
polarplot(theta1,rho1,LineSpec1,...,thetaN,rhoN,LineSpecN)

polarplot(theta1,rho1,...,thetaN,rhoN) plots multiple rho,theta
pairs.

polarplot(theta1,rho1,LineSpec1,...,thetaN,rhoN,LineSpecN) specifies
the line style, marker symbol, and color for each line.

However, given that it looks like you're trying to plot complex numbers, that's not what polar plot it for.  Polar plot is expecting a vector of angles and a corresponding vector of distances from the origin.

Do you have an example of what you are trying to achieve?  If you are trying to plot a number in the complex plane you can try something like:

plot(real(z), imag(Z), '-', real(Z1), imag(Z1), '--')


问:
How to keep one accordion item always open in Bootstrap 5?
I have the first accordion item opened by default so what I wanted to do was to always have at least one opened at any time (so the picture on the side keeps a decent aspect ratio). By default I can close all of them and when I open a new one, all the others get closed.

答:
You need to set a watcher on all accordion items and check if any of them are open.

If none is open then open the first one.

```<code>$('#accordion-id .collapse').each((i, e) =>
    $(e).on('hidden.bs.collapse', () => {
        // check if an accordion item is expanded
        let isExpanded = false;
        $('#accordion-id [aria-expanded]').each((i, element) => {
            if ($(element).attr("aria-expanded") === 'true') {
                isExpanded = true;
            }
        });

        // show the first accordion item
        if (!isExpanded) {
            $('#btn-firs-accordion-id').click();
        }
    })
);

</code>```

Body:
You need to set a watcher on all accordion items and check if any of them are open.

If none is open then open the first one.

$('#accordion-id .collapse').each((i, e) =>
    $(e).on('hidden.bs.collapse', () => {
        // check if an accordion item is expanded
        let isExpanded = false;
        $('#accordion-id [aria-expanded]').each((i, element) => {
            if ($(element).attr("aria-expanded") === 'true') {
                isExpanded = true;
            }
        });

        // show the first accordion item
        if (!isExpanded) {
            $('#btn-firs-accordion-id').click();
        }
    })
);


问:
spring httpinvoker client can not find the service url
I have following configuration for the web application.

web.xml

```<code><context-param>
    <param-name>contextConfigLocation</param-name>
    <param-value>
        classpath:mail-application-context.xml
....
    </context-param>
....
<servlet>
<servlet-name>mailbox</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
    <load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
    <servlet-name>mailbox</servlet-name>
        <url-pattern>*.htm</url-pattern>
</servlet-mapping>
</code>```

mailbox-servlet.xml

```<code>    <bean name="remoteProvisioningServiceImpl" class="pw.domain.service.RemoteProvisioningServiceImpl"/>

<bean name="/remote/domain/provision.htm" class="org.springframework.remoting.httpinvoker.HttpInvokerServiceExporter">
    <property name="service" ref="remoteProvisioningServiceImpl" />
    <property name="serviceInterface" value="pw.domain.service.RemoteProvisioningService" />
</bean>
</code>```

I have the clients configured properly, like following, in mail-application-context.xml

```<code>    <bean id="remoteProvisioningService1" class="org.springframework.remoting.httpinvoker.HttpInvokerProxyFactoryBean">
    <property name="serviceUrl" value="http://${mailapp.dc.host.1.url}/remote/domain/provision.htm" />
    <property name="serviceInterface" value="pw.domain.service.RemoteProvisioningService" />
</bean>

<bean id="remoteProvisioningService2" class="org.springframework.remoting.httpinvoker.HttpInvokerProxyFactoryBean">
    <property name="serviceUrl" value="http://${mailapp.dc.host.2.url}/remote/domain/provision.htm" />
    <property name="serviceInterface" value="pw.domain.service.RemoteProvisioningService" />
</bean>
</code>```

And now... the problem.
On an appropriate event, the clients rightly call service through httpinvoker facility but the response is http-404. In nginx logs, i trace that spring makes a POST call to http://{host}/remote/domain/provision.htm.

Questions :

Do i need to create a separate app-context for httpInvoker bit? i mean, i already have one web context to deal with normal web operations. Do i need to declare {another-context} in web.xml for httpInvoker facility and having the service config. defined in {another-context}-servlet.xml?

If not 1, what is wrong in my configuration?

答:
Got it.. Question 1 above has the answer attached to it. I need to create a separate web context for http-invoking facility to work.

This is because, in my normal webapp context (mailbox), i already have defined SimpleUrlHandlerMapping which maps appropriate urls to controllers. There it doesnt find place for http-invoker-serivce i want to define. When i separated web contexts, it worked like a charm! :D

Happy coding! :)

ContentLicense: CC BY-SA 3.0

Body:
I have following configuration for the web application.

web.xml

<context-param>
    <param-name>contextConfigLocation</param-name>
    <param-value>
        classpath:mail-application-context.xml
....
    </context-param>
....
<servlet>
<servlet-name>mailbox</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
    <load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
    <servlet-name>mailbox</servlet-name>
        <url-pattern>*.htm</url-pattern>
</servlet-mapping>

mailbox-servlet.xml

    <bean name="remoteProvisioningServiceImpl" class="pw.domain.service.RemoteProvisioningServiceImpl"/>

<bean name="/remote/domain/provision.htm" class="org.springframework.remoting.httpinvoker.HttpInvokerServiceExporter">
    <property name="service" ref="remoteProvisioningServiceImpl" />
    <property name="serviceInterface" value="pw.domain.service.RemoteProvisioningService" />
</bean>

I have the clients configured properly, like following, in mail-application-context.xml

    <bean id="remoteProvisioningService1" class="org.springframework.remoting.httpinvoker.HttpInvokerProxyFactoryBean">
    <property name="serviceUrl" value="http://${mailapp.dc.host.1.url}/remote/domain/provision.htm" />
    <property name="serviceInterface" value="pw.domain.service.RemoteProvisioningService" />
</bean>

<bean id="remoteProvisioningService2" class="org.springframework.remoting.httpinvoker.HttpInvokerProxyFactoryBean">
    <property name="serviceUrl" value="http://${mailapp.dc.host.2.url}/remote/domain/provision.htm" />
    <property name="serviceInterface" value="pw.domain.service.RemoteProvisioningService" />
</bean>

And now... the problem.
On an appropriate event, the clients rightly call service through httpinvoker facility but the response is http-404. In nginx logs, i trace that spring makes a POST call to http://{host}/remote/domain/provision.htm.

Questions :

Do i need to create a separate app-context for httpInvoker bit? i mean, i already have one web context to deal with normal web operations. Do i need to declare {another-context} in web.xml for httpInvoker facility and having the service config. defined in {another-context}-servlet.xml?

If not 1, what is wrong in my configuration?


问:
Google Maps iOS SDK animate map padding SwiftUI
I'm looking to animate my Google Map's padding, as when a bottom sheet appears, the map padding resizes dynamically.

The GMSMapView.padding documentation says it can be accomplished with a UIView block based animation, but I'm not sure how that would tie in to a SwiftUI application?

The bottom sheet works fine, it shows when expected and passes the correct padding value through to the MapView. It's just the animation I can't figure out. (The bottom sheet uses this component if you're curious https://github.com/LucasMucGH/BottomSheet)

Any help would be greatly appreciated, thanks.

Current relevant code:

```<code>struct MapView: UIViewRepresentable {

  var bottomPadding: CGFloat
  private let mapView = GMSMapView(frame: .zero)

  func makeUIView(context: Context) -> GMSMapView {
    return mapView
  }

  func updateUIView(_ mapView: GMSMapView, context: Context) {
    mapView.padding = UIEdgeInsets(top: 0, left: 0, bottom: bottomPadding, right: 0)
  }
}

struct ContentView: View {

  @State var showBottomSheet: ShowBottomSheet = .hidden

  var bottomSheetHeight: CGFloat {
    if showBottomSheet == .visible {
      return showBottomSheet.rawValue
    } else {
      return 0
    }
  }

  var body: some View {

    GeometryReader { geometry in
      ZStack {

        // Map
        MapView(bottomPadding: geometry.size.height * bottomSheetHeight)
        .edgesIgnoringSafeArea(.all)
        .bottomSheet(
          bottomSheetPosition: $showBottomSheet,
          options: [
            .allowContentDrag,
            .swipeToDismiss,
            .noBottomPosition,
            .shadow()
          ],
          content: {}
        )
      }
    }
  }
}

enum ShowBottomSheet: CGFloat, CaseIterable {
    case hidden = 0, visible = 0.5
  }
</code>```

答:
If anyone's interested I worked out how to do it. The solution was simpler than I expected, it's literally just wrapping the padding parameter in a UIView.animate closure, then calling it in the updateUIViewController method:</p>
```<code>private func setMapPadding(mapView: GMSMapView) {
    UIView.animate(withDuration: 0.5, delay: 0.18, usingSpringWithDamping: 0.75, initialSpringVelocity: 0) {
      mapView.padding = UIEdgeInsets(top: 0, left: 0, bottom: bottomPadding, right: 0)
    }
  }

func updateUIViewController(_ uiViewController: MapViewController, context: Context) {
    animateCameraToMarker(mapView: uiViewController.mapView)
  }

</code>```

Body:
I'm looking to animate my Google Map's padding, as when a bottom sheet appears, the map padding resizes dynamically.

The GMSMapView.padding documentation says it can be accomplished with a UIView block based animation, but I'm not sure how that would tie in to a SwiftUI application?

The bottom sheet works fine, it shows when expected and passes the correct padding value through to the MapView. It's just the animation I can't figure out. (The bottom sheet uses this component if you're curious https://github.com/LucasMucGH/BottomSheet)

Any help would be greatly appreciated, thanks.

Current relevant code:

struct MapView: UIViewRepresentable {

  var bottomPadding: CGFloat
  private let mapView = GMSMapView(frame: .zero)

  func makeUIView(context: Context) -> GMSMapView {
    return mapView
  }

  func updateUIView(_ mapView: GMSMapView, context: Context) {
    mapView.padding = UIEdgeInsets(top: 0, left: 0, bottom: bottomPadding, right: 0)
  }
}

struct ContentView: View {

  @State var showBottomSheet: ShowBottomSheet = .hidden

  var bottomSheetHeight: CGFloat {
    if showBottomSheet == .visible {
      return showBottomSheet.rawValue
    } else {
      return 0
    }
  }

  var body: some View {

    GeometryReader { geometry in
      ZStack {

        // Map
        MapView(bottomPadding: geometry.size.height * bottomSheetHeight)
        .edgesIgnoringSafeArea(.all)
        .bottomSheet(
          bottomSheetPosition: $showBottomSheet,
          options: [
            .allowContentDrag,
            .swipeToDismiss,
            .noBottomPosition,
            .shadow()
          ],
          content: {}
        )
      }
    }
  }
}

enum ShowBottomSheet: CGFloat, CaseIterable {
    case hidden = 0, visible = 0.5
  }

Body:
If anyone's interested I worked out how to do it. The solution was simpler than I expected, it's literally just wrapping the padding parameter in a UIView.animate closure, then calling it in the updateUIViewController method:

private func setMapPadding(mapView: GMSMapView) {
    UIView.animate(withDuration: 0.5, delay: 0.18, usingSpringWithDamping: 0.75, initialSpringVelocity: 0) {
      mapView.padding = UIEdgeInsets(top: 0, left: 0, bottom: bottomPadding, right: 0)
    }
  }

func updateUIViewController(_ uiViewController: MapViewController, context: Context) {
    animateCameraToMarker(mapView: uiViewController.mapView)
  }


问:
Is there a shorthand for tuple assignment in a for loop in Python?
Wondering if there is a shorter version of the following in Python 3:

```<code>a = [(1,2), (2,3), (1,4)]
for e in a:
    n1, n2 = e
    ...
</code>```

Access to all three variables e, n1, n2 within the for-loop is required.

Thought of something like the following, but it isn't working.

```<code>for n1,n2=e in a:
    ...
</code>```

The question has more of an academic character. I know it is not of a great importance.

答:
for loop in python can unpack the iterated element.

so, the below code should give you the exact result:

a = [(1,2), (2,3), (1,4)]
for i,j in a:
    print(i,j)
# out:
# 1 2
# 2 3
# 1 4
```
<h4>basic iterator(specific to this case)</h4>
<pre class="lang-py prettyprint-override"><code>class Test(object):
    def __init__(self, values):
        self.values = values

    def __iter__(self):
        for tple in self.values:
            yield (*tple,tple)

case1 = Test([(1,2), (2,3), (1,4)])
for i,j,e in case1:
    print(i,j,e)
# out:
1 2 (1, 2)
2 3 (2, 3)
1 4 (1, 4)
</code>```

Body:
Wondering if there is a shorter version of the following in Python 3:

a = [(1,2), (2,3), (1,4)]
for e in a:
    n1, n2 = e
    ...

Access to all three variables e, n1, n2 within the for-loop is required.

Thought of something like the following, but it isn't working.

for n1,n2=e in a:
    ...

The question has more of an academic character. I know it is not of a great importance.

Body:
for loop in python can unpack the iterated element.

so, the below code should give you the exact result:

a = [(1,2), (2,3), (1,4)]
for i,j in a:
    print(i,j)
# out:
# 1 2
# 2 3
# 1 4

basic iterator(specific to this case)

class Test(object):
    def __init__(self, values):
        self.values = values

    def __iter__(self):
        for tple in self.values:
            yield (*tple,tple)

case1 = Test([(1,2), (2,3), (1,4)])
for i,j,e in case1:
    print(i,j,e)
# out:
1 2 (1, 2)
2 3 (2, 3)
1 4 (1, 4)


问:
powershell - deleting tab delimited file and matching subfolder
In a folder structure I have .stb files where name is unknown, and subfolders matching the name of the .stb file.

A folder can look like this:

```<code>C:\path\file1.stb
C:\path\file1\...
C:\path\file2.stb
C:\path\file2\..
</code>```

The .stb file is tab delimited and look something like this:

```<code>Call ID Latitude    Longitude   Date and Time   Noe
wasd    12.1241234  12.1243 2021-12-15 07:45:13.123 Noe
wasd    12.1241234  12.1243 2021-12-15 07:45:13.123 Noe
wasd    12.1241234  12.1243 2022-01-15 07:45:13.123 Noe
</code>```

If a .stb contain a line where date is older than "$limit" the file and matching subfolder (and its content) should be deleted.

What I tested is:

```<code>$limit = (Get-Date).AddDays(-41).Date
$test = (Import-Csv -Path  (Get-ChildItem -Path C:\Users\steff\Documents\ -Filter '*.stb').FullName  -Delimiter "`t" | Where-Object {  ([datetime]$_.'Date and Time') -lt $limit }  )
</code>```

But this only gives the output of file, and im not sure how to proceed to know what the actual filename is, in order to delte the .stb file and the matching subfolder. I am limited to Powershell here. Anyone know how to proceed?

答:
Try it like this:

```<code>$limit = (Get-Date).AddDays(-41).Date
$test = Get-ChildItem -Path C:\Users\steff\Documents\ -Filter '*.stb' | Import-Csv -Delimiter "`t" | Where-Object {  ([datetime]$_.'Date and Time') -lt $limit }  )

</code>```

To complete your task, you can finish your code like this

```<code>$limit = (Get-Date).AddDays(-41).Date
# This code works in Windows PowerShell and PowerShell 7.2
Get-ChildItem -Path C:\Users\steff\Documents\ -Filter '*.stb' -Recurse | Foreach-Object {
    # Test the array of objects
    $OldFile = Import-csv -Delimiter "`t" -Path $_.FullName | Where-Object {  ([datetime]$_.'Date and Time') -lt $limit }
    if ($OldFile){
        # The file had old data, delete it
        Remove-Item $_.FullName -Force
        # Test the folder containing the file. If it is empty, delete it
        if (-not (Get-ChildItem -Path $_.Parent.FullName)){
            # Delete the folder
            Remove-Item $_.Parent.FullName -Force
        }
    }
}
</code>```

Any file with old information will be deleted and the containing folder will be removed, if it contains no other files. Recurse switch is required to get the files in the subfolders.

Body:
In a folder structure I have .stb files where name is unknown, and subfolders matching the name of the .stb file.

A folder can look like this:

C:\path\file1.stb
C:\path\file1\...
C:\path\file2.stb
C:\path\file2\..

The .stb file is tab delimited and look something like this:

Call ID Latitude    Longitude   Date and Time   Noe
wasd    12.1241234  12.1243 2021-12-15 07:45:13.123 Noe
wasd    12.1241234  12.1243 2021-12-15 07:45:13.123 Noe
wasd    12.1241234  12.1243 2022-01-15 07:45:13.123 Noe

If a .stb contain a line where date is older than "$limit" the file and matching subfolder (and its content) should be deleted.

What I tested is:

$limit = (Get-Date).AddDays(-41).Date
$test = (Import-Csv -Path  (Get-ChildItem -Path C:\Users\steff\Documents\ -Filter '*.stb').FullName  -Delimiter "`t" | Where-Object {  ([datetime]$_.'Date and Time') -lt $limit }  )

But this only gives the output of file, and im not sure how to proceed to know what the actual filename is, in order to delte the .stb file and the matching subfolder. I am limited to Powershell here. Anyone know how to proceed?

Body:
Try it like this:

$limit = (Get-Date).AddDays(-41).Date
$test = Get-ChildItem -Path C:\Users\steff\Documents\ -Filter '*.stb' | Import-Csv -Delimiter "`t" | Where-Object {  ([datetime]$_.'Date and Time') -lt $limit }  )

To complete your task, you can finish your code like this

$limit = (Get-Date).AddDays(-41).Date
# This code works in Windows PowerShell and PowerShell 7.2
Get-ChildItem -Path C:\Users\steff\Documents\ -Filter '*.stb' -Recurse | Foreach-Object {
    # Test the array of objects
    $OldFile = Import-csv -Delimiter "`t" -Path $_.FullName | Where-Object {  ([datetime]$_.'Date and Time') -lt $limit }
    if ($OldFile){
        # The file had old data, delete it
        Remove-Item $_.FullName -Force
        # Test the folder containing the file. If it is empty, delete it
        if (-not (Get-ChildItem -Path $_.Parent.FullName)){
            # Delete the folder
            Remove-Item $_.Parent.FullName -Force
        }
    }
}

Any file with old information will be deleted and the containing folder will be removed, if it contains no other files. Recurse switch is required to get the files in the subfolders.


问:
Qt slot still receives signals after disconnecting
I have such problem. In my threaded application I need to disconnect slot and reconnect signal to another slot. Unfortunately if new signals send before disconnecting it will be handled in the old slot. Such behaviour is not described in Qt documentation and looks like a bug. So here example code how to reproduce this.

void Tester::start()
{
    connect(this, &Tester::signal, this, &Tester::slot, Qt::ConnectionType::QueuedConnection);

    QTimer::singleShot(0, this, [=]() {
        emit signal();
        emit signal();
    });

    QTimer::singleShot(1000, this, [=]() {
        emit signal();
    });

    QTimer::singleShot(2000, qApp, &QCoreApplication::quit);
}

void Tester::slot()
{
    qDebug() << "Invoke slot";
    disconnect(this, &Tester::signal, this, &Tester::slot);
    connect(this, &Tester::signal, this, &Tester::slot2);
}

void Tester::slot2()
{
    qDebug() << "Invoke slot2";
}
```
<p>Output:</p>
```Invoke slot
Invoke slot
Invoke slot2
Invoke slot2
```
<p>I expect</p>
```Invoke slot
Invoke slot2
Invoke slot2
```

So there is a way to fix this in global sense? Or I can only to handle this in each particular case?

答:
This is not a bug. Once the signal is emitted, the corresponding event requesting calling the connected slot is put to the queue in the receiver thread's even loop. When you disconnect the signal, there is no way the event loop queue to be cleaned from the already enqueued events. So when the event loop gets to processing of this event, it calls the original slot. For more details how this works read https://woboq.com/blog/how-qt-signals-slots-work-part3-queuedconnection.html

I do not understand why you decided for this strange and fragile design. I do not know your specific usecase. But in general I would probably use two different signals sent one after the other, each connected to a different slot.

Body:
I have such problem. In my threaded application I need to disconnect slot and reconnect signal to another slot. Unfortunately if new signals send before disconnecting it will be handled in the old slot. Such behaviour is not described in Qt documentation and looks like a bug. So here example code how to reproduce this.

void Tester::start()
{
    connect(this, &Tester::signal, this, &Tester::slot, Qt::ConnectionType::QueuedConnection);

    QTimer::singleShot(0, this, [=]() {
        emit signal();
        emit signal();
    });

    QTimer::singleShot(1000, this, [=]() {
        emit signal();
    });

    QTimer::singleShot(2000, qApp, &QCoreApplication::quit);
}

void Tester::slot()
{
    qDebug() << "Invoke slot";
    disconnect(this, &Tester::signal, this, &Tester::slot);
    connect(this, &Tester::signal, this, &Tester::slot2);
}

void Tester::slot2()
{
    qDebug() << "Invoke slot2";
}

Output:

Invoke slot
Invoke slot
Invoke slot2
Invoke slot2

I expect

Invoke slot
Invoke slot2
Invoke slot2

So there is a way to fix this in global sense? Or I can only to handle this in each particular case?


问:
GCP VPC-Peering setup for CloudSQL fails with "INVALID_ARGUMENT: The resource id 917163699144/global/networks/projects/barbarus-game is invalid"
I am following this guide https://cloud.google.com/sql/docs/mysql/configure-private-services-access#gcloud to setup a VPC private peering connection so my GKE nodes can connect to the CloudSQL instance.

However when following the steps I receive an error that stops me from continuing.
Here are the steps I take:

#1 Check if addresses exist

➜  google-cloud-sdk gcloud compute addresses list
Listed 0 items.
```
<p>#2 Setup an new address range</p>
<pre class="lang-sh prettyprint-override"><code>➜  google-cloud-sdk gcloud compute addresses create google-managed-services-default \
--global \
--purpose=VPC_PEERING \
--prefix-length=16 \
--network=projects/barbarus-game/global/networks/default
Created [https://www.googleapis.com/compute/v1/projects/barbarus-game/global/addresses/google-managed-services-default].
</code>```

#3 Assert success

➜  google-cloud-sdk gcloud compute addresses list
NAME                             ADDRESS/RANGE  TYPE      PURPOSE      NETWORK  REGION  SUBNET  STATUS
google-managed-services-default  10.77.0.0/16   INTERNAL  VPC_PEERING  default                  RESERVED
```
<p>#4 Continue with next stop of creating a private connection</p>
<pre class="lang-sh prettyprint-override"><code>➜  google-cloud-sdk gcloud services vpc-peerings connect \
--service=servicenetworking.googleapis.com \
--ranges=google-managed-services-default \
--network=projects/barbarus-game/global/networks/default \
--project=barbarus-game
ERROR: (gcloud.services.vpc-peerings.connect) INVALID_ARGUMENT: The resource id 917163699144/global/networks/projects/barbarus-game is invalid.
Help Token: Ae-hA1NzWbuVH5BSUV2Fn4IdzVTSjiWy2a10u_PyDO5qRIWbTeWzT7-2ybQxgtW_RojO1_XzicJW-NW80qKFglNlqLZKmym7S8A1mp_d2UGfwsP8
- '@type': type.googleapis.com/google.rpc.PreconditionFailure
  violations:
  - subject: ?error_code=210001&resource_id=917163699144/global/networks/projects/barbarus-game
    type: googleapis.com
- '@type': type.googleapis.com/google.rpc.ErrorInfo
  domain: servicenetworking.googleapis.com
  metadata:
    resource_id: 917163699144/global/networks/projects/barbarus-game
  reason: RESOURCES_INVALID_RESOURCE_ID
</code>```

To verify I use the proper project id:

➜  google-cloud-sdk gcloud projects list
PROJECT_ID            NAME                  PROJECT_NUMBER
barbarus-game         Barbarus              917163699144
```
<p>Also additionally here is the VPC network description:</p>
<pre class="lang-sh prettyprint-override"><code>➜  google-cloud-sdk gcloud compute networks describe default
autoCreateSubnetworks: false
creationTimestamp: '2021-12-01T00:17:59.241-08:00'
description: Default network for the project
id: '1930871717275275608'
kind: compute#network
name: default
peerings:
- autoCreateRoutes: true
  exchangeSubnetRoutes: true
  exportCustomRoutes: false
  exportSubnetRoutesWithPublicIp: false
  importCustomRoutes: false
  importSubnetRoutesWithPublicIp: false
  name: servicenetworking-googleapis-com
  network: https://www.googleapis.com/compute/v1/projects/m3b741e040bfc8610p-tp/global/networks/servicenetworking
  state: ACTIVE
  stateDetails: '[2021-12-09T07:56:58.748-08:00]: Connected.'
routingConfig:
  routingMode: REGIONAL
selfLink: https://www.googleapis.com/compute/v1/projects/barbarus-game/global/networks/default
subnetworks:
- [...]
x_gcloud_bgp_routing_mode: REGIONAL
x_gcloud_subnet_mode: CUSTOM
</code>```

As you can see here the magic stops and I have no idea why. The project name is equivalent in the previous step (and any gcloud commands I've used before) so I have no idea why it fails.

Note
The error message is kind of confusing

```<code>The resource id 1071923183712/global/networks/projects/barbarus-game is invalid.
</code>```

I've never seen the network url to have projects path segment in between. It should look like this I expect (just how I passed the argument to the command):

```<code>071923183712/global/networks/barbarus-game
</code>```

答:
From what you posted, it looks like you are entering the PROJECT_NAME instead of the PROJECT_ID.

You should make sure to enter the PROJECT_ID, as mentioned in the guideline.

==============

The following are used to identify your project:

Project name: A human-readable name for your project.

The project name isn't used by any Google APIs. You can edit the project name at any time during or after project creation. Project names do not need to be unique.

Project ID: A globally unique identifier for your project.

A project ID is a unique string used to differentiate your project from all others in Google Cloud.

Reference

Body:
I am following this guide https://cloud.google.com/sql/docs/mysql/configure-private-services-access#gcloud to setup a VPC private peering connection so my GKE nodes can connect to the CloudSQL instance.

However when following the steps I receive an error that stops me from continuing.
Here are the steps I take:

#1 Check if addresses exist

➜  google-cloud-sdk gcloud compute addresses list
Listed 0 items.

#2 Setup an new address range

➜  google-cloud-sdk gcloud compute addresses create google-managed-services-default \
--global \
--purpose=VPC_PEERING \
--prefix-length=16 \
--network=projects/barbarus-game/global/networks/default
Created [https://www.googleapis.com/compute/v1/projects/barbarus-game/global/addresses/google-managed-services-default].

#3 Assert success

➜  google-cloud-sdk gcloud compute addresses list
NAME                             ADDRESS/RANGE  TYPE      PURPOSE      NETWORK  REGION  SUBNET  STATUS
google-managed-services-default  10.77.0.0/16   INTERNAL  VPC_PEERING  default                  RESERVED

#4 Continue with next stop of creating a private connection

➜  google-cloud-sdk gcloud services vpc-peerings connect \
--service=servicenetworking.googleapis.com \
--ranges=google-managed-services-default \
--network=projects/barbarus-game/global/networks/default \
--project=barbarus-game
ERROR: (gcloud.services.vpc-peerings.connect) INVALID_ARGUMENT: The resource id 917163699144/global/networks/projects/barbarus-game is invalid.
Help Token: Ae-hA1NzWbuVH5BSUV2Fn4IdzVTSjiWy2a10u_PyDO5qRIWbTeWzT7-2ybQxgtW_RojO1_XzicJW-NW80qKFglNlqLZKmym7S8A1mp_d2UGfwsP8
- '@type': type.googleapis.com/google.rpc.PreconditionFailure
  violations:
  - subject: ?error_code=210001&resource_id=917163699144/global/networks/projects/barbarus-game
    type: googleapis.com
- '@type': type.googleapis.com/google.rpc.ErrorInfo
  domain: servicenetworking.googleapis.com
  metadata:
    resource_id: 917163699144/global/networks/projects/barbarus-game
  reason: RESOURCES_INVALID_RESOURCE_ID

To verify I use the proper project id:

➜  google-cloud-sdk gcloud projects list
PROJECT_ID            NAME                  PROJECT_NUMBER
barbarus-game         Barbarus              917163699144

Also additionally here is the VPC network description:

➜  google-cloud-sdk gcloud compute networks describe default
autoCreateSubnetworks: false
creationTimestamp: '2021-12-01T00:17:59.241-08:00'
description: Default network for the project
id: '1930871717275275608'
kind: compute#network
name: default
peerings:
- autoCreateRoutes: true
  exchangeSubnetRoutes: true
  exportCustomRoutes: false
  exportSubnetRoutesWithPublicIp: false
  importCustomRoutes: false
  importSubnetRoutesWithPublicIp: false
  name: servicenetworking-googleapis-com
  network: https://www.googleapis.com/compute/v1/projects/m3b741e040bfc8610p-tp/global/networks/servicenetworking
  state: ACTIVE
  stateDetails: '[2021-12-09T07:56:58.748-08:00]: Connected.'
routingConfig:
  routingMode: REGIONAL
selfLink: https://www.googleapis.com/compute/v1/projects/barbarus-game/global/networks/default
subnetworks:
- [...]
x_gcloud_bgp_routing_mode: REGIONAL
x_gcloud_subnet_mode: CUSTOM

As you can see here the magic stops and I have no idea why. The project name is equivalent in the previous step (and any gcloud commands I've used before) so I have no idea why it fails.

Note
The error message is kind of confusing

The resource id 1071923183712/global/networks/projects/barbarus-game is invalid.

I've never seen the network url to have projects path segment in between. It should look like this I expect (just how I passed the argument to the command):

071923183712/global/networks/barbarus-game


问:
how to create a view/table from a single column
enter image description here

so i have the following table and want to create a query that will output the days it was most requested.
for example on 01/02/2000 there was 3 requests in total, on 02/02/2000 there was 2 request in total, on 03/03/2000 there was 6 request in total and on 04/02/2000 there was 4 request in total. so basically i want to output this in table is that possible or will it be easier to just create another table with all this info and make dates a foreign key?

答:
use group by count like this</p>
```<code>select Date,Count(Date) as Total from Table Group by Date
</code>```

Body:
use group by count like this

select Date,Count(Date) as Total from Table Group by Date


问:
How to set different images alternately in listView's row?
I have a listview, in which I am fetching data from Twitter, I also show it in listView,
but I want to show different images in different rows of listView.

I used convert-view.setBackGroundResource(R.drawable.strip1);, it repeats this image in all rows, but I want to set it alternatively. How is it possible?

答:
Take a look at List14 which is an example of exactly that. It's using your own custom adapter and then they alternate the pictures depending on the position, in this case if it's an even or odd row.

Take a look at this part of the getView method:

```<code>// Bind the data efficiently with the holder.
        holder.text.setText(DATA[position]);
        holder.icon.setImageBitmap((position & 1) == 1 ? mIcon1 : mIcon2);
</code>```

Body:
Take a look at List14 which is an example of exactly that. It's using your own custom adapter and then they alternate the pictures depending on the position, in this case if it's an even or odd row.

Take a look at this part of the getView method:

// Bind the data efficiently with the holder.
        holder.text.setText(DATA[position]);
        holder.icon.setImageBitmap((position & 1) == 1 ? mIcon1 : mIcon2);


问:
Bundle multiple safeTransferFrom calls into single transaction
is there a chance to bundle multiple NFT transfers into single transaction so user has to confirm only once? I am trying to implement bulk NFT transfer function

```<code>    for(let i = 0; i < nftCount; i++) {
      contract.methods.safeTransferFrom(from, to, userNFT[0][i]).send({ from: account });
    }
</code>```

This works great, but user has to approve every transfer and if he tries to transfer 100 NFTs it is very annoying and expensive gas.

Are there any better ways to do that bulk transfer on single go?

答:
Assuming that the collection contract doesn't support bulk transfers, you can implement a custom contract that bulks them into one transaction.

```<code>pragma solidity ^0.8;

interface IERC721 {
    function safeTransferFrom(address _from, address _to, uint256 _tokenId) external;
}

contract BulkTransferer {
    IERC721 collection;

    constructor (address _collection) {
        collection = IERC721(_collection);
    }

    function bulkTransfer(address _from, address _to, uint256[] memory _tokenIds) external {
        for (uint256 i = 0; i < _tokenIds.length; i++) {
            collection.safeTransferFrom(_from, _to, _tokenIds[i]);
        }
    }
}
</code>```

Because the invoker of the safeTransferFrom() function (on the collection) is now your BulkTransferer contract address (and not the user), the user needs to approve your contract to transfer their tokens before performing the actual transfer.

Either by executing the approve() function multiple times, once for each token ID. Or a less safe option - by executing the setApprovalForAll() giving the BulkTransferer contract address approval to transfer any of the user's tokens.

Body:
is there a chance to bundle multiple NFT transfers into single transaction so user has to confirm only once? I am trying to implement bulk NFT transfer function

    for(let i = 0; i < nftCount; i++) {
      contract.methods.safeTransferFrom(from, to, userNFT[0][i]).send({ from: account });
    }

This works great, but user has to approve every transfer and if he tries to transfer 100 NFTs it is very annoying and expensive gas.

Are there any better ways to do that bulk transfer on single go?

Body:
Assuming that the collection contract doesn't support bulk transfers, you can implement a custom contract that bulks them into one transaction.

pragma solidity ^0.8;

interface IERC721 {
    function safeTransferFrom(address _from, address _to, uint256 _tokenId) external;
}

contract BulkTransferer {
    IERC721 collection;

    constructor (address _collection) {
        collection = IERC721(_collection);
    }

    function bulkTransfer(address _from, address _to, uint256[] memory _tokenIds) external {
        for (uint256 i = 0; i < _tokenIds.length; i++) {
            collection.safeTransferFrom(_from, _to, _tokenIds[i]);
        }
    }
}

Because the invoker of the safeTransferFrom() function (on the collection) is now your BulkTransferer contract address (and not the user), the user needs to approve your contract to transfer their tokens before performing the actual transfer.

Either by executing the approve() function multiple times, once for each token ID. Or a less safe option - by executing the setApprovalForAll() giving the BulkTransferer contract address approval to transfer any of the user's tokens.


答:
Please give it a try like this:

```<code><script>
  $( document ).ready(function(){
    var userLang = navigator.language || navigator.userLanguage;
    if (userLang == "fr") {
        window.location.href = "https://www.facebook.com"
    }
    else if(userLang == "de"){
       window.location.href = "https://www.facebook.com"
    }
    else {
        window.location.href = "https://www.google.com"
    }
});
</script>
</code>```

And find this documentation MDN HTML Script tag regarding how to use the  tag.

Title: JS redirect based on browser language

Body:
I'm using this test code:

But nothing happens. I must be dumb?

You can see it here:
URL removed

Body:
Please give it a try like this:

<script>
  $( document ).ready(function(){
    var userLang = navigator.language || navigator.userLanguage;
    if (userLang == "fr") {
        window.location.href = "https://www.facebook.com"
    }
    else if(userLang == "de"){
       window.location.href = "https://www.facebook.com"
    }
    else {
        window.location.href = "https://www.google.com"
    }
});
</script>

And find this documentation MDN HTML Script tag regarding how to use the  tag.


问:
Swift progress bar completedUnitCount and totalUnitCount
I don't know if I understood completedUnitCount and totalUnitCount well, I will describe you my problem.

Declaration of progress bar:

```<code>@IBOutlet weak var progressBar: UIProgressView!
let progress = Progress(totalUnitCount: 5)
</code>```

This '5' makes no sense but I put it just to test filling of progress bar.

I want to when I click on button below, to make that button disappear and make progressbar appear on button's place. By default, progressbar is hidden and button is not.
 It works well, but problem is because I want to dismiss current VC when completedUnitCount is equal to totalUnitCount.

When I select 5 cardsets, my completedUnitCount is 5 so it is equal to totalUnitCount.
It starts to fill progressBar and dismisses VC before it is fulfilled.

Here is my code, I think you don't have to pay attention on Realm stuff, and cardsets in just an array loaded from API and selected ones should be posted in realmTable and it works OK:

```<code>@IBAction func btnDownload(_ sender: Any) {
    print("button download pressed")

    let realm = try! Realm()

    for id in cardsetIds {
        for cardset in cardsets {
            if id == cardset.id && cardset.cards != "0" {
                let newSet = CardsetTable()
                newSet.cards = cardset.cards
                newSet.size = cardset.size
                newSet.title = cardset.title
                newSet.id = cardset.id

                try? realm.write { realm.add(newSet) }

                btnDownload.isHidden = true
                progressBar.isHidden = false

                progress.completedUnitCount += 1
                let progressFloat = Float(self.progress.fractionCompleted)

                self.progressBar.setProgress(progressFloat, animated: true)
            }
        }
    }
    if progress.completedUnitCount == progress.totalUnitCount {

        self.dismiss(animated: true, completion: nil)
    }
}
</code>```

答:
for calculate the progress bar to fit any number you want to add:   for example  you have 10 questions and user answer them. you have to check how many questions you have and user in which questions!  you can use this logic to calculate the progress bar  for example :

```<code>func getProgress() -> Float{
    return Float(questionsNumber + 1) / Float(quize.count)
}
</code>```

here (quize.count) is the number of the questions we have

and which mean (total questions number). and the (questionsNumber) is
user in which questions.  so to you fit your progress bar  your 1000 card of the total card number  and you have to make another variable to check user in which card and  the result must in float because the progress bar value is between  0 to 1

Body:
I don't know if I understood completedUnitCount and totalUnitCount well, I will describe you my problem.

Declaration of progress bar:

@IBOutlet weak var progressBar: UIProgressView!
let progress = Progress(totalUnitCount: 5)

This '5' makes no sense but I put it just to test filling of progress bar.

I want to when I click on button below, to make that button disappear and make progressbar appear on button's place. By default, progressbar is hidden and button is not.
 It works well, but problem is because I want to dismiss current VC when completedUnitCount is equal to totalUnitCount.

When I select 5 cardsets, my completedUnitCount is 5 so it is equal to totalUnitCount.
It starts to fill progressBar and dismisses VC before it is fulfilled.

Here is my code, I think you don't have to pay attention on Realm stuff, and cardsets in just an array loaded from API and selected ones should be posted in realmTable and it works OK:

@IBAction func btnDownload(_ sender: Any) {
    print("button download pressed")

    let realm = try! Realm()

    for id in cardsetIds {
        for cardset in cardsets {
            if id == cardset.id && cardset.cards != "0" {
                let newSet = CardsetTable()
                newSet.cards = cardset.cards
                newSet.size = cardset.size
                newSet.title = cardset.title
                newSet.id = cardset.id

                try? realm.write { realm.add(newSet) }

                btnDownload.isHidden = true
                progressBar.isHidden = false

                progress.completedUnitCount += 1
                let progressFloat = Float(self.progress.fractionCompleted)

                self.progressBar.setProgress(progressFloat, animated: true)
            }
        }
    }
    if progress.completedUnitCount == progress.totalUnitCount {

        self.dismiss(animated: true, completion: nil)
    }
}

Body:
for calculate the progress bar to fit any number you want to add:   for example  you have 10 questions and user answer them. you have to check how many questions you have and user in which questions!  you can use this logic to calculate the progress bar  for example :

func getProgress() -> Float{
    return Float(questionsNumber + 1) / Float(quize.count)
}

here (quize.count) is the number of the questions we have

and which mean (total questions number). and the (questionsNumber) is
user in which questions.  so to you fit your progress bar  your 1000 card of the total card number  and you have to make another variable to check user in which card and  the result must in float because the progress bar value is between  0 to 1


问:
Creating a Binary Search Tree using Binary Search Tree class Implementation
I have defined the BinarySearchTree class below:

```<code>class BinarySearchTree:

    def __init__(self, data, left=None, right=None):
        self.data = data
        self.left = left
        self.right = right

    def insert(self, new_data):
        if new_data == self.data:
            return
        elif new_data < self.data:
            if self.left == None:
                self.left = BinarySearchTree(new_data)
            else:
                self.left.insert(new_data)
        else:
            if self.right == None:
                self.right = BinarySearchTree(new_data)
            else:
                self.right.insert(new_data)

    def search(self, find_data):
        if self.data == find_data:
            return True
        elif find_data < self.data and self.left != None:
            return self.left.search(find_data)
        elif find_data > self.data and self.right != None:
            return self.right.search(find_data)
        else:
            return False

    def get_data(self):
        return self.data

    def set_data(self, new_data):
        self.data = new_data

    def get_left(self):
        return self.left

    def get_right(self):
        return self.right
</code>```

Using this class implementation now I need to create a binary tree as shown in the vertical representation:

```<code>>>> bst = create_bst()
    print_tree(bst, 0)
27
(L)    14
(L)        10
(R)        19
(R)    35
(L)        31
(R)        42
</code>```

With my code here:

```<code>def create_bst():
    root = BinarySearchTree(27)
    root.insert(14)
    root.insert(10)

    root.get_left().insert(19)
    root.get_left().insert(35)
    root.get_left().get_left().insert(31)
    root.get_left().get_right().insert(42)
    return root
</code>```

This is the representation I'm getting:

```<code>27
(L)    14
(L)        10
(R)            31
(R)        19
(R)            35
(R)                42
</code>```

答:
It seems to be working fine so far. Just put all the elements directly into root without using get_left, get_right (since you are inserting them into the wrong node).

def create_bst():
    root = BinarySearchTree(27)
    root.insert(14)
    root.insert(10)

    root.insert(19)
    root.insert(35)
    root.insert(31)
    root.insert(42)
    return root
```

Body:
I have defined the BinarySearchTree class below:

class BinarySearchTree:

    def __init__(self, data, left=None, right=None):
        self.data = data
        self.left = left
        self.right = right

    def insert(self, new_data):
        if new_data == self.data:
            return
        elif new_data < self.data:
            if self.left == None:
                self.left = BinarySearchTree(new_data)
            else:
                self.left.insert(new_data)
        else:
            if self.right == None:
                self.right = BinarySearchTree(new_data)
            else:
                self.right.insert(new_data)

    def search(self, find_data):
        if self.data == find_data:
            return True
        elif find_data < self.data and self.left != None:
            return self.left.search(find_data)
        elif find_data > self.data and self.right != None:
            return self.right.search(find_data)
        else:
            return False

    def get_data(self):
        return self.data

    def set_data(self, new_data):
        self.data = new_data

    def get_left(self):
        return self.left

    def get_right(self):
        return self.right

Using this class implementation now I need to create a binary tree as shown in the vertical representation:

>>> bst = create_bst()
    print_tree(bst, 0)
27
(L)    14
(L)        10
(R)        19
(R)    35
(L)        31
(R)        42

With my code here:

def create_bst():
    root = BinarySearchTree(27)
    root.insert(14)
    root.insert(10)

    root.get_left().insert(19)
    root.get_left().insert(35)
    root.get_left().get_left().insert(31)
    root.get_left().get_right().insert(42)
    return root

This is the representation I'm getting:

27
(L)    14
(L)        10
(R)            31
(R)        19
(R)            35
(R)                42


问:
Is there a way to keep only the bottom part in vis.js timeline frame?
I built the following frame using vis.js timeline:

But I'd like to keep only the bottom part (highlighted in blue). Is there a way to achieve that?

Respectively code:

export const TimelineGraph = (props) => {
  const items = props.items;
  const container = useRef(null);

  const options = {
    showCurrentTime: false
  };

  useEffect(() => {
    const timeline = container.current && new Timeline(container.current, items, options);
  }, [container, items]);

  return (

  );
};
```

答:
I think I found a solution. You just need to add min and max options to the options object, like so:

const options = {
  showCurrentTime: false,
  min: getLowestDate(),
  max: getHighestDate(),
};
```

After that, the upper bar was gone.

Body:
I think I found a solution. You just need to add min and max options to the options object, like so:

const options = {
  showCurrentTime: false,
  min: getLowestDate(),
  max: getHighestDate(),
};

After that, the upper bar was gone.


问:
jQuery loop through all h3 and selects on page and format output in textarea
So I have a basic structure of a page and my corresponding script:

jQuery('select').change(function() {
  var abc = jQuery("select option:selected").text();
  var def = jQuery("h3").text();
  jQuery('textarea[name="ghi"]', $form).val(def + "\n\n" + abc).change();
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<h3>Title</h3>
<select>
  <option value="A">This is Option a</option>
</select>

<h3>Title</h3>
<select>
  <option value="B">This is Option b</option>
</select></code>```

This outputs each as

```<code>Title Title This is Option a This is Option b
</code>```

Which I understand - but how do I get the textarea to output as

```<code>Title This is Option a
Title This is Option b
</code>```

Is that even possible?

答:
Changes had to be made to the HTML as well as the JavaScript:

Added <option default> to each <select> because having a select with only one option is pointless.

Gave each <option value='Title'> which makes it easier to extract data from a single element like <option value='val'>text</option>

There were a few problems in OP code:

jQuery("h3").text() will print both h3. So in the example there is specific jQuery methods used to pinpoint what is being accessed:

```<code>// <option value="VALUE">...</option>
$('select').first().find(':selected').val()

// <option value="">TEXT</option>
$('select').first().find(':selected').text()
</code>```

Rendering to <textarea> with text or setting the .value property doesn't have a way of inserting linebreaks (that I know of least -- go ahead and comment if the contrary). Rendering HTML to a <textarea> actually allows us to add '
' for a linebreak.

```<code> $('textarea').html(A + B)
</code>```

$('select').on('change', function(e) {
  var A = $('select').first().find(':selected').val() + ' ' + $('select').first().find(':selected').text() + '
';

  var B = $('select').last().find(':selected').val() + ' ' + $('select').last().find(':selected').text()

  $('textarea').html(A + B)
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>body {
  display: flex;
  justify-content: center
}

h3 {
  margin: 3px 0
}

h3:first-of-type {
  margin-top: -3px
}</code>```

<fieldset>

Title

  <select>
    <option default></option>
    <option value='Title'> This is Option a</option>
  </select>

Title

  <select>
    <option default></option>
    <option value='Title'> This is Option b</option>
  </select>
</fieldset>

<textarea></textarea>

```

Body:
So I have a basic structure of a page and my corresponding script:

jQuery('select').change(function() {
  var abc = jQuery("select option:selected").text();
  var def = jQuery("h3").text();
  jQuery('textarea[name="ghi"]', $form).val(def + "\n\n" + abc).change();
});

Title

<select>
  <option value="A">This is Option a</option>
</select>

Title

<select>
  <option value="B">This is Option b</option>
</select>

This outputs each as

Title Title This is Option a This is Option b

Which I understand - but how do I get the textarea to output as

Title This is Option a
Title This is Option b

Is that even possible?

Body:
Changes had to be made to the HTML as well as the JavaScript:

Added <option default> to each <select> because having a select with only one option is pointless.

Gave each <option value='Title'> which makes it easier to extract data from a single element like <option value='val'>text</option>

There were a few problems in OP code:

jQuery("h3").text() will print both h3. So in the example there is specific jQuery methods used to pinpoint what is being accessed:

// <option value="VALUE">...</option>
$('select').first().find(':selected').val()

// <option value="">TEXT</option>
$('select').first().find(':selected').text()

Rendering to <textarea> with text or setting the .value property doesn't have a way of inserting linebreaks (that I know of least -- go ahead and comment if the contrary). Rendering HTML to a <textarea> actually allows us to add '&#10;' for a linebreak.

 $('textarea').html(A + B)

$('select').on('change', function(e) {
  var A = $('select').first().find(':selected').val() + ' ' + $('select').first().find(':selected').text() + '&#10;';

  var B = $('select').last().find(':selected').val() + ' ' + $('select').last().find(':selected').text()

  $('textarea').html(A + B)
});

body {
  display: flex;
  justify-content: center
}

h3 {
  margin: 3px 0
}

h3:first-of-type {
  margin-top: -3px
}

<fieldset>
  <h3>Title</h3>
  <select>
    <option default></option>
    <option value='Title'> This is Option a</option>
  </select>

  <h3>Title</h3>
  <select>
    <option default></option>
    <option value='Title'> This is Option b</option>
  </select>
</fieldset>

<textarea></textarea>

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>


问:
a complex computing of the average value in pandas
This is my first question on this forum.

I am conducting experiments in which I measure the current-voltage curve of a device applying different experimental conditions.

The different experimental condition are encoded into a parameter K

I am performing measurements of the current I using back & forth voltage sweeps with V varying from O to 2V then from 2V to -2V and then back to 0V.

Measurements are conducted several times for each value of Kto get an average of the current at each voltage point (backward and forward values). Each measurement is ascribed to a parameter named iter (varying from 0 to 3 for instance).

I have collected all data into a pandas dataframe df and I am putting below a code able of produce the typical dfI have (the real one is way too large):

```<code>import numpy as np
import pandas as pd

K_col=[]
iter_col=[]
V_col=[]
I_col=[]
niter = 3
V_val = [0,1,2,1,0,-1,-2,-1,0]
K_val = [1,2]
for K in K_val:
    for it in range(niter):
        for V in V_val:
            K_col.append(K)
            iter_col.append(it+1)
            V_col.append(V)
            I_col.append((2*K+np.random.random())*V)
d={'K':K_col,'iter':iter_col,'V':V_col,'I':I_col}
df=pd.DataFrame(d)
</code>```

I would like to compute the average value of I at each voltage and compare the impact of the experimental condition K.

For example let's look at 2 measurements conducted for K=1:

```<code>df[(df.K==1)&(df.iter.isin([1,2]))]
</code>```

output:

```<code>
    K iter  V      I
0   1   1   0   0.000000
1   1   1   1   2.513330
2   1   1   2   4.778719
3   1   1   1   2.430393
4   1   1   0   0.000000
5   1   1   -1  -2.705487
6   1   1   -2  -4.235055
7   1   1   -1  -2.278295
8   1   1   0   0.000000
9   1   2   0   0.000000
10  1   2   1   2.535058
11  1   2   2   4.529292
12  1   2   1   2.426209
13  1   2   0   0.000000
14  1   2   -1  -2.878359
15  1   2   -2  -4.061515
16  1   2   -1  -2.294630
17  1   2   0   0.000000
</code>```

We can see that for experiment 1 (iter=1) V goes multiple times at 0 (indexes 0, 4 and 8). i do not want to loose these different datapoints.

the first data point for I_avg should be  (I[0]+I[9])/2 which would correspond to the first measurement at 0V. The second data point should be (I[1]+I[10])/2 that would correspond the the avg_I measured at 1V with increasing values of V etc...up to  (I[8]+I[17])/2 which would be my last data point at 0V.

My first thought was to use the groupby() method using K and V as keys but this wouldn't work because V is varying back & forth hence we have duplicate values of V for each measurements and the groupby would just focus on unique values of V.

The final dataframe I would like to have should looks like this:

```<code>    K   V   avg_I
0   1   0   0.000000
1   1   1   2.513330
2   1   2   4.778719
3   1   1   2.430393
4   1   0   0.000000
5   1   -1  -2.705487
6   1   -2  -4.235055
7   1   1   -2.278295
8   1   0   0.000000
9   1   0   0.000000
10  2   1   2.513330
11  2   2   4.778719
12  2   1   2.430393
13  2   0   0.000000
14  2   -1  -2.705487
15  2   -2  -4.235055
16  2   1   -2.278295
17  2   0   0.000000
</code>```

Would anyone have an idea on how doing this?

答:
If I understand this correctly, you want to have a new datapoint that represents the average I for each V category. We can achieve this by getting the average value of I for each V and then map it on the full dataframe.

avg_I = df.groupby(['V'], as_index=False).mean()[['V', 'I']]
df['avg_I'] = df.apply(lambda x: float(avg_I['I'][avg_I['V'] == x['V']]), axis=1)
df.head()
```
<p>output:</p>
```    K   iter    V   I       avg_I
0   1   1       0   0.00    0.00
1   1   1       1   2.34    3.55
2   1   1       2   4.54    6.89
3   1   1       1   2.02    3.55
4   1   1       0   0.00    0.00
```
```df.plot()
```

Body:
This is my first question on this forum.

I am conducting experiments in which I measure the current-voltage curve of a device applying different experimental conditions.

The different experimental condition are encoded into a parameter K

I am performing measurements of the current I using back & forth voltage sweeps with V varying from O to 2V then from 2V to -2V and then back to 0V.

Measurements are conducted several times for each value of Kto get an average of the current at each voltage point (backward and forward values). Each measurement is ascribed to a parameter named iter (varying from 0 to 3 for instance).

I have collected all data into a pandas dataframe df and I am putting below a code able of produce the typical dfI have (the real one is way too large):

import numpy as np
import pandas as pd

K_col=[]
iter_col=[]
V_col=[]
I_col=[]
niter = 3
V_val = [0,1,2,1,0,-1,-2,-1,0]
K_val = [1,2]
for K in K_val:
    for it in range(niter):
        for V in V_val:
            K_col.append(K)
            iter_col.append(it+1)
            V_col.append(V)
            I_col.append((2*K+np.random.random())*V)
d={'K':K_col,'iter':iter_col,'V':V_col,'I':I_col}
df=pd.DataFrame(d)

I would like to compute the average value of I at each voltage and compare the impact of the experimental condition K.

For example let's look at 2 measurements conducted for K=1:

df[(df.K==1)&(df.iter.isin([1,2]))]

output:

    K iter  V      I
0   1   1   0   0.000000
1   1   1   1   2.513330
2   1   1   2   4.778719
3   1   1   1   2.430393
4   1   1   0   0.000000
5   1   1   -1  -2.705487
6   1   1   -2  -4.235055
7   1   1   -1  -2.278295
8   1   1   0   0.000000
9   1   2   0   0.000000
10  1   2   1   2.535058
11  1   2   2   4.529292
12  1   2   1   2.426209
13  1   2   0   0.000000
14  1   2   -1  -2.878359
15  1   2   -2  -4.061515
16  1   2   -1  -2.294630
17  1   2   0   0.000000

We can see that for experiment 1 (iter=1) V goes multiple times at 0 (indexes 0, 4 and 8). i do not want to loose these different datapoints.

the first data point for I_avg should be  (I[0]+I[9])/2 which would correspond to the first measurement at 0V. The second data point should be (I[1]+I[10])/2 that would correspond the the avg_I measured at 1V with increasing values of V etc...up to  (I[8]+I[17])/2 which would be my last data point at 0V.

My first thought was to use the groupby() method using K and V as keys but this wouldn't work because V is varying back & forth hence we have duplicate values of V for each measurements and the groupby would just focus on unique values of V.

The final dataframe I would like to have should looks like this:

    K   V   avg_I
0   1   0   0.000000
1   1   1   2.513330
2   1   2   4.778719
3   1   1   2.430393
4   1   0   0.000000
5   1   -1  -2.705487
6   1   -2  -4.235055
7   1   1   -2.278295
8   1   0   0.000000
9   1   0   0.000000
10  2   1   2.513330
11  2   2   4.778719
12  2   1   2.430393
13  2   0   0.000000
14  2   -1  -2.705487
15  2   -2  -4.235055
16  2   1   -2.278295
17  2   0   0.000000

Would anyone have an idea on how doing this?

Body:
If I understand this correctly, you want to have a new datapoint that represents the average I for each V category. We can achieve this by getting the average value of I for each V and then map it on the full dataframe.

avg_I = df.groupby(['V'], as_index=False).mean()[['V', 'I']]
df['avg_I'] = df.apply(lambda x: float(avg_I['I'][avg_I['V'] == x['V']]), axis=1)
df.head()

output:

    K   iter    V   I       avg_I
0   1   1       0   0.00    0.00
1   1   1       1   2.34    3.55
2   1   1       2   4.54    6.89
3   1   1       1   2.02    3.55
4   1   1       0   0.00    0.00

df.plot()


问:
PayPal REST API v2/checkout/orders does not redirect back after approval
I've never used PayPal before, it's not really popular here, and I'm confused by how the order and payment works. Can anyone explain it to me? I've read the documentation and I'm still confused.

To complete payer approval, use the approve link to redirect the
payer. The API caller has 3 hours (default setting, this which can be
changed by your account manager to 24/48/72 hours to accommodate your
use case) from the time the order is created, to redirect your payer.
Once redirected, the API caller has 3 hours for the payer to approve
the order and either authorize or capture the order.

I have created a working PHP curl call for this API in sandbox env according to the sample
https://developer.paypal.com/docs/api/orders/v2/#orders_create

The APIs I created before work like this:

Send a request to 3rd party payment

Get a response containing a checkout link

Redirect customer to link

Customer complete payment

3rd party send a request containing order and payment detail to a file/path on my server

My server receives the request and updates the order status/payment in my database

3rd party redirect the customer to my webpage

With PayPal, what I got so far is:

Send request containing order detail to /v2/checkout/orders

Get a response containing various links

Redirect my customer to the rel:approve checkout link

Log in to my sandbox customer account and pay using PayPal balance, click Continue

A popup message is shown: We're sending you back to xxx's Test Store to complete this purchase

The popup message is closed and I'm still at the same payment page with the Continue button as seen in the image

答:
I had this issue too, and I eventually got a solution from the documentation.

You have to add application_context.return_url to your request.

Attached is an example in PHP:

```<code>$postData = [
        "intent"              => "CAPTURE",
        "purchase_units"      => $purchase_units,

        "application_context" => [
            "return_url"    => "",
            "cancel_url"    => "",
        ],
    ];
</code>```

You can make a whole lot of customisations to the PayPal Payment page by adding the Application Context option, For a full list of the possible customisations, you can check up the official documentation Application Context Documentation

Body:
I had this issue too, and I eventually got a solution from the documentation.

You have to add application_context.return_url to your request.

Attached is an example in PHP:

$postData = [
        "intent"              => "CAPTURE",
        "purchase_units"      => $purchase_units,

        "application_context" => [
            "return_url"    => "",
            "cancel_url"    => "",
        ],
    ];

You can make a whole lot of customisations to the PayPal Payment page by adding the Application Context option, For a full list of the possible customisations, you can check up the official documentation Application Context Documentation


答:
You might be confusing this layer with a min-max scaling. The docs clearly state that:

This layer will shift and scale inputs into a distribution centered around 0 with standard deviation 1. It accomplishes this by precomputing the mean and variance of the data, and calling (input - mean) / sqrt(var) at runtime

import tensorflow as tf

normalizer = tf.keras.layers.Normalization(axis=-1)
x_train = tf.constant([[82.83, 31.04, 47., 151., 17.88, 0., 58.],
                        [59.71, 19.01, 50., 141., 6.08, 0., 60.],
                        [133.33, 62.68, 84., 279., 15.17, 0., 65.]])
normalizer.adapt(x_train)
norm_x = normalizer(x_train)
print(tf.reduce_mean(norm_x), tf.math.reduce_std(norm_x))
```
```tf.Tensor(6.81196e-08, shape=(), dtype=float32) tf.Tensor(0.9258201, shape=(), dtype=float32)
```

With more data, you should come close to mean 0 and std 1. Check this post for min-max scaling.

Title: keras.Normalization column wise

Body:
I want to add a Normalization layer to my keras model.
And I am testing it in a simpler example, but I don't understand the results.

I did a simple test:

normalizer = Normalization(axis=-1)
normalizer.adapt(x_train[:3])
print(x_train[:3])
print(normalizer(x_train[:3]))

And I got following results:

[[ 82.83  31.04  47.   151.    17.88   0.    58.  ]
 [ 59.71  19.01  50.   141.     6.08   0.    60.  ]
 [133.33  62.68  84.   279.    15.17   0.    65.  ]]
tf.Tensor(
[[-0.2968958  -0.3549137  -0.79461485 -0.62603205  0.95840394  0.
  -1.0190493 ]
 [-1.0490034  -1.0080925  -0.6158265  -0.7851927  -1.3798107   0.
  -0.3396831 ]
 [ 1.3458993   1.3630061   1.4104416   1.411225    0.42140734  0.
   1.3587323 ]], shape=(3, 7), dtype=float32)

My question is: if the element in the third row, first column is the maximum of its column, shouldn't it be 1 in the normalized output?

UPDATE

It is clear, I was confusing with min_max scale.

Now, I have the issue that if I use adapt with the whole training dataset:

normalizer = Normalization(axis=-1)
normalizer.adapt(x_train)
print(x_train[:3])
print(normalizer(x_train[:3]))

Then, the second column always gives me nan value:

[[ 82.83  31.04  47.   151.    17.88   0.    58.  ]
 [ 59.71  19.01  50.   141.     6.08   0.    60.  ]
 [133.33  62.68  84.   279.    15.17   0.    65.  ]]
tf.Tensor(
[[-0.51946616         nan -1.4330941  -0.5569647   0.8550693  -0.05900022
  -0.17098609]
 [-1.3537331          nan -1.2127512  -0.62386954 -0.8509362  -0.05900022
  -0.1282853 ]
 [ 1.3027862          nan  1.2844696   0.29941723  0.4632664  -0.05900022
  -0.02153332]], shape=(3, 7), dtype=float32)

Why that column has nan value?

Body:
You might be confusing this layer with a min-max scaling. The docs clearly state that:

This layer will shift and scale inputs into a distribution centered around 0 with standard deviation 1. It accomplishes this by precomputing the mean and variance of the data, and calling (input - mean) / sqrt(var) at runtime

import tensorflow as tf

normalizer = tf.keras.layers.Normalization(axis=-1)
x_train = tf.constant([[82.83, 31.04, 47., 151., 17.88, 0., 58.],
                        [59.71, 19.01, 50., 141., 6.08, 0., 60.],
                        [133.33, 62.68, 84., 279., 15.17, 0., 65.]])
normalizer.adapt(x_train)
norm_x = normalizer(x_train)
print(tf.reduce_mean(norm_x), tf.math.reduce_std(norm_x))

tf.Tensor(6.81196e-08, shape=(), dtype=float32) tf.Tensor(0.9258201, shape=(), dtype=float32)

With more data, you should come close to mean 0 and std 1. Check this post for min-max scaling.


问:
heat map on city plot (Geopandas)
Hey I am trying to plot a heat map where the 'heat' is indicates by the 'count' column of the data frame:

```<code>|             geometry        | count |
|-----------------------------|-------|
|   POINT (6.92334 50.91695)  |   10  |
|   POINT (6.91970 50.93167)  |    8  |
|   POINT (6.96946 50.91469)  |    2  |
|   POINT (6.96266 50.94713)  |   72  |
|   POINT (6.93751 50.93832)  |  267  |
</code>```

I have matched the coordinate system to the base map:

```<code>gdg_crs = gdg.to_crs(epsg=3857)
</code>```

and tried to plot it with the following code;   cx.add_basemap to plot it on the city map (this worked before without putting column='count' and cmap='coolwormth' yielding a map with all the point coordinates as points on the city map):

```<code>g_plot = gdg_crs.plot(column='count', cmap='coolwarmth', figsize = (15,15))
plt.ylim(6.606e6, 6.616e6)
plt.xlim(768000,784000)
cx.add_basemap(g_plot)
</code>```

it worked but the map was only purple and i want to adjust the colours (say which color ranges over which interval) because they range very widely is that possible?
Any ideas?

答:
an alternate is an interactive folium map

have experimented with explore() and found I couldn't fully control color and size at same time.  Hence used monkey patching to override style_function

```<code>import io
import pandas as pd
import geopandas as gpd
import shapely
import folium
import wrapt

df = pd.read_csv(
    io.StringIO(
        """|             geometry        | count |
|   POINT (6.92334 50.91695)  |   10  |
|   POINT (6.91970 50.93167)  |    8  |
|   POINT (6.96946 50.91469)  |    2  |
|   POINT (6.96266 50.94713)  |   72  |
|   POINT (6.93751 50.93832)  |  267  |"""
    ),
    sep="|",
).pipe(
    lambda d: d.drop(columns=[c for c in d.columns if "Unnamed" in c]).rename(
        columns={c: c.strip() for c in d.columns}
    )
)

# wanna intercept geopandas.explore() style function so can set size too
@wrapt.patch_function_wrapper(folium, "GeoJson")
def new_style(wrapped, instance, args, kwargs):
    def style_fn(x):
        return {
            "fillColor": x["properties"]["__folium_color"],
            "color": x["properties"]["__folium_color"],
            "radius": x["properties"]["size"],
            "fillOpacity":.8
        }

    if "_style_column" in str(kwargs["style_function"]):
        kwargs["style_function"] = style_fn
    return wrapped(*args, **kwargs)

gdf = gpd.GeoDataFrame(
    df, geometry=df["geometry"].apply(shapely.wkt.loads), crs="epsg:4326"
)
# normalize sizes...
gdf["size"] = gdf["count"].rank() * 20

gdf.explore(cmap="Reds", column="count")

</code>```

Title: heat map on city plot (Geopandas)

Body:
Hey I am trying to plot a heat map where the 'heat' is indicates by the 'count' column of the data frame:

|             geometry        | count |
|-----------------------------|-------|
|   POINT (6.92334 50.91695)  |   10  |
|   POINT (6.91970 50.93167)  |    8  |
|   POINT (6.96946 50.91469)  |    2  |
|   POINT (6.96266 50.94713)  |   72  |
|   POINT (6.93751 50.93832)  |  267  |

I have matched the coordinate system to the base map:

gdg_crs = gdg.to_crs(epsg=3857)

and tried to plot it with the following code;   cx.add_basemap to plot it on the city map (this worked before without putting column='count' and cmap='coolwormth' yielding a map with all the point coordinates as points on the city map):

g_plot = gdg_crs.plot(column='count', cmap='coolwarmth', figsize = (15,15))
plt.ylim(6.606e6, 6.616e6)
plt.xlim(768000,784000)
cx.add_basemap(g_plot)

it worked but the map was only purple and i want to adjust the colours (say which color ranges over which interval) because they range very widely is that possible?
Any ideas?

Body:
an alternate is an interactive folium map

have experimented with explore() and found I couldn't fully control color and size at same time.  Hence used monkey patching to override style_function

import io
import pandas as pd
import geopandas as gpd
import shapely
import folium
import wrapt

df = pd.read_csv(
    io.StringIO(
        """|             geometry        | count |
|   POINT (6.92334 50.91695)  |   10  |
|   POINT (6.91970 50.93167)  |    8  |
|   POINT (6.96946 50.91469)  |    2  |
|   POINT (6.96266 50.94713)  |   72  |
|   POINT (6.93751 50.93832)  |  267  |"""
    ),
    sep="|",
).pipe(
    lambda d: d.drop(columns=[c for c in d.columns if "Unnamed" in c]).rename(
        columns={c: c.strip() for c in d.columns}
    )
)

# wanna intercept geopandas.explore() style function so can set size too
@wrapt.patch_function_wrapper(folium, "GeoJson")
def new_style(wrapped, instance, args, kwargs):
    def style_fn(x):
        return {
            "fillColor": x["properties"]["__folium_color"],
            "color": x["properties"]["__folium_color"],
            "radius": x["properties"]["size"],
            "fillOpacity":.8
        }

    if "_style_column" in str(kwargs["style_function"]):
        kwargs["style_function"] = style_fn
    return wrapped(*args, **kwargs)

gdf = gpd.GeoDataFrame(
    df, geometry=df["geometry"].apply(shapely.wkt.loads), crs="epsg:4326"
)
# normalize sizes...
gdf["size"] = gdf["count"].rank() * 20

gdf.explore(cmap="Reds", column="count")


问:
Button type submit - How to validate first
I have a form with a submit button. I can not change it and anything about the html.

```<code><form>
  <input type="text" class="form-control" id="username" required />
  <label for="username">Username</label>
  <input type="password" class="form-control" id="password" required />
  <label for="password">Password</label>
  <button id="submit" class="btn btn-lg" type="submit">Sign in</button>
  <form></form>
</form>
</code>```

This is my js:

```<code>let nombre = document.getElementById("username").value;
let pass = document.getElementById("password").value;

async function login() {
  try {
    const response = await fetch("http://localhost:8888/login", {
      method: "POST",
      headers: {
        "Content-Type": "application/json",
      },
      body: JSON.stringify({ username: nombre, password: pass }),
    });
    if (response.status !== 200) throw response.statusText;
    const content = await response.json();
    return content;
  } catch (error) {
    console.log("Errorr:" + error);
  }
}

function submit() {
  let validacion1 = document.getElementById("username").checkValidity();
  let validacion2 = document.getElementById("pass").checkValidity();
  if (validacion1 == true && validacion2 == true) {
    login();
  }
}

document.getElementById("submit").addEventListener("click", submit);

</code>```

But if I click on my submit button, the page "recharge" and I can not do the login properly.

I should click the submit button and wait for the username and password to be correct.

How can I click the submit button and not instantly recharge the page?

Thank you so much

答:
Try this. It prevents the default action for the submit button and lets you perform your own code:

```<code>function submit(event) {
  event.preventDefault();
  let validacion1 = document.getElementById("username").checkValidity();
  let validacion2 = document.getElementById("pass").checkValidity();
  if (validacion1 == true && validacion2 == true) {
    login();
  }
}

</code>```

More about that: https://developer.mozilla.org/en-US/docs/Web/API/HTMLFormElement/submit_event

Body:
I have a form with a submit button. I can not change it and anything about the html.

<form>
  <input type="text" class="form-control" id="username" required />
  Username
  <input type="password" class="form-control" id="password" required />
  Password
  <button id="submit" class="btn btn-lg" type="submit">Sign in</button>
  <form></form>
</form>

This is my js:

let nombre = document.getElementById("username").value;
let pass = document.getElementById("password").value;

async function login() {
  try {
    const response = await fetch("http://localhost:8888/login", {
      method: "POST",
      headers: {
        "Content-Type": "application/json",
      },
      body: JSON.stringify({ username: nombre, password: pass }),
    });
    if (response.status !== 200) throw response.statusText;
    const content = await response.json();
    return content;
  } catch (error) {
    console.log("Errorr:" + error);
  }
}

function submit() {
  let validacion1 = document.getElementById("username").checkValidity();
  let validacion2 = document.getElementById("pass").checkValidity();
  if (validacion1 == true && validacion2 == true) {
    login();
  }
}

document.getElementById("submit").addEventListener("click", submit);

But if I click on my submit button, the page "recharge" and I can not do the login properly.

I should click the submit button and wait for the username and password to be correct.

How can I click the submit button and not instantly recharge the page?

Thank you so much

Body:
Try this. It prevents the default action for the submit button and lets you perform your own code:

function submit(event) {
  event.preventDefault();
  let validacion1 = document.getElementById("username").checkValidity();
  let validacion2 = document.getElementById("pass").checkValidity();
  if (validacion1 == true && validacion2 == true) {
    login();
  }
}

More about that: https://developer.mozilla.org/en-US/docs/Web/API/HTMLFormElement/submit_event