问:
How can I implement a typed "both" function in TypeScript?
The storybook actions addon provides a convenient way to log callback invocations:

```<code>renderButton({onClick: action('onClick')});
</code>```

The action call returns a function that logs the string (onClick) and the arguments with which it's invoked.

Sometimes I want to have both the action and something else:

renderButton({
  onClick: (arg1, arg2, arg3) => {
    action('onClick')(arg1, arg2, arg3);
    // ... my code
  }
});
```

<p>The <code>action</code> call has gotten more verbose since I have to pass in all the arguments. So I've implemented a <code>both</code> function to let me write:</p>

<pre class="lang-js prettyprint-override"><code>renderButton({
  onClick: both(action('onClick'), (arg1, arg2, arg3) => {
    // ... my code
  })
});
</code>```

This works great until I try to add TypeScript types. Here's my implementation:

```<code>function both<T extends unknown[], This extends unknown>(
  a: (this: This, ...args: T) => void,
  b: (this: This, ...args: T) => void,
): (this: This, ...args: T) => void {
  return function(this: This, ...args: T) {
    a.apply(this, args);
    b.apply(this, args);
  };
}
</code>```

This type checks and works at runtime, but depending on the context, it either results in unwanted any types or type errors. For example:

```<code>const fnWithCallback = (cb: (a: string, b: number) => void) => {};

fnWithCallback((a, b) => {
  a;  // type is string
  b;  // type is number
});

fnWithCallback(
  both(action('callback'), (a, b) => {
    a;  // type is any
    b;  // type is any
  }),
);

fnWithCallback(
  both(action('callback'), (a, b) => {
//                         ~~~~~~~~~~~
// Argument of type '(a: T[0], b: T[1]) => number' is not assignable to
// parameter of type '() => void'.
  }),
);
</code>```

Is it possible to have both correctly capture argument types from the callback context? And to avoid the any types that presumably come arise from the action declaration:

```<code>export type HandlerFunction = (...args: any[]) => void;
</code>```

Here's a playground link with the full example.

答:
This should work and keep correct callback argument types:

```<code>type UniversalCallback<Args extends any[]> = (...args: Args) => void;
function both<
    Args extends any[],
    CB1 extends UniversalCallback<Args>,
    CB2 extends UniversalCallback<Args>
>(fn1: CB1, fn2: CB2): UniversalCallback<Args> {
  return (...args:Args) => {
    fn1(...args);
    fn2(...args);
  };
}
</code>```

This solution ignores this but I don't know if it's a problem for you because the examples of usage you gave didn't really use this.

It's easy enough to extend support to passing this to callbacks:

```<code>type UniversalCallback<T, Args extends any[]> = (this:T, ...args: Args) => void;
function both<
    T,
    Args extends any[],
    CB1 extends UniversalCallback<T, Args>,
    CB2 extends UniversalCallback<T, Args>
>(fn1: CB1, fn2: CB2): UniversalCallback<T, Args> {
  return function(this:T, ...args:Args) {
    fn1.apply(this, args);
    fn2.apply(this, args);
  };
}
</code>```

It works perfectly in the following test:

```<code>class A { f() {} }

const fnWithCallback = (cb: (this: A, a: string, b: number) => void) => { };

fnWithCallback(function(a, b) {
  a;  // type is string
  b;  // type is number
  this.f(); // works
});

fnWithCallback(
  both(function (a) {
    a; // correct type
    this.f(); // works
  }, function (a, b) {
    a; b; // correct types
    this.f(); // works
  }),
);
</code>```

Body:
The storybook actions addon provides a convenient way to log callback invocations:

renderButton({onClick: action('onClick')});

The action call returns a function that logs the string (onClick) and the arguments with which it's invoked.

Sometimes I want to have both the action and something else:

renderButton({
  onClick: (arg1, arg2, arg3) => {
    action('onClick')(arg1, arg2, arg3);
    // ... my code
  }
});

The action call has gotten more verbose since I have to pass in all the arguments. So I've implemented a both function to let me write:

renderButton({
  onClick: both(action('onClick'), (arg1, arg2, arg3) => {
    // ... my code
  })
});

This works great until I try to add TypeScript types. Here's my implementation:

function both<T extends unknown[], This extends unknown>(
  a: (this: This, ...args: T) => void,
  b: (this: This, ...args: T) => void,
): (this: This, ...args: T) => void {
  return function(this: This, ...args: T) {
    a.apply(this, args);
    b.apply(this, args);
  };
}

This type checks and works at runtime, but depending on the context, it either results in unwanted any types or type errors. For example:

const fnWithCallback = (cb: (a: string, b: number) => void) => {};

fnWithCallback((a, b) => {
  a;  // type is string
  b;  // type is number
});

fnWithCallback(
  both(action('callback'), (a, b) => {
    a;  // type is any
    b;  // type is any
  }),
);

fnWithCallback(
  both(action('callback'), (a, b) => {
//                         ~~~~~~~~~~~
// Argument of type '(a: T[0], b: T[1]) => number' is not assignable to
// parameter of type '() => void'.
  }),
);

Is it possible to have both correctly capture argument types from the callback context? And to avoid the any types that presumably come arise from the action declaration:

export type HandlerFunction = (...args: any[]) => void;

Here's a <a href="https://www.typescriptlang.org/play/?ssl=1&ssc=1&pln=46&pc=1#code/GYVwdgxgLglg9mABAIzlAFgHgCqIKYAeUeYAJgM6LgDWYcA7mANoC6ANItujJYcWZRp1GAPgAUAKESIAhgC5EYjDwVceHAHRaZAJwDm5VQEpEAXhGIAbnBik2UlAqXdDnF5u37X2E+as27CSMnZW93RC0NXQNjMwtrW0QAbwcdPCgQHSRQSFgEZxU3dQjPGM4TFOlpGSiAB1qAGwBPAvIOaPIjAG4HaWQ6xpbQ9q9uhwBfHvGJCQgEcihEYDAAdRgMAGEZBobkGQhqM0UIZCd5RAWdGDA9DlPEMBAAW2Q8HV94gI-kxEmZ5bWm22u321DEYhkd2+lVkXWkAHp4YgoE1anhEDwLlArjcHMg4YhEcjUejMY8Xm8JOMxhIAet0FsdnsDpI+mh0ODob8OBCoXFkr1CUiqiKRQA-CWSqViwVEgCC+meJEWcGAxLRiAA5K0FEIGGB2qomAAGdiOThMACMLG+CVImoxlDoixk5HIMD0YBkyAaeFlSKgcEQtV0Mie6TeiFV6vR2tCurAtH1toCmo0EyM9hpdKBTNBrJQ7PBkJQ0P9iGllfLCr0SrAKrVKI1cZcCaTjENFtNdyN1pTtgdZLQsjdHq9Pr9IqJgeDofDxB0UcbJK1OqoieEYH79vT0nGPK51KzPQkTfRAAkZGRfToAGLgaDwJCmRSRDoKK9NVjbnqkPAQBpdHRHJHwQWRQLAMQvXDBRLmuPRgkQS9rzee9cifE8cwZYFmTBPEi0FfY8kgzUIBw0FNUzQVeVLfkYRFGQCWnFdMU-QU+iYgMWMoNiRX3BwjCCCQgA" rel="nofollow noreferrer">playground link with the full example.

Body:
This should work and keep correct callback argument types:

type UniversalCallback<Args extends any[]> = (...args: Args) => void;
function both<
    Args extends any[],
    CB1 extends UniversalCallback<Args>,
    CB2 extends UniversalCallback<Args>
>(fn1: CB1, fn2: CB2): UniversalCallback<Args> {
  return (...args:Args) => {
    fn1(...args);
    fn2(...args);
  };
}

This solution ignores this but I don't know if it's a problem for you because the examples of usage you gave didn't really use this.

It's easy enough to extend support to passing this to callbacks:

type UniversalCallback<T, Args extends any[]> = (this:T, ...args: Args) => void;
function both<
    T,
    Args extends any[],
    CB1 extends UniversalCallback<T, Args>,
    CB2 extends UniversalCallback<T, Args>
>(fn1: CB1, fn2: CB2): UniversalCallback<T, Args> {
  return function(this:T, ...args:Args) {
    fn1.apply(this, args);
    fn2.apply(this, args);
  };
}

It works perfectly in the following test:

class A { f() {} }

const fnWithCallback = (cb: (this: A, a: string, b: number) => void) => { };

fnWithCallback(function(a, b) {
  a;  // type is string
  b;  // type is number
  this.f(); // works
});

fnWithCallback(
  both(function (a) {
    a; // correct type
    this.f(); // works
  }, function (a, b) {
    a; b; // correct types
    this.f(); // works
  }),
);


来源: stackexchange

问:
How to remove an element from a nested list?
if I have a nested list such as:

```<code>m=[[34,345,232],[23,343,342]]
</code>```

if I write m.remove(345) it gives an error message saying the element is not in the list.

I want to know how to remove an element from the nested list, easily.

答:
You can delete by using delete:-  del m[1][1]
or  by using below code

```<code>for i in m:
    for j in i:
        if j==345:
            i.remove(j)
print(m)
</code>```

ContentLicense: CC BY-SA 4.0

Body:
if I have a nested list such as:

m=[[34,345,232],[23,343,342]]

if I write m.remove(345) it gives an error message saying the element is not in the list.

I want to know how to remove an element from the nested list, easily.

Body:
You can delete by using delete:-  del m[1][1]
or  by using below code

for i in m:
    for j in i:
        if j==345:
            i.remove(j)
print(m)


问:
Profile picture is not getting displayed in django template base html page
I am creating a taskToDo web application. Most of the html files under templates are extending base.html file which includes a navbar in which i want to show the user profile picture under navbar of base.html.
The profile picture is getting saved under profile_pics directory of 'media' folder.

I have tried giving {{user.profile_pic.url}} as the source for image, but still the image is not getting linked
My models.py , project urls.py, settings.py, relevant part of views.py are as follows:-

models.py

```<code>from django.db import models
from django.contrib.auth.models import User
from django.conf import settings
from django.core.exceptions import ValidationError
from datetime import datetime
# Create your models here.

class UserCustom(models.Model):
    user=models.OneToOneField(User,on_delete=models.CASCADE)

    profile_pic=models.ImageField(upload_to='profile_pics',blank=True)

    def __str__(self):
        return self.user.username   #user os object defined above

class UserTask(models.Model):
    author = models.ForeignKey(User,on_delete=models.CASCADE)
    label=models.CharField(max_length=264)
    date=models.DateField()
    status=models.BooleanField(default=False)

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

settings.py

```<code>from django.contrib import admin
from django.urls import path,include
from taskApp import views
from django.conf.urls.static import static
from django.conf import settings # new
urlpatterns = [
    path('admin/', admin.site.urls),
    path('',views.index,name='index'),
    path('taskApp/',include('taskApp.urls')),
    path('logout/',views.user_logout,name='logout'),
]+static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
</code>```

forms.py

```<code>from django import forms
from django.forms.fields import DateField
from django.core import validators
from django.contrib.auth.models import User
from taskApp.models import UserCustom,UserTask
from django.contrib.admin.widgets import AdminDateWidget
from datetime import datetime,timedelta

class UserForm(forms.ModelForm):
    password=forms.CharField(widget=forms.PasswordInput())

    class Meta():
        model=User
        fields=('username','email','password')

class UserCustomForm(forms.ModelForm):
    class Meta():
        model=UserCustom
        fields=('profile_pic',)

class UserTaskForm(forms.ModelForm):
    date=DateField(widget=forms.DateInput(attrs={'placeholder': 'YYYY-MM-DD', 'required': 'required'}))
    status=forms.BooleanField(required=False)
    class Meta():
        model=UserTask
        fields=('label','date')

    def clean(self):
        cleaned_data=self.cleaned_data
        date2=cleaned_data.get('date')
        if str(date2)<=(datetime.today()-timedelta(days=1)).strftime('%Y-%m-%d'):
            raise forms.ValidationError("The date cannot be in the past!")
        return cleaned_data
</code>```

views.py (relevant part)

```<code>@login_required
def my_task(request):
    task_obj=UserTask.objects.filter(author=request.user)
    return render(request,'taskApp/task.html',{'task_obj':task_obj,'user_key':request.user})
</code>```

def register(request):

```<code>registered=False

if request.method == "POST":

    user_form=UserForm(data=request.POST)
    profile_form=UserCustomForm(data=request.POST)

    if user_form.is_valid() and profile_form.is_valid():
        user=user_form.save()
        user.set_password(user.password)
        user.save()

        profile=profile_form.save(commit=False)
        profile.user=user

        if 'profile_pic' in request.FILES:
            profile.profile_pic=request.FILES['profile_pic']

        profile.save()
        registered=True

    else:
        print(user_form.errors,profile_form.errors)

else: #no request=POST yet
    user_form=UserForm()
    profile_form=UserCustomForm()

return render(request,'taskApp/registration.html',{'user_form':user_form,'profile_form':profile_form,'registered':registered })

def register(request):
    registered=False

    if request.method == "POST":

        user_form=UserForm(data=request.POST)
        profile_form=UserCustomForm(data=request.POST)

        if user_form.is_valid() and profile_form.is_valid():
            user=user_form.save()
            user.set_password(user.password)
            user.save()

            profile=profile_form.save(commit=False)
            profile.user=user

            if 'profile_pic' in request.FILES:
                profile.profile_pic=request.FILES['profile_pic']

            profile.save()
            registered=True

        else:
            print(user_form.errors,profile_form.errors)

    else: #no request=POST yet
        user_form=UserForm()
        profile_form=UserCustomForm()

    return render(request,'taskApp/registration.html',{'user_form':user_form,'profile_form':profile_form,'registered':registered })

def user_login(request):

    if request.method=='POST':
        username=request.POST.get('username')  #name of element
        password=request.POST.get('password')

        user=authenticate(username=username,password=password)

        if user:
            if user.is_active:
                login(request,user)
                return HttpResponseRedirect(reverse('taskApp:myTask')) #myTask is the name of url , go to urls.py
            else:
                return HttpResponse("ACCOUNT NOT ACTIVE")

        else:
            print("Someone tried to login and failed!")
            print("Username: {} and password {}".format(username,password))
            return HttpResponse("invalid login details supllied!")

    else:
        return render(request,'taskApp/login.html',{})
</code>```

base.html

```<code><!DOCTYPE html>
{% load static %}
<html lang="en" dir="ltr">
  <head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title></title>
    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css" integrity="sha384-HSMxcRTRxnN+Bdg0JdbxYKrThecOKuH5zCYotlSAcp1+c8xmyTe9GYg1l9a69psu" crossorigin="anonymous">

    <link rel="stylesheet" href="{% static 'css/mystyle.css' %}" >

    <!-- <script src="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.11.2/js/all.min.js" crossorigin="anonymous"></script> -->

  </head>
  <body>
    <nav class="navbar navbar-default navbar-static-top">
      <div class="container">

        <ul class="nav navbar-nav">
          <li><a class="navbar-brand" href="{% url 'index' %}"><em>ToDoList</em><img src={% static "images/1567073.png" %} width="60" height="50" alt="TASK_TO_DO"></a></li>
          <!-- <li><a class="navbar-brand" href="{% url 'index' %}">Task to do</a></li> -->
          <li><a class="navbar-link" href="{% url 'admin:index' %}">Admin</a></li>
        </ul>

        <ul class="nav navbar-nav">
          {% if user.is_authenticated %}
            <li><a class="navbar-link" href="{% url 'taskApp:myTask' %}">My Tasks</a></li>
            <li><a class="navbar-link" href="{% url 'taskApp:addTask' %}">Add Task</a></li>

        </ul>

        <ul class="nav navbar-nav navbar-right">
              <li><a class="navbar-link" href="#"> {{user}} <span class="glyphicon glyphicon-user"></span></a></li>
              <img class="rounded-circle article-img" src="{{user.profile_pic.url}}" width='240' alt={{user}}> <!--PROBLEM IS HERE-->
              <li><a class="navbar-link" href="{% url 'logout' %}">Logout</a></li>
        </ul>
        <ul class="nav navbar-nav navbar-right">
        {% else %}
            <li><a class="navbar-link" href="{% url 'taskApp:register' %}">Register</a></li>
            <li><a class="navbar-link" href="{% url 'taskApp:user_login' %}">Login</a></li>
        {% endif %}
        </ul>

      </div>

    </nav>

    <div class="container">

      {% block body_block %}
      {% endblock %}

  </body>
</html>
</code>```

答:
Where did you use UserCustomForm? There is nothing related with this form in your views.py for passing image to DB. I will consider as you are trying to add image on admin panel for now.

On your html file, you can't access profile_pic directly from user. Try this src="{{user.usercustom.profile_pic.url}}"

from django.core.files.storage import FileSystemStorage add this to top of views.py

and edit related lines in register function with this

```<code>image = request.FILES['profile_pic']
if image:
    filename = FileSystemStorage().save('profile_pics/' + image.name, image)
    profile.profile_pic = filename
profile.save()
</code>```

Edit: image =request.FILES['profile_pic] is not string although we have to pass it to DB as string. image.name is a string we need but without MEDIA_ROOT value. FileSystemStorage appends the MEDIA_ROOT value to any file it saves

Body:
I am creating a taskToDo web application. Most of the html files under templates are extending base.html file which includes a navbar in which i want to show the user profile picture under navbar of base.html.
The profile picture is getting saved under profile_pics directory of 'media' folder.

I have tried giving {{user.profile_pic.url}} as the source for image, but still the image is not getting linked
My models.py , project urls.py, settings.py, relevant part of views.py are as follows:-

models.py

from django.db import models
from django.contrib.auth.models import User
from django.conf import settings
from django.core.exceptions import ValidationError
from datetime import datetime
# Create your models here.

class UserCustom(models.Model):
    user=models.OneToOneField(User,on_delete=models.CASCADE)

    profile_pic=models.ImageField(upload_to='profile_pics',blank=True)

    def __str__(self):
        return self.user.username   #user os object defined above

class UserTask(models.Model):
    author = models.ForeignKey(User,on_delete=models.CASCADE)
    label=models.CharField(max_length=264)
    date=models.DateField()
    status=models.BooleanField(default=False)

    def __str__(self):
        return str(self.label)

settings.py

from django.contrib import admin
from django.urls import path,include
from taskApp import views
from django.conf.urls.static import static
from django.conf import settings # new
urlpatterns = [
    path('admin/', admin.site.urls),
    path('',views.index,name='index'),
    path('taskApp/',include('taskApp.urls')),
    path('logout/',views.user_logout,name='logout'),
]+static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)

forms.py

from django import forms
from django.forms.fields import DateField
from django.core import validators
from django.contrib.auth.models import User
from taskApp.models import UserCustom,UserTask
from django.contrib.admin.widgets import AdminDateWidget
from datetime import datetime,timedelta

class UserForm(forms.ModelForm):
    password=forms.CharField(widget=forms.PasswordInput())

    class Meta():
        model=User
        fields=('username','email','password')

class UserCustomForm(forms.ModelForm):
    class Meta():
        model=UserCustom
        fields=('profile_pic',)

class UserTaskForm(forms.ModelForm):
    date=DateField(widget=forms.DateInput(attrs={'placeholder': 'YYYY-MM-DD', 'required': 'required'}))
    status=forms.BooleanField(required=False)
    class Meta():
        model=UserTask
        fields=('label','date')

    def clean(self):
        cleaned_data=self.cleaned_data
        date2=cleaned_data.get('date')
        if str(date2)<=(datetime.today()-timedelta(days=1)).strftime('%Y-%m-%d'):
            raise forms.ValidationError("The date cannot be in the past!")
        return cleaned_data

views.py (relevant part)

@login_required
def my_task(request):
    task_obj=UserTask.objects.filter(author=request.user)
    return render(request,'taskApp/task.html',{'task_obj':task_obj,'user_key':request.user})

def register(request):

registered=False

if request.method == "POST":

    user_form=UserForm(data=request.POST)
    profile_form=UserCustomForm(data=request.POST)

    if user_form.is_valid() and profile_form.is_valid():
        user=user_form.save()
        user.set_password(user.password)
        user.save()

        profile=profile_form.save(commit=False)
        profile.user=user

        if 'profile_pic' in request.FILES:
            profile.profile_pic=request.FILES['profile_pic']

        profile.save()
        registered=True

    else:
        print(user_form.errors,profile_form.errors)

else: #no request=POST yet
    user_form=UserForm()
    profile_form=UserCustomForm()

return render(request,'taskApp/registration.html',{'user_form':user_form,'profile_form':profile_form,'registered':registered })

def register(request):
    registered=False

    if request.method == "POST":

        user_form=UserForm(data=request.POST)
        profile_form=UserCustomForm(data=request.POST)

        if user_form.is_valid() and profile_form.is_valid():
            user=user_form.save()
            user.set_password(user.password)
            user.save()

            profile=profile_form.save(commit=False)
            profile.user=user

            if 'profile_pic' in request.FILES:
                profile.profile_pic=request.FILES['profile_pic']

            profile.save()
            registered=True

        else:
            print(user_form.errors,profile_form.errors)

    else: #no request=POST yet
        user_form=UserForm()
        profile_form=UserCustomForm()

    return render(request,'taskApp/registration.html',{'user_form':user_form,'profile_form':profile_form,'registered':registered })

def user_login(request):

    if request.method=='POST':
        username=request.POST.get('username')  #name of element
        password=request.POST.get('password')

        user=authenticate(username=username,password=password)

        if user:
            if user.is_active:
                login(request,user)
                return HttpResponseRedirect(reverse('taskApp:myTask')) #myTask is the name of url , go to urls.py
            else:
                return HttpResponse("ACCOUNT NOT ACTIVE")

        else:
            print("Someone tried to login and failed!")
            print("Username: {} and password {}".format(username,password))
            return HttpResponse("invalid login details supllied!")

    else:
        return render(request,'taskApp/login.html',{})

base.html

<!DOCTYPE html>
{% load static %}

    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title></title>
    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css" integrity="sha384-HSMxcRTRxnN+Bdg0JdbxYKrThecOKuH5zCYotlSAcp1+c8xmyTe9GYg1l9a69psu" crossorigin="anonymous">

    <link rel="stylesheet" href="{% static 'css/mystyle.css' %}" >

ToDoList

Admin

          {% if user.is_authenticated %}

My Tasks

Add Task

 {{user}}

Logout

        {% else %}

Register

Login

        {% endif %}

      {% block body_block %}
      {% endblock %}

Body:
Where did you use UserCustomForm? There is nothing related with this form in your views.py for passing image to DB. I will consider as you are trying to add image on admin panel for now.

On your html file, you can't access profile_pic directly from user. Try this src="{{user.usercustom.profile_pic.url}}"

from django.core.files.storage import FileSystemStorage add this to top of views.py

and edit related lines in register function with this

image = request.FILES['profile_pic']
if image:
    filename = FileSystemStorage().save('profile_pics/' + image.name, image)
    profile.profile_pic = filename
profile.save()

Edit: image =request.FILES['profile_pic] is not string although we have to pass it to DB as string. image.name is a string we need but without MEDIA_ROOT value. FileSystemStorage appends the MEDIA_ROOT value to any file it saves


问:
How to map a object into a object
Having a problem with two arrays of objects and I want to concat data of them related to their id's.

I have two arrays of objects like this:

const data = [
  {
    default: false,
    id: 1,
    value: true,
    idModule: 1
  },
  {
    default: false,
    id: 2,
    value: true,
    idModule: 1
  },
  {
    default: false,
    id: 3,
    value: true,
    idModule: 2
  },
  {
    default: false,
    id: 4,
    value: true,
    idModule: 2
  }
];

const modulData = [
  {
    name: 'Administration',
    id: 1,
  },
  {
    name: 'Benutzerverwaltung',
    id: 2,
  }
];
```

<p>Now I want to combine these two related with their <code>idModule == id</code>
to create a new array of objects like this for example:</p>

<pre class="lang-js prettyprint-override"><code>const result = [
  {
    name: 'Administration',
    id: 1,
    modul: [
      {
        default: false,
        id: 1,
        value: true,
        idModule: 1
      },
      {
        default: false,
        id: 2,
        value: true,
        idModule: 1
      },
    ],

  },
  {
    name: 'Benutzerverwaltung',
    id: 2,
    modul: [
      {
        default: false,
        id: 3,
        value: false,
        idModule: 2
      },
      {
        default: false,
        id: 4,
        value: false,
        idModule: 2
      },
    ],
  }
];
</code>```

How can I achieve this?

答:
You can do it simple by using map and filter:

```<code>let result = modulData.map(x => {
  x.modul = data.filter(d => d.idModule === x.id);
  return x;
});
</code>```

Full code:

const data = [{
    default: false,
    id: 1,
    value: true,
    idModule: 1
  },
  {
    default: false,
    id: 2,
    value: true,
    idModule: 1
  },
  {
    default: false,
    id: 3,
    value: true,
    idModule: 2
  },
  {
    default: false,
    id: 4,
    value: true,
    idModule: 2
  }
];

const modulData = [{
    name: 'Administration',
    id: 1,
  },
  {
    name: 'Benutzerverwaltung',
    id: 2,
  }
];

let result = modulData.map(x => {
  x.modul = data.filter(d => d.idModule === x.id);
  return x;
});
console.log(result);```

Title: How to map a object into a object

Body:
Having a problem with two arrays of objects and I want to concat data of them related to their id's.

I have two arrays of objects like this:

const data = [
  {
    default: false,
    id: 1,
    value: true,
    idModule: 1
  },
  {
    default: false,
    id: 2,
    value: true,
    idModule: 1
  },
  {
    default: false,
    id: 3,
    value: true,
    idModule: 2
  },
  {
    default: false,
    id: 4,
    value: true,
    idModule: 2
  }
];

const modulData = [
  {
    name: 'Administration',
    id: 1,
  },
  {
    name: 'Benutzerverwaltung',
    id: 2,
  }
];

Now I want to combine these two related with their idModule == id
to create a new array of objects like this for example:

const result = [
  {
    name: 'Administration',
    id: 1,
    modul: [
      {
        default: false,
        id: 1,
        value: true,
        idModule: 1
      },
      {
        default: false,
        id: 2,
        value: true,
        idModule: 1
      },
    ],

  },
  {
    name: 'Benutzerverwaltung',
    id: 2,
    modul: [
      {
        default: false,
        id: 3,
        value: false,
        idModule: 2
      },
      {
        default: false,
        id: 4,
        value: false,
        idModule: 2
      },
    ],
  }
];

How can I achieve this?

Body:
You can do it simple by using map and filter:

let result = modulData.map(x => {
  x.modul = data.filter(d => d.idModule === x.id);
  return x;
});

Full code:

const data = [{
    default: false,
    id: 1,
    value: true,
    idModule: 1
  },
  {
    default: false,
    id: 2,
    value: true,
    idModule: 1
  },
  {
    default: false,
    id: 3,
    value: true,
    idModule: 2
  },
  {
    default: false,
    id: 4,
    value: true,
    idModule: 2
  }
];

const modulData = [{
    name: 'Administration',
    id: 1,
  },
  {
    name: 'Benutzerverwaltung',
    id: 2,
  }
];

let result = modulData.map(x => {
  x.modul = data.filter(d => d.idModule === x.id);
  return x;
});
console.log(result);


问:
Spring WebSocket can't send message to authenticated user when pass jwtToken in header

1. scenes to be used

When connect WebSocket is permitAll

Then Subscribe /user/queue/userInfo need user authenticated

After subscribe success, send to /app/user/info need authenticated(Because I need get userInfo ), and push message to  current user subscribe queue /user/queue/userInfo

答:
2.1 Details description after I trace the source code

1) when subscribe /user/queue/userInfo with the jwtToken in header, I get the jwtToken, then get Principle user object from auth server with jwtToken, then set user in StompHeaderAccessor.
At last, the user subscribe lookupDestination is /queue/userInfo/user{sessionId}
2) Then send /app/user/userInfo with jwtToken in header, after handle the return value,
the final send destination is /user/{Principle.getName()}/queue/userInfo.

the user never subscribe this queue: /user/{Principle.getName()}/queue/userInfo, and the message cannot send to user


问:
Percentage value of a segment against segment total Power BI(DAX)

Hi guys, I am new to Power BI(DAX formulas) and I am attempting to calculate the percentage contribution of the sum of "count" where "category" = X and "item_no"=1 to the total of "count" across all categories where 'item_no' = 1.
The ideal mathematical statement here will be the (30/50)*100%
I intend to represent the percentage values in a chart showing percentage contribution of each distinct item_no to its total in the format as represented in the example above.

答:
The standard way to approach this is

```<code>calculation over partial set / same calculation over larger set
</code>```

Since you haven't made it clear what context you are trying to calculate this, I will assume it's a visual along these lines:

The measure I use here is

```<code>%ItemTotal =
DIVIDE (
    SUM ( Table1[count] ),
    CALCULATE ( SUM ( Table1[count] ), ALLEXCEPT( Table1, Table1[item_no] ) )
)
</code>```

In the numerator, you have the sum in the local filter context. For example, in that top-left cell, this means all rows that match item_no = 1 and category = "X".

In the denominator, we do the same thing except we remove all filter context except the context we say to keep (item_no) so it includes all category values.

If you're trying to calculate that 60% outside of the context of a visual, then you can explicitly define what filters you want. For example, this should work in any filter context:

```<code>X%_Item1 =
DIVIDE (
    CALCULATE (
        SUM ( Table1[count] ),
        ALL ( Table1 ),
        Table1[category] = "X",
        Table1[item_no] = 1
    ),
    CALCULATE (
        SUM ( Table1[count] ),
        ALL ( Table1 ),
        Table1[item_no] = 1
    )
)
</code>```

See here and here for other ways to modify the filter context instead of ALLEXCEPT.

Body:
The standard way to approach this is

calculation over partial set / same calculation over larger set

Since you haven't made it clear what context you are trying to calculate this, I will assume it's a visual along these lines:

The measure I use here is

%ItemTotal =
DIVIDE (
    SUM ( Table1[count] ),
    CALCULATE ( SUM ( Table1[count] ), ALLEXCEPT( Table1, Table1[item_no] ) )
)

In the numerator, you have the sum in the local filter context. For example, in that top-left cell, this means all rows that match item_no = 1 and category = "X".

In the denominator, we do the same thing except we remove all filter context except the context we say to keep (item_no) so it includes all category values.

If you're trying to calculate that 60% outside of the context of a visual, then you can explicitly define what filters you want. For example, this should work in any filter context:

X%_Item1 =
DIVIDE (
    CALCULATE (
        SUM ( Table1[count] ),
        ALL ( Table1 ),
        Table1[category] = "X",
        Table1[item_no] = 1
    ),
    CALCULATE (
        SUM ( Table1[count] ),
        ALL ( Table1 ),
        Table1[item_no] = 1
    )
)

See here and here for other ways to modify the filter context instead of ALLEXCEPT.


问:
Native crash peak on Samsung devices
In the last month I saw a strong peak of native crashes on Google Play Console and they are coming from Samsung devices at 98% mostly Android 10 (90%) and secondarily Android 9 (10%). More than the half of cases are about Samsung S9 devices, while the rest is about a pretty recent device models (Samsung s10+, Note9, etc).

There is the stacktrace:

```<code>  #00  pc 0000000000083360  /apex/com.android.runtime/lib64/bionic/libc.so (abort+176)
  #01  pc 0000000000008a74  /system/lib64/liblog.so (__android_log_assert+324)
  #02  pc 00000000003fb0dc  /system/lib64/libhwui.so (android::uirenderer::renderthread::EglManager::swapBuffers(android::uirenderer::renderthread::Frame const&, SkRect const&)+276)
  #03  pc 00000000003fae4c  /system/lib64/libhwui.so (android::uirenderer::skiapipeline::SkiaOpenGLPipeline::swapBuffers(android::uirenderer::renderthread::Frame const&, bool, SkRect const&, android::uirenderer::FrameInfo*, bool*)+92)
  #04  pc 0000000000407c8c  /system/lib64/libhwui.so (android::uirenderer::renderthread::CanvasContext::draw()+716)
  #05  pc 0000000000406d38  /system/lib64/libhwui.so (_ZNSt3__110__function6__funcIZN7android10uirenderer12renderthread13DrawFrameTask11postAndWaitEvE3$_0NS_9allocatorIS6_EEFvvEEclEv$c303f2d2360db58ed70a2d0ac7ed911b+216)
  #06  pc 0000000000417a44  /system/lib64/libhwui.so (android::uirenderer::WorkQueue::process()+228)
  #07  pc 0000000000417770  /system/lib64/libhwui.so (android::uirenderer::renderthread::RenderThread::threadLoop()+80)
  #08  pc 00000000000137a4  /system/lib64/libutils.so (android::Thread::_threadLoop(void*)+284)
  #09  pc 00000000000e3b14  /apex/com.android.runtime/lib64/bionic/libc.so (__pthread_start(void*)+36)
  #10  pc 0000000000085330  /apex/com.android.runtime/lib64/bionic/libc.so (__start_thread+64)
</code>```

In addition, also another issue appeared on Samsung devices only and Android 10 only (device model distribution seems pretty random): this was solved without any particular action taken

```<code>#00  pc 0000000002cfeadc  /data/app/com.google.android.webview-8w0eiuwFhdVaEviNzD1U7g==/base.apk!libmonochrome.so (offset 0x15b000)
</code>```

I have no clue on what is causing the issue, but I also attach my build.gradle file dependencies because these problems are usually linked to Google libraries.

Did anyone see the same issue?

UPDATE
Regarding the first issue, one of the major changes I applied to the app activity in which crashes happen, is about the newer Android View Binding. Since the crash seems to be related to UI, maybe this is the case. Does anyone use View Binding as well?

UPDATE 2
It looks like that switching to the old findViewById (just in the Activity that was active at the time of the crash) instead of using View Binding made the problem disappear. For the moment I'm testing it on a small pool of beta testers but at this time I should have already seen some crash report. I will keep this post updated.

UPDATE 3 ─ 2022
With the latest updates of Android 11, some things have changed, especially this. I don't know whether it was because I switched to API 31 or because I uploaded again Crashlytics symbols, but now I see a lot of new crash reports in Google Play console:

```<code>  #00  pc 0000000000053350  /apex/com.android.runtime/lib64/bionic/libc.so (fdsan_error(char const*, ...)+588)
  #00  pc 000000000005304c  /apex/com.android.runtime/lib64/bionic/libc.so (android_fdsan_close_with_tag+736)
  #00  pc 0000000000053884  /apex/com.android.runtime/lib64/bionic/libc.so (close+16)
  #00  pc 000000000000371c  /system/lib64/libTcpOptimizer.mobiledata.samsung.so (close+220)
  #00  pc 00000000001e7c24  /vendor/lib64/libgsl.so (!!!0000!6a7f7ec785028d96437db04399d932!4e552d6!+28)
  #00  pc 00000000000bb5f8  /vendor/lib64/libgsl.so (gsl_syncobj_destroy+152)
  #00  pc 000000000025d538  /vendor/lib64/egl/libGLESv2_adreno.so (!!!0000!10f39af3d5dda97a64124dee6a3783!4e552d6!+456)
  #00  pc 0000000000244ff8  /vendor/lib64/egl/libGLESv2_adreno.so (!!!0000!04fe7c7713a0660472688458ecb7a2!4e552d6!+144)
  #00  pc 000000000002b928  /system/lib64/libEGL.so (android::eglSwapBuffersWithDamageKHRImpl(void*, void*, int*, int)+776)
  #00  pc 0000000000027ea4  /system/lib64/libEGL.so (eglSwapBuffersWithDamageKHR+72)
  #00  pc 00000000003b0724  /system/lib64/libhwui.so (android::uirenderer::renderthread::EglManager::swapBuffers(android::uirenderer::renderthread::Frame const&, SkRect const&)+176)
  #00  pc 00000000003a3e30  /system/lib64/libhwui.so (android::uirenderer::skiapipeline::SkiaOpenGLPipeline::swapBuffers(android::uirenderer::renderthread::Frame const&, bool, SkRect const&, android::uirenderer::FrameInfo*, bool*)+92)
  #00  pc 00000000003ac81c  /system/lib64/libhwui.so (android::uirenderer::renderthread::CanvasContext::draw()+1196)
  #00  pc 00000000003ae9e4  /system/lib64/libhwui.so (_ZNSt3__110__function6__funcIZN7android10uirenderer12renderthread13DrawFrameTask11postAndWaitEvE3$_0NS_9allocatorIS6_EEFvvEEclEv$c303f2d2360db58ed70a2d0ac7ed911b+524)
  #00  pc 000000000039cefc  /system/lib64/libhwui.so (android::uirenderer::WorkQueue::process()+208)
  #00  pc 00000000003bf0ec  /system/lib64/libhwui.so (android::uirenderer::renderthread::RenderThread::threadLoop()+88)
  #00  pc 000000000001553c  /system/lib64/libutils.so (android::Thread::_threadLoop(void*)+320)
  #00  pc 0000000000014db0  /system/lib64/libutils.so (thread_data_t::trampoline(thread_data_t const*)+408)
  #00  pc 00000000000b6234  /apex/com.android.runtime/lib64/bionic/libc.so (__pthread_start(void*)+64)
  #00  pc 0000000000050e64  /apex/com.android.runtime/lib64/bionic/libc.so (__start_thread+64)
</code>```

This seems of course correlated to both the fdsan problem linked above and obscure abort stacktraces I'm seeing since two years ago. So I started digging into my code, looking for any fd-related bug and I came out with the following:

BUG #1: Found a bug in the code where I never closed a file descriptor after having passed it to [MediaExtractor].setDataSource(FileDescriptor), because I thought [MediaExtractor].release(). I was wrong.

BUG #2: Found another subtle bug in JNI code where I'm receiving a file descriptor and I use it to open a stream with fdopen() and then I close it with fclose() when finished. This whole stream thing is made inside a third-party library and I wasn't aware of that ─ or I didn't really care about ─ and I was also calling close() over the same already-closed file descriptor. This lead to the so called double-close bug and guess what? fdsan is responsible for detecting this kind of bug and then abort. Before Android 11, fdsan behavior was to just output a silent warning, but then default settings changed to a fatal abort signal. This could not be a coincidence...?

I sent out a version of the app with the above fixes to beta testers. Looking forward to post some positive results.

答:
Even I've experienced this crash in some of the ads in the app. Even you would be able to reproduce the webview crash by calling webview.loadUrl("chrome://crash"), this should crash your webview and you would be able to reproduce the scenario.

The only way to supress these crashes is to override onRenderProcessGone in webview client and handle the crash by yourself in this case Ads SDK have to handle as the webview is implemented by them.

Ref: https://github.com/mopub/mopub-android-sdk/issues/312

Title: Native crash peak on Samsung devices

Body:
In the last month I saw a strong peak of native crashes on Google Play Console and they are coming from Samsung devices at 98% mostly Android 10 (90%) and secondarily Android 9 (10%). More than the half of cases are about Samsung S9 devices, while the rest is about a pretty recent device models (Samsung s10+, Note9, etc).

There is the stacktrace:

  #00  pc 0000000000083360  /apex/com.android.runtime/lib64/bionic/libc.so (abort+176)
  #01  pc 0000000000008a74  /system/lib64/liblog.so (__android_log_assert+324)
  #02  pc 00000000003fb0dc  /system/lib64/libhwui.so (android::uirenderer::renderthread::EglManager::swapBuffers(android::uirenderer::renderthread::Frame const&, SkRect const&)+276)
  #03  pc 00000000003fae4c  /system/lib64/libhwui.so (android::uirenderer::skiapipeline::SkiaOpenGLPipeline::swapBuffers(android::uirenderer::renderthread::Frame const&, bool, SkRect const&, android::uirenderer::FrameInfo*, bool*)+92)
  #04  pc 0000000000407c8c  /system/lib64/libhwui.so (android::uirenderer::renderthread::CanvasContext::draw()+716)
  #05  pc 0000000000406d38  /system/lib64/libhwui.so (_ZNSt3__110__function6__funcIZN7android10uirenderer12renderthread13DrawFrameTask11postAndWaitEvE3$_0NS_9allocatorIS6_EEFvvEEclEv$c303f2d2360db58ed70a2d0ac7ed911b+216)
  #06  pc 0000000000417a44  /system/lib64/libhwui.so (android::uirenderer::WorkQueue::process()+228)
  #07  pc 0000000000417770  /system/lib64/libhwui.so (android::uirenderer::renderthread::RenderThread::threadLoop()+80)
  #08  pc 00000000000137a4  /system/lib64/libutils.so (android::Thread::_threadLoop(void*)+284)
  #09  pc 00000000000e3b14  /apex/com.android.runtime/lib64/bionic/libc.so (__pthread_start(void*)+36)
  #10  pc 0000000000085330  /apex/com.android.runtime/lib64/bionic/libc.so (__start_thread+64)

In addition, also another issue appeared on Samsung devices only and Android 10 only (device model distribution seems pretty random): this was solved without any particular action taken

#00  pc 0000000002cfeadc  /data/app/com.google.android.webview-8w0eiuwFhdVaEviNzD1U7g==/base.apk!libmonochrome.so (offset 0x15b000)

I have no clue on what is causing the issue, but I also attach my build.gradle file dependencies because these problems are usually linked to Google libraries.

Did anyone see the same issue?

UPDATE
Regarding the first issue, one of the major changes I applied to the app activity in which crashes happen, is about the newer Android View Binding. Since the crash seems to be related to UI, maybe this is the case. Does anyone use View Binding as well?

UPDATE 2
It looks like that switching to the old findViewById (just in the Activity that was active at the time of the crash) instead of using View Binding made the problem disappear. For the moment I'm testing it on a small pool of beta testers but at this time I should have already seen some crash report. I will keep this post updated.

UPDATE 3 ─ 2022
With the latest updates of Android 11, some things have changed, especially this. I don't know whether it was because I switched to API 31 or because I uploaded again Crashlytics symbols, but now I see a lot of new crash reports in Google Play console:

  #00  pc 0000000000053350  /apex/com.android.runtime/lib64/bionic/libc.so (fdsan_error(char const*, ...)+588)
  #00  pc 000000000005304c  /apex/com.android.runtime/lib64/bionic/libc.so (android_fdsan_close_with_tag+736)
  #00  pc 0000000000053884  /apex/com.android.runtime/lib64/bionic/libc.so (close+16)
  #00  pc 000000000000371c  /system/lib64/libTcpOptimizer.mobiledata.samsung.so (close+220)
  #00  pc 00000000001e7c24  /vendor/lib64/libgsl.so (!!!0000!6a7f7ec785028d96437db04399d932!4e552d6!+28)
  #00  pc 00000000000bb5f8  /vendor/lib64/libgsl.so (gsl_syncobj_destroy+152)
  #00  pc 000000000025d538  /vendor/lib64/egl/libGLESv2_adreno.so (!!!0000!10f39af3d5dda97a64124dee6a3783!4e552d6!+456)
  #00  pc 0000000000244ff8  /vendor/lib64/egl/libGLESv2_adreno.so (!!!0000!04fe7c7713a0660472688458ecb7a2!4e552d6!+144)
  #00  pc 000000000002b928  /system/lib64/libEGL.so (android::eglSwapBuffersWithDamageKHRImpl(void*, void*, int*, int)+776)
  #00  pc 0000000000027ea4  /system/lib64/libEGL.so (eglSwapBuffersWithDamageKHR+72)
  #00  pc 00000000003b0724  /system/lib64/libhwui.so (android::uirenderer::renderthread::EglManager::swapBuffers(android::uirenderer::renderthread::Frame const&, SkRect const&)+176)
  #00  pc 00000000003a3e30  /system/lib64/libhwui.so (android::uirenderer::skiapipeline::SkiaOpenGLPipeline::swapBuffers(android::uirenderer::renderthread::Frame const&, bool, SkRect const&, android::uirenderer::FrameInfo*, bool*)+92)
  #00  pc 00000000003ac81c  /system/lib64/libhwui.so (android::uirenderer::renderthread::CanvasContext::draw()+1196)
  #00  pc 00000000003ae9e4  /system/lib64/libhwui.so (_ZNSt3__110__function6__funcIZN7android10uirenderer12renderthread13DrawFrameTask11postAndWaitEvE3$_0NS_9allocatorIS6_EEFvvEEclEv$c303f2d2360db58ed70a2d0ac7ed911b+524)
  #00  pc 000000000039cefc  /system/lib64/libhwui.so (android::uirenderer::WorkQueue::process()+208)
  #00  pc 00000000003bf0ec  /system/lib64/libhwui.so (android::uirenderer::renderthread::RenderThread::threadLoop()+88)
  #00  pc 000000000001553c  /system/lib64/libutils.so (android::Thread::_threadLoop(void*)+320)
  #00  pc 0000000000014db0  /system/lib64/libutils.so (thread_data_t::trampoline(thread_data_t const*)+408)
  #00  pc 00000000000b6234  /apex/com.android.runtime/lib64/bionic/libc.so (__pthread_start(void*)+64)
  #00  pc 0000000000050e64  /apex/com.android.runtime/lib64/bionic/libc.so (__start_thread+64)

This seems of course correlated to both the fdsan problem linked above and obscure abort stacktraces I'm seeing since two years ago. So I started digging into my code, looking for any fd-related bug and I came out with the following:

BUG #1: Found a bug in the code where I never closed a file descriptor after having passed it to [MediaExtractor].setDataSource(FileDescriptor), because I thought [MediaExtractor].release(). I was wrong.

BUG #2: Found another subtle bug in JNI code where I'm receiving a file descriptor and I use it to open a stream with fdopen() and then I close it with fclose() when finished. This whole stream thing is made inside a third-party library and I wasn't aware of that ─ or I didn't really care about ─ and I was also calling close() over the same already-closed file descriptor. This lead to the so called double-close bug and guess what? fdsan is responsible for detecting this kind of bug and then abort. Before Android 11, fdsan behavior was to just output a silent warning, but then default settings changed to a fatal abort signal. This could not be a coincidence...?

I sent out a version of the app with the above fixes to beta testers. Looking forward to post some positive results.


问:
Get execution ID for Google Cloud Functions triggered from PubSub event
For Google Cloud Functions triggered from HTTP, it is possible to retrieve the execution id by inspecting the headers of the HTTP request ("Function-Execution-Id") :

```<code>package p

import (
    "fmt"
    "net/http"
)

func F(w http.ResponseWriter, r *http.Request) {
    executionID := r.Header.Get("Function-Execution-Id")
    fmt.Println(executionID)
}
</code>```

However, for GCF triggered by PubSub events, I can't find how to retrieve this execution ID :

```<code>package p

import (
    "context"
)

type PubSubMessage struct {
    Data []byte `json:"data"`
}

func F(ctx context.Context, m PubSubMessage) error {
    executionID := "" // ???
    fmt.Println(executionID)
    return nil
}
</code>```

I have looked into the PubSubMessage (https://cloud.google.com/pubsub/docs/reference/rest/v1/PubsubMessage), but it only contains data + an empty attributes map.

I have also checked if execution ID is in the metadata handled by the context. However, from my tests, and the docs (https://godoc.org/cloud.google.com/go/functions/metadata#FromContext), only EventID, Timestamp, EventType and Resource are present.

How can I retrieve the execution id of a GCF function triggered by a PubSub event?

答:
No, it is currently not possible to get execution id from pubsub triggered events.

You can get the event id from context as Lauren stated but that does not match execution id.

Also, pubsub triggered events do have execution ids.  You can see this by using a default logger to log the event id.  In stackdriver there will be an attached execution id label and it will not match the event id.  We have observed that event id is numeric while execution id is alphanumeric.

Further, if the function is retried, it will keep the same event id but get a different execution id.

This is a recent (undocumented) change but can be easily observed.

Body:
For Google Cloud Functions triggered from HTTP, it is possible to retrieve the execution id by inspecting the headers of the HTTP request ("Function-Execution-Id") :

package p

import (
    "fmt"
    "net/http"
)

func F(w http.ResponseWriter, r *http.Request) {
    executionID := r.Header.Get("Function-Execution-Id")
    fmt.Println(executionID)
}

However, for GCF triggered by PubSub events, I can't find how to retrieve this execution ID :

package p

import (
    "context"
)

type PubSubMessage struct {
    Data []byte `json:"data"`
}

func F(ctx context.Context, m PubSubMessage) error {
    executionID := "" // ???
    fmt.Println(executionID)
    return nil
}

I have looked into the PubSubMessage (https://cloud.google.com/pubsub/docs/reference/rest/v1/PubsubMessage), but it only contains data + an empty attributes map.

I have also checked if execution ID is in the metadata handled by the context. However, from my tests, and the docs (https://godoc.org/cloud.google.com/go/functions/metadata#FromContext), only EventID, Timestamp, EventType and Resource are present.

How can I retrieve the execution id of a GCF function triggered by a PubSub event?


问:
Packages or functions for summarizing matrix in R that works similarly as dplyr?
I am running a very big simulation with 10,000 loops and to achieve better performance I have transformed the codes to generate matrix outputs, rather than data frame. It runs faster. However for each loop I need to summarize the outputs. For example, for below matrix,

```<code>mtx <- matrix(data = c(rep(c(1, 2), each = 6),
                       rep(c(3, 5, 7), each = 4),
                       rnorm(0, 1, n = 12)),
          ncol = 3)
colnames(mtx) <- c("A", "B", "Value")
</code>```

I want to summarize the number of observations in each A and B group, and calculate the mean values of Value, like the way that you could do with group_by() and summarize() in dplyr, if it's a data frame:

```<code>mtx %>% group_by(A, B) %>% summarize(N = n(), MEAN = mean(Value))
</code>```

Are there any functions/packages to do this directly on matrix, without transforming it into data frame? Because the simulation is too big, collecting all the raw outputs and summarizing after the for loop is not an option.

答:
An option with tapply

```<code>tapply(mtx[, 'Value'], list(mtx[, 'A'], mtx[, 'B']), FUN = mean)
</code>```

Body:
I am running a very big simulation with 10,000 loops and to achieve better performance I have transformed the codes to generate matrix outputs, rather than data frame. It runs faster. However for each loop I need to summarize the outputs. For example, for below matrix,

mtx <- matrix(data = c(rep(c(1, 2), each = 6),
                       rep(c(3, 5, 7), each = 4),
                       rnorm(0, 1, n = 12)),
          ncol = 3)
colnames(mtx) <- c("A", "B", "Value")

I want to summarize the number of observations in each A and B group, and calculate the mean values of Value, like the way that you could do with group_by() and summarize() in dplyr, if it's a data frame:

mtx %>% group_by(A, B) %>% summarize(N = n(), MEAN = mean(Value))

Are there any functions/packages to do this directly on matrix, without transforming it into data frame? Because the simulation is too big, collecting all the raw outputs and summarizing after the for loop is not an option.

Body:
An option with tapply

tapply(mtx[, 'Value'], list(mtx[, 'A'], mtx[, 'B']), FUN = mean)


问:
Spliting and Writing a Text file Lines into dataframe columns
I have a text file which is written in Notepad++, which contains a series of numbers at each line. like:

12451

I want to read this text file into python and assign each digit to a specific column of a dataframe, in a same order for all lines (here with 5 columns, as the length of each line).
how can I do that?

答:
You can do that by using pd.read_fwf function. e.g.</p>

```<code>import pandas as pd
df=pd.read_fwf("file.txt",widths=[1,1,1,1,1],header=None)
</code>```

Body:
You can do that by using pd.read_fwf function. e.g.

import pandas as pd
df=pd.read_fwf("file.txt",widths=[1,1,1,1,1],header=None)


问:
Dismiss iOS 13 keyboard tutorial when running on a fresh simulator
I am using Xcode 11 & iOS 13 as part of a workflow for a UITest, but when I engage with the keyboard for the first time, the following appears and disrupts the test by blocking the keyboard:

Calling code in UI test:

```<code>app.textFields.element(boundBy: 0).tap()
</code>```

What the simulator shows:

Since this obstructs the keys, my test will then fail. However, the next time I run the test on the same simulator, it will work properly.

答:
CodeBender's answer is nice and leads down the right path, but doesn't compile since continue is a reserved keyword in Swift. Plus it would be nice to wait a small amount of time for the keyboard to show up.

    // Sometimes the Apple Keyboard shows some sort of "Swipe" tutorial. Dismiss it!
    private func begoneSwipeTutorial(app: XCUIApplication) {
        let continueButton = app.buttons["Continue"]
        if continueButton.waitForExistence(timeout: 2.0) {
            continueButton.tap()
        }
    }

    // Then use like this
    func inputTextWhatever(app: XCUIApplication, element: XCUIElement) {
        element.tap()
        begoneSwipeTutorial(app: app)
        // Do whatever you need to do
    }
```

Body:
I am using Xcode 11 & iOS 13 as part of a workflow for a UITest, but when I engage with the keyboard for the first time, the following appears and disrupts the test by blocking the keyboard:

Calling code in UI test:

app.textFields.element(boundBy: 0).tap()

What the simulator shows:

Since this obstructs the keys, my test will then fail. However, the next time I run the test on the same simulator, it will work properly.


问:
Error during making video of extracted frames
I extracted the video frames into a folder called "images". Let's consider:

a0.jpg
a1.jpg
a2.jpg
a3.jpg
and ......

now I want to make a video of those frames.

I have got this code to create video from extracted videos

```<code>  import cv2
import os

image_folder = 'images'
video_name = 'video.avi'

images = [img for img in os.listdir(image_folder) if img.endswith(".jpg")]
for i in range(len(images)):
    image_name = 'a' + str(i) + '.jpg'
    frame = cv2.imread(os.path.join(image_folder, images[0]))

    height, width, layers = frame.shape

    video = cv2.VideoWriter(video_name, 0, 1, (width, height))

    video.write(cv2.imread(os.path.join(image_folder, image_name)))
cv2.destroyAllWindows()
video.release()
</code>```

The problem is when I am making the video,  I get the video but the frames are ordered randomly, how can I arrange them in sequential order? thanks for the post How can I fix this?

答:
As you stated that your frames are not in order so that means when you are obtaining them via os.listdir they are not coming in order. You also stated that their names are like a0, a1 and so on so you can do this:

```<code>images = [img for img in os.listdir(image_folder) if img.endswith(".jpg")]
for i in range(len(images)):
    image_name = 'a' + str(i) + '.jpg'
    video.write(cv2.imread(os.path.join(image_folder, image_name)))
</code>```

EDIT

You placed your video writer inside the loop so it is being recreated every time. I have attached the complete code this time which should work.

```<code>import cv2
import os

image_folder = 'images'
video_name = 'video.avi'

images = [img for img in os.listdir(image_folder) if img.endswith(".jpg")]

frame = cv2.imread(os.path.join(image_folder, images[0]))
height, width, layers = frame.shape
video = cv2.VideoWriter(video_name, 0, 1, (width, height))

for i in range(len(images)):
    image_name = 'a' + str(i) + '.jpg'
    video.write(cv2.imread(os.path.join(image_folder, image_name)))

cv2.destroyAllWindows()
video.release()
</code>```

Body:
I extracted the video frames into a folder called "images". Let's consider:

a0.jpg
a1.jpg
a2.jpg
a3.jpg
and ......

now I want to make a video of those frames.

I have got this code to create video from extracted videos

  import cv2
import os

image_folder = 'images'
video_name = 'video.avi'

images = [img for img in os.listdir(image_folder) if img.endswith(".jpg")]
for i in range(len(images)):
    image_name = 'a' + str(i) + '.jpg'
    frame = cv2.imread(os.path.join(image_folder, images[0]))

    height, width, layers = frame.shape

    video = cv2.VideoWriter(video_name, 0, 1, (width, height))

    video.write(cv2.imread(os.path.join(image_folder, image_name)))
cv2.destroyAllWindows()
video.release()

The problem is when I am making the video,  I get the video but the frames are ordered randomly, how can I arrange them in sequential order? thanks for the post How can I fix this?

Body:
As you stated that your frames are not in order so that means when you are obtaining them via os.listdir they are not coming in order. You also stated that their names are like a0, a1 and so on so you can do this:

images = [img for img in os.listdir(image_folder) if img.endswith(".jpg")]
for i in range(len(images)):
    image_name = 'a' + str(i) + '.jpg'
    video.write(cv2.imread(os.path.join(image_folder, image_name)))

EDIT

You placed your video writer inside the loop so it is being recreated every time. I have attached the complete code this time which should work.

import cv2
import os

image_folder = 'images'
video_name = 'video.avi'

images = [img for img in os.listdir(image_folder) if img.endswith(".jpg")]

frame = cv2.imread(os.path.join(image_folder, images[0]))
height, width, layers = frame.shape
video = cv2.VideoWriter(video_name, 0, 1, (width, height))

for i in range(len(images)):
    image_name = 'a' + str(i) + '.jpg'
    video.write(cv2.imread(os.path.join(image_folder, image_name)))

cv2.destroyAllWindows()
video.release()


问:
SQLite on C#. Select query does not work with string of letters
I'm learning C# since the past week and databases since a couple of days ago, so if you see something dodgy and you ask yourself "Why did he do that like that?", the answer is probably going to be "Because that's all I know for the moment".

In the title I said "of letters" because if I use a string of numbers, it works.

I have a tiny database with three columns. Id (int), FirstName (text) and LastName (text).
Id is unique, primary key and autoincrements. FirstName is unique. The three are not null.
In that database I have two records:

Id FirstName LastName

3- 6666 2222

4- Test O'Test

This is my method:

```<code>public static bool isOnDb(string nombre, string apellido)
{
    bool flag = false;
    {
        try
        {
            using (IDbConnection cnn = new SQLiteConnection(LoadConnectionString()))
            {
                string tempName = "Test"; // This is temporarily replacing the argument 'nombre'
                int tempNum= 3; // More testing. See below
                //cnn.Query<Person>($"select * from Person where FirstName = { tempName }", new DynamicParameters());

                // This four lines below are just for testing. They are going to be deleted
                var output = cnn.Query<Person>($"select * from Person where FirstName = { tempName }", new DynamicParameters());
                var person = output.First();
                Console.WriteLine("Funciona");
                Console.WriteLine($"{ person.Id } - { person.FullName }");

                flag = true;
                return flag;
            }
        }
        catch (Exception)
        {
            Console.WriteLine("Derecho a excepcion");

            return flag;
        }
    }
}
</code>```

Basically, if tempName = "Test", it falls into an exception. But if tempName = "6666" it returns the row.
I also tried selecting by id. That's why tempNum is there.

```<code>int tempNum= 4;
var output = cnn.Query<Person>($"select * from Person where Id = { tempNum }", new DynamicParameters());
</code>```

答:
Well in SQLite the strings are signified by '' so when you pass FirstName = { tempName } and its FirstName = Test it looks for the column called Test in Table person rather than equating it to the 'Test' string

So you can do:

```<code>var output = cnn.Query<Person>($"select * from Person where FirstName = '{ tempName }'");
</code>```

Or better yet:

```<code>var people = cnn.Query<Person>("SELECT * FROM PERSON WHERE FirstName = @FirstName", new { FirstName = tempName });
</code>```

Body:
I'm learning C# since the past week and databases since a couple of days ago, so if you see something dodgy and you ask yourself "Why did he do that like that?", the answer is probably going to be "Because that's all I know for the moment".

In the title I said "of letters" because if I use a string of numbers, it works.

I have a tiny database with three columns. Id (int), FirstName (text) and LastName (text).
Id is unique, primary key and autoincrements. FirstName is unique. The three are not null.
In that database I have two records:

Id FirstName LastName

3- 6666 2222

4- Test O'Test

This is my method:

public static bool isOnDb(string nombre, string apellido)
{
    bool flag = false;
    {
        try
        {
            using (IDbConnection cnn = new SQLiteConnection(LoadConnectionString()))
            {
                string tempName = "Test"; // This is temporarily replacing the argument 'nombre'
                int tempNum= 3; // More testing. See below
                //cnn.Query<Person>($"select * from Person where FirstName = { tempName }", new DynamicParameters());

                // This four lines below are just for testing. They are going to be deleted
                var output = cnn.Query<Person>($"select * from Person where FirstName = { tempName }", new DynamicParameters());
                var person = output.First();
                Console.WriteLine("Funciona");
                Console.WriteLine($"{ person.Id } - { person.FullName }");

                flag = true;
                return flag;
            }
        }
        catch (Exception)
        {
            Console.WriteLine("Derecho a excepcion");

            return flag;
        }
    }
}

Basically, if tempName = "Test", it falls into an exception. But if tempName = "6666" it returns the row.
I also tried selecting by id. That's why tempNum is there.

int tempNum= 4;
var output = cnn.Query<Person>($"select * from Person where Id = { tempNum }", new DynamicParameters());

Body:
Well in SQLite the strings are signified by '' so when you pass FirstName = { tempName } and its FirstName = Test it looks for the column called Test in Table person rather than equating it to the 'Test' string

So you can do:

var output = cnn.Query<Person>($"select * from Person where FirstName = '{ tempName }'");

Or better yet:

var people = cnn.Query<Person>("SELECT * FROM PERSON WHERE FirstName = @FirstName", new { FirstName = tempName });


问:
How do disable paging by swiping with finger in ViewPager but still be able to swipe programmatically?
I have ViewPager and below it I have 10 buttons. By clicking on button, for example #4, the pager goes immediately to page #4 by mPager.setCurrentItem(3);. But, I want to disable the paging by swiping with finger horizontally. Thus, the paging is done ONLY by clicking on the buttons.
So, how I can disable the swiping with finger?

答:
If your are using ViewPager2 you just have to use:

viewpager.setUserInputEnabled(false);

From the docs:

Enable or disable user initiated scrolling. This includes touch input (scroll and fling gestures) and accessibility input. Disabling keyboard input is not yet supported. When user initiated scrolling is disabled, programmatic scrolls through setCurrentItem still work. By default, user initiated scrolling is enabled.

Thanks to: https://stackoverflow.com/a/61685871/9026710

ContentLicense: CC BY-SA 3.0


问:
How can I update the values of table using spark sql or hive?
I have tried working with the update statement but I think spark SQL doesn't allow it.</p>

答:
It depends where and how your data is stored.
If your data is stored in HDFS or other kind of object stores(like S3) your data is immutable.

A single option is in case you have your Hive table defined as transactional. In this case the table has to be clustered and stored as ORC.

In other cases unfortunately you can't update.
More information about hive transactions you can find here: https://cwiki.apache.org/confluence/display/Hive/Hive+Transactions


问:
How to clear conditional formatting (not all formatting) in Google Apps script
I need a way to remove all conditional formatting by running a script (my client will be using this and he doesn't want to have to repeat the process of removing conditional formatting for each worksheet in each of a large number of spreadsheet files).

Is there any way to do this via Google Apps script? All I see is .clearFormat(), which unfortunately clears all formatting, of which a lot should not be deleted (eg, font color, bg color, font, font weight, font rotation, cell outlines)

How to do this in such a way that only one button needs to be pressed for each spreadsheet file?

答:
I ended up finding a solution based on David Friedman's answer. This script successfully removed the conditional format from just one column (D), and left the conditional formats in other columns unchanged.</p>

```<code>// clearConditionalFormat
// Data must have header row that does NOT have conditional formatting
// Otherwise you must identify some other cell on the sheet that does not
//                 have conditional formatting

function test(){
var sheetName = "Sheet13";   // replace with your sheet's name
var rangeText = "D3:D";      // replace with the your range
clearConditionalFormat(rangeText,sheetName);
};

function clearConditionalFormat(rangeText,sheetName){
var ss = SpreadsheetApp.getActive();
var sheet = ss.getActiveSheet();
var rangeText = rangeText.toString().toUpperCase();
var range =  ss.getRange(rangeText).activate();

var rangeTextSplit = rangeText.split(":");
     // example: returns  AA22 from AA22:AZ37
var rangeFirstLetter = rangeTextSplit[0].replace(/[0-9]+/g, "");
    // example: returns  AA from AA22
var rangeRowNum1 = rangeTextSplit[0].replace(/[A-Z]+/g, "")*1;
    // example: returns the 22 of AA22:AZ37
var rangeHeaderText = rangeFirstLetter + (rangeRowNum1 - 1);

sheet.getRange(rangeHeaderText)
    .copyTo(range,SpreadsheetApp.CopyPasteType
    .PASTE_CONDITIONAL_FORMATTING, false);
 };
</code>```

Body:
I ended up finding a solution based on David Friedman's answer. This script successfully removed the conditional format from just one column (D), and left the conditional formats in other columns unchanged.

// clearConditionalFormat
// Data must have header row that does NOT have conditional formatting
// Otherwise you must identify some other cell on the sheet that does not
//                 have conditional formatting

function test(){
var sheetName = "Sheet13";   // replace with your sheet's name
var rangeText = "D3:D";      // replace with the your range
clearConditionalFormat(rangeText,sheetName);
};

function clearConditionalFormat(rangeText,sheetName){
var ss = SpreadsheetApp.getActive();
var sheet = ss.getActiveSheet();
var rangeText = rangeText.toString().toUpperCase();
var range =  ss.getRange(rangeText).activate();

var rangeTextSplit = rangeText.split(":");
     // example: returns  AA22 from AA22:AZ37
var rangeFirstLetter = rangeTextSplit[0].replace(/[0-9]+/g, "");
    // example: returns  AA from AA22
var rangeRowNum1 = rangeTextSplit[0].replace(/[A-Z]+/g, "")*1;
    // example: returns the 22 of AA22:AZ37
var rangeHeaderText = rangeFirstLetter + (rangeRowNum1 - 1);

sheet.getRange(rangeHeaderText)
    .copyTo(range,SpreadsheetApp.CopyPasteType
    .PASTE_CONDITIONAL_FORMATTING, false);
 };


问:
Any way to see map results in a mapreduce function?
For debugging purposes it would be great to be able to see just what you are getting back from the map method.  Is this possible in ruby?</p>

答:
To do this in the Mongo shell, you can define you own debug version of the emit() function to print trace information.

```<code>function emit(k, v) {
    print("emit");
    print("  k:" + k + " v:" + tojson(v));
}
</code>```

Check out Troubleshooting MapReduce in the MongoDB docs for more info.

Body:
To do this in the Mongo shell, you can define you own debug version of the emit() function to print trace information.

function emit(k, v) {
    print("emit");
    print("  k:" + k + " v:" + tojson(v));
}

Check out Troubleshooting MapReduce in the MongoDB docs for more info.


问:
Perl tar file creates directory recursively
I am taring the directory contents using Archive::Tar module.

My scripts is below:

```<code>#!/usr/bin/perl -w

use strict;
use warnings;
use Archive::Tar;
use File::Find;
use Data::Dumper;

my $home_dir = "C:/Users/Documents/Vinod/Perl_Scripts/test/";

my $src_location = $home_dir."LOG_DIR";
my $dst_location = $home_dir."file.tar.gz";

my @inventory = ();
find (sub { push @inventory, $File::Find::name }, $src_location);

print "Files:".Dumper(\@inventory);

my $tar = Archive::Tar->new();

$tar->add_files( @inventory );

$tar->write( $dst_location , 9 );
</code>```

Script is able to create file.tar.gz file in location C:/Users/Documents/Vinod/Perl_Scripts/test/.

But when I extract the file.tar.gz manually it creates a whole path recursively once again. So LOG_DIR contents would be visible in the location C:/Users/Documents/Vinod/Perl_Scripts/test/file.tar/file/Users/Documents/Vinod/Perl_Scripts/test/LOG_DIR/

How can I have the contents which is inside C:/Users/Documents/Vinod/Perl_Scripts/test/LOG_DIR/ in C:/Users/Documents/Vinod/Perl_Scripts/test/file.tar/file/ while extracting it.

答:
Since you use $File::Find::name for your list, you get the absolute path to each file. That's the name that you give Archive::Tar, so that's the name that it uses. You can see the files in a tarball:

```<code>$ tar -tzf archive.tgz
</code>```

There are various ways to get relative paths instead. You might do that in the wanted function. Remove the part of the path that you do not want. That's typically not going to be the directory you used for find (src_location) because you want to keep that level of structure:

```<code>my @inventory;
find(
    sub {
        return if /\A\.\.?\z/;
        push @inventory, abs2rel( $File::Find::name, $home_dir )
        }, $src_location
    );
</code>```

Or do it after:

```<code>@inventory = map { abs2rel($_, $home_dir) } @inventory;
</code>```

Body:
I am taring the directory contents using Archive::Tar module.

My scripts is below:

#!/usr/bin/perl -w

use strict;
use warnings;
use Archive::Tar;
use File::Find;
use Data::Dumper;

my $home_dir = "C:/Users/Documents/Vinod/Perl_Scripts/test/";

my $src_location = $home_dir."LOG_DIR";
my $dst_location = $home_dir."file.tar.gz";

my @inventory = ();
find (sub { push @inventory, $File::Find::name }, $src_location);

print "Files:".Dumper(\@inventory);

my $tar = Archive::Tar->new();

$tar->add_files( @inventory );

$tar->write( $dst_location , 9 );

Script is able to create file.tar.gz file in location C:/Users/Documents/Vinod/Perl_Scripts/test/.

But when I extract the file.tar.gz manually it creates a whole path recursively once again. So LOG_DIR contents would be visible in the location C:/Users/Documents/Vinod/Perl_Scripts/test/file.tar/file/Users/Documents/Vinod/Perl_Scripts/test/LOG_DIR/

How can I have the contents which is inside C:/Users/Documents/Vinod/Perl_Scripts/test/LOG_DIR/ in C:/Users/Documents/Vinod/Perl_Scripts/test/file.tar/file/ while extracting it.

Body:
Since you use $File::Find::name for your list, you get the absolute path to each file. That's the name that you give Archive::Tar, so that's the name that it uses. You can see the files in a tarball:

$ tar -tzf archive.tgz

There are various ways to get relative paths instead. You might do that in the wanted function. Remove the part of the path that you do not want. That's typically not going to be the directory you used for find (src_location) because you want to keep that level of structure:

my @inventory;
find(
    sub {
        return if /\A\.\.?\z/;
        push @inventory, abs2rel( $File::Find::name, $home_dir )
        }, $src_location
    );

Or do it after:

@inventory = map { abs2rel($_, $home_dir) } @inventory;


问:
Why does my regex not work on input from file.read()?
I have a section of code that I need to remove from multiple files that starts like this:

```<code><?php
//{{56541616
</code>```

and ends like this:

```<code>//}}18420732
?>
</code>```

where both strings of numbers can be any sequence of letters and numbers (not the same).

I wrote a Python program that will return the entire input string except for this problem string:

```<code>def removeInsert(text):
    m = re.search(r"<\?php\n\/\/\{\{[a-zA-Z0-9]{8}.*\/\/\}\}[a-zA-Z0-9]{8}\n\?>", text, re.DOTALL)
    return text[:m.start()] + text[m.end():]
</code>```

This program works great when I call it with removeInsert("""[file text]""") -- the triple quotes allow it to be read in as multiline.

I attempted to extend this to open a file and pass the string contents of the file to removeInsert() with this:

```<code>def fileRW(filename):
    input_file = open(filename, 'r')
    text = input_file.read()
    newText = removeInsert(text)
    ...
</code>```

However, when I run fileRW([input-file]), I get this error:

```<code>return text[:m.start()] + text[m.end():]
AttributeError: 'NoneType' object has no attribute 'start'
</code>```

I can confirm that "text" in that last code is actually a string, and does contain the problem code, but it seems that the removeInsert() code doesn't work on this string.  My best guess is that it's related to the triple quoting I do when inputting the string manually into removeInsert().  Perhaps the text that fileRW() passes to removeInsert() is not triple-quoted (I've tried different ways of forcing it to have triple quotes ("\"\"\"" added), but that doesn't work).  I have no idea how to fix this, though, and can't find any information about it in my google searching.  Any suggestions?

答:
Keep the \n in your regular expressions and open the file as:

```<code>input_file= open(filename, 'rU')
</code>```

Note the extra U in the mode. This will allow your code to work even if used on other operating systems, or given files having “foreign” end-of-line.

Body:
I have a section of code that I need to remove from multiple files that starts like this:

<?php
//{{56541616

and ends like this:

//}}18420732
?>

where both strings of numbers can be any sequence of letters and numbers (not the same).

I wrote a Python program that will return the entire input string except for this problem string:

def removeInsert(text):
    m = re.search(r"<\?php\n\/\/\{\{[a-zA-Z0-9]{8}.*\/\/\}\}[a-zA-Z0-9]{8}\n\?>", text, re.DOTALL)
    return text[:m.start()] + text[m.end():]

This program works great when I call it with removeInsert("""[file text]""") -- the triple quotes allow it to be read in as multiline.

I attempted to extend this to open a file and pass the string contents of the file to removeInsert() with this:

def fileRW(filename):
    input_file = open(filename, 'r')
    text = input_file.read()
    newText = removeInsert(text)
    ...

However, when I run fileRW([input-file]), I get this error:

return text[:m.start()] + text[m.end():]
AttributeError: 'NoneType' object has no attribute 'start'

I can confirm that "text" in that last code is actually a string, and does contain the problem code, but it seems that the removeInsert() code doesn't work on this string.  My best guess is that it's related to the triple quoting I do when inputting the string manually into removeInsert().  Perhaps the text that fileRW() passes to removeInsert() is not triple-quoted (I've tried different ways of forcing it to have triple quotes ("\"\"\"" added), but that doesn't work).  I have no idea how to fix this, though, and can't find any information about it in my google searching.  Any suggestions?

Body:
Keep the \n in your regular expressions and open the file as:

input_file= open(filename, 'rU')

Note the extra U in the mode. This will allow your code to work even if used on other operating systems, or given files having “foreign” end-of-line.


问:
QThread still running after the main loop die
I'm working on a software which has to count the emails in outlook avec update the amount every x minutes.

I created a QThread to complete this task which freezes my GUI.

Everything works fine, but, when I quit the software, the thread is still running because I used an infinity loop so that it can update the amount permanently.

I found a solution by the declaration of a global variable and a local variable with incrementation by signal.
My while loop compare them, and continue if it's ok.

As Qthread don't have the isDaemon method, I'm not sure that the thread is really dead, and not just don't do visible task anymore.

Here is an example of my code:

```<code>continuation=1
class App_Direction(QtWidgets.QWidget):

        def __init__(self):
            super(App_Direction,self).__init__()
            self.setWindowTitle("test")
            self.resize(1000,1050)
            self.move(1500,100)
            self.setStyleSheet("font: 10pt;")
            self.feed_stats_label()

        @QtCore.pyqtSlot(int)
        def feed_stats_label(self):
            self.workthread=WorkerThread()
            self.workthread.mail_sig.connect(self.modif)
            self.workthread.continuation_sig.connect(self.continuation)
            self.workthread.start()

        @QtCore.pyqtSlot(list)
        def modif (self,liste=()):
            print("Je ne recois plus le signal, car je suis mort")

        @QtCore.pyqtSlot(list)
        def continuation(self, arg):
            global continuation
            continuation+=1

    class WorkerThread(QtCore.QThread):
        mail_sig = QtCore.pyqtSignal(list)
        continuation_sig=QtCore.pyqtSignal(list)

        def __init__(self, parent=None):
            super().__init__(parent)
        def run(self):

            self.continuation=1
            global continuation
            while self.continuation==continuation:
            print("Et ca continue encore et encore")
            self.mail_sig.emit([]) # envoi du signal de progression d'exécution
            self.continuation+=1
            self.continuation_sig.emit([self.continuation])
            time.sleep(10)
    if __name__ == '__main__':
        QtWidgets.QApplication.setStyle("Fusion")
        app=QtWidgets.QApplication ([])
        win= App_Direction()
        win.show()
        app.exec_()
</code>```

答:
While QThread doesn't have a Daemon flag, it does act like a Daemon. Consider your example with the continuation variable removed (and some refactoring):

```<code>from PyQt5 import QtWidgets, QtCore
import time

class AppDirection(QtWidgets.QWidget):

    def __init__(self):
        super(AppDirection, self).__init__()
        self.setWindowTitle("test")
        self.resize(800, 600)
        self.setStyleSheet("font: 10pt;")
        self.work_thread = None
        self.feed_stats_label()

    @QtCore.pyqtSlot(int)
    def feed_stats_label(self):
        self.work_thread = WorkerThread()
        self.work_thread.mail_sig.connect(self.modif)
        self.work_thread.start()

    @QtCore.pyqtSlot()
    def modif(self):
        print("I am receiving the signal")

class WorkerThread(QtCore.QThread):
    mail_sig = QtCore.pyqtSignal()

    def __init__(self, parent=None):
        super().__init__(parent)

    def run(self):
        while True:
            print("I am sending the signal.")
            self.mail_sig.emit()
            time.sleep(0.5)

if __name__ == '__main__':
    QtWidgets.QApplication.setStyle("Fusion")
    app = QtWidgets.QApplication([])
    win = AppDirection()
    win.show()
    app.exec_()
</code>```

When you close the Window, the thread also stops printing.

Body:
I'm working on a software which has to count the emails in outlook avec update the amount every x minutes.

I created a QThread to complete this task which freezes my GUI.

Everything works fine, but, when I quit the software, the thread is still running because I used an infinity loop so that it can update the amount permanently.

I found a solution by the declaration of a global variable and a local variable with incrementation by signal.
My while loop compare them, and continue if it's ok.

As Qthread don't have the isDaemon method, I'm not sure that the thread is really dead, and not just don't do visible task anymore.

Here is an example of my code:

continuation=1
class App_Direction(QtWidgets.QWidget):

        def __init__(self):
            super(App_Direction,self).__init__()
            self.setWindowTitle("test")
            self.resize(1000,1050)
            self.move(1500,100)
            self.setStyleSheet("font: 10pt;")
            self.feed_stats_label()

        @QtCore.pyqtSlot(int)
        def feed_stats_label(self):
            self.workthread=WorkerThread()
            self.workthread.mail_sig.connect(self.modif)
            self.workthread.continuation_sig.connect(self.continuation)
            self.workthread.start()

        @QtCore.pyqtSlot(list)
        def modif (self,liste=()):
            print("Je ne recois plus le signal, car je suis mort")

        @QtCore.pyqtSlot(list)
        def continuation(self, arg):
            global continuation
            continuation+=1

    class WorkerThread(QtCore.QThread):
        mail_sig = QtCore.pyqtSignal(list)
        continuation_sig=QtCore.pyqtSignal(list)

        def __init__(self, parent=None):
            super().__init__(parent)
        def run(self):

            self.continuation=1
            global continuation
            while self.continuation==continuation:
            print("Et ca continue encore et encore")
            self.mail_sig.emit([]) # envoi du signal de progression d'exécution
            self.continuation+=1
            self.continuation_sig.emit([self.continuation])
            time.sleep(10)
    if __name__ == '__main__':
        QtWidgets.QApplication.setStyle("Fusion")
        app=QtWidgets.QApplication ([])
        win= App_Direction()
        win.show()
        app.exec_()

Body:
While QThread doesn't have a Daemon flag, it does act like a Daemon. Consider your example with the continuation variable removed (and some refactoring):

from PyQt5 import QtWidgets, QtCore
import time

class AppDirection(QtWidgets.QWidget):

    def __init__(self):
        super(AppDirection, self).__init__()
        self.setWindowTitle("test")
        self.resize(800, 600)
        self.setStyleSheet("font: 10pt;")
        self.work_thread = None
        self.feed_stats_label()

    @QtCore.pyqtSlot(int)
    def feed_stats_label(self):
        self.work_thread = WorkerThread()
        self.work_thread.mail_sig.connect(self.modif)
        self.work_thread.start()

    @QtCore.pyqtSlot()
    def modif(self):
        print("I am receiving the signal")

class WorkerThread(QtCore.QThread):
    mail_sig = QtCore.pyqtSignal()

    def __init__(self, parent=None):
        super().__init__(parent)

    def run(self):
        while True:
            print("I am sending the signal.")
            self.mail_sig.emit()
            time.sleep(0.5)

if __name__ == '__main__':
    QtWidgets.QApplication.setStyle("Fusion")
    app = QtWidgets.QApplication([])
    win = AppDirection()
    win.show()
    app.exec_()

When you close the Window, the thread also stops printing.


问:
Replace a Date with last business day
I am trying to replace a date with last business day of that month and getting message

'TypeError: Invalid "to_replace" type: 'str'

Code:

```<code>df['curr_date'] = pd.to_datetime(df['curr_date'])
df['curr_date'] = df['curr_date'].replace('curr_date',df.loc[df.curr_date.isin(df.curr_date + pd.offsets.BMonthEnd(1))],inplace = True)
</code>```

curr_date: 2020-01-31, 2020-02-29, 2020-03-31
I want the 2020-02-29 to be replaced with 2020-02-28 which is last business day in february. Thanks

答:
Start from defining an offset to business month end:

```<code>offs = pd.offsets.BMonthEnd(0)
</code>```

Then define a function to compute the last business day for the current date:

```<code>def dateCorr(dat : pd.Timestamp) -> pd.Timestamp:
    dFwd = offs.rollforward(dat)
    return dFwd if dFwd.month == dat.month else offs.rollback(dat)
</code>```

For the test purpose, save the "corrected" dates as a new column:

```<code>df['LastBDay'] = df.curr_date.apply(dateCorr)
</code>```

so you will be able to compare source dates with new dates.

Of course in the final version of code replace LastBDay with
curr_date, to overwrite the existing column.

Another, much faster solution

As you probably know, Numpy operates much quicker than Pandas, so
I looked for the way to do your task based solely on Numpy.

The result is that I found much faster solution:

```<code>df['LastBDay'] = np.busday_offset(
    df.curr_date.values.astype('M8[M]') + np.timedelta64(1, 'M'), -1, roll='forward')
</code>```

Steps:

df.curr_date.values.astype('M8[M]') - Convert curr_date to a date with
month resolution.

+ np.timedelta64(1, 'M') - Forward this date by one month.

np.busday_offset( - Find the business day, starting from the first
argument.

-1 - 1 day back.

roll='forward' - This is a tricky detail. Since the offset is -1,
the roll direction is back. But passing back here rolls the date
sometimes another day back. So to avoid this another shift,
this parameter must be just forward.

And now how faster is this solution.

Using %timeit I measured the execution time of the previous solution
for a sample of 16,000 rows, getting 2,47 s.

But the execution time of this (second) solution is 12,8 ms - 190 times
faster.

This much better execution speed results also from the fact that the
second solution uses vectorized operations instead of application
of a function to each row.

Title: Replace a Date with last business day

Body:
I am trying to replace a date with last business day of that month and getting message

'TypeError: Invalid "to_replace" type: 'str'

Code:

df['curr_date'] = pd.to_datetime(df['curr_date'])
df['curr_date'] = df['curr_date'].replace('curr_date',df.loc[df.curr_date.isin(df.curr_date + pd.offsets.BMonthEnd(1))],inplace = True)

curr_date: 2020-01-31, 2020-02-29, 2020-03-31
I want the 2020-02-29 to be replaced with 2020-02-28 which is last business day in february. Thanks

Body:
Start from defining an offset to business month end:

offs = pd.offsets.BMonthEnd(0)

Then define a function to compute the last business day for the current date:

def dateCorr(dat : pd.Timestamp) -> pd.Timestamp:
    dFwd = offs.rollforward(dat)
    return dFwd if dFwd.month == dat.month else offs.rollback(dat)

For the test purpose, save the "corrected" dates as a new column:

df['LastBDay'] = df.curr_date.apply(dateCorr)

so you will be able to compare source dates with new dates.

Of course in the final version of code replace LastBDay with
curr_date, to overwrite the existing column.

Another, much faster solution

As you probably know, Numpy operates much quicker than Pandas, so
I looked for the way to do your task based solely on Numpy.

The result is that I found much faster solution:

df['LastBDay'] = np.busday_offset(
    df.curr_date.values.astype('M8[M]') + np.timedelta64(1, 'M'), -1, roll='forward')

Steps:

df.curr_date.values.astype('M8[M]') - Convert curr_date to a date with
month resolution.

+ np.timedelta64(1, 'M') - Forward this date by one month.

np.busday_offset( - Find the business day, starting from the first
argument.

-1 - 1 day back.

roll='forward' - This is a tricky detail. Since the offset is -1,
the roll direction is back. But passing back here rolls the date
sometimes another day back. So to avoid this another shift,
this parameter must be just forward.

And now how faster is this solution.

Using %timeit I measured the execution time of the previous solution
for a sample of 16,000 rows, getting 2,47 s.

But the execution time of this (second) solution is 12,8 ms - 190 times
faster.

This much better execution speed results also from the fact that the
second solution uses vectorized operations instead of application
of a function to each row.


问:
Write a program in Prolog to implement vanish(R,L,N) where R denotes the element whose all occurrences has to be remove from list L to obtain list N
Write a program in Prolog to implement vanish(R,L,N) where R denotes
the element whose all occurrences has to be remove from list L to obtain
list N.</p>

答:
This should work :</p>

```<code>vanish(_,[],[]).
vanish(E,[E|Ls],N) :- vanish(E,Ls,N).
vanish(E,[L|Ls],[L|Ns]) :- L\=E, vanish(E,Ls,Ns).
</code>```

Body:
This should work :

vanish(_,[],[]).
vanish(E,[E|Ls],N) :- vanish(E,Ls,N).
vanish(E,[L|Ls],[L|Ns]) :- L\=E, vanish(E,Ls,Ns).


问:
Logitech Mouse: One Click = 2 Keys Pressed
Is it possible to program logitech mouse with lua script to press 2 keys (J and K) when I press a mouse button?</p>

答:
```<code>function OnEvent(event, arg, family)
   if event == "MOUSE_BUTTON_PRESSED" and arg == 5 then  -- mouse button 5
      PressAndReleaseKey("J", "K")
   end
end
</code>```


问:
unable to run 'aws' from cygwin
I'm using cygwin installed on Windows 10 and trying to access awscli from it.

I used pip install awscli to install awscli. This installed awscli. I then tried to run only aws to see if it is installed and I get the following error:

```<code>-bash: /cygdrive/c/Program Files/Anaconda2/Scripts/aws: C:\Program: bad interpreter: No such file or directory
</code>```

I'm not sure why this is happening. Any help in this regard would be highly apreciated.

答:
The Problem comes from "Program Files" having a space. This is something that is related to cygwin (I encountered the same error with git bash on windows). In a script I had something like this:

```<code>#!/c/Program Files/some_program/executable.exe
</code>```

Escaping the space with a backslash or using quotes didn't work.

The solution is to use the DOS' short filename:

Progra~1 for "Program Files"

Progra~2 for "Program Files (x86)"

So my line would turn into:

```<code>#!/c/Progra~1/some_program/executable.exe
</code>```

Title: unable to run 'aws' from cygwin

Body:
I'm using cygwin installed on Windows 10 and trying to access awscli from it.

I used pip install awscli to install awscli. This installed awscli. I then tried to run only aws to see if it is installed and I get the following error:

-bash: /cygdrive/c/Program Files/Anaconda2/Scripts/aws: C:\Program: bad interpreter: No such file or directory

I'm not sure why this is happening. Any help in this regard would be highly apreciated.

Body:
The Problem comes from "Program Files" having a space. This is something that is related to cygwin (I encountered the same error with git bash on windows). In a script I had something like this:

#!/c/Program Files/some_program/executable.exe

Escaping the space with a backslash or using quotes didn't work.

The solution is to use the DOS' short filename:

Progra~1 for "Program Files"

Progra~2 for "Program Files (x86)"

So my line would turn into:

#!/c/Progra~1/some_program/executable.exe


问:
Convert date string (from gmail) to timestamp | Python
I want to save the received date of emails from a Gmail account into a time-series database.

The problem is that I cannot convert the string that I got from the email to timestamp.

I tried this:

```<code>from datetime import datetime

date1 = 'Thu, 28 May 2020 08:15:58 -0700 (PDT)'

date1_obj = datetime.strptime(date1, '%a, %d %b %Y %H:%M:%S %z %Z')

print(date1_obj)
</code>```

But got this error:

```<code>Traceback (most recent call last):
  File "/format_date.py", line 11, in <module>
    date1_obj = datetime.strptime(date1, '%a, %d %b %Y %H:%M:%S %z %Z')
  File "/usr/local/Cellar/python/3.7.7/Frameworks/Python.framework/Versions/3.7/lib/python3.7/_strptime.py", line 577, in _strptime_datetime
    tt, fraction, gmtoff_fraction = _strptime(data_string, format)
  File "/usr/local/Cellar/python/3.7.7/Frameworks/Python.framework/Versions/3.7/lib/python3.7/_strptime.py", line 359, in _strptime
    (data_string, format))
ValueError: time data 'Thu, 28 May 2020 08:15:58 -0700 (PDT)' does not match format '%a, %d %b %Y %H:%M:%S %z %Z'
</code>```

Tried with or without parenthesis wrapping Timezone.
Read a lot, but nothing about how to deal with date strings containing "(PDT)" or any other timezones. It's very important to get the right date... If I run the same code without "(PDT)", got an incorrect time (because of my local time).

I know I can use string methods to manipulate it and convert to a right datetime, but I feel like this would be flexible.

Sorry for my terrible English.

Thank you!

答:
you could use dateutil's parser to parse the string, automatically inferring the format:

```<code>import dateutil
s = 'Thu, 28 May 2020 08:15:58 -0700 (PDT)'
dt = dateutil.parser.parse(s)
# datetime.datetime(2020, 5, 28, 8, 15, 58, tzinfo=tzoffset('PDT', -25200))
dt.utcoffset().total_seconds()
# -25200.0
</code>```

Note that although the timezone is given a name ("PDT"), it is only a UTC offset of 25200 s. In many cases that is sufficient, at least to convert to UTC.

If you need the specific timezone (e.g. to account for DST transitions etc.), you can use a mapping dict that you supply to dateutil.parser.parse as tzinfos:

```<code>tzmap = {'PDT': dateutil.tz.gettz('US/Pacific'),
         'PST': dateutil.tz.gettz('US/Pacific')}

dt = dateutil.parser.parse(s, tzinfos=tzmap)
# datetime.datetime(2020, 5, 28, 8, 15, 58, tzinfo=tzfile('US/Pacific'))
dt.utcoffset().total_seconds()
# -25200.0
</code>```

Body:
I want to save the received date of emails from a Gmail account into a time-series database.

The problem is that I cannot convert the string that I got from the email to timestamp.

I tried this:

from datetime import datetime

date1 = 'Thu, 28 May 2020 08:15:58 -0700 (PDT)'

date1_obj = datetime.strptime(date1, '%a, %d %b %Y %H:%M:%S %z %Z')

print(date1_obj)

But got this error:

Traceback (most recent call last):
  File "/format_date.py", line 11, in <module>
    date1_obj = datetime.strptime(date1, '%a, %d %b %Y %H:%M:%S %z %Z')
  File "/usr/local/Cellar/python/3.7.7/Frameworks/Python.framework/Versions/3.7/lib/python3.7/_strptime.py", line 577, in _strptime_datetime
    tt, fraction, gmtoff_fraction = _strptime(data_string, format)
  File "/usr/local/Cellar/python/3.7.7/Frameworks/Python.framework/Versions/3.7/lib/python3.7/_strptime.py", line 359, in _strptime
    (data_string, format))
ValueError: time data 'Thu, 28 May 2020 08:15:58 -0700 (PDT)' does not match format '%a, %d %b %Y %H:%M:%S %z %Z'

Tried with or without parenthesis wrapping Timezone.
Read a lot, but nothing about how to deal with date strings containing "(PDT)" or any other timezones. It's very important to get the right date... If I run the same code without "(PDT)", got an incorrect time (because of my local time).

I know I can use string methods to manipulate it and convert to a right datetime, but I feel like this would be flexible.

Sorry for my terrible English.

Thank you!

Body:
you could use dateutil's parser to parse the string, automatically inferring the format:

import dateutil
s = 'Thu, 28 May 2020 08:15:58 -0700 (PDT)'
dt = dateutil.parser.parse(s)
# datetime.datetime(2020, 5, 28, 8, 15, 58, tzinfo=tzoffset('PDT', -25200))
dt.utcoffset().total_seconds()
# -25200.0

Note that although the timezone is given a name ("PDT"), it is only a UTC offset of 25200 s. In many cases that is sufficient, at least to convert to UTC.

If you need the specific timezone (e.g. to account for DST transitions etc.), you can use a mapping dict that you supply to dateutil.parser.parse as tzinfos:

tzmap = {'PDT': dateutil.tz.gettz('US/Pacific'),
         'PST': dateutil.tz.gettz('US/Pacific')}

dt = dateutil.parser.parse(s, tzinfos=tzmap)
# datetime.datetime(2020, 5, 28, 8, 15, 58, tzinfo=tzfile('US/Pacific'))
dt.utcoffset().total_seconds()
# -25200.0


问:
AWS Lambda scheduled event source via cloudformation
I already have my lambda / roles defined in cloudformation and would love to also use it to add a scheduled eventsources ... are there any docs or examples around ?</p>

答:
If you use function name as

```<code>"FunctionName": {
      "Fn::GetAtt": [
        "TagWatcherFunction",
        "Arn"
      ]
    }
</code>```

and you not specify the function then it'll throw you
"Template is not valid: Template error: instance of Fn::GetAtt references undefined resource TagWatcherFunction"

So instead of function name you can directly specify the "lambda ARN".
you can see example below

```<code>"TagWatcherRule": {
  "Type": "AWS::Events::Rule",
  "Properties": {
    "ScheduleExpression": "rate(10 minutes)",
    "Targets": [
      {
        "Id": "TagWatcherScheduler",
        "Arn": {
          "Fn::GetAtt": [
            "TagWatcherFunction",
            "Arn"
          ]
        }
      }
    ]
  }
},
// role may call the lambda
"InvokeLambdaPermission": {
  "Type": "AWS::Lambda::Permission",
  "Properties": {
    "FunctionName": "arn:aws:lambda:<region>:<awsid>:function:<lambd name>",
    "Action": "lambda:InvokeFunction",
    "Principal": "events.amazonaws.com",
    "SourceArn": {
      "Fn::GetAtt": [
        "TagWatcherRule",
        "Arn"
      ]
    }
  }
}
</code>```

Body:
If you use function name as

"FunctionName": {
      "Fn::GetAtt": [
        "TagWatcherFunction",
        "Arn"
      ]
    }

and you not specify the function then it'll throw you
"Template is not valid: Template error: instance of Fn::GetAtt references undefined resource TagWatcherFunction"

So instead of function name you can directly specify the "lambda ARN".
you can see example below

"TagWatcherRule": {
  "Type": "AWS::Events::Rule",
  "Properties": {
    "ScheduleExpression": "rate(10 minutes)",
    "Targets": [
      {
        "Id": "TagWatcherScheduler",
        "Arn": {
          "Fn::GetAtt": [
            "TagWatcherFunction",
            "Arn"
          ]
        }
      }
    ]
  }
},
// role may call the lambda
"InvokeLambdaPermission": {
  "Type": "AWS::Lambda::Permission",
  "Properties": {
    "FunctionName": "arn:aws:lambda:<region>:<awsid>:function:<lambd name>",
    "Action": "lambda:InvokeFunction",
    "Principal": "events.amazonaws.com",
    "SourceArn": {
      "Fn::GetAtt": [
        "TagWatcherRule",
        "Arn"
      ]
    }
  }
}