问:
Recycleview custom layout constraint are changing for each inflated view causing problems
I have a recyclerview that inflates data fetched from json.

The issue I am facing are design issues - sometimes the text is aligned correctly and the image is shown and sometimes the text is too long, causing what I think is for the image not to be shown.

here is my XML:

```<code><?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="wrap_content">

    <android.support.constraint.ConstraintLayout
        android:layout_width="395dp"
        android:layout_height="170dp"
        android:layout_marginStart="8dp"
        android:layout_marginTop="8dp"
        android:layout_marginEnd="8dp"
        android:background="#335634"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent">

        <de.hdodenhof.circleimageview.CircleImageView
            android:id="@+id/heroImage"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginStart="8dp"
            android:src="@mipmap/ic_launcher"
            app:layout_constraintBottom_toBottomOf="parent"
            app:layout_constraintStart_toStartOf="parent"
            app:layout_constraintTop_toTopOf="parent" />

        <TextView
            android:id="@+id/heroTitle"
            android:layout_width="200dp"
            android:layout_height="wrap_content"
            android:layout_marginTop="16dp"
            android:layout_marginEnd="16dp"
            android:autoSizeMaxTextSize="25dp"
            android:autoSizeMinTextSize="15dp"
            android:text="Hero Title"
            android:textSize="25dp"
            android:textStyle="bold"
            app:layout_constraintEnd_toEndOf="parent"
            app:layout_constraintTop_toTopOf="parent" />

        <TextView
            android:id="@+id/heroDescription"
            android:layout_width="200dp"
            android:breakStrategy="simple"
            android:layout_height="wrap_content"
            android:layout_marginStart="36dp"
            android:layout_marginTop="24dp"
            android:layout_marginEnd="16dp"
            android:autoSizeMaxTextSize="25dp"
            android:autoSizeMinTextSize="15dp"
            android:text="TextView"
            android:textAlignment="center"
            android:textSize="18dp"
            app:layout_constraintEnd_toEndOf="parent"
            app:layout_constraintStart_toEndOf="@+id/heroImage"
            app:layout_constraintTop_toBottomOf="@+id/heroTitle" />

    </android.support.constraint.ConstraintLayout>
</android.support.constraint.ConstraintLayout>
</code>```

and here is my adapter:

```<code>public class HeroesAdapter extends RecyclerView.Adapter<HeroesAdapter.HeroesViewHolder> {

    private List<Hero> heroList;

    public HeroesAdapter(List<Hero> heroList) {
        this.heroList = heroList;
    }

    @NonNull
    @Override
    public HeroesViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {

        View rowView = LayoutInflater.from(parent.getContext()).inflate(R.layout.hero_cell, parent, false);
        return new HeroesViewHolder(rowView);
    }

    @Override
    public void onBindViewHolder(@NonNull HeroesViewHolder holder, int position) {

        Hero currentHero = heroList.get(position);
        String str = String.join(",", currentHero.abilities);

        holder.heroTitle.setText(currentHero.title);
        holder.heroAbilties.setText(str);
        Picasso.get().load(currentHero.image).resize(500,500).into(holder.heroesImage);

    }

    @Override
    public int getItemCount() {
        return heroList.size();
    }

    public static class HeroesViewHolder extends RecyclerView.ViewHolder {

        ImageView heroesImage;
        TextView heroTitle;
        TextView heroAbilties;

        public HeroesViewHolder(@NonNull View itemView) {
            super(itemView);
            heroesImage = itemView.findViewById(R.id.heroImage);
            heroTitle = itemView.findViewById(R.id.heroTitle);
            heroAbilties = itemView.findViewById(R.id.heroDescription);
        }
    }
}
</code>```

This is the result I am getting and this is the wanted result.

the issues I am facing are:

making each row have a clean design and act the same for all.

images are sometimes shown, sometimes not.

bottom view is "half in screen" and half out of screen.

答:
According to your expectation, you should use card-view and I've updated the layout. Please check</p>

```<code><?xml version="1.0" encoding="utf-8"?>
<android.support.v7.widget.CardView
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_margin="10dp"
    app:cardCornerRadius="10dp"
    android:elevation="10dp"
    android:layout_height="wrap_content">

    <android.support.constraint.ConstraintLayout
        android:layout_width="395dp"
        android:layout_height="170dp"
        android:background="#fff"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent">

        <de.hdodenhof.circleimageview.CircleImageView
            android:id="@+id/heroImage"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginStart="8dp"
            android:src="@mipmap/ic_launcher"
            app:layout_constraintBottom_toBottomOf="parent"
            app:layout_constraintStart_toStartOf="parent"
            app:layout_constraintTop_toTopOf="parent" />

        <TextView
            android:id="@+id/heroTitle"
            android:layout_width="200dp"
            android:layout_height="wrap_content"
            android:layout_marginStart="16dp"
            android:layout_marginTop="20dp"
            android:layout_marginEnd="16dp"
            android:autoSizeMaxTextSize="25dp"
            android:autoSizeMinTextSize="15dp"
            android:text="Hero Title"
            android:textColor="#000"
            android:textSize="25dp"
            android:textStyle="bold"
            app:layout_constraintBottom_toTopOf="@+id/heroDescription"
            app:layout_constraintEnd_toEndOf="parent"
            app:layout_constraintStart_toEndOf="@+id/heroImage"
            app:layout_constraintTop_toTopOf="parent" />

        <TextView
            android:id="@+id/heroDescription"
            android:layout_width="200dp"
            android:layout_height="wrap_content"
            android:layout_marginStart="16dp"
            android:layout_marginTop="16dp"
            android:layout_marginEnd="16dp"
            android:autoSizeMaxTextSize="25dp"
            android:autoSizeMinTextSize="15dp"
            android:breakStrategy="simple"
            android:text="TextView"
            android:textColor="#444"
            android:textSize="18dp"
            app:layout_constraintEnd_toEndOf="parent"
            app:layout_constraintStart_toEndOf="@+id/heroImage"
            app:layout_constraintTop_toBottomOf="@+id/heroTitle" />

    </android.support.constraint.ConstraintLayout>
</android.support.v7.widget.CardView>
</code>```

Body:
I have a recyclerview that inflates data fetched from json.

The issue I am facing are design issues - sometimes the text is aligned correctly and the image is shown and sometimes the text is too long, causing what I think is for the image not to be shown.

here is my XML:

<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="wrap_content">

    <android.support.constraint.ConstraintLayout
        android:layout_width="395dp"
        android:layout_height="170dp"
        android:layout_marginStart="8dp"
        android:layout_marginTop="8dp"
        android:layout_marginEnd="8dp"
        android:background="#335634"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent">

        <de.hdodenhof.circleimageview.CircleImageView
            android:id="@+id/heroImage"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginStart="8dp"
            android:src="@mipmap/ic_launcher"
            app:layout_constraintBottom_toBottomOf="parent"
            app:layout_constraintStart_toStartOf="parent"
            app:layout_constraintTop_toTopOf="parent" />

        <TextView
            android:id="@+id/heroTitle"
            android:layout_width="200dp"
            android:layout_height="wrap_content"
            android:layout_marginTop="16dp"
            android:layout_marginEnd="16dp"
            android:autoSizeMaxTextSize="25dp"
            android:autoSizeMinTextSize="15dp"
            android:text="Hero Title"
            android:textSize="25dp"
            android:textStyle="bold"
            app:layout_constraintEnd_toEndOf="parent"
            app:layout_constraintTop_toTopOf="parent" />

        <TextView
            android:id="@+id/heroDescription"
            android:layout_width="200dp"
            android:breakStrategy="simple"
            android:layout_height="wrap_content"
            android:layout_marginStart="36dp"
            android:layout_marginTop="24dp"
            android:layout_marginEnd="16dp"
            android:autoSizeMaxTextSize="25dp"
            android:autoSizeMinTextSize="15dp"
            android:text="TextView"
            android:textAlignment="center"
            android:textSize="18dp"
            app:layout_constraintEnd_toEndOf="parent"
            app:layout_constraintStart_toEndOf="@+id/heroImage"
            app:layout_constraintTop_toBottomOf="@+id/heroTitle" />

    </android.support.constraint.ConstraintLayout>
</android.support.constraint.ConstraintLayout>

and here is my adapter:

public class HeroesAdapter extends RecyclerView.Adapter<HeroesAdapter.HeroesViewHolder> {

    private List<Hero> heroList;

    public HeroesAdapter(List<Hero> heroList) {
        this.heroList = heroList;
    }

    @NonNull
    @Override
    public HeroesViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {

        View rowView = LayoutInflater.from(parent.getContext()).inflate(R.layout.hero_cell, parent, false);
        return new HeroesViewHolder(rowView);
    }

    @Override
    public void onBindViewHolder(@NonNull HeroesViewHolder holder, int position) {

        Hero currentHero = heroList.get(position);
        String str = String.join(",", currentHero.abilities);

        holder.heroTitle.setText(currentHero.title);
        holder.heroAbilties.setText(str);
        Picasso.get().load(currentHero.image).resize(500,500).into(holder.heroesImage);

    }

    @Override
    public int getItemCount() {
        return heroList.size();
    }

    public static class HeroesViewHolder extends RecyclerView.ViewHolder {

        ImageView heroesImage;
        TextView heroTitle;
        TextView heroAbilties;

        public HeroesViewHolder(@NonNull View itemView) {
            super(itemView);
            heroesImage = itemView.findViewById(R.id.heroImage);
            heroTitle = itemView.findViewById(R.id.heroTitle);
            heroAbilties = itemView.findViewById(R.id.heroDescription);
        }
    }
}

This is the result I am getting and this is the wanted result.

the issues I am facing are:

making each row have a clean design and act the same for all.

images are sometimes shown, sometimes not.

bottom view is "half in screen" and half out of screen.

Body:
According to your expectation, you should use card-view and I've updated the layout. Please check

<?xml version="1.0" encoding="utf-8"?>
<android.support.v7.widget.CardView
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_margin="10dp"
    app:cardCornerRadius="10dp"
    android:elevation="10dp"
    android:layout_height="wrap_content">

    <android.support.constraint.ConstraintLayout
        android:layout_width="395dp"
        android:layout_height="170dp"
        android:background="#fff"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent">

        <de.hdodenhof.circleimageview.CircleImageView
            android:id="@+id/heroImage"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginStart="8dp"
            android:src="@mipmap/ic_launcher"
            app:layout_constraintBottom_toBottomOf="parent"
            app:layout_constraintStart_toStartOf="parent"
            app:layout_constraintTop_toTopOf="parent" />

        <TextView
            android:id="@+id/heroTitle"
            android:layout_width="200dp"
            android:layout_height="wrap_content"
            android:layout_marginStart="16dp"
            android:layout_marginTop="20dp"
            android:layout_marginEnd="16dp"
            android:autoSizeMaxTextSize="25dp"
            android:autoSizeMinTextSize="15dp"
            android:text="Hero Title"
            android:textColor="#000"
            android:textSize="25dp"
            android:textStyle="bold"
            app:layout_constraintBottom_toTopOf="@+id/heroDescription"
            app:layout_constraintEnd_toEndOf="parent"
            app:layout_constraintStart_toEndOf="@+id/heroImage"
            app:layout_constraintTop_toTopOf="parent" />

        <TextView
            android:id="@+id/heroDescription"
            android:layout_width="200dp"
            android:layout_height="wrap_content"
            android:layout_marginStart="16dp"
            android:layout_marginTop="16dp"
            android:layout_marginEnd="16dp"
            android:autoSizeMaxTextSize="25dp"
            android:autoSizeMinTextSize="15dp"
            android:breakStrategy="simple"
            android:text="TextView"
            android:textColor="#444"
            android:textSize="18dp"
            app:layout_constraintEnd_toEndOf="parent"
            app:layout_constraintStart_toEndOf="@+id/heroImage"
            app:layout_constraintTop_toBottomOf="@+id/heroTitle" />

    </android.support.constraint.ConstraintLayout>
</android.support.v7.widget.CardView>


来源: stackexchange

问:
Why do I not have to define the variable in a for loop using range(), but I do have to in a while loop in Python?
I have the following code using a for loop:

```<code>    total = 0
    for num in range(101):
       total = total + num
       print(total)
</code>```

Now the same result using a while loop:

```<code>    num = 0
    total = 0
    while num <= 99:
         num = num + 1
         total = total + num
         print(total)
</code>```

Why is it that I do not have to define num in the first case, but I do have to define it in the second? Are they both not variables?

答:
If you are coming from other programming languages like C, C++ or Java then do not confuse with for in loop of python.

In python, for in loop pick one item from list of items and does something with help of the picked item.

ContentLicense: CC BY-SA 4.0

Body:
I have the following code using a for loop:

    total = 0
    for num in range(101):
       total = total + num
       print(total)

Now the same result using a while loop:

    num = 0
    total = 0
    while num <= 99:
         num = num + 1
         total = total + num
         print(total)

Why is it that I do not have to define num in the first case, but I do have to define it in the second? Are they both not variables?


问:
Export certain cells only to PDF when a certain string/number is chosen in the drop downlist
So I am trying to export certain cells only to PDF when a choice is chosen in the drop box. I am not sure on what I need to do in the For Loop. I always get an empty PDF file when I am trying to export it. I believe I have put in the right if conditions but I'm not sure how to fix this issue.   </p>

```<code>Public Sub exportPDF()
Dim wsA As Worksheet
Dim wbA As Workbook
Dim strTime As String
Dim strName As String
Dim strPath As String
Dim strFile As String
Dim strPathFile As String
Dim myFile As Variant
Dim Answers As Double
Worksheets("Sheet1").Activate
On Error GoTo errHandler

'export to PDF if a folder was selected
 For Each Answer In Worksheets("Sheet1").Range("A2")
 If myFile <> "False" And Answer.Value = "99" Then
    ActiveWorkbook.Worksheets("Sheet1").Range("A3").ExportAsFixedFormat _
    Type:=xlTypePDF, _
    Filename:=myFile, _
    Quality:=xlQualityStandard, _
    IncludeDocProperties:=True, _
    IgnorePrintAreas:=False, _
    OpenAfterPublish:=False
'confirmation message with file info
MsgBox "PDF file has been created: " _
  & vbCrLf _
  & myFile

ElseIf myFile <> "False" And Answer.Value = "66" Then
ActiveWorkbook.Worksheets("Sheet1").Range("A2").ExportAsFixedFormat _
    Type:=xlTypePDF, _
    Filename:=myFile, _
    Quality:=xlQualityStandard, _
    IncludeDocProperties:=True, _
    IgnorePrintAreas:=False, _
    OpenAfterPublish:=False
'confirmation message with file info
MsgBox "PDF file has been created: " _
  & vbCrLf _
  & myFile

Else
ActiveWorkbook.Worksheets("Sheet1").Range("A1").ExportAsFixedFormat _
    Type:=xlTypePDF, _
    Filename:=myFile, _
    Quality:=xlQualityStandard, _
    IncludeDocProperties:=True, _
    IgnorePrintAreas:=False, _
    OpenAfterPublish:=False
'confirmation message with file info
MsgBox "PDF file has been created: " _
  & vbCrLf _
  & myFile
End if
Next Answer

End Sub
</code>```

答:
Without seeing the data it's hard to give a solution but i've given a try. There is no need to loop over a single cell you can just test that cell for the necessary value. Also i would put option explicit at the top this is to avoid using undeclared varables, error handle label not used properly so no point to keep it...you need to put the label at the bottom and provide some error handleing code for that to work. Exporting not too sure why you want to export that specific range  ActiveWorkbook.Worksheets("Sheet1").Range("A3") to me this does not export the whole page just part of it.

```<code>Option Explicit

Public Sub exportPDF()
Dim wsA As Worksheet
Dim wbA As Workbook
Dim strTime As String
Dim strName As String
Dim strPath As String
Dim strFile As String
Dim strPathFile As String
Dim myFile As Variant

myFile = "exported file.pdf"

'export to PDF if a folder was selected
 If Range("A2").Value = 99 Then

    ActiveWorkbook.Worksheets("Sheet1").Range("A3").ExportAsFixedFormat _
    Type:=xlTypePDF, _
    Filename:=myFile, _
    Quality:=xlQualityStandard, _
    IncludeDocProperties:=True, _
    IgnorePrintAreas:=False, _
    OpenAfterPublish:=False
'confirmation message with file info
MsgBox "PDF file has been created: " _
  & vbCrLf _
  & myFile

ElseIf Range("A2").Value = 66 Then
ActiveWorkbook.Worksheets("Sheet1").Range("A2").ExportAsFixedFormat _
    Type:=xlTypePDF, _
    Filename:=myFile, _
    Quality:=xlQualityStandard, _
    IncludeDocProperties:=True, _
    IgnorePrintAreas:=False, _
    OpenAfterPublish:=False
'confirmation message with file info
MsgBox "PDF file has been created: " _
  & vbCrLf _
  & myFile

Else
ActiveWorkbook.Worksheets("Sheet1").Range("A1").ExportAsFixedFormat _
    Type:=xlTypePDF, _
    Filename:=myFile, _
    Quality:=xlQualityStandard, _
    IncludeDocProperties:=True, _
    IgnorePrintAreas:=False, _
    OpenAfterPublish:=False
'confirmation message with file info
MsgBox "PDF file has been created: " _
  & vbCrLf _
  & myFile
End If
'Next Answer

End Sub
</code>```

Body:
So I am trying to export certain cells only to PDF when a choice is chosen in the drop box. I am not sure on what I need to do in the For Loop. I always get an empty PDF file when I am trying to export it. I believe I have put in the right if conditions but I'm not sure how to fix this issue.

Public Sub exportPDF()
Dim wsA As Worksheet
Dim wbA As Workbook
Dim strTime As String
Dim strName As String
Dim strPath As String
Dim strFile As String
Dim strPathFile As String
Dim myFile As Variant
Dim Answers As Double
Worksheets("Sheet1").Activate
On Error GoTo errHandler

'export to PDF if a folder was selected
 For Each Answer In Worksheets("Sheet1").Range("A2")
 If myFile <> "False" And Answer.Value = "99" Then
    ActiveWorkbook.Worksheets("Sheet1").Range("A3").ExportAsFixedFormat _
    Type:=xlTypePDF, _
    Filename:=myFile, _
    Quality:=xlQualityStandard, _
    IncludeDocProperties:=True, _
    IgnorePrintAreas:=False, _
    OpenAfterPublish:=False
'confirmation message with file info
MsgBox "PDF file has been created: " _
  & vbCrLf _
  & myFile

ElseIf myFile <> "False" And Answer.Value = "66" Then
ActiveWorkbook.Worksheets("Sheet1").Range("A2").ExportAsFixedFormat _
    Type:=xlTypePDF, _
    Filename:=myFile, _
    Quality:=xlQualityStandard, _
    IncludeDocProperties:=True, _
    IgnorePrintAreas:=False, _
    OpenAfterPublish:=False
'confirmation message with file info
MsgBox "PDF file has been created: " _
  & vbCrLf _
  & myFile

Else
ActiveWorkbook.Worksheets("Sheet1").Range("A1").ExportAsFixedFormat _
    Type:=xlTypePDF, _
    Filename:=myFile, _
    Quality:=xlQualityStandard, _
    IncludeDocProperties:=True, _
    IgnorePrintAreas:=False, _
    OpenAfterPublish:=False
'confirmation message with file info
MsgBox "PDF file has been created: " _
  & vbCrLf _
  & myFile
End if
Next Answer

End Sub

Body:
Without seeing the data it's hard to give a solution but i've given a try. There is no need to loop over a single cell you can just test that cell for the necessary value. Also i would put option explicit at the top this is to avoid using undeclared varables, error handle label not used properly so no point to keep it...you need to put the label at the bottom and provide some error handleing code for that to work. Exporting not too sure why you want to export that specific range  ActiveWorkbook.Worksheets("Sheet1").Range("A3") to me this does not export the whole page just part of it.

Option Explicit

Public Sub exportPDF()
Dim wsA As Worksheet
Dim wbA As Workbook
Dim strTime As String
Dim strName As String
Dim strPath As String
Dim strFile As String
Dim strPathFile As String
Dim myFile As Variant

myFile = "exported file.pdf"

'export to PDF if a folder was selected
 If Range("A2").Value = 99 Then

    ActiveWorkbook.Worksheets("Sheet1").Range("A3").ExportAsFixedFormat _
    Type:=xlTypePDF, _
    Filename:=myFile, _
    Quality:=xlQualityStandard, _
    IncludeDocProperties:=True, _
    IgnorePrintAreas:=False, _
    OpenAfterPublish:=False
'confirmation message with file info
MsgBox "PDF file has been created: " _
  & vbCrLf _
  & myFile

ElseIf Range("A2").Value = 66 Then
ActiveWorkbook.Worksheets("Sheet1").Range("A2").ExportAsFixedFormat _
    Type:=xlTypePDF, _
    Filename:=myFile, _
    Quality:=xlQualityStandard, _
    IncludeDocProperties:=True, _
    IgnorePrintAreas:=False, _
    OpenAfterPublish:=False
'confirmation message with file info
MsgBox "PDF file has been created: " _
  & vbCrLf _
  & myFile

Else
ActiveWorkbook.Worksheets("Sheet1").Range("A1").ExportAsFixedFormat _
    Type:=xlTypePDF, _
    Filename:=myFile, _
    Quality:=xlQualityStandard, _
    IncludeDocProperties:=True, _
    IgnorePrintAreas:=False, _
    OpenAfterPublish:=False
'confirmation message with file info
MsgBox "PDF file has been created: " _
  & vbCrLf _
  & myFile
End If
'Next Answer

End Sub


问:
Granting a third-party access via api for AWS S3
How can I let another user access to my AWS S3 bucket without having to create an IAM role for it and sending the key/secret.
I want the third-party to decide the credentials for himself.

Is this even possible?

Basically I'm searching for something similar to OAuth for S3

答:
By default, Amazon S3 buckets are private.

Access to objects can be granted in several ways:

A Bucket Policy can make a bucket, or part of a bucket, publicly accessible (not applicable for your use-case)

The Access Control List (ACL) on an object can make it publicly accessible (not applicable for your use-case)

IAM Users can be granted permissions on an Amazon S3 bucket (but IAM Users should only be used for your staff, not for application users)

IAM Roles can be temporarily assumed, but first require authentication (more on this below)

Pre-Signed URLs can be generated to provide time-limited access to Amazon S3 objects

For your use-case, the most applicable approach would be:

Users authenticate to your application. This could use Amazon Cognito, or whatever authentication method you wish to use.

When a user wishes to access a private object, your application determines whether they are entitled to such access (done via your own code).

If they are permitted access, the application should generate a pre-signed URL. This URL can be included in tags like  and .

When the user accesses the URL, they will be able to access the object directly from Amazon S3.

Once the expiry time passes, the pre-signed URL no longer works.

So, you are welcome to use OAuth or any other authentication method, but it is the responsibility of your application to determine whether they are entitled to access individual objects and, if so, generate and return the pre-signed URL. (It's just a couple of lines of code, no API calls required to generate it.)

See: Share an Object with Others - Amazon Simple Storage Service

Amazon Cognito has the ability to issue credentials associated with an IAM Role, and users could then use these credentials to make API calls to AWS. However, it is generic role that would be shared by many users and is not a way to grant user-specific permissions.

Body:
By default, Amazon S3 buckets are private.

Access to objects can be granted in several ways:

A Bucket Policy can make a bucket, or part of a bucket, publicly accessible (not applicable for your use-case)

The Access Control List (ACL) on an object can make it publicly accessible (not applicable for your use-case)

IAM Users can be granted permissions on an Amazon S3 bucket (but IAM Users should only be used for your staff, not for application users)

IAM Roles can be temporarily assumed, but first require authentication (more on this below)

Pre-Signed URLs can be generated to provide time-limited access to Amazon S3 objects

For your use-case, the most applicable approach would be:

Users authenticate to your application. This could use Amazon Cognito, or whatever authentication method you wish to use.

When a user wishes to access a private object, your application determines whether they are entitled to such access (done via your own code).

If they are permitted access, the application should generate a pre-signed URL. This URL can be included in tags like <a> and <img>.

When the user accesses the URL, they will be able to access the object directly from Amazon S3.

Once the expiry time passes, the pre-signed URL no longer works.

So, you are welcome to use OAuth or any other authentication method, but it is the responsibility of your application to determine whether they are entitled to access individual objects and, if so, generate and return the pre-signed URL. (It's just a couple of lines of code, no API calls required to generate it.)

See: Share an Object with Others - Amazon Simple Storage Service

Amazon Cognito has the ability to issue credentials associated with an IAM Role, and users could then use these credentials to make API calls to AWS. However, it is generic role that would be shared by many users and is not a way to grant user-specific permissions.


问:
Change headertext in dynamic gridview with sqlCommand
I created a dynamic gridview which I send in an email. But all works except for the headertext. I can't seem to find how i can define the headertext.

My sqlCommand displays 4 columns, but when i use:

```<code> LabelTest.Text = "Init Count: " +grd.Columns.Count;
</code>```

it shows, Init Count: 0

So i'm trying to do grd.Columns[0].HeaderText = "Something"; to set the headertext but nothing seems to work. I also tried changing the 0 to 3,4,5 but same problem.

The error is:

```<code>System.ArgumentOutOfRangeException: Index was out of range. Must be non-negative and less than the size of the collection. Parameter name: index at System.Collections.ArrayList.get_Item(Int32 index) at..
</code>```

Any ideas anyone? Thank you.

Edit: How i have created my gridview:

```<code>GridView grd = new GridView();

        // Css style voor de gridview

        grd.BorderStyle = System.Web.UI.WebControls.BorderStyle.None;
        grd.GridLines = GridLines.None;
        grd.RowStyle.HorizontalAlign = HorizontalAlign.Center;

        grd.Columns[0].HeaderText = "Something"; //error
        grd.Width = 600;
        LabelTest.Text = "Init Count: " +grd.Columns.Count;

        foreach (DataControlField field in grd.Columns)
        {
            field.ItemStyle.Width = Unit.Percentage(100 / grd.Columns.Count);
        }

        if (sendGrid != null)
        {
            grd.DataSource = sendGrid.ExecuteReader();
            grd.DataBind();
        }
</code>```

sendGrid is the name of my sqlCommand in which I select 4 columns.

The foreach statement only sets my columns a bit more apart from each other. Other than that i'm not specifying any columns or so to set the headertext.

答:
If you are using the

DataControlField

to add Columns set its

RowHeaderColumn

property and then add it to the GridView.

ContentLicense: CC BY-SA 3.0

Body:
I created a dynamic gridview which I send in an email. But all works except for the headertext. I can't seem to find how i can define the headertext.

My sqlCommand displays 4 columns, but when i use:

 LabelTest.Text = "Init Count: " +grd.Columns.Count;

it shows, Init Count: 0

So i'm trying to do grd.Columns[0].HeaderText = "Something"; to set the headertext but nothing seems to work. I also tried changing the 0 to 3,4,5 but same problem.

The error is:

System.ArgumentOutOfRangeException: Index was out of range. Must be non-negative and less than the size of the collection. Parameter name: index at System.Collections.ArrayList.get_Item(Int32 index) at..

Any ideas anyone? Thank you.

Edit: How i have created my gridview:

GridView grd = new GridView();

        // Css style voor de gridview

        grd.BorderStyle = System.Web.UI.WebControls.BorderStyle.None;
        grd.GridLines = GridLines.None;
        grd.RowStyle.HorizontalAlign = HorizontalAlign.Center;

        grd.Columns[0].HeaderText = "Something"; //error
        grd.Width = 600;
        LabelTest.Text = "Init Count: " +grd.Columns.Count;

        foreach (DataControlField field in grd.Columns)
        {
            field.ItemStyle.Width = Unit.Percentage(100 / grd.Columns.Count);
        }

        if (sendGrid != null)
        {
            grd.DataSource = sendGrid.ExecuteReader();
            grd.DataBind();
        }

sendGrid is the name of my sqlCommand in which I select 4 columns.

The foreach statement only sets my columns a bit more apart from each other. Other than that i'm not specifying any columns or so to set the headertext.


问:
How to properly cleanup incorrectly initialized object?
I was asked this question in an interview.

There is a class, lets call it A. It has a default constructor and it initializes  2 different connections in its constructor.

Methods initDB & initSocket creates a DB connection and a socket connection and saves them in an instance field. They are just an example. They could also be file open or anything else.

Lets say a client instantiates an instance of this class. Now initDB executed successfully, but initSocket threw exception. So the object creation was aborted. But the DB connection was not closed prior to the exception. This resulted in a resource leak. How would I tackle this kind of resource leak?

E.g.

```<code>class A {
    public A(){
        this.dbConnection = initDB();
        this.socketConnection = initSocket(); // throws exception
    }
}
</code>```

My initial answer was that I would not initialize these in constructor but in a separate init(). He countered by suggesting that this could be a legacy class, and I have been asked to maintain this. In which case I need to somehow clear the resource leak. How would I approach this problem?

I got stumped because instance creation threw an exception I lost any kind of reference to those connection fields. So I cannot call close() on them. But they will still be present in the OS level (this is my guess).

Note 1

As stated by Interviewer, I cannot change the behavior of the already written constructor. I can extend or do something around it, but cannot change the code.

Note 2

I think interviewer was not looking for explicitly any code that would handle this scenario. Would any JMX stuff help? I took a jibe at it & then we moved on. For those who think this is a very good question, I think interviewer knew this is not a general practice and probably would not be able to answer.

答:
Solution 1:

Provided that:

You can extend class A, and then use instances of class B instead,

method initSocket is overridable (not final nor private)

field dbConnection is accessible from class B (not private)

You can override method initSocket to close the dbConnection in case of an exception:

```<code>@Override
protected Socket initSocket() {
    boolean ok = false;
    try {
        Socket result = super.initSocket();
        ok = true;
        return result;
    } finally {
        if (!ok) {
            dbConnection.close();
        }
    }
}
</code>```

Solution 2:

Provided that:

You can extend class A

method initDb is overridable (not final nor private)

You can wrap your A object in another class, and save the connection so that it can be closed in case of an exception:

```<code>class B {
    private static ThreadLocal<Connection> CONNECTION = new ThreadLocal<>();
    private final A delegate;

    public B() {
        boolean ok = false;
        try {
            delegate = new A() {
                @Override
                protected Connection initDb() {
                    Connection result = super.initDb();
                    CONNECTION.set(result);
                    return result;
                }
            };
            ok = true;
        } finally {
            if (!ok) {
                Connection cnt = CONNECTION.get();
                if (cnt != null) {
                    cnt.close();
                }
            }
            CONNECTION.set(null);
        }
    }
}
</code>```

Body:
I was asked this question in an interview.

There is a class, lets call it A. It has a default constructor and it initializes  2 different connections in its constructor.

Methods initDB & initSocket creates a DB connection and a socket connection and saves them in an instance field. They are just an example. They could also be file open or anything else.

Lets say a client instantiates an instance of this class. Now initDB executed successfully, but initSocket threw exception. So the object creation was aborted. But the DB connection was not closed prior to the exception. This resulted in a resource leak. How would I tackle this kind of resource leak?

E.g.

class A {
    public A(){
        this.dbConnection = initDB();
        this.socketConnection = initSocket(); // throws exception
    }
}

My initial answer was that I would not initialize these in constructor but in a separate init(). He countered by suggesting that this could be a legacy class, and I have been asked to maintain this. In which case I need to somehow clear the resource leak. How would I approach this problem?

I got stumped because instance creation threw an exception I lost any kind of reference to those connection fields. So I cannot call close() on them. But they will still be present in the OS level (this is my guess).

Note 1

As stated by Interviewer, I cannot change the behavior of the already written constructor. I can extend or do something around it, but cannot change the code.

Note 2

I think interviewer was not looking for explicitly any code that would handle this scenario. Would any JMX stuff help? I took a jibe at it & then we moved on. For those who think this is a very good question, I think interviewer knew this is not a general practice and probably would not be able to answer.

Body:
Solution 1:

Provided that:

You can extend class A, and then use instances of class B instead,

method initSocket is overridable (not final nor private)

field dbConnection is accessible from class B (not private)

You can override method initSocket to close the dbConnection in case of an exception:

@Override
protected Socket initSocket() {
    boolean ok = false;
    try {
        Socket result = super.initSocket();
        ok = true;
        return result;
    } finally {
        if (!ok) {
            dbConnection.close();
        }
    }
}

Solution 2:

Provided that:

You can extend class A

method initDb is overridable (not final nor private)

You can wrap your A object in another class, and save the connection so that it can be closed in case of an exception:

class B {
    private static ThreadLocal<Connection> CONNECTION = new ThreadLocal<>();
    private final A delegate;

    public B() {
        boolean ok = false;
        try {
            delegate = new A() {
                @Override
                protected Connection initDb() {
                    Connection result = super.initDb();
                    CONNECTION.set(result);
                    return result;
                }
            };
            ok = true;
        } finally {
            if (!ok) {
                Connection cnt = CONNECTION.get();
                if (cnt != null) {
                    cnt.close();
                }
            }
            CONNECTION.set(null);
        }
    }
}


答:
For Loop iterates each element from the list until the given range. So no need of any variable to check condition.

While Loop iterates until the given condition is true. Here we need some variable or value to check the condition, So the variable num is used before the loop.

Title: Why do I not have to define the variable in a for loop using range(), but I do have to in a while loop in Python?


问:
Remove items in a list based on a list of substrings in another list in python3.x
I am trying to subset a list of strings based on another list of substrings. I want to remove strings in list1 if the string includes a substring in list2.

```<code>list1 = ['lunch time', 'sandwich shop', 'starts at noon','grocery store']

list2 = ['lunch','noon']
</code>```

The output I want:

```<code>output = ['sandwich shop','grocery store']
</code>```

答:
One approach is to iterate on the copy of list1 and remove the string from it if it contains a substring from list2

```<code>list1 = ['lunch time', 'sandwich shop', 'starts at noon','grocery store']

list2 = ['lunch','noon']

#Iterate on copy of list1
for item1 in list1[:]:
    #If substring is present, remove string from list
    for item2 in list2:
        if item2 in item1:
            list1.remove(item1)

print(list1)
</code>```

Another approach is to find the matching substrings, and then subtract that result with the actual list

```<code>list1 = ['lunch time', 'sandwich shop', 'starts at noon','grocery store']

list2 = ['lunch','noon']

#List of strings where the substrings are contained
result = [item1 for item1 in list1 for item2 in list2 if item2 in item1 ]

#List of strings where the substrings are not contained, found by set difference between original list and the list above
print(list(set(list1) - set(result)))
</code>```

The output will be the same in both cases as below

```<code>['grocery store', 'sandwich shop']
</code>```

Body:
I am trying to subset a list of strings based on another list of substrings. I want to remove strings in list1 if the string includes a substring in list2.

list1 = ['lunch time', 'sandwich shop', 'starts at noon','grocery store']

list2 = ['lunch','noon']

The output I want:

output = ['sandwich shop','grocery store']

Body:
One approach is to iterate on the copy of list1 and remove the string from it if it contains a substring from list2

list1 = ['lunch time', 'sandwich shop', 'starts at noon','grocery store']

list2 = ['lunch','noon']

#Iterate on copy of list1
for item1 in list1[:]:
    #If substring is present, remove string from list
    for item2 in list2:
        if item2 in item1:
            list1.remove(item1)

print(list1)

Another approach is to find the matching substrings, and then subtract that result with the actual list

list1 = ['lunch time', 'sandwich shop', 'starts at noon','grocery store']

list2 = ['lunch','noon']

#List of strings where the substrings are contained
result = [item1 for item1 in list1 for item2 in list2 if item2 in item1 ]

#List of strings where the substrings are not contained, found by set difference between original list and the list above
print(list(set(list1) - set(result)))

The output will be the same in both cases as below

['grocery store', 'sandwich shop']


答:
Using Regex.

Ex:

```<code>import re

list1 = ['lunch time', 'sandwich shop', 'starts at noon','grocery store']
list2 = ['lunch','noon']
pattern = re.compile(r"|".join(list2))
print([i for i in list1 if not pattern.search(i)])
</code>```

Output:

```<code>['sandwich shop', 'grocery store']
</code>```

Title: Remove items in a list based on a list of substrings in another list in python3.x

Body:
Using Regex.

Ex:

import re

list1 = ['lunch time', 'sandwich shop', 'starts at noon','grocery store']
list2 = ['lunch','noon']
pattern = re.compile(r"|".join(list2))
print([i for i in list1 if not pattern.search(i)])

Output:

['sandwich shop', 'grocery store']


问:
scala case class with synthetic val
The documentation page for case classes states

Case classes are good for modeling immutable data

Would be any risk/disadvantage to have a synthetic val in a case class like

```<code>case class Square(val side: Int) {
    val area = side * side
}
</code>```

答:
There is no issue with defining an additional val in the case class body but keep in mind that this value will not be treated in any special way by the compiler, as opposed to the values that are part of the constructor.

This means that it won't be used in the implementations of methods like hashCode, equals, toString, copy and others from the Product which all case classes implicitly extend.

In the case of a value that is completely defined by other values from the constructor, like area here, this is of course completely fine. I would even argue that is the only correct choice, because area as a constructor parameter of Square would make it redundant with side, and every compiler-generated method would have to uselessly deal with area. It would also allow to pick areas that don't match side.

Note that declaring area as a val computes it only once, and then the value is stored, which makes every Square instance a bit larger in memory. You could also decide to declare it as a def to compute it every time you need it. For area, you only do a simple multiplication, so it probably doesn't matter, but it does in more complex scenarios.

Also note that, as far as I know, the synthetic vals terminology is usually reserved for values that are compiler-generated.

Title: scala case class with synthetic val

Body:
The documentation page for case classes states

Case classes are good for modeling immutable data

Would be any risk/disadvantage to have a synthetic val in a case class like

case class Square(val side: Int) {
    val area = side * side
}


问:
Which Lisp should I learn?

Which Lisp (dialect) should I learn, and why?

The fragmentation between CL and Scheme slows uptake (at least for me!).

So, give me the "true answer", please!

I have tried to read feature comparisons, and they seem to get bogged down in esoterica (that I don't fully understand) like whether the dialect is fully tail-recursive, and the like.  I'm hoping you all (collectively) can make the opaque differences clear.

Things I like

Good library support, good environments, and Unicode support.

Things I dislike

Flamewars. Features that are useful at the beginning, but interfere with long-term learning.

Updates

I've been mostly using MzScheme, which I'm enjoying just fine, once I got readline support going.  I don't run a GUI on Unix, so it seemed to be a fine environment option for me.

I'm also very happy that Clojure has an easy to install .deb package on debian, so it's much easier to play with.  This is a big win.  Despite the hostility of some rather easy-to-anger below, low barrier to entry is a win.  I like being spoonfed.

After reading a lot more of SICP, I do understand the issues around tail recursion much better.

答: Just pick one, and learn it.  By the time you figure out the differences, you'll be in a position to choose again, if you chose badly the first time.</p>

OwnerDisplayName: Gregg Lind

Title: Which Lisp should I learn?

LastEditorDisplayName: Gregg Lind

ContentLicense: CC BY-SA 2.5


问:
library for editing photos
I want to implement an algorithm for compressing BMP images. What library/sdk would you recommend for helping with reading a picture's pixels, and creating an image pixel by pixel?</p>

答:
System.Drawing.Imaging (GDI+) http://msdn.microsoft.com/en-us/library/system.drawing.bitmap.aspx

Could help you... It has functionality to save with saveoptions and encodings that will allow for compression.

Title: library for editing photos


答:
Python for loops assign the variable and let you use it. We can transform a for loop into a while loop to understand how Python actually does it (hint: it uses iterables!):

iterator = iter(iterable)  # fresh new iterator object
done = False
while not done:
    try:
        item = next(iterator)
    except StopIteration:
        done = True
    else:
        # inside code of a for loop, we can use `item` here
        pass
```


问:
How can I get consecutive nowrap spans to wrap as separate elements?
I have a block of text where I want to group words up as pairs so the two words do not break. There is an unintended consequence where when you have two  tags in a row he whole line turns into nowrap.

Example:
......

Code below is baseline: The result will wrap at any " "(space) or "-" that the container has.
(NOTE: This example is meant to be on a responsive web-page.)

```<code><div class="block-of-text" style="max-width: 550px">
  One-two Buckle-my-shoe, Three-four Shut-the-door,
  Five-six Pick-up-sticks, Seven-eight Lay-them-straight,
  Nine-ten Do-it-again.
</div>
</code>```

The Result of the Base line will look something like this.

```<code>|--------------- My Web Page ---------------| (550px)
|                                           |
|  One-two Buckle-my-shoe, Three-four Shut- |
|  the-door, Five-six Pick-up-sticks, Seven-|
|  eight Lay-them-straight, Nine-ten Do-it- |
|  again.                                   |
|                                           |
|-------------------------------------------|
</code>```

I want to make sure any hyphenated word surrounded by ... stays on the same line.
Below is my attempt. (NOTE: I have One-two not surrounded by nowrap on purpose to show how it will not be included in the result.)

```<code><style>
  .nowrap {
    white-space: nowrap;
  }
</style>

<div class="block-of-text" style="max-width: 550px">
  One-two <span class="nowrap">Buckle-my-shoe, </span>
  <span class="nowrap">Three-four </span><span class="nowrap">Shut-the-door, </span>
  <span class="nowrap">Five-six </span><span class="nowrap">Pick-up-sticks, </span>
  <span class="nowrap">Seven-eight </span><span class="nowrap">Lay-them-straight, </span>
  <span class="nowrap">Nine-ten </span><span class="nowrap">Do-it-again.</span>
</div>
</code>```

My unintended result looks something like this and is NOT what I want. The  tags are acting as one giant nowrap.

```<code>|--------------- My Web Page ---------------| (550px)
|                                           |
|  One-two                                  |
|  Buckle-my-shoe, Three-four Shut-the-door, Five-six Pick-up-sticks, Seven-eight Lay-them-straight, Nine-ten Do-it-again.
|                                           |
|-------------------------------------------|
</code>```

What I want to have happen:

```<code>|--------------- My Web Page ---------------| (550px)
|                                           |
|  One-two Buckle-my-shoe, Three-four       |
|  Shut-the-door, Five-six Pick-up-sticks,  |
|  Seven-eight Lay-them-straight, Nine-ten  |
|  Do-it-again.                             |
|                                           |
|-------------------------------------------|
</code>```

SOLUTION

Thanks to everyone and especially @Kravimir for helping find the solution:

It works when adding style display: inline-block;, while having all spans on the same line, and adding spacing with   inside the span.

```<code><style>
  .nowrap {
    white-space: nowrap;
    display: inline-block;
  }
</style>

<div class="block-of-text" style="max-width: 550px; border: solid 1px red">
  One-two <span class="nowrap">Buckle-my-shoe, </span><span class="nowrap">Three-four </span><span class="nowrap">Shut-the-door, </span><span class="nowrap">Five-six </span><span class="nowrap">Pick-up-sticks, </span><span class="nowrap">Seven-eight </span><span class="nowrap">Lay-them-straight, </span><span class="nowrap">Nine-ten </span><span class="nowrap">Do-it-again.</span>
</div>
</code>```

Additional info on solution: If you put " "(space) or   outside of the span it does not work as intended or you get 2 spaces between spans. Also the whitespace at the end of a line is not observed when the  tag is on a new line.

TLDR; Solution was edited in above.

答:
You are not closing span so

.nowrap {
  white-space: nowrap;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="block-of-text" style="max-width: 550px">
  One-two <span class="nowrap">Buckle-my-shoe, </span>
  <span class="nowrap">Three-four </span><span class="nowrap">Shut-the-door, </span>
  <span class="nowrap">Five-six </span><span class="nowrap">Pick-up-sticks, </span>
  <span class="nowrap">Seven-eight </span><span class="nowrap">Lay-them-straight, </span>
  <span class="nowrap">Nine-ten </span><span class="nowrap">Do-it-again.</span>
</div></code>```

Body:
I have a block of text where I want to group words up as pairs so the two words do not break. There is an unintended consequence where when you have two  tags in a row he whole line turns into nowrap.

Example:
......

Code below is baseline: The result will wrap at any " "(space) or "-" that the container has.
(NOTE: This example is meant to be on a responsive web-page.)

  One-two Buckle-my-shoe, Three-four Shut-the-door,
  Five-six Pick-up-sticks, Seven-eight Lay-them-straight,
  Nine-ten Do-it-again.

The Result of the Base line will look something like this.

|--------------- My Web Page ---------------| (550px)
|                                           |
|  One-two Buckle-my-shoe, Three-four Shut- |
|  the-door, Five-six Pick-up-sticks, Seven-|
|  eight Lay-them-straight, Nine-ten Do-it- |
|  again.                                   |
|                                           |
|-------------------------------------------|

I want to make sure any hyphenated word surrounded by ... stays on the same line.
Below is my attempt. (NOTE: I have One-two not surrounded by nowrap on purpose to show how it will not be included in the result.)

  One-two Buckle-my-shoe,
  Three-four Shut-the-door,
  Five-six Pick-up-sticks,
  Seven-eight Lay-them-straight,
  Nine-ten Do-it-again.

My unintended result looks something like this and is NOT what I want. The  tags are acting as one giant nowrap.

|--------------- My Web Page ---------------| (550px)
|                                           |
|  One-two                                  |
|  Buckle-my-shoe, Three-four Shut-the-door, Five-six Pick-up-sticks, Seven-eight Lay-them-straight, Nine-ten Do-it-again.
|                                           |
|-------------------------------------------|

What I want to have happen:

|--------------- My Web Page ---------------| (550px)
|                                           |
|  One-two Buckle-my-shoe, Three-four       |
|  Shut-the-door, Five-six Pick-up-sticks,  |
|  Seven-eight Lay-them-straight, Nine-ten  |
|  Do-it-again.                             |
|                                           |
|-------------------------------------------|

SOLUTION

Thanks to everyone and especially @Kravimir for helping find the solution:

It works when adding style display: inline-block;, while having all spans on the same line, and adding spacing with   inside the span.

  One-two Buckle-my-shoe, Three-four Shut-the-door, Five-six Pick-up-sticks, Seven-eight Lay-them-straight, Nine-ten Do-it-again.

Additional info on solution: If you put " "(space) or   outside of the span it does not work as intended or you get 2 spaces between spans. Also the whitespace at the end of a line is not observed when the  tag is on a new line.

TLDR; Solution was edited in above.

Body:
You are not closing span so

.nowrap {
  white-space: nowrap;
}

<div class="block-of-text" style="max-width: 550px">
  One-two <span class="nowrap">Buckle-my-shoe, </span>
  <span class="nowrap">Three-four </span><span class="nowrap">Shut-the-door, </span>
  <span class="nowrap">Five-six </span><span class="nowrap">Pick-up-sticks, </span>
  <span class="nowrap">Seven-eight </span><span class="nowrap">Lay-them-straight, </span>
  <span class="nowrap">Nine-ten </span><span class="nowrap">Do-it-again.</span>
</div>


问:
How to store an image in two different folders in Laravel
The code below stores the image in only one folder. I would like to store the image in two different folders (Folder-A and Folder-B)

Here is my controller:

```<code><?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Service;

class ServiceController extends Controller
{
    public function __construct()
    {
        $this->middleware('auth');
    }

    public function store(Request $request)
    {
        $this->validate($request, [
            'image' => 'required|image|mimes:jpeg,png,jpg|max:2048',
        ]);

        $input['image'] = time().'.'.$request->image->getClientOriginalExtension();
        $request->image->move(public_path('Folder-A/'), $input['image']);
        Service::create($input);

        return back()->with('success', 'CREATED SUCCESSFULLY.');
    }
}
</code>```

答:
You can't run move() twice for the same file because as it name says, it moves the file, so on the second run, the original file won't exist anymore.

You must copy the file:

```<code>$uploadPath = public_path('folder-one/');
$file = $request->file('image');
$photo_jpeg= time() . '.' .$file->getClientOriginalExtension();
$file->move($uploadPath,$photo_jpeg);
\File::copy($uploadPath.$photo_jpeg,public_path('folder-two/').$photo_jpeg);
</code>```

Body:
The code below stores the image in only one folder. I would like to store the image in two different folders (Folder-A and Folder-B)

Here is my controller:

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Service;

class ServiceController extends Controller
{
    public function __construct()
    {
        $this->middleware('auth');
    }

    public function store(Request $request)
    {
        $this->validate($request, [
            'image' => 'required|image|mimes:jpeg,png,jpg|max:2048',
        ]);

        $input['image'] = time().'.'.$request->image->getClientOriginalExtension();
        $request->image->move(public_path('Folder-A/'), $input['image']);
        Service::create($input);

        return back()->with('success', 'CREATED SUCCESSFULLY.');
    }
}

Body:
You can't run move() twice for the same file because as it name says, it moves the file, so on the second run, the original file won't exist anymore.

You must copy the file:

$uploadPath = public_path('folder-one/');
$file = $request->file('image');
$photo_jpeg= time() . '.' .$file->getClientOriginalExtension();
$file->move($uploadPath,$photo_jpeg);
\File::copy($uploadPath.$photo_jpeg,public_path('folder-two/').$photo_jpeg);


问:
Mailkit SMTP - StartTLS & TLS flags
I am trying to connect to iCloud via SmtpClient

The settings I am using are as follows:

Server name: smtp.mail.me.com

SSL Required: Yes

If you see an error message when using SSL, try using TLS or STARTTLS instead.

Port: 587

SMTP Authentication Required: Yes - with relevant username and password

If I use SSL I get "Handshake failed due to unexpected packet format"

If I don't use SSL visual studio debugger hangs on connect.

I think the problem is I am not telling the SmtpClient to use tls but I cant find documentation on how to do this.

The code is as follows:

```<code>using (var client = new SmtpClient()) {
    client.Timeout = 1000 * 20;
    //client.Capabilities.
    client.AuthenticationMechanisms.Remove ("XOAUTH2");

    client.Connect("SMTP.mail.me.com", 587, false); //dies here
    //client.Connect(servername, port, useSsl);
    //can I set tls or starttls here??
    client.Authenticate(username, password);
    client.Send(FormatOptions.Default, message);
}
</code>```

Am I able to set TLS or StartTLS manually. One thing I did try is the following but it did not seem to work

```<code>client.Connect(new Uri("smtp://" + servername + ":" + port + "/?starttls=true"));
</code>```

Thanks for any help with this.

答:
According to MailKit Doc

```<code>Connect(string host,int port,bool useSsl,CancellationToken cancellationToken = null)
</code>```

The useSsl argument only controls whether or not the client makes an SSL-wrapped connection. In other words, even if the useSsl parameter is false, SSL/TLS may still be used if the mail server supports the STARTTLS extension.

Title: Mailkit SMTP - StartTLS & TLS flags

Body:
I am trying to connect to iCloud via SmtpClient

The settings I am using are as follows:

Server name: smtp.mail.me.com

SSL Required: Yes

If you see an error message when using SSL, try using TLS or STARTTLS instead.

Port: 587

SMTP Authentication Required: Yes - with relevant username and password

If I use SSL I get "Handshake failed due to unexpected packet format"

If I don't use SSL visual studio debugger hangs on connect.

I think the problem is I am not telling the SmtpClient to use tls but I cant find documentation on how to do this.

The code is as follows:

using (var client = new SmtpClient()) {
    client.Timeout = 1000 * 20;
    //client.Capabilities.
    client.AuthenticationMechanisms.Remove ("XOAUTH2");

    client.Connect("SMTP.mail.me.com", 587, false); //dies here
    //client.Connect(servername, port, useSsl);
    //can I set tls or starttls here??
    client.Authenticate(username, password);
    client.Send(FormatOptions.Default, message);
}

Am I able to set TLS or StartTLS manually. One thing I did try is the following but it did not seem to work

client.Connect(new Uri("smtp://" + servername + ":" + port + "/?starttls=true"));

Thanks for any help with this.

Body:
According to MailKit Doc

Connect(string host,int port,bool useSsl,CancellationToken cancellationToken = null)

The useSsl argument only controls whether or not the client makes an SSL-wrapped connection. In other words, even if the useSsl parameter is false, SSL/TLS may still be used if the mail server supports the STARTTLS extension.


问:
Interface conversion of fields on equivalent structures
Is there a straightforward way to convert a struct where some fields are "generic" (interface{}) into another type which has the same field names but is "strongly-typed" (int, string, etc)?

Lets say that, given the definitions:

```<code>package main

import (
    "fmt"
)

type GenericData struct {
    Hard int
    Soft interface{}
}

type Data struct {
    Hard int
    Soft int
}

type GenericDataGenerator func() GenericData

func generateGenericData() interface{} {
    return GenericData{1, 2}
}

func returnsGenericDataGenerator() interface{} {
    return generateGenericData
}
</code>```

Does converting from GenericData to Data require explicitly casting all interface{} fields? Is there a more straightforwad way to do this?

```<code>func main() {
    gd := generateGenericData()
    fmt.Println(gd)
    fmt.Println(gd.(GenericData))

    // Doesn't work, but is straightforward
    // fmt.Println(gd.(Data))

    // Works, but is not straight forward
    fmt.Println(Data{gd.(GenericData).Hard, gd.(GenericData).Soft.(int)})

    genDataGenerator := returnsGenericDataGenerator()

    // Doesn't work, but is straightforward
    //genDataGenerator.(GenericDataGenerator)()

    // Works, but is not straight forward
    resp := genDataGenerator.(func() interface{})()
    fmt.Println(resp.(GenericData))
}
</code>```

The code can be executed in:
https://play.golang.org/p/_UVBi5It1FY

答:
Is there a straightforward way to convert a struct where some fields are "generic" (interface{}) into another type which has the same field names but is "strongly-typed" (int, string, etc)?

No.

And this is obvious once you understand that interface{} is not some kind of "generic" or "arbitrary" type but a single, "strongly-type" type just like string or int32. The empty interface interface{} is a totally normal type just like a uint16 or a map[float32]bool is. It is a interface type (in contrast to the other examples which are a numeric type and a map type) and its method set is the empty set. It is as strict or strongly typed as any of the other types.

The fact that you can assign any value to a variable of type interface{} does not mean that interface{} somehow means "any type". You can assign the values 3, -1234and 435948 (to name a few) to a int32. This is allowed because the allowed value range of a int32 contains these values (3, -1234, 435948). You can assign a value of type func(int) string to a variable of type interface{} because the allowed value range of interface{} contains func(int)string. This is a vacuous truth and not a "generic" one.

Body:
Is there a straightforward way to convert a struct where some fields are "generic" (interface{}) into another type which has the same field names but is "strongly-typed" (int, string, etc)?

Lets say that, given the definitions:

package main

import (
    "fmt"
)

type GenericData struct {
    Hard int
    Soft interface{}
}

type Data struct {
    Hard int
    Soft int
}

type GenericDataGenerator func() GenericData

func generateGenericData() interface{} {
    return GenericData{1, 2}
}

func returnsGenericDataGenerator() interface{} {
    return generateGenericData
}

Does converting from GenericData to Data require explicitly casting all interface{} fields? Is there a more straightforwad way to do this?

func main() {
    gd := generateGenericData()
    fmt.Println(gd)
    fmt.Println(gd.(GenericData))

    // Doesn't work, but is straightforward
    // fmt.Println(gd.(Data))

    // Works, but is not straight forward
    fmt.Println(Data{gd.(GenericData).Hard, gd.(GenericData).Soft.(int)})

    genDataGenerator := returnsGenericDataGenerator()

    // Doesn't work, but is straightforward
    //genDataGenerator.(GenericDataGenerator)()

    // Works, but is not straight forward
    resp := genDataGenerator.(func() interface{})()
    fmt.Println(resp.(GenericData))
}

The code can be executed in:
https://play.golang.org/p/_UVBi5It1FY


问:
Regular Expression for matching parentheses
What is the regular expression for matching '(' in a string?

Following is the scenario :

I have a string

```<code>str = "abc(efg)";
</code>```

I want to split the string at '(' using regular expression.For that i am using

```<code>Arrays.asList(Pattern.compile("/(").split(str))
</code>```

But i am getting the following exception.

```<code>java.util.regex.PatternSyntaxException: Unclosed group near index 2
/(
</code>```

Escaping '(' doesn't seems to work.

答:
Two options:

Firstly, you can escape it using a backslash -- \(

Alternatively, since it's a single character, you can put it in a character class, where it doesn't need to be escaped -- [(]

Body:
What is the regular expression for matching '(' in a string?

Following is the scenario :

I have a string

str = "abc(efg)";

I want to split the string at '(' using regular expression.For that i am using

Arrays.asList(Pattern.compile("/(").split(str))

But i am getting the following exception.

java.util.regex.PatternSyntaxException: Unclosed group near index 2
/(

Escaping '(' doesn't seems to work.


问:
How to add css for ion-menu in ionic 4 as there is no app.css is available?
I want to design the ion-menu and implement css in the menu but where we will write the css i am not getting as there is no app.css is available.
I want to add the categories and inside that i want to add sub categories but from the web service. How to do this please help me.

I have tried but i am able to show the menu options static not dynamic which i will get from the api.
Please guide me what to do.

```<code><ion-app>
  <ion-menu contentId="content" side="start">
    <ion-header>
      <ion-toolbar>
        <ion-title>Menu</ion-title>
      </ion-toolbar>
    </ion-header>
    <ion-content>
      <div *ngFor="let p of pages">
        <ion-menu-toggle *ngIf="p.url">
          <ion-item [routerLink]="p.url" routerDirection="root" routerLinkActive="active">
            <ion-icon [name]="p.icon" slot="start"></ion-icon>
            <ion-label>
              {{p.title}}
            </ion-label>
          </ion-item>
        </ion-menu-toggle>
        <ion-item button *ngIf="p.children?.length > 0" (click)="p.open = !p.open" [class.parent-active]="p.open"
          style="font-weight: 500;" detail="false">
          <ion-icon slot="start" name="arrow-forward" *ngIf="!p.open"></ion-icon>
          <ion-icon slot="start" name="arrow-down" *ngIf="p.open"></ion-icon>
          <ion-label>{{ p.title }}</ion-label>
        </ion-item>

        <ion-list *ngIf="p.open">
          <ion-menu-toggle>
            <ion-item *ngFor="let sub of p.children" class="sub-item" style="padding-left: 20px;
                  font-size: small;" [routerLink]="sub.url" routerDirection="root" routerLinkActive="active"
              style="--ion-text-color: var(--ion-color-primary);">
              <ion-icon [name]="sub.icon" slot="start"></ion-icon>
              <ion-label>
                {{ sub.title }}
              </ion-label>
            </ion-item>
          </ion-menu-toggle>
        </ion-list>
      </div>
    </ion-content>
  </ion-menu>
  <ion-router-outlet [swipeGesture]="false" id="content" main></ion-router-outlet>
</ion-app>
</code>```

I want the dynamic data to display in the side menu and design the side menu.

app.component.ts

```<code>pages = [
    {
      title: 'Main',
      url: '/home',
      icon: 'home'
    },
    {
      title: 'Categories',
      children: [
        {
          title: 'categories',
          url: '/categories',
          icon: 'arrow-dropright'
        },
        {
          title: 'wishlist',
          url: '/wishlist',
          icon: 'arrow-dropright'
        }, {
          title: 'Your Orders',
          url: '/your-orders',
          icon: 'arrow-dropright'
        }, {
          title: 'My Profile',
          url: '/profile',
          icon: 'play'
        }
      ]
    }, {
      title: 'Offers',
      children: [
        {
          title: 'categories',
          url: '/categories',
          icon: 'play'
        },
        {
          title: 'wishlist',
          url: '/wishlist',
          icon: 'play'
        },
      ]
    }, {
      title: 'LogOut',
      url: '/user-login',
      icon: 'log-out'
    }
  ];
</code>```

答:
Use style below ion-content

for example this will make your ion-menu background black.Like that do for other elements inside your menu

```<code><style>
   ion-content{
    background:black;
  }
</style>
</code>```

Body:
I want to design the ion-menu and implement css in the menu but where we will write the css i am not getting as there is no app.css is available.
I want to add the categories and inside that i want to add sub categories but from the web service. How to do this please help me.

I have tried but i am able to show the menu options static not dynamic which i will get from the api.
Please guide me what to do.

<ion-app>
  <ion-menu contentId="content" side="start">
    <ion-header>
      <ion-toolbar>
        <ion-title>Menu</ion-title>
      </ion-toolbar>
    </ion-header>
    <ion-content>

        <ion-menu-toggle *ngIf="p.url">
          <ion-item [routerLink]="p.url" routerDirection="root" routerLinkActive="active">
            <ion-icon [name]="p.icon" slot="start"></ion-icon>
            <ion-label>
              {{p.title}}
            </ion-label>
          </ion-item>
        </ion-menu-toggle>
        <ion-item button *ngIf="p.children?.length > 0" (click)="p.open = !p.open" [class.parent-active]="p.open"
          style="font-weight: 500;" detail="false">
          <ion-icon slot="start" name="arrow-forward" *ngIf="!p.open"></ion-icon>
          <ion-icon slot="start" name="arrow-down" *ngIf="p.open"></ion-icon>
          <ion-label>{{ p.title }}</ion-label>
        </ion-item>

        <ion-list *ngIf="p.open">
          <ion-menu-toggle>
            <ion-item *ngFor="let sub of p.children" class="sub-item" style="padding-left: 20px;
                  font-size: small;" [routerLink]="sub.url" routerDirection="root" routerLinkActive="active"
              style="--ion-text-color: var(--ion-color-primary);">
              <ion-icon [name]="sub.icon" slot="start"></ion-icon>
              <ion-label>
                {{ sub.title }}
              </ion-label>
            </ion-item>
          </ion-menu-toggle>
        </ion-list>

    </ion-content>
  </ion-menu>
  <ion-router-outlet [swipeGesture]="false" id="content" main></ion-router-outlet>
</ion-app>

I want the dynamic data to display in the side menu and design the side menu.

app.component.ts

pages = [
    {
      title: 'Main',
      url: '/home',
      icon: 'home'
    },
    {
      title: 'Categories',
      children: [
        {
          title: 'categories',
          url: '/categories',
          icon: 'arrow-dropright'
        },
        {
          title: 'wishlist',
          url: '/wishlist',
          icon: 'arrow-dropright'
        }, {
          title: 'Your Orders',
          url: '/your-orders',
          icon: 'arrow-dropright'
        }, {
          title: 'My Profile',
          url: '/profile',
          icon: 'play'
        }
      ]
    }, {
      title: 'Offers',
      children: [
        {
          title: 'categories',
          url: '/categories',
          icon: 'play'
        },
        {
          title: 'wishlist',
          url: '/wishlist',
          icon: 'play'
        },
      ]
    }, {
      title: 'LogOut',
      url: '/user-login',
      icon: 'log-out'
    }
  ];

Body:
Use style below ion-content

for example this will make your ion-menu background black.Like that do for other elements inside your menu

<style>
   ion-content{
    background:black;
  }
</style>


问:
IPFS search file mechanism
I am using IPFS(Inter Planetary File System) to store documents/files in a decentralized manner.

In order to search a file from the network, is there a record of all the hashes on the network(like leeches)?

How does my request travel through the network?

答:
Apologies, but it's unclear to me if you intend to search the contents of files on the network or to just search for files on the network. I'm going to assume the latter, please correct me if that's wrong.

What follows is a bit of an oversimplification, but here it goes:

In order to search a file from the network, is there a record of all the hashes on the network(like leeches)?

There is not a single record, no. Instead, each of the ipfs nodes that makes up the network holds a piece of the total record. When you add a block to your node, the node will announce to the network that it will provide that block if asked to. The process of announcing means letting a number of other ipfs nodes in the network know that you have that block. Essentially, your node asks its peers who ask their peers, and so on, until you find some nodes with ids that are near the hash of the block. Near could be measured using something simple like xor.

The important thing to understand is that, given the hash for a block, your node finds other ipfs nodes in the network that have ids which are similar to the hash of the block, and tells them "if anyone asks, I have the block with this hash". This is important because someone who wants to go find the content for the same hash can use the same process to find nodes that have been told where the hash can be retrieved from.

How does my request travel through the network?

Basically the reverse of above.

You can read more about ipfs content routing in the following:

https://ipfs.io/ipfs/QmR7GSQM93Cx5eAg6a6yRzNde1FQv7uL6X1o4k7zrJa3LX/ipfs.draft3.pdf

https://discuss.ipfs.io/t/how-does-resolution-and-routing-work-with-ipfs/365/3

Title: IPFS search file mechanism


问:
Why does this tkinter login window not work?
Im learning tkinter and ran into a problem while making a login window. Im not sure if i even made it the right or most effective ay but id appreciate some help.

Ive tried a few different ways to do this but havnt found anything yet.

```<code>from tkinter import *
from tkinter import messagebox

def userpass():

    u = username.get
    p = password.get()

    if (p == '123' and u == 'test'):
        messagebox.showinfo("Login", "Correct")

    else:
        messagebox.showinfo("Login", "incorrect")

app = Tk()
password = StringVar()
username = StringVar()
userlabel = Label(app, text = 'username:').grid(row = 1, column = 0)
passlabel = Label(app, text = 'password:').grid(row = 2, column = 0)
userEntry = Entry(app, textvariable = username,).grid(row = 1,
column = 1)
    passEntry = Entry(app, textvariable = password, show = '*').grid(row = 2, column = 1)
    login = Button(app, text = 'login',command = userpass).grid(row = 3, column = 1)

app.mainloop()
</code>```

When i run the program and enter the correct login details, the wrong messagebox pops up.

答:
There is a bug in userpass function. username.get is a function, which on call returns the current value of the corresponding Entry text box. thus, it should be called as

```<code>u = username.get()
</code>```

and, this should work.

Body:
Im learning tkinter and ran into a problem while making a login window. Im not sure if i even made it the right or most effective ay but id appreciate some help.

Ive tried a few different ways to do this but havnt found anything yet.

from tkinter import *
from tkinter import messagebox

def userpass():

    u = username.get
    p = password.get()

    if (p == '123' and u == 'test'):
        messagebox.showinfo("Login", "Correct")

    else:
        messagebox.showinfo("Login", "incorrect")

app = Tk()
password = StringVar()
username = StringVar()
userlabel = Label(app, text = 'username:').grid(row = 1, column = 0)
passlabel = Label(app, text = 'password:').grid(row = 2, column = 0)
userEntry = Entry(app, textvariable = username,).grid(row = 1,
column = 1)
    passEntry = Entry(app, textvariable = password, show = '*').grid(row = 2, column = 1)
    login = Button(app, text = 'login',command = userpass).grid(row = 3, column = 1)

app.mainloop()

When i run the program and enter the correct login details, the wrong messagebox pops up.

Body:
There is a bug in userpass function. username.get is a function, which on call returns the current value of the corresponding Entry text box. thus, it should be called as

u = username.get()

and, this should work.


问:
How do cryptocurrencies verify that the mining reward is initiated by the system and is valid?
I want to verify that the mining reward transaction is in fact valid and that it was initiated by the system. Currently I don't know how I would verify the identity of the system, without hard coding public and private keys, which again wouldn't be secure

Currently I'm using elliptic to generate keys and to verify them.

```<code>  valid() {
    if (this.from === null) {
        return true;
        }
    if (!this.signature || this.signature.length === 0) {
        console.log('No signature on this transaction!\n');
        return false;
    }
    if (typeof this.amount !== 'number' || this.amount <= 0) {
        console.log('Amount must be a positive number\n');
        return false;
    }
    const publicKey = ec.keyFromPublic(this.from, "hex");
    return publicKey.verify(this.hash(), this.signature)
}
</code>```

Right now, if the from address is null, meaning that it was a mining reward, the transaction is automatically true. However, someone could simply give a from address of "null", and then essentially give themselves money.

How would I verify that the mining reward is correct, and coming from the system only when mining has actually been done.

答:
It depends on how the mining rewards are paid out. In an account based model, the balance of the miner included in the header can be incremented according to the mining reward. The world state not matching would cause the block to be rejected ensuring that the system increments the balance accordingly.
In a UTXO model, one approach would be to have the miner sign the empty transaction themselves. This would verify that they control the private key for the "to" address, however it's not really necessary.
It all depends on the constraints of your system. In bitcoin the rule for a coinbase transaction is that it should be the first transaction in the block, and that the output utxo contains an amount that equal to the current mining reward + the fees contained in that block. The coinbase should also include the current block height as part of its data according to BIP 34. See this for more info on coinbase transactions in Bitcoin.</p>

Body:
I want to verify that the mining reward transaction is in fact valid and that it was initiated by the system. Currently I don't know how I would verify the identity of the system, without hard coding public and private keys, which again wouldn't be secure

Currently I'm using elliptic to generate keys and to verify them.

  valid() {
    if (this.from === null) {
        return true;
        }
    if (!this.signature || this.signature.length === 0) {
        console.log('No signature on this transaction!\n');
        return false;
    }
    if (typeof this.amount !== 'number' || this.amount <= 0) {
        console.log('Amount must be a positive number\n');
        return false;
    }
    const publicKey = ec.keyFromPublic(this.from, "hex");
    return publicKey.verify(this.hash(), this.signature)
}

Right now, if the from address is null, meaning that it was a mining reward, the transaction is automatically true. However, someone could simply give a from address of "null", and then essentially give themselves money.

How would I verify that the mining reward is correct, and coming from the system only when mining has actually been done.


问:
Wrong redirecting but only standard WP-Rules in .htaccess

Problem:

I have a download link with an ip as "site name"

http://192.168.1.1/downloads/file.txt

This is redirecting to

https://www.mywebsite.comdownloads/file.txt

Now I want it of course to redirect correctly to

https://www.mywebsite.com/downloads/file.txt

What I've checked:

I've checked some WP options. There was nothing obvious.. I've checked the .htacess. There were only the standard WP rules:

```<code># BEGIN WordPress
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /
RewriteRule ^index\.php$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /index.php [L]
</IfModule>

# END WordPress
</code>```

Any ideas? Is there maybe another file where I can set rules?

答:
Check this rewrite in .htaccess file (before #BEGIN WordPress rules)</p>

```<code>RewriteEngine on
RewriteCond %{HTTP_HOST} ^192\.168\.1\.1
RewriteCond %{REQUEST_URI} ^\/downloads\/file.txt$
RewriteRule ^(.*)$ https://www.mywebsite.com/downloads/file.txt [L,R=301]
</code>```

Body:
Problem:

I have a download link with an ip as "site name"

http://192.168.1.1/downloads/file.txt

This is redirecting to

https://www.mywebsite.comdownloads/file.txt

Now I want it of course to redirect correctly to

https://www.mywebsite.com/downloads/file.txt

What I've checked:

I've checked some WP options. There was nothing obvious.. I've checked the .htacess. There were only the standard WP rules:

# BEGIN WordPress
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /
RewriteRule ^index\.php$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /index.php [L]
</IfModule>

# END WordPress

Any ideas? Is there maybe another file where I can set rules?

Body:
Check this rewrite in .htaccess file (before #BEGIN WordPress rules)

RewriteEngine on
RewriteCond %{HTTP_HOST} ^192\.168\.1\.1
RewriteCond %{REQUEST_URI} ^\/downloads\/file.txt$
RewriteRule ^(.*)$ https://www.mywebsite.com/downloads/file.txt [L,R=301]


问:
Why is there a `null` check in the implementation of the `unapply` method for case classes?
I'm working to replace the unapply method on a case class's companion object with my own implementation. And after investigating lots of different tangents related to implementing unapply, it appears there is a null guard in most of them, both in the compiler generated code and in the implementations where it is explicitly being redefined. The code from the compiler generated code for unapply looks similar to this (some of them use eq instead of ne):

```<code>def unapply(location: Location): Option[(Double, Double)] =
  if (location ne null)
    Some((location.longitude, location.latitude))
  else
    None
</code>```

Given there should be absolutely no use of null in pure (i.e. idiomatic) Scala code, why is this null check being performed? Does it have something to do with Java interop (because Java is still addicted to exploiting null) leaking into the unapply method? What, if any, undesirable consequences will I suffer if I remove the check because I have eliminated the possibility of the case class instance to which the unapply method is being passed can be null nor invalid?  IOW, what's the harm of replacing the above implementation with this one?

```<code>def unapply(location: Location): Option[(Double, Double)] =
  Some((location.longitude, location.latitude))
</code>```

答:
Otherwise, this would give very surprising behavior:

```<code>nullableJavaMethod() match {
  case Location(lat, long) => "Handle location here!"
  case null => "Handle null here!"
}
</code>```

You might prefer another approach to handling null, but that doesn't mean you should make cases like the above crash with NPE if someone prefers that approach. Note that this is specific to unapply, as other methods will not suffer from the problem above.

Body:
I'm working to replace the unapply method on a case class's companion object with my own implementation. And after investigating lots of different tangents related to implementing unapply, it appears there is a null guard in most of them, both in the compiler generated code and in the implementations where it is explicitly being redefined. The code from the compiler generated code for unapply looks similar to this (some of them use eq instead of ne):

def unapply(location: Location): Option[(Double, Double)] =
  if (location ne null)
    Some((location.longitude, location.latitude))
  else
    None

Given there should be absolutely no use of null in pure (i.e. idiomatic) Scala code, why is this null check being performed? Does it have something to do with Java interop (because Java is still addicted to exploiting null) leaking into the unapply method? What, if any, undesirable consequences will I suffer if I remove the check because I have eliminated the possibility of the case class instance to which the unapply method is being passed can be null nor invalid?  IOW, what's the harm of replacing the above implementation with this one?

def unapply(location: Location): Option[(Double, Double)] =
  Some((location.longitude, location.latitude))

Body:
Otherwise, this would give very surprising behavior:

nullableJavaMethod() match {
  case Location(lat, long) => "Handle location here!"
  case null => "Handle null here!"
}

You might prefer another approach to handling null, but that doesn't mean you should make cases like the above crash with NPE if someone prefers that approach. Note that this is specific to unapply, as other methods will not suffer from the problem above.


问:
Azure Java API - How to get vmss scaling settings json
I have a virtual machine scale set (vmss) in Azure cloud.
How can I get its scaling settings json though my Java app?

In general I need to get its maximum and minimum instance limits, and its scaling rules.

To define my vmss I use:

```<code>Azure azure = Azure.configure().authenticate(new File(myAzureCredentialsFilePath)).withDefaultSubscription();
VirtualMachineScaleSet vmss = azure.virtualMachineScaleSets().getById("someId");
</code>```

答:
you can use Azure-SDK's for Java for querying scale set information.

```<code>System.out.println("Listing scale set virtual machine instance network interfaces and SSH connection string...");
            for (VirtualMachineScaleSetVM instance : virtualMachineScaleSet.virtualMachines().list()) {
                System.out.println("Scale set virtual machine instance #" + instance.instanceId());
                System.out.println(instance.id());
                PagedList<VirtualMachineScaleSetNetworkInterface> networkInterfaces = instance.listNetworkInterfaces();
                // Pick the first NIC
                VirtualMachineScaleSetNetworkInterface networkInterface = networkInterfaces.get(0);
                for (VirtualMachineScaleSetNicIPConfiguration ipConfig :networkInterface.ipConfigurations().values()) {
                    if (ipConfig.isPrimary()) {
                        List<LoadBalancerInboundNatRule> natRules = ipConfig.listAssociatedLoadBalancerInboundNatRules();
                        for (LoadBalancerInboundNatRule natRule : natRules) {
                            if (natRule.backendPort() == 22) {
                                System.out.println("SSH connection string: " + userName + "@" + publicIPAddress.fqdn() + ":" + natRule.frontendPort());
                                break;
                            }
                        }
                        break;
                    }
                }
            }

virtualMachineScaleSet.virtualMachines().list() might give you what you are looking for.
</code>```

You can find more samples here. Hope it helps.

Body:
I have a virtual machine scale set (vmss) in Azure cloud.
How can I get its scaling settings json though my Java app?

In general I need to get its maximum and minimum instance limits, and its scaling rules.

To define my vmss I use:

Azure azure = Azure.configure().authenticate(new File(myAzureCredentialsFilePath)).withDefaultSubscription();
VirtualMachineScaleSet vmss = azure.virtualMachineScaleSets().getById("someId");

Body:
you can use Azure-SDK's for Java for querying scale set information.

System.out.println("Listing scale set virtual machine instance network interfaces and SSH connection string...");
            for (VirtualMachineScaleSetVM instance : virtualMachineScaleSet.virtualMachines().list()) {
                System.out.println("Scale set virtual machine instance #" + instance.instanceId());
                System.out.println(instance.id());
                PagedList<VirtualMachineScaleSetNetworkInterface> networkInterfaces = instance.listNetworkInterfaces();
                // Pick the first NIC
                VirtualMachineScaleSetNetworkInterface networkInterface = networkInterfaces.get(0);
                for (VirtualMachineScaleSetNicIPConfiguration ipConfig :networkInterface.ipConfigurations().values()) {
                    if (ipConfig.isPrimary()) {
                        List<LoadBalancerInboundNatRule> natRules = ipConfig.listAssociatedLoadBalancerInboundNatRules();
                        for (LoadBalancerInboundNatRule natRule : natRules) {
                            if (natRule.backendPort() == 22) {
                                System.out.println("SSH connection string: " + userName + "@" + publicIPAddress.fqdn() + ":" + natRule.frontendPort());
                                break;
                            }
                        }
                        break;
                    }
                }
            }

virtualMachineScaleSet.virtualMachines().list() might give you what you are looking for.

You can find more samples here. Hope it helps.


问:
Android - How to Enable Autostart option programmatically in Xiaomi devices?
I am developing an android application in which I want to display the Push notification.

It has displayed well in most of the devices except Xiaomi phones (I am using Redmi Note 4). The problem that I found is, it is because of Autostart option provided by Xiomi which will be disabled by default and the user need to enable it manually.

But I wonder that some of the Android Apps I could see enabling this option without any user interaction Ex: WhatsApp. If I try reinstalling WhatsApp and see the Autostart option , it is enabled!

I am unable to convince our client by telling it is the feature of Xiomi like devices as he is pointing out some apps which is working fine like the example I have mentioned above.

This question has been asked by some other people

Add my app to AutoStart apps list in android programmatically

How to check AutoStart is enabled for our App in Xiaomi manufacturer mobile device Programmatically

But I could not see any answers for them and Posting here with the hope that someone will have an answer for this.

答:
Few popular apps run in background without being killed during memory cleanup cycle (many of the popular OEMs customize the stock ROM for battery/memory optimization), because they are "White listed" by these manufactures.
For your app you can whitelist it either manually (via corresponding "settings" for the devices) or programmatically by redirecting users to the corresponding settings page to white list the app. programmatically you can do like below:

Add below permissions in the App's manifest file:`

```<code><uses-permission android:name="oppo.permission.OPPO_COMPONENT_SAFE"/>
<uses-permission android:name="com.huawei.permission.external_app_settings.USE_COMPONENT"/>`
</code>```

Redirect your to the Auto Start setting:

```<code>if (Build.BRAND.equalsIgnoreCase("xiaomi")) {
                Intent intent = new Intent();
                intent.setComponent(new

ComponentName("com.miui.securitycenter",
                            "com.miui.permcenter.autostart.AutoStartManagementActivity"));
                    startActivity(intent);
            } else if (Build.MANUFACTURER.equalsIgnoreCase("oppo")) {
                try {
                    Intent intent = new Intent();
                    intent.setClassName("com.coloros.safecenter",
                            "com.coloros.safecenter.permission.startup.StartupAppListActivity");
                    startActivity(intent);
                } catch (Exception e) {
                    try {
                        Intent intent = new Intent();
                        intent.setClassName("com.oppo.safe",
                                "com.oppo.safe.permission.startup.StartupAppListActivity");
                        startActivity(intent);
                    } catch (Exception ex) {
                        try {
                            Intent intent = new Intent();
                            intent.setClassName("com.coloros.safecenter",
                                    "com.coloros.safecenter.startupapp.StartupAppListActivity");
                            startActivity(intent);
                        } catch (Exception exx) {

                        }
                    }
                }
            }
</code>```

AutoStart Reference For other OEMs

I have tested this method and it worked but the reliability is still a question as system taking time (approx 2 Min on PoccoF1 & Xiaomi devices) to restart the killed service.

But as an user we can prevent the app's background services to get killed all together as below :

Press Recent apps physical key (left side button).

Drag down the app once (select, hold & slide it down) tap on the lock icon (if the lock is in open state) to lock the app.

The app will be put in lock condition (even if you clear the background app processes by clearing, the app will keep on running).

Same way, if you want to remove it from the lock condition, just drag down again once and the lock symbol will disappear (clearing the background process will clear the app from running too).

But, With this way App's locking status will be reset on reboot on most of the devices.

EDIT:
After observing the behavior (on Xiaomi's RedmiS3, Android V6.0) of Foreground service here is the analysis:

Even after enabling the "AutoStart" programatically (via user intervention, as explained above) the service didn't restarts always (Service restarted only on few occasions, but most of the time it didn't).

Also, if I search for "AutoStart" in device settings I can't see my app there in the AutoStart list. It seems above method only providing Autostart permission but not enabling it, NOT SURE!.
And, if I add my app into "AutoStart" list via device setting, my service gets restarted (though it takes some time).

Restarting the killed service in onTaskRemoved() callback could be another option but this callback gets called in surprising way when service gets killed. This callback gets executed only when app is been closed properly by back key press. If we minimized the app (Pause state) this callback never gets called on service kill. (Looking for the reason)

Recently I found another way, the killed service could be restarted via GCM notification event. I doubt that weather the GCM works when App's gets killed on the devices or not (I need to check this and verify the behavior). But one this is for sure "These OEMs has made the programmer life hell!).

Body:
Few popular apps run in background without being killed during memory cleanup cycle (many of the popular OEMs customize the stock ROM for battery/memory optimization), because they are "White listed" by these manufactures.
For your app you can whitelist it either manually (via corresponding "settings" for the devices) or programmatically by redirecting users to the corresponding settings page to white list the app. programmatically you can do like below:

Add below permissions in the App's manifest file:`

<uses-permission android:name="oppo.permission.OPPO_COMPONENT_SAFE"/>
<uses-permission android:name="com.huawei.permission.external_app_settings.USE_COMPONENT"/>`

Redirect your to the Auto Start setting:

if (Build.BRAND.equalsIgnoreCase("xiaomi")) {
                Intent intent = new Intent();
                intent.setComponent(new

ComponentName("com.miui.securitycenter",
                            "com.miui.permcenter.autostart.AutoStartManagementActivity"));
                    startActivity(intent);
            } else if (Build.MANUFACTURER.equalsIgnoreCase("oppo")) {
                try {
                    Intent intent = new Intent();
                    intent.setClassName("com.coloros.safecenter",
                            "com.coloros.safecenter.permission.startup.StartupAppListActivity");
                    startActivity(intent);
                } catch (Exception e) {
                    try {
                        Intent intent = new Intent();
                        intent.setClassName("com.oppo.safe",
                                "com.oppo.safe.permission.startup.StartupAppListActivity");
                        startActivity(intent);
                    } catch (Exception ex) {
                        try {
                            Intent intent = new Intent();
                            intent.setClassName("com.coloros.safecenter",
                                    "com.coloros.safecenter.startupapp.StartupAppListActivity");
                            startActivity(intent);
                        } catch (Exception exx) {

                        }
                    }
                }
            }

AutoStart Reference For other OEMs

I have tested this method and it worked but the reliability is still a question as system taking time (approx 2 Min on PoccoF1 & Xiaomi devices) to restart the killed service.

But as an user we can prevent the app's background services to get killed all together as below :

Press Recent apps physical key (left side button).

Drag down the app once (select, hold & slide it down) tap on the lock icon (if the lock is in open state) to lock the app.

The app will be put in lock condition (even if you clear the background app processes by clearing, the app will keep on running).

Same way, if you want to remove it from the lock condition, just drag down again once and the lock symbol will disappear (clearing the background process will clear the app from running too).

But, With this way App's locking status will be reset on reboot on most of the devices.

EDIT:
After observing the behavior (on Xiaomi's RedmiS3, Android V6.0) of Foreground service here is the analysis:

Even after enabling the "AutoStart" programatically (via user intervention, as explained above) the service didn't restarts always (Service restarted only on few occasions, but most of the time it didn't).

Also, if I search for "AutoStart" in device settings I can't see my app there in the AutoStart list. It seems above method only providing Autostart permission but not enabling it, NOT SURE!.
And, if I add my app into "AutoStart" list via device setting, my service gets restarted (though it takes some time).

Restarting the killed service in onTaskRemoved() callback could be another option but this callback gets called in surprising way when service gets killed. This callback gets executed only when app is been closed properly by back key press. If we minimized the app (Pause state) this callback never gets called on service kill. (Looking for the reason)

Recently I found another way, the killed service could be restarted via GCM notification event. I doubt that weather the GCM works when App's gets killed on the devices or not (I need to check this and verify the behavior). But one this is for sure "These OEMs has made the programmer life hell!).